commit f92b57c7b664a3e91cf330c7a76c53d01d20ee34 Author: sudacode Date: Mon Feb 9 19:04:19 2026 -0800 initial commit diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c7c7d020 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,50 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + lint-and-audit: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: true + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + + - name: Install dependencies + run: pnpm install + + - name: Build (TypeScript check) + run: pnpm run build + + - name: Config tests + run: pnpm run test:config + + - name: Security audit + run: pnpm audit --audit-level=high + continue-on-error: true + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Verify Bun subminer wrapper + run: | + chmod +x subminer + ./subminer --help >/dev/null diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml new file mode 100644 index 0000000..d300267 --- /dev/null +++ b/.github/workflows/claude.yml @@ -0,0 +1,50 @@ +name: Claude Code + +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + issues: + types: [opened, assigned] + pull_request_review: + types: [submitted] + +jobs: + claude: + if: | + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) || + (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude'))) + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + issues: read + id-token: write + actions: read # Required for Claude to read CI results on PRs + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Run Claude Code + id: claude + uses: anthropics/claude-code-action@v1 + with: + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + + # This is an optional setting that allows Claude to read CI results on PRs + additional_permissions: | + actions: read + + # Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it. + # prompt: 'Update the pull request description to include a summary of changes.' + + # Optional: Add claude_args to customize behavior and configuration + # See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md + # or https://code.claude.com/docs/en/cli-reference for available options + # claude_args: '--allowed-tools Bash(gh pr:*)' + diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..6dc2c2d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,200 @@ +name: Release + +on: + push: + tags: + - 'v*' + +permissions: + contents: write + +jobs: + build-linux: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: true + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + + - name: Install dependencies + run: pnpm install + + - name: Build texthooker-ui + run: | + cd vendor/texthooker-ui + pnpm install + pnpm build + + - name: Build AppImage + run: pnpm run build:appimage + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Upload AppImage artifact + uses: actions/upload-artifact@v4 + with: + name: appimage + path: release/*.AppImage + + build-macos: + runs-on: macos-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: true + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + + - name: Validate macOS signing/notarization secrets + run: | + missing=0 + for name in CSC_LINK CSC_KEY_PASSWORD APPLE_ID APPLE_APP_SPECIFIC_PASSWORD APPLE_TEAM_ID; do + if [ -z "${!name}" ]; then + echo "Missing required secret: $name" + missing=1 + fi + done + if [ "$missing" -ne 0 ]; then + echo "Set all required macOS signing/notarization secrets and rerun." + exit 1 + fi + env: + CSC_LINK: ${{ secrets.CSC_LINK }} + CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + + - name: Install dependencies + run: pnpm install + + - name: Build texthooker-ui + run: | + cd vendor/texthooker-ui + pnpm install + pnpm build + + - name: Build signed + notarized macOS artifacts + run: pnpm run build:mac + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CSC_LINK: ${{ secrets.CSC_LINK }} + CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + + - name: Upload macOS artifacts + uses: actions/upload-artifact@v4 + with: + name: macos + path: | + release/*.dmg + release/*.zip + + release: + needs: [build-linux, build-macos] + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Download AppImage + uses: actions/download-artifact@v4 + with: + name: appimage + path: release + + - name: Download macOS artifacts + uses: actions/download-artifact@v4 + with: + name: macos + path: release + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Verify Bun subminer wrapper + run: | + chmod +x subminer + ./subminer --help >/dev/null + + - name: Get version from tag + id: version + run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT + + - name: Generate changelog + id: changelog + run: | + PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "") + if [ -n "$PREV_TAG" ]; then + CHANGES=$(git log --pretty=format:"- %s" ${PREV_TAG}..HEAD) + else + COMMIT_COUNT=$(git rev-list --count HEAD) + if [ "$COMMIT_COUNT" -gt 10 ]; then + CHANGES=$(git log --pretty=format:"- %s" HEAD~10..HEAD) + else + CHANGES=$(git log --pretty=format:"- %s") + fi + fi + echo "CHANGES<> $GITHUB_OUTPUT + echo "$CHANGES" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + - name: Create Release + uses: softprops/action-gh-release@v2 + with: + name: ${{ steps.version.outputs.VERSION }} + body: | + ## Changes + ${{ steps.changelog.outputs.CHANGES }} + + ## Installation + + ### AppImage (Recommended) + 1. Download the AppImage below + 2. Make it executable: `chmod +x SubMiner-*.AppImage` + 3. Run: `./SubMiner-*.AppImage` + + ### macOS + 1. Download `subminer-*.dmg` + 2. Open the DMG and drag `SubMiner.app` into `/Applications` + 3. If needed, use the ZIP artifact as an alternative + + ### Manual Installation + See the [README](https://github.com/${{ github.repository }}#installation) for manual installation instructions. + + Note: the `subminer` wrapper script uses Bun (`#!/usr/bin/env bun`), so `bun` must be installed and on `PATH`. + files: | + release/*.AppImage + release/*.dmg + release/*.zip + subminer + draft: false + prerelease: false diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9cb5579 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# Dependencies +node_modules/ + +# Electron build output +out/ +dist/ +release/ + +# Logs +*.log +npm-debug.log* + +# OS files +.DS_Store +Thumbs.db + +# IDE +.idea/ +*.swp +*.swo +**/CLAUDE.md +environment.toml +**/CLAUDE.md +.env +.vscode/* diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..31ab7ff --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "vendor/texthooker-ui"] + path = vendor/texthooker-ui + url = https://github.com/ksyasuda/texthooker-ui.git + branch = subminer diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..a798053 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +only-built-dependencies[]=electron 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/Makefile b/Makefile new file mode 100644 index 0000000..6fab30a --- /dev/null +++ b/Makefile @@ -0,0 +1,190 @@ +.PHONY: help deps build install build-linux build-macos build-macos-unsigned install-linux install-macos install-plugin uninstall uninstall-linux uninstall-macos print-dirs pretty ensure-pnpm generate-config generate-example-config + +APP_NAME := subminer +THEME_FILE := subminer.rasi +PLUGIN_LUA := plugin/subminer.lua +PLUGIN_CONF := plugin/subminer.conf + +# Default install prefix for the wrapper script. +PREFIX ?= $(HOME)/.local +BINDIR ?= $(PREFIX)/bin + +# Linux data dir defaults to XDG_DATA_HOME/SubMiner. +XDG_DATA_HOME ?= $(HOME)/.local/share +LINUX_DATA_DIR ?= $(XDG_DATA_HOME)/SubMiner + +# macOS data dir uses the standard Application Support location. +# Note: contains spaces; recipes must quote it. +MACOS_DATA_DIR ?= $(HOME)/Library/Application Support/SubMiner +MACOS_APP_DIR ?= $(HOME)/Applications +MACOS_APP_DEST ?= $(MACOS_APP_DIR)/SubMiner.app + +# mpv plugin install directories. +MPV_CONFIG_DIR ?= $(HOME)/.config/mpv +MPV_SCRIPTS_DIR ?= $(MPV_CONFIG_DIR)/scripts +MPV_SCRIPT_OPTS_DIR ?= $(MPV_CONFIG_DIR)/script-opts + +# If building from source, the AppImage will typically land in release/. +APPIMAGE_SRC := $(firstword $(wildcard release/SubMiner-*.AppImage)) +MACOS_APP_SRC := $(firstword $(wildcard release/*.app release/*/*.app)) +MACOS_ZIP_SRC := $(firstword $(wildcard release/SubMiner-*.zip)) + +UNAME_S := $(shell uname -s 2>/dev/null || echo Unknown) +ifeq ($(OS),Windows_NT) +PLATFORM := windows +else ifeq ($(UNAME_S),Linux) +PLATFORM := linux +else ifeq ($(UNAME_S),Darwin) +PLATFORM := macos +else +PLATFORM := unknown +endif + +help: + @printf '%s\n' \ + "Targets:" \ + " build Build platform package for detected OS ($(PLATFORM))" \ + " install Install platform artifacts for detected OS ($(PLATFORM))" \ + " build-linux Build Linux AppImage" \ + " build-macos Build macOS DMG/ZIP (signed if configured)" \ + " build-macos-unsigned Build macOS DMG/ZIP without signing/notarization" \ + " install-linux Install Linux wrapper/theme/app artifacts" \ + " install-macos Install macOS wrapper/theme/app artifacts" \ + " install-plugin Install mpv Lua plugin and plugin config" \ + " generate-config Generate ~/.config/SubMiner/config.jsonc from centralized defaults" \ + "" \ + "Other targets:" \ + " deps Install JS dependencies (root + texthooker-ui)" \ + " uninstall-linux Remove Linux install artifacts" \ + " uninstall-macos Remove macOS install artifacts" \ + " print-dirs Show resolved install locations" \ + "" \ + "Variables:" \ + " PREFIX=... Override wrapper install prefix (default: $$HOME/.local)" \ + " BINDIR=... Override wrapper install bin dir" \ + " XDG_DATA_HOME=... Override Linux data dir base (default: $$HOME/.local/share)" \ + " LINUX_DATA_DIR=... Override Linux app data dir" \ + " MACOS_DATA_DIR=... Override macOS app data dir" \ + " MACOS_APP_DIR=... Override macOS app install dir (default: $$HOME/Applications)" \ + " MPV_CONFIG_DIR=... Override mpv config dir (default: $$HOME/.config/mpv)" + +print-dirs: + @printf '%s\n' \ + "PLATFORM=$(PLATFORM)" \ + "UNAME_S=$(UNAME_S)" \ + "BINDIR=$(BINDIR)" \ + "LINUX_DATA_DIR=$(LINUX_DATA_DIR)" \ + "MACOS_DATA_DIR=$(MACOS_DATA_DIR)" \ + "MACOS_APP_DIR=$(MACOS_APP_DIR)" \ + "MACOS_APP_DEST=$(MACOS_APP_DEST)" \ + "APPIMAGE_SRC=$(APPIMAGE_SRC)" \ + "MACOS_APP_SRC=$(MACOS_APP_SRC)" \ + "MACOS_ZIP_SRC=$(MACOS_ZIP_SRC)" + +deps: + @$(MAKE) --no-print-directory ensure-pnpm + @pnpm install + @pnpm -C vendor/texthooker-ui install + +ensure-pnpm: + @command -v pnpm >/dev/null 2>&1 || { printf '%s\n' "[ERROR] pnpm not found"; exit 1; } + +pretty: + @pnpm exec prettier --write 'src/**/*.ts' + +build: + @printf '%s\n' "[INFO] Detected platform: $(PLATFORM)" + @case "$(PLATFORM)" in \ + linux) $(MAKE) --no-print-directory build-linux ;; \ + macos) $(MAKE) --no-print-directory build-macos ;; \ + *) printf '%s\n' "[ERROR] Unsupported OS for this Makefile target: $(PLATFORM)"; exit 1 ;; \ + esac + +install: + @printf '%s\n' "[INFO] Detected platform: $(PLATFORM)" + @case "$(PLATFORM)" in \ + linux) $(MAKE) --no-print-directory install-linux ;; \ + macos) $(MAKE) --no-print-directory install-macos ;; \ + *) printf '%s\n' "[ERROR] Unsupported OS for this Makefile target: $(PLATFORM)"; exit 1 ;; \ + esac + +build-linux: deps + @printf '%s\n' "[INFO] Building Linux package (AppImage)" + @pnpm -C vendor/texthooker-ui build + @pnpm run build:appimage + +build-macos: deps + @printf '%s\n' "[INFO] Building macOS package (DMG + ZIP)" + @pnpm -C vendor/texthooker-ui build + @pnpm run build:mac + +build-macos-unsigned: deps + @printf '%s\n' "[INFO] Building macOS package (DMG + ZIP, unsigned)" + @pnpm -C vendor/texthooker-ui build + @pnpm run build:mac:unsigned + +generate-config: ensure-pnpm + @pnpm run build + @pnpm exec electron . --generate-config + +generate-example-config: ensure-pnpm + @pnpm run build + @pnpm run generate:config-example + + +install-linux: + @printf '%s\n' "[INFO] Installing Linux wrapper/theme artifacts" + @install -d "$(BINDIR)" + @install -m 0755 "./$(APP_NAME)" "$(BINDIR)/$(APP_NAME)" + @install -d "$(LINUX_DATA_DIR)/themes" + @install -m 0644 "./$(THEME_FILE)" "$(LINUX_DATA_DIR)/themes/$(THEME_FILE)" + @if [ -n "$(APPIMAGE_SRC)" ]; then \ + install -m 0755 "$(APPIMAGE_SRC)" "$(BINDIR)/SubMiner.AppImage"; \ + else \ + printf '%s\n' "[WARN] No release/SubMiner-*.AppImage found; skipping AppImage install"; \ + printf '%s\n' " Build one with: make build"; \ + fi + @printf '%s\n' "Installed to:" " $(BINDIR)/subminer" " $(LINUX_DATA_DIR)/themes/$(THEME_FILE)" + +install-macos: + @printf '%s\n' "[INFO] Installing macOS wrapper/theme/app artifacts" + @install -d "$(BINDIR)" + @install -m 0755 "./$(APP_NAME)" "$(BINDIR)/$(APP_NAME)" + @install -d "$(MACOS_DATA_DIR)/themes" + @install -m 0644 "./$(THEME_FILE)" "$(MACOS_DATA_DIR)/themes/$(THEME_FILE)" + @install -d "$(MACOS_APP_DIR)" + @if [ -n "$(MACOS_APP_SRC)" ]; then \ + rm -rf "$(MACOS_APP_DEST)"; \ + cp -R "$(MACOS_APP_SRC)" "$(MACOS_APP_DEST)"; \ + printf '%s\n' "[INFO] Installed app bundle from $(MACOS_APP_SRC)"; \ + elif [ -n "$(MACOS_ZIP_SRC)" ]; then \ + rm -rf "$(MACOS_APP_DEST)"; \ + ditto -x -k "$(MACOS_ZIP_SRC)" "$(MACOS_APP_DIR)"; \ + printf '%s\n' "[INFO] Installed app bundle from $(MACOS_ZIP_SRC)"; \ + else \ + printf '%s\n' "[WARN] No macOS app bundle or zip found in release/; skipping app install"; \ + printf '%s\n' " Build one with: make build"; \ + fi + @printf '%s\n' "Installed to:" " $(BINDIR)/subminer" " $(MACOS_DATA_DIR)/themes/$(THEME_FILE)" " $(MACOS_APP_DEST)" + +install-plugin: + @printf '%s\n' "[INFO] Installing mpv plugin artifacts" + @install -d "$(MPV_SCRIPTS_DIR)" + @install -d "$(MPV_SCRIPT_OPTS_DIR)" + @install -m 0644 "./$(PLUGIN_LUA)" "$(MPV_SCRIPTS_DIR)/subminer.lua" + @install -m 0644 "./$(PLUGIN_CONF)" "$(MPV_SCRIPT_OPTS_DIR)/subminer.conf" + @printf '%s\n' "Installed to:" " $(MPV_SCRIPTS_DIR)/subminer.lua" " $(MPV_SCRIPT_OPTS_DIR)/subminer.conf" + +# Uninstall behavior kept unchanged by default. +uninstall: uninstall-linux + +uninstall-linux: + @rm -f "$(BINDIR)/subminer" "$(BINDIR)/SubMiner.AppImage" + @rm -f "$(LINUX_DATA_DIR)/themes/$(THEME_FILE)" + @printf '%s\n' "Removed:" " $(BINDIR)/subminer" " $(BINDIR)/SubMiner.AppImage" " $(LINUX_DATA_DIR)/themes/$(THEME_FILE)" + +uninstall-macos: + @rm -f "$(BINDIR)/subminer" + @rm -f "$(MACOS_DATA_DIR)/themes/$(THEME_FILE)" + @rm -rf "$(MACOS_APP_DEST)" + @printf '%s\n' "Removed:" " $(BINDIR)/subminer" " $(MACOS_DATA_DIR)/themes/$(THEME_FILE)" " $(MACOS_APP_DEST)" diff --git a/README.md b/README.md new file mode 100644 index 0000000..ae8f009 --- /dev/null +++ b/README.md @@ -0,0 +1,116 @@ +
+ SubMiner logo +

SubMiner

+
+ +An all-in-one sentence mining overlay for MPV with AnkiConnect and dictionary (Yomitan) integration. + +## Features + +- Real-time subtitle display from MPV via IPC socket +- Yomitan integration for fast, on-screen lookups +- Japanese text tokenization using MeCab with smart word boundary detection +- Integrated texthooker-ui server for use with Yomitan +- Integrated websocket server (if [mpv_websocket](https://github.com/kuroahna/mpv_websocket) is not found) to send lines to the texthooker +- AnkiConnect integration for automatic card creation with media (audio/image) + +## Demo + +[![Demo screenshot](./assets/demo-poster.jpg)](https://github.com/user-attachments/assets/9235a554-ea51-4284-b14b-7bbf3defaf58) + +## Requirements + +- `mpv` with IPC socket support +- `mecab` and `mecab-ipadic` (recommended for Japanese tokenization) +- Linux: Hyprland (`hyprctl`) or X11 (`xdotool` + `xwininfo`) +- macOS: Accessibility permission for window tracking + +Optional but recommended: `yt-dlp`, `fzf`, `rofi`, `chafa`, `ffmpegthumbnailer`. + +## Install + +### Linux (AppImage) + +```bash +wget https://github.com/sudacode/subminer/releases/download/v1.0.0/subminer-1.0.0.AppImage -O ~/.local/bin/subminer.AppImage +chmod +x ~/.local/bin/subminer.AppImage +wget https://github.com/sudacode/subminer/releases/download/v1.0.0/subminer -O ~/.local/bin/subminer +chmod +x ~/.local/bin/subminer +``` + +`subminer` uses a [Bun](https://bun.com) shebang, so `bun` must be on `PATH`. + +### From source + +```bash +git clone https://github.com/sudacode/subminer.git +cd subminer +make build +make install +``` + +For macOS app bundle / signing / permissions details, use `docs/installation.md`. + +## Quick Start + +1. Copy and customize [`config.example.jsonc`](config.example.jsonc) to `~/.config/SubMiner/config.jsonc`. +2. Start mpv with IPC enabled: + +```bash +mpv --input-ipc-server=/tmp/subminer-socket video.mkv +``` + +3. Launch SubMiner: + +```bash +subminer video.mkv +# or +subminer https://youtu.be/... +``` + +## Common Commands + +```bash +subminer # pick video from current dir (fzf) +subminer -R # use rofi picker +subminer -d ~/Videos # set source directory +subminer -r -d ~/Anime # recursive search +subminer video.mkv # launch with default mpv profile (subminer) +subminer -p gpu-hq video.mkv # override mpv profile +subminer -T video.mkv # disable texthooker +``` + +## MPV Plugin (Optional) + +```bash +cp plugin/subminer.lua ~/.config/mpv/scripts/ +cp plugin/subminer.conf ~/.config/mpv/script-opts/ +``` + +Requires mpv IPC: `--input-ipc-server=/tmp/subminer-socket` + +Default chord prefix: `y` (`y-y` menu, `y-s` start, `y-S` stop, `y-t` toggle visible layer). + +## Documentation + +Detailed guides live in [`docs/`](docs/README.md): + +- [Installation](docs/installation.md) +- [Usage](docs/usage.md) +- [Configuration](docs/configuration.md) +- [Development](docs/development.md) + +### Third-Party Components + +This project includes the following third-party components: + +- **[Yomitan](https://github.com/yomidevs/yomitan)** - GPL-3.0 +- **[texthooker-ui](https://github.com/Renji-XD/texthooker-ui)** - MIT + +### Acknowledgments + +This project was inspired by **[GameSentenceMiner](https://github.com/bpwhelan/GameSentenceMiner)**'s subtitle overlay and Yomitan integration + +## License + +GNU General Public License v3.0. See [LICENSE](LICENSE). diff --git a/assets/SubMiner.png b/assets/SubMiner.png new file mode 100644 index 0000000..ed163b0 Binary files /dev/null and b/assets/SubMiner.png differ diff --git a/assets/card-mine.mkv b/assets/card-mine.mkv new file mode 100644 index 0000000..c5d398f Binary files /dev/null and b/assets/card-mine.mkv differ diff --git a/assets/card-mine.webm b/assets/card-mine.webm new file mode 100644 index 0000000..a6c9472 Binary files /dev/null and b/assets/card-mine.webm differ diff --git a/assets/demo-poster.jpg b/assets/demo-poster.jpg new file mode 100644 index 0000000..ad030fd Binary files /dev/null and b/assets/demo-poster.jpg differ diff --git a/assets/kiku-integration-poster.jpg b/assets/kiku-integration-poster.jpg new file mode 100644 index 0000000..9f23cd0 Binary files /dev/null and b/assets/kiku-integration-poster.jpg differ diff --git a/assets/kiku-integration.mkv b/assets/kiku-integration.mkv new file mode 100644 index 0000000..3f8a513 Binary files /dev/null and b/assets/kiku-integration.mkv differ diff --git a/assets/kiku-integration.webm b/assets/kiku-integration.webm new file mode 100644 index 0000000..bb995f0 Binary files /dev/null and b/assets/kiku-integration.webm differ diff --git a/build/entitlements.mac.plist b/build/entitlements.mac.plist new file mode 100644 index 0000000..2936796 --- /dev/null +++ b/build/entitlements.mac.plist @@ -0,0 +1,14 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + com.apple.security.cs.disable-library-validation + + com.apple.security.automation.apple-events + + + diff --git a/config.example.jsonc b/config.example.jsonc new file mode 100644 index 0000000..64c607b --- /dev/null +++ b/config.example.jsonc @@ -0,0 +1,210 @@ +/** + * SubMiner Example Configuration File + * + * This file is auto-generated from src/config/definitions.ts. + * Copy to ~/.config/SubMiner/config.jsonc and edit as needed. + */ +{ + + // ========================================== + // Overlay Auto-Start + // When overlay connects to mpv, automatically show overlay and hide mpv subtitles. + // ========================================== + "auto_start_overlay": false, + + // ========================================== + // Visible Overlay Subtitle Binding + // Control whether visible overlay toggles also toggle MPV subtitle visibility. + // When enabled, visible overlay hides MPV subtitles; when disabled, MPV subtitles are left unchanged. + // ========================================== + "bind_visible_overlay_to_mpv_sub_visibility": true, + + // ========================================== + // Texthooker Server + // Control whether browser opens automatically for texthooker. + // ========================================== + "texthooker": { + "openBrowser": true + }, + + // ========================================== + // WebSocket Server + // Built-in WebSocket server broadcasts subtitle text to connected clients. + // Auto mode disables built-in server if mpv_websocket is detected. + // ========================================== + "websocket": { + "enabled": "auto", + "port": 6677 + }, + + // ========================================== + // AnkiConnect Integration + // Automatic Anki updates and media generation options. + // ========================================== + "ankiConnect": { + "enabled": false, + "url": "http://127.0.0.1:8765", + "pollingRate": 3000, + "fields": { + "audio": "ExpressionAudio", + "image": "Picture", + "sentence": "Sentence", + "miscInfo": "MiscInfo", + "translation": "SelectionText" + }, + "ai": { + "enabled": false, + "alwaysUseAiTranslation": false, + "apiKey": "", + "model": "openai/gpt-4o-mini", + "baseUrl": "https://openrouter.ai/api", + "targetLanguage": "English", + "systemPrompt": "You are a translation engine. Return only the translated text with no explanations." + }, + "media": { + "generateAudio": true, + "generateImage": true, + "imageType": "static", + "imageFormat": "jpg", + "imageQuality": 92, + "animatedFps": 10, + "animatedMaxWidth": 640, + "animatedCrf": 35, + "audioPadding": 0.5, + "fallbackDuration": 3, + "maxMediaDuration": 30 + }, + "behavior": { + "overwriteAudio": true, + "overwriteImage": true, + "mediaInsertMode": "append", + "highlightWord": true, + "notificationType": "osd", + "autoUpdateNewCards": true + }, + "metadata": { + "pattern": "[SubMiner] %f (%t)" + }, + "isLapis": { + "enabled": false, + "sentenceCardModel": "Japanese sentences", + "sentenceCardSentenceField": "Sentence", + "sentenceCardAudioField": "SentenceAudio" + }, + "isKiku": { + "enabled": false, + "fieldGrouping": "disabled", + "deleteDuplicateInAuto": true + } + }, + + // ========================================== + // Keyboard Shortcuts + // Overlay keyboard shortcuts. Set a shortcut to null to disable. + // ========================================== + "shortcuts": { + "toggleVisibleOverlayGlobal": "Alt+Shift+O", + "toggleInvisibleOverlayGlobal": "Alt+Shift+I", + "copySubtitle": "CommandOrControl+C", + "copySubtitleMultiple": "CommandOrControl+Shift+C", + "updateLastCardFromClipboard": "CommandOrControl+V", + "triggerFieldGrouping": "CommandOrControl+G", + "triggerSubsync": "Ctrl+Alt+S", + "mineSentence": "CommandOrControl+S", + "mineSentenceMultiple": "CommandOrControl+Shift+S", + "multiCopyTimeoutMs": 3000, + "toggleSecondarySub": "CommandOrControl+Shift+V", + "markAudioCard": "CommandOrControl+Shift+A", + "openRuntimeOptions": "CommandOrControl+Shift+O" + }, + + // ========================================== + // Invisible Overlay + // Startup behavior for the invisible interactive subtitle mining layer. + // ========================================== + "invisibleOverlay": { + "startupVisibility": "platform-default" + }, + + // ========================================== + // Keybindings (MPV Commands) + // Extra keybindings that are merged with built-in defaults. + // Set command to null to disable a default keybinding. + // ========================================== + "keybindings": [], + + // ========================================== + // Subtitle Appearance + // Primary and secondary subtitle styling. + // ========================================== + "subtitleStyle": { + "fontFamily": "Noto Sans CJK JP Regular, Noto Sans CJK JP, Arial Unicode MS, Arial, sans-serif", + "fontSize": 35, + "fontColor": "#cad3f5", + "fontWeight": "normal", + "fontStyle": "normal", + "backgroundColor": "rgba(54, 58, 79, 0.5)", + "secondary": { + "fontSize": 24, + "fontColor": "#ffffff", + "backgroundColor": "transparent", + "fontWeight": "normal", + "fontStyle": "normal", + "fontFamily": "Noto Sans CJK JP Regular, Noto Sans CJK JP, Arial Unicode MS, Arial, sans-serif" + } + }, + + // ========================================== + // Secondary Subtitles + // Dual subtitle track options. + // Used by subminer YouTube subtitle generation as secondary language preferences. + // ========================================== + "secondarySub": { + "secondarySubLanguages": [], + "autoLoadSecondarySub": false, + "defaultMode": "hover" + }, + + // ========================================== + // Auto Subtitle Sync + // Subsync engine and executable paths. + // ========================================== + "subsync": { + "defaultMode": "auto", + "alass_path": "", + "ffsubsync_path": "", + "ffmpeg_path": "" + }, + + // ========================================== + // Subtitle Position + // Initial vertical subtitle position from the bottom. + // ========================================== + "subtitlePosition": { + "yPercent": 10 + }, + + // ========================================== + // Jimaku + // Jimaku API configuration and defaults. + // ========================================== + "jimaku": { + "apiBaseUrl": "https://jimaku.cc", + "languagePreference": "ja", + "maxEntryResults": 10 + }, + + // ========================================== + // YouTube Subtitle Generation + // Defaults for subminer YouTube subtitle extraction/transcription mode. + // ========================================== + "youtubeSubgen": { + "mode": "automatic", + "whisperBin": "", + "whisperModel": "", + "primarySubLanguages": [ + "ja", + "jpn" + ] + } +} diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..9f797b6 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,18 @@ +# Documentation + +Use this directory for detailed SubMiner documentation. + +- [Installation](installation.md) + - Platform requirements + - AppImage / macOS / source installs + - mpv plugin setup +- [Usage](usage.md) + - Script vs plugin workflow + - Running SubMiner with mpv + - Keybindings and runtime behavior +- [Configuration](configuration.md) + - Full config file reference and option details +- [Development](development.md) + - Contributor notes + - Environment variables + - License and acknowledgments diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..0573166 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,565 @@ +# Configuration + +Settings are stored in `~/.config/SubMiner/config.jsonc` + +### Configuration File + +See `config.example.jsonc` for a comprehensive example configuration file with all available options, default values, and detailed comments. Only include the options you want to customize in your config file. + +Generate a fresh default config from the centralized config registry: + +```bash +subminer.AppImage --generate-config +subminer.AppImage --generate-config --config-path /tmp/subminer.jsonc +subminer.AppImage --generate-config --backup-overwrite +``` + +- `--generate-config` writes a default JSONC config template. +- If the target file exists, SubMiner prompts to create a timestamped backup and overwrite. +- In non-interactive shells, use `--backup-overwrite` to explicitly back up and overwrite. +- `pnpm run generate:config-example` regenerates repository `config.example.jsonc` from the same centralized defaults. +- `make generate-config` builds and runs the same default-config generator via local Electron. + +Invalid config values are handled with warn-and-fallback behavior: SubMiner logs the bad key/value and continues with the default for that option. + + +### Configuration Options Overview + +The configuration file includes several main sections: + +- [**AnkiConnect**](#ankiconnect) - Automatic Anki card creation with media +- [**Auto-Start Overlay**](#auto-start-overlay) - Automatically show overlay on MPV connection +- [**Visible Overlay Subtitle Binding**](#visible-overlay-subtitle-binding) - Link visible overlay toggles to MPV subtitle visibility +- [**Auto Subtitle Sync**](#auto-subtitle-sync) - Sync current subtitle with `alass`/`ffsubsync` +- [**Invisible Overlay**](#invisible-overlay) - Startup visibility behavior for the invisible mining layer +- [**Jimaku**](#jimaku) - Jimaku API configuration and defaults +- [**Keybindings**](#keybindings) - MPV command shortcuts +- [**Runtime Option Palette**](#runtime-option-palette) - Live, session-only option toggles +- [**Secondary Subtitles**](#secondary-subtitles) - Dual subtitle track support +- [**Shortcuts Configuration**](#shortcuts-configuration) - Overlay keyboard shortcuts +- [**Subtitle Position**](#subtitle-position) - Overlay vertical positioning +- [**Subtitle Style**](#subtitle-style) - Appearance customization +- [**Texthooker**](#texthooker) - Control browser opening behavior +- [**WebSocket Server**](#websocket-server) - Built-in subtitle broadcasting server +- [**YouTube Subtitle Generation**](#youtube-subtitle-generation) - Launcher defaults for yt-dlp + local whisper fallback + + +### AnkiConnect + +Enable automatic Anki card creation and updates with media generation: + +```json +{ + "ankiConnect": { + "enabled": true, + "url": "http://127.0.0.1:8765", + "pollingRate": 3000, + "deck": "Learning::Japanese", + "fields": { + "audio": "ExpressionAudio", + "image": "Picture", + "sentence": "Sentence", + "miscInfo": "MiscInfo", + "translation": "SelectionText" + }, + "ai": { + "enabled": false, + "alwaysUseAiTranslation": false, + "apiKey": "", + "model": "openai/gpt-4o-mini", + "baseUrl": "https://openrouter.ai/api", + "targetLanguage": "English", + "systemPrompt": "You are a translation engine. Return only the translated text with no explanations." + }, + "media": { + "generateAudio": true, + "generateImage": true, + "imageType": "static", + "imageFormat": "jpg", + "imageQuality": 92, + "imageMaxWidth": 1280, + "imageMaxHeight": 720, + "animatedFps": 10, + "animatedMaxWidth": 640, + "animatedMaxHeight": 360, + "animatedCrf": 35, + "audioPadding": 0.5, + "fallbackDuration": 3, + "maxMediaDuration": 30 + }, + "behavior": { + "autoUpdateNewCards": true, + "overwriteAudio": true, + "overwriteImage": true + }, + "metadata": { + "pattern": "[SubMiner] %f (%t)" + }, + "isLapis": { + "enabled": true, + "sentenceCardModel": "Japanese sentences", + "sentenceCardSentenceField": "Sentence", + "sentenceCardAudioField": "SentenceAudio" + }, + "isKiku": { + "enabled": false, + "fieldGrouping": "disabled", + "deleteDuplicateInAuto": true + } + } +} +``` + +This example is intentionally compact. The option table below documents available `ankiConnect` settings and behavior. + +**Requirements:** [AnkiConnect](https://github.com/FooSoft/anki-connect) plugin must be installed and running in Anki. ffmpeg must be installed for media generation. + +| Option | Values | Description | +| -------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| `enabled` | `true`, `false` | Enable AnkiConnect integration (default: `false`) | +| `url` | string (URL) | AnkiConnect API URL (default: `http://127.0.0.1:8765`) | +| `pollingRate` | number (ms) | How often to check for new cards (default: `3000`) | +| `deck` | string | Anki deck to monitor for new cards | +| `fields.audio` | string | Card field for audio files (default: `ExpressionAudio`) | +| `fields.image` | string | Card field for images (default: `Picture`) | +| `fields.sentence` | string | Card field for sentences (default: `Sentence`) | +| `fields.miscInfo` | string | Card field for metadata (default: `"MiscInfo"`, set to `null` to disable) | +| `fields.translation` | string | Card field for sentence-card translation/back text (default: `SelectionText`) | +| `ai.enabled` | `true`, `false` | Use AI translation for sentence cards. Also auto-attempted when secondary subtitle is missing. | +| `ai.alwaysUseAiTranslation` | `true`, `false` | When `true`, always use AI translation even if secondary subtitles exist. When `false`, AI is used only when no secondary subtitle exists. | +| `ai.apiKey` | string | API key for your OpenAI-compatible endpoint (required for translation). | +| `ai.model` | string | Model id for your OpenAI-compatible endpoint (default: `openai/gpt-4o-mini`). | +| `ai.baseUrl` | string (URL) | OpenAI-compatible API base URL; accepts with or without `/v1`. | +| `ai.targetLanguage` | string | Target language name used in translation prompt (default: `English`). | +| `ai.systemPrompt` | string | System prompt used for translation (default returns translation text only). | +| `media.generateAudio` | `true`, `false` | Generate audio clips from video (default: `true`) | +| `media.generateImage` | `true`, `false` | Generate image/animation screenshots (default: `true`) | +| `media.imageType` | `"static"`, `"avif"` | Image type: static screenshot or animated AVIF (default: `"static"`) | +| `media.imageFormat` | `"jpg"`, `"png"`, `"webp"` | Image format (default: `"jpg"`) | +| `media.imageQuality` | number (1-100) | Image quality for JPG/WebP; PNG ignores this (default: `92`) | +| `media.imageMaxWidth` | number (px) | Optional max width for static screenshots. Unset keeps source width. | +| `media.imageMaxHeight` | number (px) | Optional max height for static screenshots. Unset keeps source height. | +| `media.animatedFps` | number (1-60) | FPS for animated AVIF (default: `10`) | +| `media.animatedMaxWidth` | number (px) | Max width for animated AVIF (default: `640`) | +| `media.animatedMaxHeight` | number (px) | Optional max height for animated AVIF. Unset keeps source aspect-constrained height. | +| `media.animatedCrf` | number (0-63) | CRF quality for AVIF; lower = higher quality (default: `35`) | +| `media.audioPadding` | number (seconds) | Padding around audio clip timing (default: `0.5`) | +| `media.fallbackDuration` | number (seconds) | Default duration if timing unavailable (default: `3.0`) | +| `media.maxMediaDuration` | number (seconds) | Max duration for generated media from multi-line copy (default: `30`, `0` to disable) | +| `behavior.overwriteAudio` | `true`, `false` | Replace existing audio on updates; when `false`, new audio is appended/prepended per `behavior.mediaInsertMode` (default: `true`) | +| `behavior.overwriteImage` | `true`, `false` | Replace existing images on updates; when `false`, new images are appended/prepended per `behavior.mediaInsertMode` (default: `true`) | +| `behavior.mediaInsertMode` | `"append"`, `"prepend"` | Where to insert new media when overwrite is off (default: `"append"`) | +| `behavior.highlightWord` | `true`, `false` | Highlight the word in sentence context (default: `true`) | +| `behavior.notificationType` | `"osd"`, `"system"`, `"both"`, `"none"` | Notification type on card update (default: `"osd"`) | +| `behavior.autoUpdateNewCards` | `true`, `false` | Automatically update cards on creation (default: `true`) | +| `metadata.pattern` | string | Format pattern for metadata: `%f`=filename, `%F`=filename+ext, `%t`=time | +| `isLapis` | object | Lapis/shared sentence-card config: `{ enabled, sentenceCardModel, sentenceCardSentenceField, sentenceCardAudioField }` | +| `isKiku` | object | Kiku-only config: `{ enabled, fieldGrouping, deleteDuplicateInAuto }` (shared sentence/audio/model settings are inherited from `isLapis`) | + +**Kiku / Lapis Note Type Support:** + +SubMiner supports the [Lapis](https://github.com/donkuri/lapis) and [Kiku](https://kiku.youyoumu.my.id/) note types. Both `isLapis.enabled` and `isKiku.enabled` can be true; Kiku takes precedence for grouping behavior, while sentence-card model/field settings come from `isLapis`. + +When enabled, sentence cards automatically set `IsSentenceCard` to `"x"` and populate the `Expression` field. Audio cards set `IsAudioCard` to `"x"`. + +Kiku extends Lapis with **field grouping** — when a duplicate card is detected (same Word/Expression), SubMiner merges the two cards' content into one using Kiku's `data-group-id` HTML structure, organizing each mining instance into separate pages within the note. + +[![Field Grouping Demo](assets/kiku-integration-poster.jpg)](https://github.com/user-attachments/assets/bf2476cb-2351-4622-8143-c90e59b19213) + + +| Mode | Behavior | +| ---------- | -------------------------------------------------------------------------------------------------------------------------- | +| `auto` | Automatically merges the new card's content into the original; duplicate deletion is controlled by `deleteDuplicateInAuto` | +| `manual` | Shows an overlay popup to choose which card to keep and whether to delete the duplicate after merge | +| `disabled` | No field grouping; duplicate cards are left as-is | + +`deleteDuplicateInAuto` controls whether `auto` mode deletes the duplicate after merge (default: `true`). In `manual` mode, the popup asks each time whether to delete the duplicate. + +**Image Quality Notes:** + +- `imageQuality` affects JPG and WebP only; PNG is lossless and ignores this setting +- JPG quality is mapped to FFmpeg's scale (2-31, lower = better) +- WebP quality uses FFmpeg's native 0-100 scale + +**Manual Card Update:** + +When `behavior.autoUpdateNewCards` is set to `false`, new cards are detected but not automatically updated. Instead, you can manually update cards using keyboard shortcuts: + +| Shortcut | Action | +| -------------- | ------------------------------------------------------------------------------------------------------------ | +| `Ctrl+C` | Copy the current subtitle line to clipboard (preserves line breaks) | +| `Ctrl+Shift+C` | Enter multi-copy mode. Press `1-9` to copy that many recent lines, or `Esc` to cancel. Timeout: 3 seconds | +| `Ctrl+V` | Update the last added Anki card using subtitles from clipboard | +| `Ctrl+G` | Trigger Kiku duplicate field grouping for the last added card (only when `behavior.autoUpdateNewCards` is `false`) | +| `Ctrl+S` | Create a sentence card from the current subtitle line | +| `Ctrl+Shift+S` | Enter multi-mine mode. Press `1-9` to create a sentence card from that many recent lines, or `Esc` to cancel | +| `Ctrl+Shift+V` | Cycle secondary subtitle display mode (hidden → visible → hover) | +| `Ctrl+Shift+A` | Mark the last added Anki card as an audio card (sets IsAudioCard, SentenceAudio, Sentence, Picture) | +| `Ctrl+Shift+O` | Open runtime options palette (session-only live toggles) | + +To copy multiple lines (current + previous): + +1. Press `Ctrl+Shift+C` +2. Press a number key (`1-9`) within 3 seconds +3. The specified number of most recent subtitle lines are copied +4. Press `Ctrl+V` to update the last added card with the copied lines + +These shortcuts are only active when the overlay window is visible. They are automatically disabled when the overlay is hidden to avoid interfering with normal system clipboard operations. + + +### Auto-Start Overlay + +Control whether the overlay automatically becomes visible when it connects to mpv: + +```json +{ + "auto_start_overlay": false +} +``` + +| Option | Values | Description | +| -------------------- | --------------- | ------------------------------------------------------ | +| `auto_start_overlay` | `true`, `false` | Auto-show overlay on mpv connection (default: `false`) | + +The mpv plugin now controls startup per layer via `auto_start_visible_overlay` and `auto_start_invisible_overlay` in `subminer.conf` (`platform-default` for invisible means hidden on Linux, visible on macOS/Windows). + +### Visible Overlay Subtitle Binding + +Control whether toggling the visible overlay also toggles MPV subtitle visibility: + +```json +{ + "bind_visible_overlay_to_mpv_sub_visibility": true +} +``` + +| Option | Values | Description | +| --------------------------------------------- | --------------- | ----------- | +| `bind_visible_overlay_to_mpv_sub_visibility` | `true`, `false` | When `true` (default), visible overlay hides MPV primary/secondary subtitles and restores them when hidden. When `false`, visible overlay toggles do not change MPV subtitle visibility. | + + +### Auto Subtitle Sync + +Sync the active subtitle track using `alass` (preferred) or `ffsubsync`: + +```json +{ + "subsync": { + "defaultMode": "auto", + "alass_path": "", + "ffsubsync_path": "", + "ffmpeg_path": "" + } +} +``` + +| Option | Values | Description | +| ---------------- | -------------------- | ----------- | +| `defaultMode` | `"auto"`, `"manual"` | `auto`: try `alass` against secondary subtitle, then fallback to `ffsubsync`; `manual`: open overlay picker | +| `alass_path` | string path | Path to `alass` executable. Empty or `null` falls back to `/usr/bin/alass`. | +| `ffsubsync_path` | string path | Path to `ffsubsync` executable. Empty or `null` falls back to `/usr/bin/ffsubsync`. | +| `ffmpeg_path` | string path | Path to `ffmpeg` (used for internal subtitle extraction). Empty or `null` falls back to `/usr/bin/ffmpeg`. | + +Default trigger is `Ctrl+Alt+S` via `shortcuts.triggerSubsync`. +Customize it there, or set it to `null` to disable. + + +### Invisible Overlay + +SubMiner includes a second subtitle mining layer that can be visually invisible while still interactive for Yomitan lookups. + +- `invisibleOverlay.startupVisibility` values: +1. `"platform-default"`: hidden on Wayland, visible on Windows/macOS/other sessions. +2. `"visible"`: always shown on startup. +3. `"hidden"`: always hidden on startup. + + +### Jimaku + +Configure Jimaku API access and defaults: + +```json +{ + "jimaku": { + "apiKey": "YOUR_API_KEY", + "apiKeyCommand": "cat ~/.jimaku_key", + "apiBaseUrl": "https://jimaku.cc", + "languagePreference": "ja", + "maxEntryResults": 10 + } +} +``` + +Jimaku is rate limited; if you hit a limit, SubMiner will surface the retry delay from the API response. + +Set `openBrowser` to `false` to only print the URL without opening a browser. + + +### Keybindings + +Add a `keybindings` array to configure keyboard shortcuts that send commands to mpv: + +See `config.example.jsonc` for detailed configuration options and more examples. + +**Default keybindings:** + +| Key | Command | Description | +| ----------------- | -------------------------- | ------------------------------------- | +| `Space` | `["cycle", "pause"]` | Toggle pause | +| `ArrowRight` | `["seek", 5]` | Seek forward 5 seconds | +| `ArrowLeft` | `["seek", -5]` | Seek backward 5 seconds | +| `ArrowUp` | `["seek", 60]` | Seek forward 60 seconds | +| `ArrowDown` | `["seek", -60]` | Seek backward 60 seconds | +| `Shift+KeyH` | `["sub-seek", -1]` | Jump to previous subtitle | +| `Shift+KeyL` | `["sub-seek", 1]` | Jump to next subtitle | +| `Ctrl+Shift+KeyH` | `["__replay-subtitle"]` | Replay current subtitle, pause at end | +| `Ctrl+Shift+KeyL` | `["__play-next-subtitle"]` | Play next subtitle, pause at end | +| `KeyQ` | `["quit"]` | Quit mpv | +| `Ctrl+KeyW` | `["quit"]` | Quit mpv | + +**Custom keybindings example:** + +```json +{ + "keybindings": [ + { "key": "ArrowRight", "command": ["seek", 5] }, + { "key": "ArrowLeft", "command": ["seek", -5] }, + { "key": "Shift+ArrowRight", "command": ["seek", 30] }, + { "key": "KeyR", "command": ["script-binding", "immersive/auto-replay"] }, + { "key": "KeyA", "command": ["script-message", "ankiconnect-add-note"] } + ] +} +``` + +**Key format:** Use `KeyboardEvent.code` values (`Space`, `ArrowRight`, `KeyR`, etc.) with optional modifiers (`Ctrl+`, `Alt+`, `Shift+`, `Meta+`). + +**Disable a default binding:** Set command to `null`: + +```json +{ "key": "Space", "command": null } +``` + +**Special commands:** Commands prefixed with `__` are handled internally by the overlay rather than sent to mpv. `__replay-subtitle` replays the current subtitle and pauses at its end. `__play-next-subtitle` seeks to the next subtitle, plays it, and pauses at its end. `__runtime-options-open` opens the runtime options palette. `__runtime-option-cycle:[:next|prev]` cycles a runtime option value. + +**Supported commands:** Any valid mpv JSON IPC command array (`["cycle", "pause"]`, `["seek", 5]`, `["script-binding", "..."]`, etc.) + +**See `config.example.jsonc`** for more keybinding examples and configuration options. + + +### Runtime Option Palette + +Use the runtime options palette to toggle settings live while SubMiner is running. These changes are session-only and reset on restart. + +Current runtime options: + +- `ankiConnect.behavior.autoUpdateNewCards` (`On` / `Off`) +- `ankiConnect.isKiku.fieldGrouping` (`auto` / `manual` / `disabled`) + +Default shortcut: `Ctrl+Shift+O` + +Palette controls: + +- `Arrow Up/Down`: select option +- `Arrow Left/Right`: change selected value +- `Enter`: apply selected value +- `Esc`: close + + +### Secondary Subtitles + +Display a second subtitle track (e.g., English alongside Japanese) in the overlay: + +See `config.example.jsonc` for detailed configuration options. + +```json +{ + "secondarySub": { + "secondarySubLanguages": ["eng", "en"], + "autoLoadSecondarySub": true, + "defaultMode": "hover" + } +} +``` + +| Option | Values | Description | +| ----------------------- | ---------------------------------- | ------------------------------------------------------ | +| `secondarySubLanguages` | string[] | Language codes to auto-load (e.g., `["eng", "en"]`) | +| `autoLoadSecondarySub` | `true`, `false` | Auto-detect and load matching secondary subtitle track | +| `defaultMode` | `"hidden"`, `"visible"`, `"hover"` | Initial display mode (default: `"hover"`) | + +**Display modes:** + +- **hidden** — Secondary subtitles not shown +- **visible** — Always visible at top of overlay +- **hover** — Only visible when hovering over the subtitle area (default) + +**See `config.example.jsonc`** for additional secondary subtitle configuration options. + + +### Shortcuts Configuration + +Customize or disable the overlay keyboard shortcuts: + +See `config.example.jsonc` for detailed configuration options. + +```json +{ + "shortcuts": { + "toggleVisibleOverlayGlobal": "Alt+Shift+O", + "toggleInvisibleOverlayGlobal": "Alt+Shift+I", + "copySubtitle": "CommandOrControl+C", + "copySubtitleMultiple": "CommandOrControl+Shift+C", + "updateLastCardFromClipboard": "CommandOrControl+V", + "triggerFieldGrouping": "CommandOrControl+G", + "triggerSubsync": "Ctrl+Alt+S", + "mineSentence": "CommandOrControl+S", + "mineSentenceMultiple": "CommandOrControl+Shift+S", + "markAudioCard": "CommandOrControl+Shift+A", + "openRuntimeOptions": "CommandOrControl+Shift+O", + "multiCopyTimeoutMs": 3000 + } +} +``` + +| Option | Values | Description | +| ----------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `toggleVisibleOverlayGlobal` | string \| `null` | Global accelerator for toggling visible subtitle overlay (default: `"Alt+Shift+O"`) | +| `toggleInvisibleOverlayGlobal` | string \| `null` | Global accelerator for toggling invisible interactive overlay (default: `"Alt+Shift+I"`) | +| `copySubtitle` | string \| `null` | Accelerator for copying current subtitle (default: `"CommandOrControl+C"`) | +| `copySubtitleMultiple` | string \| `null` | Accelerator for multi-copy mode (default: `"CommandOrControl+Shift+C"`) | +| `updateLastCardFromClipboard` | string \| `null` | Accelerator for updating card from clipboard (default: `"CommandOrControl+V"`) | +| `triggerFieldGrouping` | string \| `null` | Accelerator for Kiku field grouping on last card (default: `"CommandOrControl+G"`; only active when `behavior.autoUpdateNewCards` is `false`) | +| `triggerSubsync` | string \| `null` | Accelerator for running Subsync (default: `"Ctrl+Alt+S"`) | +| `mineSentence` | string \| `null` | Accelerator for creating sentence card from current subtitle (default: `"CommandOrControl+S"`) | +| `mineSentenceMultiple` | string \| `null` | Accelerator for multi-mine sentence card mode (default: `"CommandOrControl+Shift+S"`) | +| `multiCopyTimeoutMs` | number | Timeout in ms for multi-copy/mine digit input (default: `3000`) | +| `toggleSecondarySub` | string \| `null` | Accelerator for cycling secondary subtitle mode (default: `"CommandOrControl+Shift+V"`) | +| `markAudioCard` | string \| `null` | Accelerator for marking last card as audio card (default: `"CommandOrControl+Shift+A"`) | +| `openRuntimeOptions` | string \| `null` | Opens runtime options palette for live session-only toggles (default: `"CommandOrControl+Shift+O"`) | + +**See `config.example.jsonc`** for the complete list of shortcut configuration options. + +Set any shortcut to `null` to disable it. + + +### Subtitle Position + +Set the initial vertical subtitle position (measured from the bottom of the screen): + +```json +{ + "subtitlePosition": { + "yPercent": 10 + } +} +``` + +| Option | Values | Description | +| ---------- | --------------- | ------------------------------------------------------------------ | +| `yPercent` | number (0 - 100) | Distance from the bottom as a percent of screen height (default: `10`) | + + +### Subtitle Style + +Customize the appearance of primary and secondary subtitles: + +See `config.example.jsonc` for detailed configuration options. + +```json +{ + "subtitleStyle": { + "fontFamily": "Noto Sans CJK JP Regular, Noto Sans CJK JP, Arial Unicode MS, Arial, sans-serif", + "fontSize": 35, + "fontColor": "#cad3f5", + "fontWeight": "normal", + "fontStyle": "normal", + "backgroundColor": "rgba(54, 58, 79, 0.5)", + "secondary": { + "fontSize": 24, + "fontColor": "#ffffff", + "backgroundColor": "transparent" + } + } +} +``` + +| Option | Values | Description | +| ----------------- | ----------- | ----------------------------------------------------------------------------- | +| `fontFamily` | string | CSS font-family value (default: `"Noto Sans CJK JP Regular, ..."`) | +| `fontSize` | number (px) | Font size in pixels (default: `35`) | +| `fontColor` | string | Any CSS color value (default: `"#cad3f5"`) | +| `fontWeight` | string | CSS font-weight, e.g. `"bold"`, `"normal"`, `"600"` (default: `"normal"`) | +| `fontStyle` | string | `"normal"` or `"italic"` (default: `"normal"`) | +| `backgroundColor` | string | Any CSS color, including `"transparent"` (default: `"rgba(54, 58, 79, 0.5)"`) | +| `secondary` | object | Override any of the above for secondary subtitles (optional) | + +Secondary subtitle defaults: `fontSize: 24`, `fontColor: "#ffffff"`, `backgroundColor: "transparent"`. Any property not set in `secondary` falls back to the CSS defaults. + +**See `config.example.jsonc`** for the complete list of subtitle style configuration options. + + +### Texthooker + +Control whether the browser opens automatically when texthooker starts: + +See `config.example.jsonc` for detailed configuration options. + +```json +{ + "texthooker": { + "openBrowser": true + } +} +``` + + +### WebSocket Server + +The overlay includes a built-in WebSocket server that broadcasts subtitle text to connected clients (such as texthooker-ui) for external processing. + +By default, the server uses "auto" mode: it starts automatically unless [mpv_websocket](https://github.com/kuroahna/mpv_websocket) is detected at `~/.config/mpv/mpv_websocket`. If you have mpv_websocket installed, the built-in server is skipped to avoid conflicts. + +See `config.example.jsonc` for detailed configuration options. + +```json +{ + "websocket": { + "enabled": "auto", + "port": 6677 + } +} +``` + +| Option | Values | Description | +| --------- | ------------------------- | -------------------------------------------------------- | +| `enabled` | `true`, `false`, `"auto"` | `"auto"` (default) disables if mpv_websocket is detected | +| `port` | number | WebSocket server port (default: 6677) | + + +### YouTube Subtitle Generation + +Set defaults used by the `subminer` launcher for YouTube subtitle extraction/transcription: + +```json +{ + "youtubeSubgen": { + "mode": "automatic", + "whisperBin": "/path/to/whisper-cli", + "whisperModel": "/path/to/ggml-model.bin", + "primarySubLanguages": ["ja", "jpn"] + } +} +``` + +| Option | Values | Description | +| -------------- | --------------------------------------- | ----------- | +| `mode` | `"automatic"`, `"preprocess"`, `"off"` | `automatic`: play immediately and load generated subtitles in background; `preprocess`: generate before playback; `off`: disable launcher generation. | +| `whisperBin` | string path | Path to `whisper.cpp` CLI binary used as fallback transcription engine. | +| `whisperModel` | string path | Path to whisper model used by fallback transcription. | +| `primarySubLanguages` | string[] | Primary subtitle language priority for YouTube subtitle generation (default `["ja", "jpn"]`). | + +YouTube language targets are derived from subtitle config: +- primary track: `youtubeSubgen.primarySubLanguages` (falls back to `["ja","jpn"]`) +- secondary track: `secondarySub.secondarySubLanguages` (falls back to English when empty) + +Precedence for launcher defaults is: CLI flag > environment variable > `config.jsonc` > built-in default. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..ca3cbfd --- /dev/null +++ b/docs/development.md @@ -0,0 +1,15 @@ +# Contributor Note + +To add or change a config option, update `src/config/definitions.ts` first. Defaults, runtime-option metadata, and generated `config.example.jsonc` are derived from this centralized source. + +## Environment Variables + +| Variable | Description | +| ------------------------ | ---------------------------------------------- | +| `SUBMINER_APPIMAGE_PATH` | Override AppImage location for subminer script | +| `SUBMINER_YT_SUBGEN_MODE` | Override `youtubeSubgen.mode` for launcher | +| `SUBMINER_WHISPER_BIN` | Override `youtubeSubgen.whisperBin` for launcher | +| `SUBMINER_WHISPER_MODEL` | Override `youtubeSubgen.whisperModel` for launcher | +| `SUBMINER_YT_SUBGEN_OUT_DIR` | Override generated subtitle output directory | +| `SUBMINER_YT_SUBGEN_AUDIO_FORMAT` | Override extraction format used for whisper fallback | +| `SUBMINER_YT_SUBGEN_KEEP_TEMP` | Set to `1` to keep temporary subtitle-generation workspace | diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..c642334 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,246 @@ +# Requirements + +### Linux + +- **Wayland/X11 compositor** (one of the following): + - Hyprland (uses `hyprctl`) + - X11 (uses `xdotool` and `xwininfo`) +- mpv (with IPC socket support) +- mecab and mecab-ipadic (Japanese morphological analyzer) +- fuse2 (for AppImage support) + +### macOS + +- macOS 10.13 or later +- mpv (with IPC socket support) +- mecab and mecab-ipadic (Japanese morphological analyzer) - optional +- **Accessibility permission** required for window tracking (see [macOS Installation](#macos-installation)) + +**Optional:** + +- fzf (terminal-based video picker, default) +- rofi (GUI-based video picker) +- chafa (thumbnail previews in fzf) +- ffmpegthumbnailer (generate video thumbnails) +- yt-dlp (recommended for reliable YouTube playback/subtitles in mpv) +- bun (required to run the `subminer` wrapper script from source/local installs) + +## Installation + +### From AppImage (Recommended) + +Download the latest AppImage from GitHub Releases: + +```bash +# Download and install AppImage +wget https://github.com/sudacode/subminer/releases/download/v1.0.0/subminer-1.0.0.AppImage -O ~/.local/bin/subminer.AppImage +chmod +x ~/.local/bin/subminer.AppImage + +# Download subminer wrapper script +wget https://github.com/sudacode/subminer/releases/download/v1.0.0/subminer -O ~/.local/bin/subminer +chmod +x ~/.local/bin/subminer +``` + +Note: the `subminer` wrapper uses a Bun shebang (`#!/usr/bin/env bun`), so `bun` must be installed and available on `PATH`. + +### macOS Installation + +If you download a release, use the **DMG** artifact. Open it and drag `SubMiner.app` into `/Applications`. +If needed, you can use the **ZIP** artifact as a fallback by unzipping and dragging `SubMiner.app` into `/Applications`. + +Install dependencies using Homebrew: + +```bash +brew install mpv mecab mecab-ipadic +``` + +Build from source: + +```bash +git clone https://github.com/sudacode/subminer.git +cd subminer +pnpm install +cd vendor/texthooker-ui && pnpm install && pnpm build && cd ../.. +pnpm run build:mac +``` + +The built app will be available in the `release` directory (`.dmg` and `.zip` on macOS). + +If you are building locally without Apple signing credentials, use: + +```bash +pnpm run build:mac:unsigned +``` + +You can launch `SubMiner.app` directly (double-click or `open -a SubMiner`). +Use `--start` when you want SubMiner to begin MPV IPC connection/reconnect behavior. +Use `--texthooker` when you only want the texthooker page (no overlay window). + +**Accessibility Permission:** + +After launching the app for the first time, grant accessibility permission: + +1. Open **System Preferences** → **Security & Privacy** → **Privacy** tab +2. Select **Accessibility** from the left sidebar +3. Add SubMiner to the list + +Without this permission, window tracking will not work and the overlay won't follow the MPV window. + + + +### From Source + +```bash +git clone https://github.com/sudacode/subminer.git +cd subminer +make build + +# Install platform artifacts +# - Linux: wrapper + theme (+ AppImage if present) +# - macOS: wrapper + theme + SubMiner.app (from release/*.app or release/*.zip) +make install +``` + + + + + + + + +### macOS Usage Notes + +**Launching MPV with IPC:** + +```bash +mpv --input-ipc-server=/tmp/subminer-socket video.mkv +``` + +**Config Location:** + +Settings are stored in `~/.config/SubMiner/config.jsonc` (same as Linux). + +**MeCab Installation Paths:** + +Common Homebrew install paths: + +- Apple Silicon (M1/M2): `/opt/homebrew/bin/mecab` +- Intel: `/usr/local/bin/mecab` + +Ensure that `mecab` is available on your PATH when launching subminer (for example, by starting it from a terminal where `which mecab` works), otherwise MeCab may not be detected. + +**Fullscreen Mode:** + +The overlay should appear correctly in fullscreen. If you encounter issues, check that macOS accessibility permissions are granted (see [macOS Installation](#macos-installation)). + +**mpv Plugin Binary Path (macOS):** + +Set `binary_path` to your app binary, for example: + +```ini +binary_path=/Applications/SubMiner.app/Contents/MacOS/subminer +``` + +### MPV Plugin (Optional) + +The Lua plugin allows you to control the overlay directly from mpv using keybindings: + +> [!IMPORTANT] +> `mpv` must be launched with `--input-ipc-server=/tmp/subminer-socket` to allow communication with the application + +```bash +# Copy plugin files to mpv config +cp plugin/subminer.lua ~/.config/mpv/scripts/ +cp plugin/subminer.conf ~/.config/mpv/script-opts/ +``` + +#### Plugin Keybindings + +All keybindings use chord sequences starting with `y`: + +| Keybind | Action | +| ------- | ------------------------------------- | +| `y-y` | Open SubMiner menu (fuzzy-searchable) | +| `y-s` | Start overlay | +| `y-S` | Stop overlay | +| `y-t` | Toggle visible overlay | +| `y-i` | Toggle invisible overlay | +| `y-I` | Show invisible overlay | +| `y-u` | Hide invisible overlay | +| `y-o` | Open Yomitan settings | +| `y-r` | Restart overlay | +| `y-c` | Check overlay status | + +The menu provides options to start/stop/toggle the visible or invisible overlay layers and open settings. Type to filter or use arrow keys to navigate. + +#### Plugin Configuration + +Edit `~/.config/mpv/script-opts/subminer.conf`: + +```ini +# Path to SubMiner binary (leave empty for auto-detection) +binary_path= + +# Path to mpv IPC socket (must match input-ipc-server in mpv.conf) +socket_path=/tmp/subminer-socket + +# Enable texthooker WebSocket server +texthooker_enabled=yes + +# Texthooker WebSocket port +texthooker_port=5174 + +# Window manager backend: auto, hyprland, x11, macos +backend=auto + +# Automatically start overlay when a file is loaded +auto_start=no + +# Automatically show visible overlay when overlay starts +auto_start_visible_overlay=no + +# Automatically show invisible overlay when overlay starts +# Values: platform-default, visible, hidden +# platform-default => hidden on Linux, visible on macOS/Windows +auto_start_invisible_overlay=platform-default + +# Show OSD messages for overlay status +osd_messages=yes +``` + +The plugin auto-detects the binary location, searching: + +- `/Applications/SubMiner.app/Contents/MacOS/subminer` +- `~/Applications/SubMiner.app/Contents/MacOS/subminer` +- `C:\Program Files\subminer\subminer.exe` +- `C:\Program Files (x86)\subminer\subminer.exe` +- `C:\subminer\subminer.exe` +- `~/.local/bin/subminer.AppImage` +- `/opt/subminer/subminer.AppImage` +- `/usr/local/bin/subminer` +- `/usr/bin/subminer` + +**Windows Notes:** + +Set the binary and socket path like this: + +```ini +binary_path=C:\\Program Files\\subminer\\subminer.exe +socket_path=\\\\.\\pipe\\subminer-socket +``` + +Launch mpv with: + +```bash +mpv --input-ipc-server=\\\\.\\pipe\\subminer-socket video.mkv +``` + diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..120d7da --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,131 @@ +# SubMiner Script vs MPV Plugin + +There are two ways to use SubMiner: + +| Approach | Best For | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **subminer script** | All-in-one solution. Handles video selection, launches MPV with the correct socket, starts the overlay automatically, and cleans up on exit. | +| **MPV plugin** | When you launch MPV yourself or from other tools. Provides in-MPV chord keybindings (e.g. `y-y` for menu) to control visible and invisible overlay layers. Requires `--input-ipc-server=/tmp/subminer-socket`. | + +You can use both together—install the plugin for on-demand control, but use `subminer` when you want the streamlined workflow. + +`subminer` is implemented as a Bun script and runs directly via shebang (no `bun run` needed), for example: `subminer video.mkv`. + +## Usage + +```bash +# Browse and play videos +subminer # Current directory (uses fzf) +subminer -R # Use rofi instead of fzf +subminer -d ~/Videos # Specific directory +subminer -r -d ~/Anime # Recursive search +subminer video.mkv # Play specific file +subminer https://youtu.be/... # Play a YouTube URL +subminer ytsearch:"jp news" # Play first YouTube search result + +# Options +subminer -T video.mkv # Disable texthooker server +subminer -b x11 video.mkv # Force X11 backend +subminer video.mkv # Uses mpv profile "subminer" by default +subminer -p gpu-hq video.mkv # Override mpv profile +subminer --yt-subgen-mode preprocess --whisper-bin /path/to/whisper-cli --whisper-model /path/to/model.bin https://youtu.be/... # Pre-generate subtitle tracks before playback + +# Direct AppImage control +subminer.AppImage --start --texthooker # Start overlay with texthooker +subminer.AppImage --texthooker # Launch texthooker only (no overlay window) +subminer.AppImage --stop # Stop overlay +subminer.AppImage --start --toggle # Start MPV IPC + toggle visibility +subminer.AppImage --start --toggle-invisible-overlay # Start MPV IPC + toggle invisible layer +subminer.AppImage --show-visible-overlay # Force show visible overlay +subminer.AppImage --hide-visible-overlay # Force hide visible overlay +subminer.AppImage --show-invisible-overlay # Force show invisible overlay +subminer.AppImage --hide-invisible-overlay # Force hide invisible overlay +subminer.AppImage --settings # Open Yomitan settings +subminer.AppImage --help # Show all options +``` + +### MPV Profile Example (mpv.conf) + +Add a profile to `~/.config/mpv/mpv.conf`; `subminer` now launches mpv with `--profile=subminer` by default (or override with `subminer -p ...`): + +```ini +[subminer] +# IPC socket (must match SubMiner config) +input-ipc-server=/tmp/subminer-socket + +# Prefer JP subs, then EN +slang=ja,jpn,en,eng + +# Auto-load external subtitles +sub-auto=fuzzy +sub-file-paths=.;subs;subtitles + +# Select primary + secondary subtitle tracks automatically +sid=auto +secondary-sid=auto +secondary-sub-visibility=no +``` + +`secondary-slang` is not an mpv option; use `slang` with `sid=auto` / `secondary-sid=auto` instead. + +### YouTube Playback + +`subminer` accepts direct URLs (for example, YouTube links) and `ytsearch:` targets, and forwards them to mpv. + +Notes: + +- Install `yt-dlp` so mpv can resolve YouTube streams and subtitle tracks reliably. +- `subminer` supports three subtitle-generation modes for YouTube URLs: + - `automatic` (default): starts playback immediately, generates subtitles in the background, and loads them into mpv when ready. + - `preprocess`: generates subtitles first, then starts playback with generated `.srt` files attached. + - `off`: disables launcher generation and leaves subtitle handling to mpv/yt-dlp. +- Primary subtitle target languages come from `youtubeSubgen.primarySubLanguages` (defaults to `["ja","jpn"]`). +- Secondary target languages come from `secondarySub.secondarySubLanguages` (defaults to English if unset). +- `subminer` prefers subtitle tracks from yt-dlp first, then falls back to local `whisper.cpp` (`whisper-cli`) when tracks are missing. +- Whisper translation fallback currently only supports English secondary targets; non-English secondary targets rely on yt-dlp subtitle availability. +- Configure defaults in `~/.config/SubMiner/config.jsonc` under `youtubeSubgen` and `secondarySub`, or override mode/tool paths via CLI flags/environment variables. + +## Keybindings + +### Global Shortcuts + +| Keybind | Action | +| ------------- | ------------------------- | +| `Alt+Shift+O` | Toggle visible overlay | +| `Alt+Shift+I` | Toggle invisible overlay | +| `Alt+Shift+Y` | Open Yomitan settings | + +### Overlay Controls (Configurable) + +| Input | Action | +| -------------------- | -------------------------------------------------- | +| `Space` | Toggle MPV pause | +| `ArrowRight` | Seek forward 5 seconds | +| `ArrowLeft` | Seek backward 5 seconds | +| `ArrowUp` | Seek forward 60 seconds | +| `ArrowDown` | Seek backward 60 seconds | +| `Shift+H` | Jump to previous subtitle | +| `Shift+L` | Jump to next subtitle | +| `Ctrl+Shift+H` | Replay current subtitle (play to end, then pause) | +| `Ctrl+Shift+L` | Play next subtitle (jump, play to end, then pause) | +| `Q` | Quit mpv | +| `Ctrl+W` | Quit mpv | +| `Right-click` | Toggle MPV pause (outside subtitle area) | +| `Right-click + drag` | Move subtitle position (on subtitle) | + +These keybindings only work when the overlay window has focus. See [Configuration](configuration.md) for customization. + +### Overlay Chord Shortcuts + +| Chord | Action | +| --------- | ------------------------- | +| `y` → `j` | Open Jimaku subtitle menu | + +## How It Works + +1. MPV runs with an IPC socket at `/tmp/subminer-socket` +2. The overlay connects and subscribes to subtitle changes +3. Subtitles are tokenized with MeCab and merged into natural word boundaries +4. Words are displayed as clickable spans +5. Clicking a word triggers Yomitan popup for dictionary lookup +6. Texthooker server runs at `http://127.0.0.1:5174` for external tools diff --git a/package.json b/package.json new file mode 100644 index 0000000..81c1376 --- /dev/null +++ b/package.json @@ -0,0 +1,86 @@ +{ + "name": "subminer", + "version": "0.1.0", + "description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration", + "main": "dist/main.js", + "scripts": { + "build": "tsc && cp src/renderer/index.html src/renderer/style.css dist/renderer/", + "test:config": "pnpm run build && node --test dist/config/config.test.js", + "generate:config-example": "pnpm run build && node dist/generate-config-example.js", + "start": "pnpm run build && electron . --start", + "dev": "pnpm run build && electron . --start --dev", + "stop": "electron . --stop", + "toggle": "electron . --toggle", + "build:appimage": "pnpm run build && electron-builder --linux AppImage", + "build:mac": "pnpm run build && electron-builder --mac dmg zip", + "build:mac:unsigned": "pnpm run build && env -u APPLE_ID -u APPLE_APP_SPECIFIC_PASSWORD -u APPLE_TEAM_ID -u CSC_LINK -u CSC_KEY_PASSWORD CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --mac dmg zip", + "build:mac:zip": "pnpm run build && electron-builder --mac zip" + }, + "keywords": [ + "anki", + "ankiconnect", + "sentence-mining", + "japanese", + "subtitles", + "overlay", + "mpv", + "yomitan" + ], + "author": "", + "license": "GPL-3.0-or-later", + "dependencies": { + "axios": "^1.13.5", + "jsonc-parser": "^3.3.1", + "ws": "^8.19.0" + }, + "devDependencies": { + "@types/node": "^25.2.2", + "@types/ws": "^8.18.1", + "electron": "^37.10.3", + "electron-builder": "^26.7.0", + "typescript": "^5.9.3" + }, + "build": { + "appId": "com.sudacode.SubMiner", + "productName": "SubMiner", + "executableName": "SubMiner", + "artifactName": "SubMiner-${version}.${ext}", + "icon": "assets/SubMiner.png", + "directories": { + "output": "release" + }, + "linux": { + "target": [ + "AppImage" + ], + "category": "AudioVideo" + }, + "mac": { + "target": [ + "dmg", + "zip" + ], + "category": "public.app-category.video", + "icon": "assets/SubMiner.png", + "hardenedRuntime": true, + "entitlements": "build/entitlements.mac.plist", + "entitlementsInherit": "build/entitlements.mac.plist" + }, + "files": [ + "dist/**/*", + "vendor/texthooker-ui/docs/**/*", + "vendor/texthooker-ui/package.json", + "package.json" + ], + "extraResources": [ + { + "from": "vendor/yomitan", + "to": "yomitan" + }, + { + "from": "assets", + "to": "assets" + } + ] + } +} diff --git a/plugin/subminer.conf b/plugin/subminer.conf new file mode 100644 index 0000000..979e7f8 --- /dev/null +++ b/plugin/subminer.conf @@ -0,0 +1,45 @@ +# SubMiner configuration +# Place this file in ~/.config/mpv/script-opts/ + +# Path to SubMiner binary (leave empty for auto-detection) +# Auto-detection searches common locations, including: +# - macOS: /Applications/SubMiner.app/Contents/MacOS/SubMiner, ~/Applications/SubMiner.app/Contents/MacOS/SubMiner +# - Linux: ~/.local/bin/SubMiner.AppImage, /opt/SubMiner/SubMiner.AppImage, /usr/local/bin/SubMiner, /usr/bin/SubMiner +binary_path= + +# Path to mpv IPC socket (must match input-ipc-server in mpv.conf) +socket_path=/tmp/subminer-socket + +# Enable texthooker WebSocket server +texthooker_enabled=yes + +# Texthooker WebSocket port +texthooker_port=5174 + +# Window manager backend: auto, hyprland, sway, x11 +# "auto" detects based on environment variables +backend=auto + +# Automatically start overlay when a file is loaded +auto_start=no + +# Automatically show visible overlay when overlay starts +auto_start_visible_overlay=no + +# Automatically show invisible overlay when overlay starts +# Values: platform-default, visible, hidden +# platform-default => hidden on Linux, visible on macOS/Windows +auto_start_invisible_overlay=platform-default + +# Legacy alias (maps to auto_start_visible_overlay) +# auto_start_overlay=no + +# Show OSD messages for overlay status +osd_messages=yes + +# Log level for plugin and SubMiner binary: debug, info, warn, error +log_level=info + +# MPV keybindings provided by plugin/subminer.lua: +# y-s start, y-S stop, y-t toggle visible overlay +# y-i toggle invisible overlay, y-I show invisible overlay, y-u hide invisible overlay diff --git a/plugin/subminer.lua b/plugin/subminer.lua new file mode 100644 index 0000000..4fab5a5 --- /dev/null +++ b/plugin/subminer.lua @@ -0,0 +1,773 @@ +local input = require("mp.input") +local mp = require("mp") +local msg = require("mp.msg") +local options = require("mp.options") +local utils = require("mp.utils") + +local function is_windows() + return package.config:sub(1, 1) == "\\" +end + +local function is_macos() + local platform = mp.get_property("platform") or "" + if platform == "macos" or platform == "darwin" then + return true + end + local ostype = os.getenv("OSTYPE") or "" + return ostype:find("darwin") ~= nil +end + +local function default_socket_path() + if is_windows() then + return "\\\\.\\pipe\\subminer-socket" + end + return "/tmp/subminer-socket" +end + +local function is_linux() + return not is_windows() and not is_macos() +end + +local opts = { + binary_path = "", + socket_path = default_socket_path(), + texthooker_enabled = true, + texthooker_port = 5174, + backend = "auto", + auto_start = true, + auto_start_overlay = false, -- legacy alias, maps to auto_start_visible_overlay + auto_start_visible_overlay = false, + auto_start_invisible_overlay = "platform-default", -- platform-default | visible | hidden + osd_messages = true, + log_level = "info", +} + +options.read_options(opts, "subminer") + +local state = { + overlay_running = false, + texthooker_running = false, + overlay_process = nil, + binary_available = false, + binary_path = nil, + detected_backend = nil, + invisible_overlay_visible = false, +} + +local LOG_LEVEL_PRIORITY = { + debug = 10, + info = 20, + warn = 30, + error = 40, +} + +local function normalize_log_level(level) + local normalized = (level or "info"):lower() + if LOG_LEVEL_PRIORITY[normalized] then + return normalized + end + return "info" +end + +local function should_log(level) + local current = normalize_log_level(opts.log_level) + local target = normalize_log_level(level) + return LOG_LEVEL_PRIORITY[target] >= LOG_LEVEL_PRIORITY[current] +end + +local function subminer_log(level, scope, message) + if not should_log(level) then + return + end + local timestamp = os.date("%Y-%m-%d %H:%M:%S") + local line = string.format("[subminer] - %s - %s - [%s] %s", timestamp, string.upper(level), scope, message) + if level == "error" then + msg.error(line) + elseif level == "warn" then + msg.warn(line) + elseif level == "debug" then + msg.debug(line) + else + msg.info(line) + end +end + +local function show_osd(message) + if opts.osd_messages then + mp.osd_message("SubMiner: " .. message, 3) + end +end + +local function detect_backend() + if state.detected_backend then + return state.detected_backend + end + + local backend = nil + + if is_macos() then + backend = "macos" + elseif is_windows() then + backend = nil + elseif os.getenv("HYPRLAND_INSTANCE_SIGNATURE") then + backend = "hyprland" + elseif os.getenv("SWAYSOCK") then + backend = "sway" + elseif os.getenv("XDG_SESSION_TYPE") == "x11" or os.getenv("DISPLAY") then + backend = "x11" + else + subminer_log("warn", "backend", "Could not detect window manager, falling back to x11") + backend = "x11" + end + + state.detected_backend = backend + if backend then + subminer_log("info", "backend", "Detected backend: " .. backend) + else + subminer_log("info", "backend", "No backend detected") + end + return backend +end + +local function file_exists(path) + local info = utils.file_info(path) + return info ~= nil +end + +local function find_binary() + if opts.binary_path ~= "" and file_exists(opts.binary_path) then + return opts.binary_path + end + + local search_paths = { + "/Applications/SubMiner.app/Contents/MacOS/SubMiner", + utils.join_path(os.getenv("HOME") or "", "Applications/SubMiner.app/Contents/MacOS/SubMiner"), + "C:\\Program Files\\SubMiner\\SubMiner.exe", + "C:\\Program Files (x86)\\SubMiner\\SubMiner.exe", + "C:\\SubMiner\\SubMiner.exe", + utils.join_path(os.getenv("HOME") or "", ".local/bin/SubMiner.AppImage"), + "/opt/SubMiner/SubMiner.AppImage", + "/usr/local/bin/SubMiner", + "/usr/bin/SubMiner", + } + + for _, path in ipairs(search_paths) do + if file_exists(path) then + subminer_log("info", "binary", "Found binary at: " .. path) + return path + end + end + + return nil +end + +local function ensure_binary_available() + if state.binary_available and state.binary_path and file_exists(state.binary_path) then + return true + end + + local discovered = find_binary() + if discovered then + state.binary_path = discovered + state.binary_available = true + return true + end + + state.binary_path = nil + state.binary_available = false + return false +end + +local function resolve_backend(override_backend) + local selected = override_backend + if selected == nil or selected == "" then + selected = opts.backend + end + if selected == "auto" then + return detect_backend() + end + return selected +end + +local function build_command_args(action, overrides) + overrides = overrides or {} + local args = { state.binary_path } + + table.insert(args, "--" .. action) + local log_level = normalize_log_level(overrides.log_level or opts.log_level) + if log_level == "debug" then + table.insert(args, "--verbose") + elseif log_level ~= "info" then + table.insert(args, "--log-level") + table.insert(args, log_level) + end + + local needs_start_context = ( + action == "start" + or action == "toggle" + or action == "show" + or action == "hide" + or action == "toggle-visible-overlay" + or action == "show-visible-overlay" + or action == "hide-visible-overlay" + or action == "toggle-invisible-overlay" + or action == "show-invisible-overlay" + or action == "hide-invisible-overlay" + ) + + if needs_start_context then + -- Explicitly request MPV IPC connection for active overlay control. + if action ~= "start" then + table.insert(args, "--start") + end + + local backend = resolve_backend(overrides.backend) + if backend and backend ~= "" then + table.insert(args, "--backend") + table.insert(args, backend) + end + + local socket_path = overrides.socket_path or opts.socket_path + table.insert(args, "--socket") + table.insert(args, socket_path) + end + + return args +end + +local function run_control_command(action) + local args = build_command_args(action) + subminer_log("debug", "process", "Control command: " .. table.concat(args, " ")) + local result = mp.command_native({ + name = "subprocess", + args = args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }) + return result and result.status == 0 +end + +local function coerce_bool(value, fallback) + if type(value) == "boolean" then + return value + end + if type(value) == "string" then + local normalized = value:lower() + if normalized == "yes" or normalized == "true" or normalized == "1" or normalized == "on" then + return true + end + if normalized == "no" or normalized == "false" or normalized == "0" or normalized == "off" then + return false + end + end + return fallback +end + +local function parse_start_script_message_overrides(...) + local overrides = {} + for i = 1, select("#", ...) do + local token = select(i, ...) + if type(token) == "string" and token ~= "" then + local key, value = token:match("^([%w_%-]+)=(.+)$") + if key and value then + local normalized_key = key:lower() + if normalized_key == "backend" then + local backend = value:lower() + if backend == "auto" or backend == "hyprland" or backend == "sway" or backend == "x11" or backend == "macos" then + overrides.backend = backend + end + elseif normalized_key == "socket" or normalized_key == "socket_path" then + overrides.socket_path = value + elseif normalized_key == "texthooker" or normalized_key == "texthooker_enabled" then + local parsed = coerce_bool(value, nil) + if parsed ~= nil then + overrides.texthooker_enabled = parsed + end + elseif normalized_key == "log-level" or normalized_key == "log_level" then + overrides.log_level = normalize_log_level(value) + end + end + end + end + return overrides +end + +local function resolve_visible_overlay_startup() + local visible = coerce_bool(opts.auto_start_visible_overlay, false) + -- Backward compatibility for old config key. + if coerce_bool(opts.auto_start_overlay, false) then + visible = true + end + return visible +end + +local function resolve_invisible_overlay_startup() + local raw = opts.auto_start_invisible_overlay + if type(raw) == "boolean" then + return raw + end + + local mode = type(raw) == "string" and raw:lower() or "platform-default" + if mode == "visible" or mode == "show" or mode == "yes" or mode == "true" or mode == "on" then + return true + end + if mode == "hidden" or mode == "hide" or mode == "no" or mode == "false" or mode == "off" then + return false + end + + -- platform-default + return not is_linux() +end + +local function apply_startup_overlay_preferences() + local should_show_visible = resolve_visible_overlay_startup() + local should_show_invisible = resolve_invisible_overlay_startup() + + local visible_action = should_show_visible and "show-visible-overlay" or "hide-visible-overlay" + if not run_control_command(visible_action) then + subminer_log("warn", "process", "Failed to apply visible startup action: " .. visible_action) + end + + local invisible_action = should_show_invisible and "show-invisible-overlay" or "hide-invisible-overlay" + if not run_control_command(invisible_action) then + subminer_log("warn", "process", "Failed to apply invisible startup action: " .. invisible_action) + end + + state.invisible_overlay_visible = should_show_invisible +end + +local function build_texthooker_args() + local args = { state.binary_path, "--texthooker", "--port", tostring(opts.texthooker_port) } + local log_level = normalize_log_level(opts.log_level) + if log_level == "debug" then + table.insert(args, "--verbose") + elseif log_level ~= "info" then + table.insert(args, "--log-level") + table.insert(args, log_level) + end + return args +end + +local function ensure_texthooker_running(callback) + if not opts.texthooker_enabled then + callback() + return + end + + if state.texthooker_running then + callback() + return + end + + local args = build_texthooker_args() + subminer_log("info", "texthooker", "Starting texthooker process: " .. table.concat(args, " ")) + state.texthooker_running = true + + mp.command_native_async({ + name = "subprocess", + args = args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }, function(success, result, error) + if not success or (result and result.status ~= 0) then + state.texthooker_running = false + subminer_log( + "warn", + "texthooker", + "Texthooker process exited unexpectedly: " .. (error or (result and result.stderr) or "unknown error") + ) + end + end) + + -- Give the process a moment to acquire the app lock before sending --start. + mp.add_timeout(0.35, callback) +end + +local function start_overlay(overrides) + if not ensure_binary_available() then + subminer_log("error", "binary", "SubMiner binary not found") + show_osd("Error: binary not found") + return + end + + if state.overlay_running then + subminer_log("info", "process", "Overlay already running") + show_osd("Already running") + return + end + + overrides = overrides or {} + local texthooker_enabled = overrides.texthooker_enabled + if texthooker_enabled == nil then + texthooker_enabled = opts.texthooker_enabled + end + + local function launch_overlay() + local args = build_command_args("start", overrides) + subminer_log("info", "process", "Starting overlay: " .. table.concat(args, " ")) + + show_osd("Starting...") + state.overlay_running = true + + mp.command_native_async({ + name = "subprocess", + args = args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }, function(success, result, error) + if not success or (result and result.status ~= 0) then + state.overlay_running = false + subminer_log( + "error", + "process", + "Overlay start failed: " .. (error or (result and result.stderr) or "unknown error") + ) + show_osd("Overlay start failed") + end + end) + + -- Apply explicit startup visibility for each overlay layer. + mp.add_timeout(0.6, function() + apply_startup_overlay_preferences() + end) + end + + if texthooker_enabled then + ensure_texthooker_running(launch_overlay) + else + launch_overlay() + end +end + +local function start_overlay_from_script_message(...) + local overrides = parse_start_script_message_overrides(...) + start_overlay(overrides) +end + +local function stop_overlay() + if not state.binary_available then + subminer_log("error", "binary", "SubMiner binary not found") + show_osd("Error: binary not found") + return + end + + local args = build_command_args("stop") + subminer_log("info", "process", "Stopping overlay: " .. table.concat(args, " ")) + + local result = mp.command_native({ + name = "subprocess", + args = args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }) + + state.overlay_running = false + state.texthooker_running = false + if result.status == 0 then + subminer_log("info", "process", "Overlay stopped") + else + subminer_log("warn", "process", "Stop command returned non-zero status: " .. tostring(result.status)) + end + show_osd("Stopped") +end + +local function toggle_overlay() + if not state.binary_available then + subminer_log("error", "binary", "SubMiner binary not found") + show_osd("Error: binary not found") + return + end + + local args = build_command_args("toggle") + subminer_log("info", "process", "Toggling overlay: " .. table.concat(args, " ")) + + local result = mp.command_native({ + name = "subprocess", + args = args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }) + + if result and result.status ~= 0 then + subminer_log("warn", "process", "Toggle command failed") + show_osd("Toggle failed") + end +end + +local function toggle_invisible_overlay() + if not state.binary_available then + subminer_log("error", "binary", "SubMiner binary not found") + show_osd("Error: binary not found") + return + end + + local args = build_command_args("toggle-invisible-overlay") + subminer_log("info", "process", "Toggling invisible overlay: " .. table.concat(args, " ")) + + local result = mp.command_native({ + name = "subprocess", + args = args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }) + + if result and result.status ~= 0 then + subminer_log("warn", "process", "Invisible toggle command failed") + show_osd("Invisible toggle failed") + return + end + + state.invisible_overlay_visible = not state.invisible_overlay_visible + show_osd("Invisible overlay: " .. (state.invisible_overlay_visible and "visible" or "hidden")) +end + +local function show_invisible_overlay() + if not state.binary_available then + subminer_log("error", "binary", "SubMiner binary not found") + show_osd("Error: binary not found") + return + end + + local args = build_command_args("show-invisible-overlay") + subminer_log("info", "process", "Showing invisible overlay: " .. table.concat(args, " ")) + + local result = mp.command_native({ + name = "subprocess", + args = args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }) + + if result and result.status ~= 0 then + subminer_log("warn", "process", "Show invisible command failed") + show_osd("Show invisible failed") + return + end + + state.invisible_overlay_visible = true + show_osd("Invisible overlay: visible") +end + +local function hide_invisible_overlay() + if not state.binary_available then + subminer_log("error", "binary", "SubMiner binary not found") + show_osd("Error: binary not found") + return + end + + local args = build_command_args("hide-invisible-overlay") + subminer_log("info", "process", "Hiding invisible overlay: " .. table.concat(args, " ")) + + local result = mp.command_native({ + name = "subprocess", + args = args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }) + + if result and result.status ~= 0 then + subminer_log("warn", "process", "Hide invisible command failed") + show_osd("Hide invisible failed") + return + end + + state.invisible_overlay_visible = false + show_osd("Invisible overlay: hidden") +end + +local function open_options() + if not state.binary_available then + subminer_log("error", "binary", "SubMiner binary not found") + show_osd("Error: binary not found") + return + end + local args = build_command_args("settings") + subminer_log("info", "process", "Opening options: " .. table.concat(args, " ")) + local result = mp.command_native({ + name = "subprocess", + args = args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }) + if result.status == 0 then + subminer_log("info", "process", "Options window opened") + show_osd("Options opened") + else + subminer_log("warn", "process", "Failed to open options") + show_osd("Failed to open options") + end +end + +local restart_overlay +local check_status + +local function show_menu() + if not state.binary_available then + subminer_log("error", "binary", "SubMiner binary not found") + show_osd("Error: binary not found") + return + end + + local items = { + "Start overlay", + "Stop overlay", + "Toggle overlay", + "Toggle invisible overlay", + "Open options", + "Restart overlay", + "Check status", + } + + local actions = { + start_overlay, + stop_overlay, + toggle_overlay, + toggle_invisible_overlay, + open_options, + restart_overlay, + check_status, + } + + input.select({ + prompt = "SubMiner: ", + items = items, + submit = function(index) + if index and actions[index] then + actions[index]() + end + end, + }) +end + +restart_overlay = function() + if not state.binary_available then + subminer_log("error", "binary", "SubMiner binary not found") + show_osd("Error: binary not found") + return + end + + subminer_log("info", "process", "Restarting overlay...") + show_osd("Restarting...") + + local stop_args = build_command_args("stop") + mp.command_native({ + name = "subprocess", + args = stop_args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }) + + state.overlay_running = false + state.texthooker_running = false + + ensure_texthooker_running(function() + local start_args = build_command_args("start") + subminer_log("info", "process", "Starting overlay: " .. table.concat(start_args, " ")) + + state.overlay_running = true + mp.command_native_async({ + name = "subprocess", + args = start_args, + playback_only = false, + capture_stdout = true, + capture_stderr = true, + }, function(success, result, error) + if not success or (result and result.status ~= 0) then + state.overlay_running = false + subminer_log( + "error", + "process", + "Overlay start failed: " .. (error or (result and result.stderr) or "unknown error") + ) + show_osd("Restart failed") + else + show_osd("Restarted successfully") + end + end) + end) +end + +check_status = function() + if not state.binary_available then + show_osd("Status: binary not found") + return + end + + local status = state.overlay_running and "running" or "stopped" + show_osd("Status: overlay is " .. status) + subminer_log("info", "process", "Status check: overlay is " .. status) +end + +local function on_file_loaded() + state.binary_path = find_binary() + if state.binary_path then + state.binary_available = true + subminer_log("info", "lifecycle", "SubMiner ready (binary: " .. state.binary_path .. ")") + local should_auto_start = coerce_bool(opts.auto_start, false) + if should_auto_start then + start_overlay() + end + else + state.binary_available = false + subminer_log("warn", "binary", "SubMiner binary not found - overlay features disabled") + if opts.binary_path ~= "" then + subminer_log("warn", "binary", "Configured path '" .. opts.binary_path .. "' does not exist") + end + end +end + +local function on_shutdown() + if (state.overlay_running or state.texthooker_running) and state.binary_available then + subminer_log("info", "lifecycle", "mpv shutting down, stopping SubMiner process") + show_osd("Shutting down...") + stop_overlay() + end +end + +local function register_keybindings() + mp.add_key_binding("y-s", "subminer-start", start_overlay) + mp.add_key_binding("y-S", "subminer-stop", stop_overlay) + mp.add_key_binding("y-t", "subminer-toggle", toggle_overlay) + mp.add_key_binding("y-i", "subminer-toggle-invisible", toggle_invisible_overlay) + mp.add_key_binding("y-I", "subminer-show-invisible", show_invisible_overlay) + mp.add_key_binding("y-u", "subminer-hide-invisible", hide_invisible_overlay) + mp.add_key_binding("y-y", "subminer-menu", show_menu) + mp.add_key_binding("y-o", "subminer-options", open_options) + mp.add_key_binding("y-r", "subminer-restart", restart_overlay) + mp.add_key_binding("y-c", "subminer-status", check_status) +end + +local function register_script_messages() + mp.register_script_message("subminer-start", start_overlay_from_script_message) + mp.register_script_message("subminer-stop", stop_overlay) + mp.register_script_message("subminer-toggle", toggle_overlay) + mp.register_script_message("subminer-toggle-invisible", toggle_invisible_overlay) + mp.register_script_message("subminer-show-invisible", show_invisible_overlay) + mp.register_script_message("subminer-hide-invisible", hide_invisible_overlay) + mp.register_script_message("subminer-menu", show_menu) + mp.register_script_message("subminer-options", open_options) + mp.register_script_message("subminer-restart", restart_overlay) + mp.register_script_message("subminer-status", check_status) +end + +local function init() + register_keybindings() + register_script_messages() + + mp.register_event("file-loaded", on_file_loaded) + mp.register_event("shutdown", on_shutdown) + + subminer_log("info", "lifecycle", "SubMiner plugin loaded") +end + +init() diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..286c3a5 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,2752 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + axios: + specifier: ^1.13.5 + version: 1.13.5 + jsonc-parser: + specifier: ^3.3.1 + version: 3.3.1 + ws: + specifier: ^8.19.0 + version: 8.19.0 + devDependencies: + '@types/node': + specifier: ^25.2.2 + version: 25.2.2 + '@types/ws': + specifier: ^8.18.1 + version: 8.18.1 + electron: + specifier: ^37.10.3 + version: 37.10.3 + electron-builder: + specifier: ^26.7.0 + version: 26.7.0(electron-builder-squirrel-windows@26.7.0) + typescript: + specifier: ^5.9.3 + version: 5.9.3 + +packages: + + 7zip-bin@5.2.0: + resolution: {integrity: sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A==} + + '@develar/schema-utils@2.6.5': + resolution: {integrity: sha512-0cp4PsWQ/9avqTVMCtZ+GirikIA36ikvjtHweU4/j8yLtgObI0+JUPhYFScgwlteveGB1rt3Cm8UhN04XayDig==} + engines: {node: '>= 8.9.0'} + + '@electron/asar@3.4.1': + resolution: {integrity: sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==} + engines: {node: '>=10.12.0'} + hasBin: true + + '@electron/fuses@1.8.0': + resolution: {integrity: sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==} + hasBin: true + + '@electron/get@2.0.3': + resolution: {integrity: sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ==} + engines: {node: '>=12'} + + '@electron/get@3.1.0': + resolution: {integrity: sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==} + engines: {node: '>=14'} + + '@electron/notarize@2.5.0': + resolution: {integrity: sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A==} + engines: {node: '>= 10.0.0'} + + '@electron/osx-sign@1.3.3': + resolution: {integrity: sha512-KZ8mhXvWv2rIEgMbWZ4y33bDHyUKMXnx4M0sTyPNK/vcB81ImdeY9Ggdqy0SWbMDgmbqyQ+phgejh6V3R2QuSg==} + engines: {node: '>=12.0.0'} + hasBin: true + + '@electron/rebuild@4.0.3': + resolution: {integrity: sha512-u9vpTHRMkOYCs/1FLiSVAFZ7FbjsXK+bQuzviJZa+lG7BHZl1nz52/IcGvwa3sk80/fc3llutBkbCq10Vh8WQA==} + engines: {node: '>=22.12.0'} + hasBin: true + + '@electron/universal@2.0.3': + resolution: {integrity: sha512-Wn9sPYIVFRFl5HmwMJkARCCf7rqK/EurkfQ/rJZ14mHP3iYTjZSIOSVonEAnhWeAXwtw7zOekGRlc6yTtZ0t+g==} + engines: {node: '>=16.4'} + + '@electron/windows-sign@1.2.2': + resolution: {integrity: sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==} + engines: {node: '>=14.14'} + hasBin: true + + '@isaacs/balanced-match@4.0.1': + resolution: {integrity: sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==} + engines: {node: 20 || >=22} + + '@isaacs/brace-expansion@5.0.1': + resolution: {integrity: sha512-WMz71T1JS624nWj2n2fnYAuPovhv7EUhk69R6i9dsVyzxt5eM3bjwvgk9L+APE1TRscGysAVMANkB0jh0LQZrQ==} + engines: {node: 20 || >=22} + + '@isaacs/cliui@8.0.2': + resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} + engines: {node: '>=12'} + + '@isaacs/fs-minipass@4.0.1': + resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} + engines: {node: '>=18.0.0'} + + '@malept/cross-spawn-promise@2.0.0': + resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==} + engines: {node: '>= 12.13.0'} + + '@malept/flatpak-bundler@0.4.0': + resolution: {integrity: sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q==} + engines: {node: '>= 10.0.0'} + + '@npmcli/agent@3.0.0': + resolution: {integrity: sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q==} + engines: {node: ^18.17.0 || >=20.5.0} + + '@npmcli/fs@4.0.0': + resolution: {integrity: sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q==} + engines: {node: ^18.17.0 || >=20.5.0} + + '@pkgjs/parseargs@0.11.0': + resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} + engines: {node: '>=14'} + + '@sindresorhus/is@4.6.0': + resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==} + engines: {node: '>=10'} + + '@szmarczak/http-timer@4.0.6': + resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==} + engines: {node: '>=10'} + + '@types/cacheable-request@6.0.3': + resolution: {integrity: sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==} + + '@types/debug@4.1.12': + resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==} + + '@types/fs-extra@9.0.13': + resolution: {integrity: sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==} + + '@types/http-cache-semantics@4.2.0': + resolution: {integrity: sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==} + + '@types/keyv@3.1.4': + resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==} + + '@types/ms@2.1.0': + resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==} + + '@types/node@22.19.10': + resolution: {integrity: sha512-tF5VOugLS/EuDlTBijk0MqABfP8UxgYazTLo3uIn3b4yJgg26QRbVYJYsDtHrjdDUIRfP70+VfhTTc+CE1yskw==} + + '@types/node@25.2.2': + resolution: {integrity: sha512-BkmoP5/FhRYek5izySdkOneRyXYN35I860MFAGupTdebyE66uZaR+bXLHq8k4DirE5DwQi3NuhvRU1jqTVwUrQ==} + + '@types/plist@3.0.5': + resolution: {integrity: sha512-E6OCaRmAe4WDmWNsL/9RMqdkkzDCY1etutkflWk4c+AcjDU07Pcz1fQwTX0TQz+Pxqn9i4L1TU3UFpjnrcDgxA==} + + '@types/responselike@1.0.3': + resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==} + + '@types/verror@1.10.11': + resolution: {integrity: sha512-RlDm9K7+o5stv0Co8i8ZRGxDbrTxhJtgjqjFyVh/tXQyl/rYtTKlnTvZ88oSTeYREWurwx20Js4kTuKCsFkUtg==} + + '@types/ws@8.18.1': + resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} + + '@types/yauzl@2.10.3': + resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==} + + '@xmldom/xmldom@0.8.11': + resolution: {integrity: sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==} + engines: {node: '>=10.0.0'} + + abbrev@3.0.1: + resolution: {integrity: sha512-AO2ac6pjRB3SJmGJo+v5/aK6Omggp6fsLrs6wN9bd35ulu4cCwaAU9+7ZhXjeqHVkaHThLuzH0nZr0YpCDhygg==} + engines: {node: ^18.17.0 || >=20.5.0} + + agent-base@7.1.4: + resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} + engines: {node: '>= 14'} + + ajv-keywords@3.5.2: + resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==} + peerDependencies: + ajv: ^6.9.1 + + ajv@6.12.6: + resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-regex@6.2.2: + resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==} + engines: {node: '>=12'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + ansi-styles@6.2.3: + resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} + engines: {node: '>=12'} + + app-builder-bin@5.0.0-alpha.12: + resolution: {integrity: sha512-j87o0j6LqPL3QRr8yid6c+Tt5gC7xNfYo6uQIQkorAC6MpeayVMZrEDzKmJJ/Hlv7EnOQpaRm53k6ktDYZyB6w==} + + app-builder-lib@26.7.0: + resolution: {integrity: sha512-/UgCD8VrO79Wv8aBNpjMfsS1pIUfIPURoRn0Ik6tMe5avdZF+vQgl/juJgipcMmH3YS0BD573lCdCHyoi84USg==} + engines: {node: '>=14.0.0'} + peerDependencies: + dmg-builder: 26.7.0 + electron-builder-squirrel-windows: 26.7.0 + + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + + assert-plus@1.0.0: + resolution: {integrity: sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==} + engines: {node: '>=0.8'} + + astral-regex@2.0.0: + resolution: {integrity: sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==} + engines: {node: '>=8'} + + async-exit-hook@2.0.1: + resolution: {integrity: sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==} + engines: {node: '>=0.12.0'} + + async@3.2.6: + resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==} + + asynckit@0.4.0: + resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} + + at-least-node@1.0.0: + resolution: {integrity: sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==} + engines: {node: '>= 4.0.0'} + + axios@1.13.5: + resolution: {integrity: sha512-cz4ur7Vb0xS4/KUN0tPWe44eqxrIu31me+fbang3ijiNscE129POzipJJA6zniq2C/Z6sJCjMimjS8Lc/GAs8Q==} + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + + bl@4.1.0: + resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + + boolean@3.2.0: + resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==} + deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. + + brace-expansion@1.1.12: + resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==} + + brace-expansion@2.0.2: + resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==} + + buffer-crc32@0.2.13: + resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==} + + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + + buffer@5.7.1: + resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + + builder-util-runtime@9.5.1: + resolution: {integrity: sha512-qt41tMfgHTllhResqM5DcnHyDIWNgzHvuY2jDcYP9iaGpkWxTUzV6GQjDeLnlR1/DtdlcsWQbA7sByMpmJFTLQ==} + engines: {node: '>=12.0.0'} + + builder-util@26.4.1: + resolution: {integrity: sha512-FlgH43XZ50w3UtS1RVGDWOz8v9qMXPC7upMtKMtBEnYdt1OVoS61NYhKm/4x+cIaWqJTXua0+VVPI+fSPGXNIw==} + + cacache@19.0.1: + resolution: {integrity: sha512-hdsUxulXCi5STId78vRVYEtDAjq99ICAUktLTeTYsLoTE6Z8dS0c8pWNCxwdrk9YfJeobDZc2Y186hD/5ZQgFQ==} + engines: {node: ^18.17.0 || >=20.5.0} + + cacheable-lookup@5.0.4: + resolution: {integrity: sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==} + engines: {node: '>=10.6.0'} + + cacheable-request@7.0.4: + resolution: {integrity: sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==} + engines: {node: '>=8'} + + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + + chownr@3.0.0: + resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} + engines: {node: '>=18'} + + chromium-pickle-js@0.2.0: + resolution: {integrity: sha512-1R5Fho+jBq0DDydt+/vHWj5KJNJCKdARKOCwZUen84I5BreWoLqRLANH1U87eJy1tiASPtMnGqJJq0ZsLoRPOw==} + + ci-info@4.3.1: + resolution: {integrity: sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==} + engines: {node: '>=8'} + + ci-info@4.4.0: + resolution: {integrity: sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==} + engines: {node: '>=8'} + + cli-cursor@3.1.0: + resolution: {integrity: sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==} + engines: {node: '>=8'} + + cli-spinners@2.9.2: + resolution: {integrity: sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==} + engines: {node: '>=6'} + + cli-truncate@2.1.0: + resolution: {integrity: sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==} + engines: {node: '>=8'} + + cliui@8.0.1: + resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} + engines: {node: '>=12'} + + clone-response@1.0.3: + resolution: {integrity: sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==} + + clone@1.0.4: + resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==} + engines: {node: '>=0.8'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + combined-stream@1.0.8: + resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} + engines: {node: '>= 0.8'} + + commander@5.1.0: + resolution: {integrity: sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==} + engines: {node: '>= 6'} + + commander@9.5.0: + resolution: {integrity: sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==} + engines: {node: ^12.20.0 || >=14} + + compare-version@0.1.2: + resolution: {integrity: sha512-pJDh5/4wrEnXX/VWRZvruAGHkzKdr46z11OlTPN+VrATlWWhSKewNCJ1futCO5C7eJB3nPMFZA1LeYtcFboZ2A==} + engines: {node: '>=0.10.0'} + + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + + core-util-is@1.0.2: + resolution: {integrity: sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==} + + crc@3.8.0: + resolution: {integrity: sha512-iX3mfgcTMIq3ZKLIsVFAbv7+Mc10kxabAGQb8HvjA1o3T1PIYprbakQ65d3I+2HGHt6nSKkM9PYjgoJO2KcFBQ==} + + cross-dirname@0.1.0: + resolution: {integrity: sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decompress-response@6.0.0: + resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} + engines: {node: '>=10'} + + defaults@1.0.4: + resolution: {integrity: sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==} + + defer-to-connect@2.0.1: + resolution: {integrity: sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==} + engines: {node: '>=10'} + + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + + delayed-stream@1.0.0: + resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} + engines: {node: '>=0.4.0'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + detect-node@2.1.0: + resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==} + + dir-compare@4.2.0: + resolution: {integrity: sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==} + + dmg-builder@26.7.0: + resolution: {integrity: sha512-uOOBA3f+kW3o4KpSoMQ6SNpdXU7WtxlJRb9vCZgOvqhTz4b3GjcoWKstdisizNZLsylhTMv8TLHFPFW0Uxsj/g==} + + dmg-license@1.0.11: + resolution: {integrity: sha512-ZdzmqwKmECOWJpqefloC5OJy1+WZBBse5+MR88z9g9Zn4VY+WYUkAyojmhzJckH5YbbZGcYIuGAkY5/Ys5OM2Q==} + engines: {node: '>=8'} + os: [darwin] + hasBin: true + + dotenv-expand@11.0.7: + resolution: {integrity: sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==} + engines: {node: '>=12'} + + dotenv@16.6.1: + resolution: {integrity: sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==} + engines: {node: '>=12'} + + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + + eastasianwidth@0.2.0: + resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + + ejs@3.1.10: + resolution: {integrity: sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==} + engines: {node: '>=0.10.0'} + hasBin: true + + electron-builder-squirrel-windows@26.7.0: + resolution: {integrity: sha512-3EqkQK+q0kGshdPSKEPb2p5F75TENMKu6Fe5aTdeaPfdzFK4Yjp5L0d6S7K8iyvqIsGQ/ei4bnpyX9wt+kVCKQ==} + + electron-builder@26.7.0: + resolution: {integrity: sha512-LoXbCvSFxLesPneQ/fM7FB4OheIDA2tjqCdUkKlObV5ZKGhYgi5VHPHO/6UUOUodAlg7SrkPx7BZJPby+Vrtbg==} + engines: {node: '>=14.0.0'} + hasBin: true + + electron-publish@26.6.0: + resolution: {integrity: sha512-LsyHMMqbvJ2vsOvuWJ19OezgF2ANdCiHpIucDHNiLhuI+/F3eW98ouzWSRmXXi82ZOPZXC07jnIravY4YYwCLQ==} + + electron-winstaller@5.4.0: + resolution: {integrity: sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==} + engines: {node: '>=8.0.0'} + + electron@37.10.3: + resolution: {integrity: sha512-3IjCGSjQmH50IbW2PFveaTzK+KwcFX9PEhE7KXb9v5IT8cLAiryAN7qezm/XzODhDRlLu0xKG1j8xWBtZ/bx/g==} + engines: {node: '>= 12.20.55'} + hasBin: true + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + emoji-regex@9.2.2: + resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + + encoding@0.1.13: + resolution: {integrity: sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==} + + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + + env-paths@2.2.1: + resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} + engines: {node: '>=6'} + + err-code@2.0.3: + resolution: {integrity: sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==} + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-object-atoms@1.1.1: + resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} + engines: {node: '>= 0.4'} + + es-set-tostringtag@2.1.0: + resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} + engines: {node: '>= 0.4'} + + es6-error@4.1.1: + resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==} + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + exponential-backoff@3.1.3: + resolution: {integrity: sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==} + + extract-zip@2.0.1: + resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==} + engines: {node: '>= 10.17.0'} + hasBin: true + + extsprintf@1.4.1: + resolution: {integrity: sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==} + engines: {'0': node >=0.6.0} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fd-slicer@1.1.0: + resolution: {integrity: sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + filelist@1.0.4: + resolution: {integrity: sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==} + + follow-redirects@1.15.11: + resolution: {integrity: sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==} + engines: {node: '>=4.0'} + peerDependencies: + debug: '*' + peerDependenciesMeta: + debug: + optional: true + + foreground-child@3.3.1: + resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} + engines: {node: '>=14'} + + form-data@4.0.5: + resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==} + engines: {node: '>= 6'} + + fs-extra@10.1.0: + resolution: {integrity: sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==} + engines: {node: '>=12'} + + fs-extra@11.3.3: + resolution: {integrity: sha512-VWSRii4t0AFm6ixFFmLLx1t7wS1gh+ckoa84aOeapGum0h+EZd1EhEumSB+ZdDLnEPuucsVB9oB7cxJHap6Afg==} + engines: {node: '>=14.14'} + + fs-extra@7.0.1: + resolution: {integrity: sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==} + engines: {node: '>=6 <7 || >=8'} + + fs-extra@8.1.0: + resolution: {integrity: sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==} + engines: {node: '>=6 <7 || >=8'} + + fs-extra@9.1.0: + resolution: {integrity: sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==} + engines: {node: '>=10'} + + fs-minipass@3.0.3: + resolution: {integrity: sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==} + engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + + fs.realpath@1.0.0: + resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + + get-stream@5.2.0: + resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==} + engines: {node: '>=8'} + + glob@10.5.0: + resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + hasBin: true + + glob@7.2.3: + resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + + global-agent@3.0.0: + resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==} + engines: {node: '>=10.0'} + + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + got@11.8.6: + resolution: {integrity: sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==} + engines: {node: '>=10.19.0'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + + has-tostringtag@1.0.2: + resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} + engines: {node: '>= 0.4'} + + hasown@2.0.2: + resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} + engines: {node: '>= 0.4'} + + hosted-git-info@4.1.0: + resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==} + engines: {node: '>=10'} + + http-cache-semantics@4.2.0: + resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==} + + http-proxy-agent@7.0.2: + resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} + engines: {node: '>= 14'} + + http2-wrapper@1.0.3: + resolution: {integrity: sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==} + engines: {node: '>=10.19.0'} + + https-proxy-agent@7.0.6: + resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} + engines: {node: '>= 14'} + + iconv-corefoundation@1.1.7: + resolution: {integrity: sha512-T10qvkw0zz4wnm560lOEg0PovVqUXuOFhhHAkixw8/sycy7TJt7v/RrkEKEQnAw2viPSJu6iAkErxnzR0g8PpQ==} + engines: {node: ^8.11.2 || >=10} + os: [darwin] + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + + ieee754@1.2.1: + resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + inflight@1.0.6: + resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} + deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + ip-address@10.1.0: + resolution: {integrity: sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==} + engines: {node: '>= 12'} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-interactive@1.0.0: + resolution: {integrity: sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==} + engines: {node: '>=8'} + + is-unicode-supported@0.1.0: + resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==} + engines: {node: '>=10'} + + isbinaryfile@4.0.10: + resolution: {integrity: sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==} + engines: {node: '>= 8.0.0'} + + isbinaryfile@5.0.7: + resolution: {integrity: sha512-gnWD14Jh3FzS3CPhF0AxNOJ8CxqeblPTADzI38r0wt8ZyQl5edpy75myt08EG2oKvpyiqSqsx+Wkz9vtkbTqYQ==} + engines: {node: '>= 18.0.0'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + isexe@3.1.4: + resolution: {integrity: sha512-jCErc4h4RnTPjFq53G4whhjAMbUAqinGrCrTT4dmMNyi4zTthK+wphqbRLJtL4BN/Mq7Zzltr0m/b1X0m7PGFQ==} + engines: {node: '>=20'} + + jackspeak@3.4.3: + resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==} + + jake@10.9.4: + resolution: {integrity: sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==} + engines: {node: '>=10'} + hasBin: true + + jiti@2.6.1: + resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} + hasBin: true + + js-yaml@4.1.1: + resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + hasBin: true + + json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-stringify-safe@5.0.1: + resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==} + + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + + jsonc-parser@3.3.1: + resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==} + + jsonfile@4.0.0: + resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==} + + jsonfile@6.2.0: + resolution: {integrity: sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==} + + keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + + lazy-val@1.0.5: + resolution: {integrity: sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==} + + lodash@4.17.23: + resolution: {integrity: sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==} + + log-symbols@4.1.0: + resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} + engines: {node: '>=10'} + + lowercase-keys@2.0.0: + resolution: {integrity: sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==} + engines: {node: '>=8'} + + lru-cache@10.4.3: + resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==} + + lru-cache@6.0.0: + resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} + engines: {node: '>=10'} + + make-fetch-happen@14.0.3: + resolution: {integrity: sha512-QMjGbFTP0blj97EeidG5hk/QhKQ3T4ICckQGLgz38QF7Vgbk6e6FTARN8KhKxyBbWn8R0HU+bnw8aSoFPD4qtQ==} + engines: {node: ^18.17.0 || >=20.5.0} + + matcher@3.0.0: + resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==} + engines: {node: '>=10'} + + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + + mime-db@1.52.0: + resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} + engines: {node: '>= 0.6'} + + mime-types@2.1.35: + resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} + engines: {node: '>= 0.6'} + + mime@2.6.0: + resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==} + engines: {node: '>=4.0.0'} + hasBin: true + + mimic-fn@2.1.0: + resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} + engines: {node: '>=6'} + + mimic-response@1.0.1: + resolution: {integrity: sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==} + engines: {node: '>=4'} + + mimic-response@3.1.0: + resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} + engines: {node: '>=10'} + + minimatch@10.1.2: + resolution: {integrity: sha512-fu656aJ0n2kcXwsnwnv9g24tkU5uSmOlTjd6WyyaKm2Z+h1qmY6bAjrcaIxF/BslFqbZ8UBtbJi7KgQOZD2PTw==} + engines: {node: 20 || >=22} + + minimatch@3.1.2: + resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==} + + minimatch@5.1.6: + resolution: {integrity: sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==} + engines: {node: '>=10'} + + minimatch@9.0.5: + resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==} + engines: {node: '>=16 || 14 >=14.17'} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + minipass-collect@2.0.1: + resolution: {integrity: sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==} + engines: {node: '>=16 || 14 >=14.17'} + + minipass-fetch@4.0.1: + resolution: {integrity: sha512-j7U11C5HXigVuutxebFadoYBbd7VSdZWggSe64NVdvWNBqGAiXPL2QVCehjmw7lY1oF9gOllYbORh+hiNgfPgQ==} + engines: {node: ^18.17.0 || >=20.5.0} + + minipass-flush@1.0.5: + resolution: {integrity: sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==} + engines: {node: '>= 8'} + + minipass-pipeline@1.2.4: + resolution: {integrity: sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==} + engines: {node: '>=8'} + + minipass-sized@1.0.3: + resolution: {integrity: sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==} + engines: {node: '>=8'} + + minipass@3.3.6: + resolution: {integrity: sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==} + engines: {node: '>=8'} + + minipass@7.1.2: + resolution: {integrity: sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==} + engines: {node: '>=16 || 14 >=14.17'} + + minizlib@3.1.0: + resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} + engines: {node: '>= 18'} + + mkdirp@0.5.6: + resolution: {integrity: sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==} + hasBin: true + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + negotiator@1.0.0: + resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==} + engines: {node: '>= 0.6'} + + node-abi@4.26.0: + resolution: {integrity: sha512-8QwIZqikRvDIkXS2S93LjzhsSPJuIbfaMETWH+Bx8oOT9Sa9UsUtBFQlc3gBNd1+QINjaTloitXr1W3dQLi9Iw==} + engines: {node: '>=22.12.0'} + + node-addon-api@1.7.2: + resolution: {integrity: sha512-ibPK3iA+vaY1eEjESkQkM0BbCqFOaZMiXRTtdB0u7b4djtY6JnsjvPdUHVMg6xQt3B8fpTTWHI9A+ADjM9frzg==} + + node-api-version@0.2.1: + resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==} + + node-gyp@11.5.0: + resolution: {integrity: sha512-ra7Kvlhxn5V9Slyus0ygMa2h+UqExPqUIkfk7Pc8QTLT956JLSy51uWFwHtIYy0vI8cB4BDhc/S03+880My/LQ==} + engines: {node: ^18.17.0 || >=20.5.0} + hasBin: true + + nopt@8.1.0: + resolution: {integrity: sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A==} + engines: {node: ^18.17.0 || >=20.5.0} + hasBin: true + + normalize-url@6.1.0: + resolution: {integrity: sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==} + engines: {node: '>=10'} + + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + onetime@5.1.2: + resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} + engines: {node: '>=6'} + + ora@5.4.1: + resolution: {integrity: sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==} + engines: {node: '>=10'} + + p-cancelable@2.1.1: + resolution: {integrity: sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==} + engines: {node: '>=8'} + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-map@7.0.4: + resolution: {integrity: sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ==} + engines: {node: '>=18'} + + package-json-from-dist@1.0.1: + resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + + path-is-absolute@1.0.1: + resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} + engines: {node: '>=0.10.0'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-scurry@1.11.1: + resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==} + engines: {node: '>=16 || 14 >=14.18'} + + pe-library@0.4.1: + resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==} + engines: {node: '>=12', npm: '>=6'} + + pend@1.2.0: + resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.3: + resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==} + engines: {node: '>=12'} + + plist@3.1.0: + resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==} + engines: {node: '>=10.4.0'} + + postject@1.0.0-alpha.6: + resolution: {integrity: sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==} + engines: {node: '>=14.0.0'} + hasBin: true + + proc-log@5.0.0: + resolution: {integrity: sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ==} + engines: {node: ^18.17.0 || >=20.5.0} + + progress@2.0.3: + resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==} + engines: {node: '>=0.4.0'} + + promise-retry@2.0.1: + resolution: {integrity: sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==} + engines: {node: '>=10'} + + proper-lockfile@4.1.2: + resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==} + + proxy-from-env@1.1.0: + resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} + + pump@3.0.3: + resolution: {integrity: sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + quick-lru@5.1.1: + resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==} + engines: {node: '>=10'} + + read-binary-file-arch@1.0.6: + resolution: {integrity: sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==} + hasBin: true + + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + + resedit@1.7.2: + resolution: {integrity: sha512-vHjcY2MlAITJhC0eRD/Vv8Vlgmu9Sd3LX9zZvtGzU5ZImdTN3+d6e/4mnTyV8vEbyf1sgNIrWxhWlrys52OkEA==} + engines: {node: '>=12', npm: '>=6'} + + resolve-alpn@1.2.1: + resolution: {integrity: sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==} + + responselike@2.0.1: + resolution: {integrity: sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==} + + restore-cursor@3.1.0: + resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==} + engines: {node: '>=8'} + + retry@0.12.0: + resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==} + engines: {node: '>= 4'} + + rimraf@2.6.3: + resolution: {integrity: sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==} + deprecated: Rimraf versions prior to v4 are no longer supported + hasBin: true + + roarr@2.15.4: + resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==} + engines: {node: '>=8.0'} + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + sanitize-filename@1.6.3: + resolution: {integrity: sha512-y/52Mcy7aw3gRm7IrcGDFx/bCk4AhRh2eI9luHOQM86nZsqwiRkkq2GekHXBBD+SmPidc8i2PqtYZl+pWJ8Oeg==} + + sax@1.4.4: + resolution: {integrity: sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==} + engines: {node: '>=11.0.0'} + + semver-compare@1.0.0: + resolution: {integrity: sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==} + + semver@5.7.2: + resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==} + hasBin: true + + semver@6.3.1: + resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} + hasBin: true + + semver@7.7.4: + resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==} + engines: {node: '>=10'} + hasBin: true + + serialize-error@7.0.1: + resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==} + engines: {node: '>=10'} + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + signal-exit@3.0.7: + resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + + simple-update-notifier@2.0.0: + resolution: {integrity: sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==} + engines: {node: '>=10'} + + slice-ansi@3.0.0: + resolution: {integrity: sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==} + engines: {node: '>=8'} + + smart-buffer@4.2.0: + resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==} + engines: {node: '>= 6.0.0', npm: '>= 3.0.0'} + + socks-proxy-agent@8.0.5: + resolution: {integrity: sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==} + engines: {node: '>= 14'} + + socks@2.8.7: + resolution: {integrity: sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==} + engines: {node: '>= 10.0.0', npm: '>= 3.0.0'} + + source-map-support@0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + + sprintf-js@1.1.3: + resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==} + + ssri@12.0.0: + resolution: {integrity: sha512-S7iGNosepx9RadX82oimUkvr0Ct7IjJbEbs4mJcTxst8um95J3sDYU1RBEOvdu6oL1Wek2ODI5i4MAw+dZ6cAQ==} + engines: {node: ^18.17.0 || >=20.5.0} + + stat-mode@1.0.0: + resolution: {integrity: sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==} + engines: {node: '>= 6'} + + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + string-width@5.1.2: + resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} + engines: {node: '>=12'} + + string_decoder@1.3.0: + resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-ansi@7.1.2: + resolution: {integrity: sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==} + engines: {node: '>=12'} + + sumchecker@3.0.1: + resolution: {integrity: sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==} + engines: {node: '>= 8.0'} + + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + tar@7.5.7: + resolution: {integrity: sha512-fov56fJiRuThVFXD6o6/Q354S7pnWMJIVlDBYijsTNx6jKSE4pvrDTs6lUnmGvNyfJwFQQwWy3owKz1ucIhveQ==} + engines: {node: '>=18'} + + temp-file@3.4.0: + resolution: {integrity: sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg==} + + temp@0.9.4: + resolution: {integrity: sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==} + engines: {node: '>=6.0.0'} + + tiny-async-pool@1.3.0: + resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==} + + tinyglobby@0.2.15: + resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==} + engines: {node: '>=12.0.0'} + + tmp-promise@3.0.3: + resolution: {integrity: sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ==} + + tmp@0.2.5: + resolution: {integrity: sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==} + engines: {node: '>=14.14'} + + truncate-utf8-bytes@1.0.2: + resolution: {integrity: sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==} + + type-fest@0.13.1: + resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==} + engines: {node: '>=10'} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + undici-types@7.16.0: + resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} + + unique-filename@4.0.0: + resolution: {integrity: sha512-XSnEewXmQ+veP7xX2dS5Q4yZAvO40cBN2MWkJ7D/6sW4Dg6wYBNwM1Vrnz1FhH5AdeLIlUXRI9e28z1YZi71NQ==} + engines: {node: ^18.17.0 || >=20.5.0} + + unique-slug@5.0.0: + resolution: {integrity: sha512-9OdaqO5kwqR+1kVgHAhsp5vPNU0hnxRa26rBFNfNgM7M6pNtgzeBn3s/xbyCQL3dcjzOatcef6UUHpB/6MaETg==} + engines: {node: ^18.17.0 || >=20.5.0} + + universalify@0.1.2: + resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==} + engines: {node: '>= 4.0.0'} + + universalify@2.0.1: + resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} + engines: {node: '>= 10.0.0'} + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + utf8-byte-length@1.0.5: + resolution: {integrity: sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + verror@1.10.1: + resolution: {integrity: sha512-veufcmxri4e3XSrT0xwfUR7kguIkaxBeosDg00yDWhk49wdwkSUrvvsm7nc75e1PUyvIeZj6nS8VQRYz2/S4Xg==} + engines: {node: '>=0.6.0'} + + wcwidth@1.0.1: + resolution: {integrity: sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==} + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + which@5.0.0: + resolution: {integrity: sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==} + engines: {node: ^18.17.0 || >=20.5.0} + hasBin: true + + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + + wrap-ansi@8.1.0: + resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} + engines: {node: '>=12'} + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + + ws@8.19.0: + resolution: {integrity: sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + xmlbuilder@15.1.1: + resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==} + engines: {node: '>=8.0'} + + y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} + + yallist@4.0.0: + resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} + + yallist@5.0.0: + resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} + engines: {node: '>=18'} + + yargs-parser@21.1.1: + resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} + engines: {node: '>=12'} + + yargs@17.7.2: + resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} + engines: {node: '>=12'} + + yauzl@2.10.0: + resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==} + + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + +snapshots: + + 7zip-bin@5.2.0: {} + + '@develar/schema-utils@2.6.5': + dependencies: + ajv: 6.12.6 + ajv-keywords: 3.5.2(ajv@6.12.6) + + '@electron/asar@3.4.1': + dependencies: + commander: 5.1.0 + glob: 7.2.3 + minimatch: 3.1.2 + + '@electron/fuses@1.8.0': + dependencies: + chalk: 4.1.2 + fs-extra: 9.1.0 + minimist: 1.2.8 + + '@electron/get@2.0.3': + dependencies: + debug: 4.4.3 + env-paths: 2.2.1 + fs-extra: 8.1.0 + got: 11.8.6 + progress: 2.0.3 + semver: 6.3.1 + sumchecker: 3.0.1 + optionalDependencies: + global-agent: 3.0.0 + transitivePeerDependencies: + - supports-color + + '@electron/get@3.1.0': + dependencies: + debug: 4.4.3 + env-paths: 2.2.1 + fs-extra: 8.1.0 + got: 11.8.6 + progress: 2.0.3 + semver: 6.3.1 + sumchecker: 3.0.1 + optionalDependencies: + global-agent: 3.0.0 + transitivePeerDependencies: + - supports-color + + '@electron/notarize@2.5.0': + dependencies: + debug: 4.4.3 + fs-extra: 9.1.0 + promise-retry: 2.0.1 + transitivePeerDependencies: + - supports-color + + '@electron/osx-sign@1.3.3': + dependencies: + compare-version: 0.1.2 + debug: 4.4.3 + fs-extra: 10.1.0 + isbinaryfile: 4.0.10 + minimist: 1.2.8 + plist: 3.1.0 + transitivePeerDependencies: + - supports-color + + '@electron/rebuild@4.0.3': + dependencies: + '@malept/cross-spawn-promise': 2.0.0 + debug: 4.4.3 + detect-libc: 2.1.2 + got: 11.8.6 + graceful-fs: 4.2.11 + node-abi: 4.26.0 + node-api-version: 0.2.1 + node-gyp: 11.5.0 + ora: 5.4.1 + read-binary-file-arch: 1.0.6 + semver: 7.7.4 + tar: 7.5.7 + yargs: 17.7.2 + transitivePeerDependencies: + - supports-color + + '@electron/universal@2.0.3': + dependencies: + '@electron/asar': 3.4.1 + '@malept/cross-spawn-promise': 2.0.0 + debug: 4.4.3 + dir-compare: 4.2.0 + fs-extra: 11.3.3 + minimatch: 9.0.5 + plist: 3.1.0 + transitivePeerDependencies: + - supports-color + + '@electron/windows-sign@1.2.2': + dependencies: + cross-dirname: 0.1.0 + debug: 4.4.3 + fs-extra: 11.3.3 + minimist: 1.2.8 + postject: 1.0.0-alpha.6 + transitivePeerDependencies: + - supports-color + optional: true + + '@isaacs/balanced-match@4.0.1': {} + + '@isaacs/brace-expansion@5.0.1': + dependencies: + '@isaacs/balanced-match': 4.0.1 + + '@isaacs/cliui@8.0.2': + dependencies: + string-width: 5.1.2 + string-width-cjs: string-width@4.2.3 + strip-ansi: 7.1.2 + strip-ansi-cjs: strip-ansi@6.0.1 + wrap-ansi: 8.1.0 + wrap-ansi-cjs: wrap-ansi@7.0.0 + + '@isaacs/fs-minipass@4.0.1': + dependencies: + minipass: 7.1.2 + + '@malept/cross-spawn-promise@2.0.0': + dependencies: + cross-spawn: 7.0.6 + + '@malept/flatpak-bundler@0.4.0': + dependencies: + debug: 4.4.3 + fs-extra: 9.1.0 + lodash: 4.17.23 + tmp-promise: 3.0.3 + transitivePeerDependencies: + - supports-color + + '@npmcli/agent@3.0.0': + dependencies: + agent-base: 7.1.4 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.6 + lru-cache: 10.4.3 + socks-proxy-agent: 8.0.5 + transitivePeerDependencies: + - supports-color + + '@npmcli/fs@4.0.0': + dependencies: + semver: 7.7.4 + + '@pkgjs/parseargs@0.11.0': + optional: true + + '@sindresorhus/is@4.6.0': {} + + '@szmarczak/http-timer@4.0.6': + dependencies: + defer-to-connect: 2.0.1 + + '@types/cacheable-request@6.0.3': + dependencies: + '@types/http-cache-semantics': 4.2.0 + '@types/keyv': 3.1.4 + '@types/node': 25.2.2 + '@types/responselike': 1.0.3 + + '@types/debug@4.1.12': + dependencies: + '@types/ms': 2.1.0 + + '@types/fs-extra@9.0.13': + dependencies: + '@types/node': 25.2.2 + + '@types/http-cache-semantics@4.2.0': {} + + '@types/keyv@3.1.4': + dependencies: + '@types/node': 25.2.2 + + '@types/ms@2.1.0': {} + + '@types/node@22.19.10': + dependencies: + undici-types: 6.21.0 + + '@types/node@25.2.2': + dependencies: + undici-types: 7.16.0 + + '@types/plist@3.0.5': + dependencies: + '@types/node': 25.2.2 + xmlbuilder: 15.1.1 + optional: true + + '@types/responselike@1.0.3': + dependencies: + '@types/node': 25.2.2 + + '@types/verror@1.10.11': + optional: true + + '@types/ws@8.18.1': + dependencies: + '@types/node': 25.2.2 + + '@types/yauzl@2.10.3': + dependencies: + '@types/node': 25.2.2 + optional: true + + '@xmldom/xmldom@0.8.11': {} + + abbrev@3.0.1: {} + + agent-base@7.1.4: {} + + ajv-keywords@3.5.2(ajv@6.12.6): + dependencies: + ajv: 6.12.6 + + ajv@6.12.6: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + ansi-regex@5.0.1: {} + + ansi-regex@6.2.2: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@6.2.3: {} + + app-builder-bin@5.0.0-alpha.12: {} + + app-builder-lib@26.7.0(dmg-builder@26.7.0)(electron-builder-squirrel-windows@26.7.0): + dependencies: + '@develar/schema-utils': 2.6.5 + '@electron/asar': 3.4.1 + '@electron/fuses': 1.8.0 + '@electron/get': 3.1.0 + '@electron/notarize': 2.5.0 + '@electron/osx-sign': 1.3.3 + '@electron/rebuild': 4.0.3 + '@electron/universal': 2.0.3 + '@malept/flatpak-bundler': 0.4.0 + '@types/fs-extra': 9.0.13 + async-exit-hook: 2.0.1 + builder-util: 26.4.1 + builder-util-runtime: 9.5.1 + chromium-pickle-js: 0.2.0 + ci-info: 4.3.1 + debug: 4.4.3 + dmg-builder: 26.7.0(electron-builder-squirrel-windows@26.7.0) + dotenv: 16.6.1 + dotenv-expand: 11.0.7 + ejs: 3.1.10 + electron-builder-squirrel-windows: 26.7.0(dmg-builder@26.7.0) + electron-publish: 26.6.0 + fs-extra: 10.1.0 + hosted-git-info: 4.1.0 + isbinaryfile: 5.0.7 + jiti: 2.6.1 + js-yaml: 4.1.1 + json5: 2.2.3 + lazy-val: 1.0.5 + minimatch: 10.1.2 + plist: 3.1.0 + proper-lockfile: 4.1.2 + resedit: 1.7.2 + semver: 7.7.4 + tar: 7.5.7 + temp-file: 3.4.0 + tiny-async-pool: 1.3.0 + which: 5.0.0 + transitivePeerDependencies: + - supports-color + + argparse@2.0.1: {} + + assert-plus@1.0.0: + optional: true + + astral-regex@2.0.0: + optional: true + + async-exit-hook@2.0.1: {} + + async@3.2.6: {} + + asynckit@0.4.0: {} + + at-least-node@1.0.0: {} + + axios@1.13.5: + dependencies: + follow-redirects: 1.15.11 + form-data: 4.0.5 + proxy-from-env: 1.1.0 + transitivePeerDependencies: + - debug + + balanced-match@1.0.2: {} + + base64-js@1.5.1: {} + + bl@4.1.0: + dependencies: + buffer: 5.7.1 + inherits: 2.0.4 + readable-stream: 3.6.2 + + boolean@3.2.0: + optional: true + + brace-expansion@1.1.12: + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + + brace-expansion@2.0.2: + dependencies: + balanced-match: 1.0.2 + + buffer-crc32@0.2.13: {} + + buffer-from@1.1.2: {} + + buffer@5.7.1: + dependencies: + base64-js: 1.5.1 + ieee754: 1.2.1 + + builder-util-runtime@9.5.1: + dependencies: + debug: 4.4.3 + sax: 1.4.4 + transitivePeerDependencies: + - supports-color + + builder-util@26.4.1: + dependencies: + 7zip-bin: 5.2.0 + '@types/debug': 4.1.12 + app-builder-bin: 5.0.0-alpha.12 + builder-util-runtime: 9.5.1 + chalk: 4.1.2 + cross-spawn: 7.0.6 + debug: 4.4.3 + fs-extra: 10.1.0 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.6 + js-yaml: 4.1.1 + sanitize-filename: 1.6.3 + source-map-support: 0.5.21 + stat-mode: 1.0.0 + temp-file: 3.4.0 + tiny-async-pool: 1.3.0 + transitivePeerDependencies: + - supports-color + + cacache@19.0.1: + dependencies: + '@npmcli/fs': 4.0.0 + fs-minipass: 3.0.3 + glob: 10.5.0 + lru-cache: 10.4.3 + minipass: 7.1.2 + minipass-collect: 2.0.1 + minipass-flush: 1.0.5 + minipass-pipeline: 1.2.4 + p-map: 7.0.4 + ssri: 12.0.0 + tar: 7.5.7 + unique-filename: 4.0.0 + + cacheable-lookup@5.0.4: {} + + cacheable-request@7.0.4: + dependencies: + clone-response: 1.0.3 + get-stream: 5.2.0 + http-cache-semantics: 4.2.0 + keyv: 4.5.4 + lowercase-keys: 2.0.0 + normalize-url: 6.1.0 + responselike: 2.0.1 + + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + + chalk@4.1.2: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + + chownr@3.0.0: {} + + chromium-pickle-js@0.2.0: {} + + ci-info@4.3.1: {} + + ci-info@4.4.0: {} + + cli-cursor@3.1.0: + dependencies: + restore-cursor: 3.1.0 + + cli-spinners@2.9.2: {} + + cli-truncate@2.1.0: + dependencies: + slice-ansi: 3.0.0 + string-width: 4.2.3 + optional: true + + cliui@8.0.1: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + + clone-response@1.0.3: + dependencies: + mimic-response: 1.0.1 + + clone@1.0.4: {} + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + combined-stream@1.0.8: + dependencies: + delayed-stream: 1.0.0 + + commander@5.1.0: {} + + commander@9.5.0: + optional: true + + compare-version@0.1.2: {} + + concat-map@0.0.1: {} + + core-util-is@1.0.2: + optional: true + + crc@3.8.0: + dependencies: + buffer: 5.7.1 + optional: true + + cross-dirname@0.1.0: + optional: true + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + decompress-response@6.0.0: + dependencies: + mimic-response: 3.1.0 + + defaults@1.0.4: + dependencies: + clone: 1.0.4 + + defer-to-connect@2.0.1: {} + + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + optional: true + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + optional: true + + delayed-stream@1.0.0: {} + + detect-libc@2.1.2: {} + + detect-node@2.1.0: + optional: true + + dir-compare@4.2.0: + dependencies: + minimatch: 3.1.2 + p-limit: 3.1.0 + + dmg-builder@26.7.0(electron-builder-squirrel-windows@26.7.0): + dependencies: + app-builder-lib: 26.7.0(dmg-builder@26.7.0)(electron-builder-squirrel-windows@26.7.0) + builder-util: 26.4.1 + fs-extra: 10.1.0 + iconv-lite: 0.6.3 + js-yaml: 4.1.1 + optionalDependencies: + dmg-license: 1.0.11 + transitivePeerDependencies: + - electron-builder-squirrel-windows + - supports-color + + dmg-license@1.0.11: + dependencies: + '@types/plist': 3.0.5 + '@types/verror': 1.10.11 + ajv: 6.12.6 + crc: 3.8.0 + iconv-corefoundation: 1.1.7 + plist: 3.1.0 + smart-buffer: 4.2.0 + verror: 1.10.1 + optional: true + + dotenv-expand@11.0.7: + dependencies: + dotenv: 16.6.1 + + dotenv@16.6.1: {} + + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + + eastasianwidth@0.2.0: {} + + ejs@3.1.10: + dependencies: + jake: 10.9.4 + + electron-builder-squirrel-windows@26.7.0(dmg-builder@26.7.0): + dependencies: + app-builder-lib: 26.7.0(dmg-builder@26.7.0)(electron-builder-squirrel-windows@26.7.0) + builder-util: 26.4.1 + electron-winstaller: 5.4.0 + transitivePeerDependencies: + - dmg-builder + - supports-color + + electron-builder@26.7.0(electron-builder-squirrel-windows@26.7.0): + dependencies: + app-builder-lib: 26.7.0(dmg-builder@26.7.0)(electron-builder-squirrel-windows@26.7.0) + builder-util: 26.4.1 + builder-util-runtime: 9.5.1 + chalk: 4.1.2 + ci-info: 4.4.0 + dmg-builder: 26.7.0(electron-builder-squirrel-windows@26.7.0) + fs-extra: 10.1.0 + lazy-val: 1.0.5 + simple-update-notifier: 2.0.0 + yargs: 17.7.2 + transitivePeerDependencies: + - electron-builder-squirrel-windows + - supports-color + + electron-publish@26.6.0: + dependencies: + '@types/fs-extra': 9.0.13 + builder-util: 26.4.1 + builder-util-runtime: 9.5.1 + chalk: 4.1.2 + form-data: 4.0.5 + fs-extra: 10.1.0 + lazy-val: 1.0.5 + mime: 2.6.0 + transitivePeerDependencies: + - supports-color + + electron-winstaller@5.4.0: + dependencies: + '@electron/asar': 3.4.1 + debug: 4.4.3 + fs-extra: 7.0.1 + lodash: 4.17.23 + temp: 0.9.4 + optionalDependencies: + '@electron/windows-sign': 1.2.2 + transitivePeerDependencies: + - supports-color + + electron@37.10.3: + dependencies: + '@electron/get': 2.0.3 + '@types/node': 22.19.10 + extract-zip: 2.0.1 + transitivePeerDependencies: + - supports-color + + emoji-regex@8.0.0: {} + + emoji-regex@9.2.2: {} + + encoding@0.1.13: + dependencies: + iconv-lite: 0.6.3 + optional: true + + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + + env-paths@2.2.1: {} + + err-code@2.0.3: {} + + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + + es-object-atoms@1.1.1: + dependencies: + es-errors: 1.3.0 + + es-set-tostringtag@2.1.0: + dependencies: + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + has-tostringtag: 1.0.2 + hasown: 2.0.2 + + es6-error@4.1.1: + optional: true + + escalade@3.2.0: {} + + escape-string-regexp@4.0.0: + optional: true + + exponential-backoff@3.1.3: {} + + extract-zip@2.0.1: + dependencies: + debug: 4.4.3 + get-stream: 5.2.0 + yauzl: 2.10.0 + optionalDependencies: + '@types/yauzl': 2.10.3 + transitivePeerDependencies: + - supports-color + + extsprintf@1.4.1: + optional: true + + fast-deep-equal@3.1.3: {} + + fast-json-stable-stringify@2.1.0: {} + + fd-slicer@1.1.0: + dependencies: + pend: 1.2.0 + + fdir@6.5.0(picomatch@4.0.3): + optionalDependencies: + picomatch: 4.0.3 + + filelist@1.0.4: + dependencies: + minimatch: 5.1.6 + + follow-redirects@1.15.11: {} + + foreground-child@3.3.1: + dependencies: + cross-spawn: 7.0.6 + signal-exit: 4.1.0 + + form-data@4.0.5: + dependencies: + asynckit: 0.4.0 + combined-stream: 1.0.8 + es-set-tostringtag: 2.1.0 + hasown: 2.0.2 + mime-types: 2.1.35 + + fs-extra@10.1.0: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.0 + universalify: 2.0.1 + + fs-extra@11.3.3: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.0 + universalify: 2.0.1 + + fs-extra@7.0.1: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 4.0.0 + universalify: 0.1.2 + + fs-extra@8.1.0: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 4.0.0 + universalify: 0.1.2 + + fs-extra@9.1.0: + dependencies: + at-least-node: 1.0.0 + graceful-fs: 4.2.11 + jsonfile: 6.2.0 + universalify: 2.0.1 + + fs-minipass@3.0.3: + dependencies: + minipass: 7.1.2 + + fs.realpath@1.0.0: {} + + function-bind@1.1.2: {} + + get-caller-file@2.0.5: {} + + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.1 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.2 + math-intrinsics: 1.1.0 + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.1 + + get-stream@5.2.0: + dependencies: + pump: 3.0.3 + + glob@10.5.0: + dependencies: + foreground-child: 3.3.1 + jackspeak: 3.4.3 + minimatch: 9.0.5 + minipass: 7.1.2 + package-json-from-dist: 1.0.1 + path-scurry: 1.11.1 + + glob@7.2.3: + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 3.1.2 + once: 1.4.0 + path-is-absolute: 1.0.1 + + global-agent@3.0.0: + dependencies: + boolean: 3.2.0 + es6-error: 4.1.1 + matcher: 3.0.0 + roarr: 2.15.4 + semver: 7.7.4 + serialize-error: 7.0.1 + optional: true + + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + optional: true + + gopd@1.2.0: {} + + got@11.8.6: + dependencies: + '@sindresorhus/is': 4.6.0 + '@szmarczak/http-timer': 4.0.6 + '@types/cacheable-request': 6.0.3 + '@types/responselike': 1.0.3 + cacheable-lookup: 5.0.4 + cacheable-request: 7.0.4 + decompress-response: 6.0.0 + http2-wrapper: 1.0.3 + lowercase-keys: 2.0.0 + p-cancelable: 2.1.1 + responselike: 2.0.1 + + graceful-fs@4.2.11: {} + + has-flag@4.0.0: {} + + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + optional: true + + has-symbols@1.1.0: {} + + has-tostringtag@1.0.2: + dependencies: + has-symbols: 1.1.0 + + hasown@2.0.2: + dependencies: + function-bind: 1.1.2 + + hosted-git-info@4.1.0: + dependencies: + lru-cache: 6.0.0 + + http-cache-semantics@4.2.0: {} + + http-proxy-agent@7.0.2: + dependencies: + agent-base: 7.1.4 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + http2-wrapper@1.0.3: + dependencies: + quick-lru: 5.1.1 + resolve-alpn: 1.2.1 + + https-proxy-agent@7.0.6: + dependencies: + agent-base: 7.1.4 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + iconv-corefoundation@1.1.7: + dependencies: + cli-truncate: 2.1.0 + node-addon-api: 1.7.2 + optional: true + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + + ieee754@1.2.1: {} + + imurmurhash@0.1.4: {} + + inflight@1.0.6: + dependencies: + once: 1.4.0 + wrappy: 1.0.2 + + inherits@2.0.4: {} + + ip-address@10.1.0: {} + + is-fullwidth-code-point@3.0.0: {} + + is-interactive@1.0.0: {} + + is-unicode-supported@0.1.0: {} + + isbinaryfile@4.0.10: {} + + isbinaryfile@5.0.7: {} + + isexe@2.0.0: {} + + isexe@3.1.4: {} + + jackspeak@3.4.3: + dependencies: + '@isaacs/cliui': 8.0.2 + optionalDependencies: + '@pkgjs/parseargs': 0.11.0 + + jake@10.9.4: + dependencies: + async: 3.2.6 + filelist: 1.0.4 + picocolors: 1.1.1 + + jiti@2.6.1: {} + + js-yaml@4.1.1: + dependencies: + argparse: 2.0.1 + + json-buffer@3.0.1: {} + + json-schema-traverse@0.4.1: {} + + json-stringify-safe@5.0.1: + optional: true + + json5@2.2.3: {} + + jsonc-parser@3.3.1: {} + + jsonfile@4.0.0: + optionalDependencies: + graceful-fs: 4.2.11 + + jsonfile@6.2.0: + dependencies: + universalify: 2.0.1 + optionalDependencies: + graceful-fs: 4.2.11 + + keyv@4.5.4: + dependencies: + json-buffer: 3.0.1 + + lazy-val@1.0.5: {} + + lodash@4.17.23: {} + + log-symbols@4.1.0: + dependencies: + chalk: 4.1.2 + is-unicode-supported: 0.1.0 + + lowercase-keys@2.0.0: {} + + lru-cache@10.4.3: {} + + lru-cache@6.0.0: + dependencies: + yallist: 4.0.0 + + make-fetch-happen@14.0.3: + dependencies: + '@npmcli/agent': 3.0.0 + cacache: 19.0.1 + http-cache-semantics: 4.2.0 + minipass: 7.1.2 + minipass-fetch: 4.0.1 + minipass-flush: 1.0.5 + minipass-pipeline: 1.2.4 + negotiator: 1.0.0 + proc-log: 5.0.0 + promise-retry: 2.0.1 + ssri: 12.0.0 + transitivePeerDependencies: + - supports-color + + matcher@3.0.0: + dependencies: + escape-string-regexp: 4.0.0 + optional: true + + math-intrinsics@1.1.0: {} + + mime-db@1.52.0: {} + + mime-types@2.1.35: + dependencies: + mime-db: 1.52.0 + + mime@2.6.0: {} + + mimic-fn@2.1.0: {} + + mimic-response@1.0.1: {} + + mimic-response@3.1.0: {} + + minimatch@10.1.2: + dependencies: + '@isaacs/brace-expansion': 5.0.1 + + minimatch@3.1.2: + dependencies: + brace-expansion: 1.1.12 + + minimatch@5.1.6: + dependencies: + brace-expansion: 2.0.2 + + minimatch@9.0.5: + dependencies: + brace-expansion: 2.0.2 + + minimist@1.2.8: {} + + minipass-collect@2.0.1: + dependencies: + minipass: 7.1.2 + + minipass-fetch@4.0.1: + dependencies: + minipass: 7.1.2 + minipass-sized: 1.0.3 + minizlib: 3.1.0 + optionalDependencies: + encoding: 0.1.13 + + minipass-flush@1.0.5: + dependencies: + minipass: 3.3.6 + + minipass-pipeline@1.2.4: + dependencies: + minipass: 3.3.6 + + minipass-sized@1.0.3: + dependencies: + minipass: 3.3.6 + + minipass@3.3.6: + dependencies: + yallist: 4.0.0 + + minipass@7.1.2: {} + + minizlib@3.1.0: + dependencies: + minipass: 7.1.2 + + mkdirp@0.5.6: + dependencies: + minimist: 1.2.8 + + ms@2.1.3: {} + + negotiator@1.0.0: {} + + node-abi@4.26.0: + dependencies: + semver: 7.7.4 + + node-addon-api@1.7.2: + optional: true + + node-api-version@0.2.1: + dependencies: + semver: 7.7.4 + + node-gyp@11.5.0: + dependencies: + env-paths: 2.2.1 + exponential-backoff: 3.1.3 + graceful-fs: 4.2.11 + make-fetch-happen: 14.0.3 + nopt: 8.1.0 + proc-log: 5.0.0 + semver: 7.7.4 + tar: 7.5.7 + tinyglobby: 0.2.15 + which: 5.0.0 + transitivePeerDependencies: + - supports-color + + nopt@8.1.0: + dependencies: + abbrev: 3.0.1 + + normalize-url@6.1.0: {} + + object-keys@1.1.1: + optional: true + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + onetime@5.1.2: + dependencies: + mimic-fn: 2.1.0 + + ora@5.4.1: + dependencies: + bl: 4.1.0 + chalk: 4.1.2 + cli-cursor: 3.1.0 + cli-spinners: 2.9.2 + is-interactive: 1.0.0 + is-unicode-supported: 0.1.0 + log-symbols: 4.1.0 + strip-ansi: 6.0.1 + wcwidth: 1.0.1 + + p-cancelable@2.1.1: {} + + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-map@7.0.4: {} + + package-json-from-dist@1.0.1: {} + + path-is-absolute@1.0.1: {} + + path-key@3.1.1: {} + + path-scurry@1.11.1: + dependencies: + lru-cache: 10.4.3 + minipass: 7.1.2 + + pe-library@0.4.1: {} + + pend@1.2.0: {} + + picocolors@1.1.1: {} + + picomatch@4.0.3: {} + + plist@3.1.0: + dependencies: + '@xmldom/xmldom': 0.8.11 + base64-js: 1.5.1 + xmlbuilder: 15.1.1 + + postject@1.0.0-alpha.6: + dependencies: + commander: 9.5.0 + optional: true + + proc-log@5.0.0: {} + + progress@2.0.3: {} + + promise-retry@2.0.1: + dependencies: + err-code: 2.0.3 + retry: 0.12.0 + + proper-lockfile@4.1.2: + dependencies: + graceful-fs: 4.2.11 + retry: 0.12.0 + signal-exit: 3.0.7 + + proxy-from-env@1.1.0: {} + + pump@3.0.3: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + + punycode@2.3.1: {} + + quick-lru@5.1.1: {} + + read-binary-file-arch@1.0.6: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.3.0 + util-deprecate: 1.0.2 + + require-directory@2.1.1: {} + + resedit@1.7.2: + dependencies: + pe-library: 0.4.1 + + resolve-alpn@1.2.1: {} + + responselike@2.0.1: + dependencies: + lowercase-keys: 2.0.0 + + restore-cursor@3.1.0: + dependencies: + onetime: 5.1.2 + signal-exit: 3.0.7 + + retry@0.12.0: {} + + rimraf@2.6.3: + dependencies: + glob: 7.2.3 + + roarr@2.15.4: + dependencies: + boolean: 3.2.0 + detect-node: 2.1.0 + globalthis: 1.0.4 + json-stringify-safe: 5.0.1 + semver-compare: 1.0.0 + sprintf-js: 1.1.3 + optional: true + + safe-buffer@5.2.1: {} + + safer-buffer@2.1.2: {} + + sanitize-filename@1.6.3: + dependencies: + truncate-utf8-bytes: 1.0.2 + + sax@1.4.4: {} + + semver-compare@1.0.0: + optional: true + + semver@5.7.2: {} + + semver@6.3.1: {} + + semver@7.7.4: {} + + serialize-error@7.0.1: + dependencies: + type-fest: 0.13.1 + optional: true + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + signal-exit@3.0.7: {} + + signal-exit@4.1.0: {} + + simple-update-notifier@2.0.0: + dependencies: + semver: 7.7.4 + + slice-ansi@3.0.0: + dependencies: + ansi-styles: 4.3.0 + astral-regex: 2.0.0 + is-fullwidth-code-point: 3.0.0 + optional: true + + smart-buffer@4.2.0: {} + + socks-proxy-agent@8.0.5: + dependencies: + agent-base: 7.1.4 + debug: 4.4.3 + socks: 2.8.7 + transitivePeerDependencies: + - supports-color + + socks@2.8.7: + dependencies: + ip-address: 10.1.0 + smart-buffer: 4.2.0 + + source-map-support@0.5.21: + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + + source-map@0.6.1: {} + + sprintf-js@1.1.3: + optional: true + + ssri@12.0.0: + dependencies: + minipass: 7.1.2 + + stat-mode@1.0.0: {} + + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + string-width@5.1.2: + dependencies: + eastasianwidth: 0.2.0 + emoji-regex: 9.2.2 + strip-ansi: 7.1.2 + + string_decoder@1.3.0: + dependencies: + safe-buffer: 5.2.1 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-ansi@7.1.2: + dependencies: + ansi-regex: 6.2.2 + + sumchecker@3.0.1: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + + tar@7.5.7: + dependencies: + '@isaacs/fs-minipass': 4.0.1 + chownr: 3.0.0 + minipass: 7.1.2 + minizlib: 3.1.0 + yallist: 5.0.0 + + temp-file@3.4.0: + dependencies: + async-exit-hook: 2.0.1 + fs-extra: 10.1.0 + + temp@0.9.4: + dependencies: + mkdirp: 0.5.6 + rimraf: 2.6.3 + + tiny-async-pool@1.3.0: + dependencies: + semver: 5.7.2 + + tinyglobby@0.2.15: + dependencies: + fdir: 6.5.0(picomatch@4.0.3) + picomatch: 4.0.3 + + tmp-promise@3.0.3: + dependencies: + tmp: 0.2.5 + + tmp@0.2.5: {} + + truncate-utf8-bytes@1.0.2: + dependencies: + utf8-byte-length: 1.0.5 + + type-fest@0.13.1: + optional: true + + typescript@5.9.3: {} + + undici-types@6.21.0: {} + + undici-types@7.16.0: {} + + unique-filename@4.0.0: + dependencies: + unique-slug: 5.0.0 + + unique-slug@5.0.0: + dependencies: + imurmurhash: 0.1.4 + + universalify@0.1.2: {} + + universalify@2.0.1: {} + + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + + utf8-byte-length@1.0.5: {} + + util-deprecate@1.0.2: {} + + verror@1.10.1: + dependencies: + assert-plus: 1.0.0 + core-util-is: 1.0.2 + extsprintf: 1.4.1 + optional: true + + wcwidth@1.0.1: + dependencies: + defaults: 1.0.4 + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + which@5.0.0: + dependencies: + isexe: 3.1.4 + + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + wrap-ansi@8.1.0: + dependencies: + ansi-styles: 6.2.3 + string-width: 5.1.2 + strip-ansi: 7.1.2 + + wrappy@1.0.2: {} + + ws@8.19.0: {} + + xmlbuilder@15.1.1: {} + + y18n@5.0.8: {} + + yallist@4.0.0: {} + + yallist@5.0.0: {} + + yargs-parser@21.1.1: {} + + yargs@17.7.2: + dependencies: + cliui: 8.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 + + yauzl@2.10.0: + dependencies: + buffer-crc32: 0.2.13 + fd-slicer: 1.1.0 + + yocto-queue@0.1.0: {} diff --git a/scripts/mkv-to-readme-video.sh b/scripts/mkv-to-readme-video.sh new file mode 100755 index 0000000..a9b2132 --- /dev/null +++ b/scripts/mkv-to-readme-video.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash + +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: + scripts/mkv-to-readme-video.sh + +Description: + Generates two browser-friendly files next to the input file: + - .mp4 (H.264 + AAC, prefers NVIDIA GPU if available) + - .webm (AV1/VP9 + Opus, prefers NVIDIA GPU if available) +EOF +} + +if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then + usage + exit 0 +fi + +if [[ $# -ne 1 ]]; then + usage + exit 1 +fi + +if ! command -v ffmpeg >/dev/null 2>&1; then + echo "Error: ffmpeg is not installed or not in PATH." >&2 + exit 1 +fi + +input="$1" + +if [[ ! -f "$input" ]]; then + echo "Error: input file not found: $input" >&2 + exit 1 +fi + +dir="$(dirname "$input")" +filename="$(basename "$input")" +base="${filename%.*}" + +mp4_out="$dir/$base.mp4" +webm_out="$dir/$base.webm" + +has_encoder() { + local encoder="$1" + ffmpeg -hide_banner -encoders 2>/dev/null | grep -qE "[[:space:]]${encoder}[[:space:]]" +} + +echo "Generating MP4: $mp4_out" +if has_encoder "h264_nvenc"; then + echo "Using GPU encoder for MP4: h264_nvenc" + ffmpeg -y -i "$input" \ + -c:v h264_nvenc -preset p5 -cq 20 \ + -profile:v high -pix_fmt yuv420p \ + -movflags +faststart \ + -c:a aac -b:a 160k \ + "$mp4_out" +else + echo "Using CPU encoder for MP4: libx264" + ffmpeg -y -i "$input" \ + -c:v libx264 -preset slow -crf 20 \ + -profile:v high -level 4.1 -pix_fmt yuv420p \ + -movflags +faststart \ + -c:a aac -b:a 160k \ + "$mp4_out" +fi + +echo "Generating WebM: $webm_out" +if has_encoder "av1_nvenc"; then + echo "Using GPU encoder for WebM: av1_nvenc" + ffmpeg -y -i "$input" \ + -c:v av1_nvenc -preset p5 -cq 30 -b:v 0 \ + -c:a libopus -b:a 128k \ + "$webm_out" +else + echo "Using CPU encoder for WebM: libvpx-vp9" + ffmpeg -y -i "$input" \ + -c:v libvpx-vp9 -crf 32 -b:v 0 \ + -c:a libopus -b:a 128k \ + "$webm_out" +fi + +echo "Done." +echo "MP4: $mp4_out" +echo "WebM: $webm_out" diff --git a/scripts/patch-texthooker.sh b/scripts/patch-texthooker.sh new file mode 100755 index 0000000..7ce3906 --- /dev/null +++ b/scripts/patch-texthooker.sh @@ -0,0 +1,236 @@ +#!/bin/bash +# +# SubMiner - All-in-one sentence mining overlay +# Copyright (C) 2024 sudacode +# +# 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 . +# +# patch-texthooker.sh - Apply patches to texthooker-ui +# +# This script patches texthooker-ui to: +# 1) Handle empty sentences from mpv. +# 2) Apply SubMiner default texthooker styling. +# +# Usage: ./patch-texthooker.sh [texthooker_dir] +# texthooker_dir: Path to the texthooker-ui directory (default: vendor/texthooker-ui) +# + +set -e + +sed_in_place() { + local script="$1" + local file="$2" + + if sed -i '' "$script" "$file" 2>/dev/null; then + return 0 + fi + + sed -i "$script" "$file" +} + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +TEXTHOOKER_DIR="${1:-$SCRIPT_DIR/../vendor/texthooker-ui}" + +if [ ! -d "$TEXTHOOKER_DIR" ]; then + echo "Error: texthooker-ui directory not found: $TEXTHOOKER_DIR" + exit 1 +fi + +echo "Patching texthooker-ui in: $TEXTHOOKER_DIR" + +SOCKET_TS="$TEXTHOOKER_DIR/src/socket.ts" +APP_CSS="$TEXTHOOKER_DIR/src/app.css" +STORES_TS="$TEXTHOOKER_DIR/src/stores/stores.ts" + +if [ ! -f "$SOCKET_TS" ]; then + echo "Error: socket.ts not found at $SOCKET_TS" + exit 1 +fi + +if [ ! -f "$APP_CSS" ]; then + echo "Error: app.css not found at $APP_CSS" + exit 1 +fi + +if [ ! -f "$STORES_TS" ]; then + echo "Error: stores.ts not found at $STORES_TS" + exit 1 +fi + +echo "Patching socket.ts..." + +# Patch 1: Change || to ?? (nullish coalescing) +# This ensures empty string is kept instead of falling back to raw JSON +if grep -q '\.sentence ?? event\.data' "$SOCKET_TS"; then + echo " - Nullish coalescing already patched, skipping" +else + sed_in_place 's/\.sentence || event\.data/.sentence ?? event.data/' "$SOCKET_TS" + echo " - Changed || to ?? (nullish coalescing)" +fi + +# Patch 2: Skip emitting empty lines +# This prevents empty sentences from being added to the UI +if grep -q "if (line)" "$SOCKET_TS"; then + echo " - Empty line check already patched, skipping" +else + sed_in_place 's/\t\tnewLine\$\.next(\[line, LineType\.SOCKET\]);/\t\tif (line) {\n\t\t\tnewLine$.next([line, LineType.SOCKET]);\n\t\t}/' "$SOCKET_TS" + echo " - Added empty line check" +fi + +echo "Patching app.css..." + +# Patch 3: Apply SubMiner default texthooker-ui styling +if grep -q "SUBMINER_DEFAULT_STYLE_START" "$APP_CSS"; then + echo " - Default SubMiner CSS already patched, skipping" +else + cat >> "$APP_CSS" << 'EOF' + +/* SUBMINER_DEFAULT_STYLE_START */ +:root { + --sm-bg: #1a1b2e; + --sm-surface: #222436; + --sm-border: rgba(255, 255, 255, 0.05); + --sm-text: #c8d3f5; + --sm-text-muted: #636da6; + --sm-hover-bg: rgba(130, 170, 255, 0.06); + --sm-scrollbar: rgba(255, 255, 255, 0.08); + --sm-scrollbar-hover: rgba(255, 255, 255, 0.15); +} + +html, +body { + margin: 0; + display: flex; + flex: 1; + min-height: 100%; + overflow: auto; + background: var(--sm-bg); + color: var(--sm-text); +} + +body[data-theme] { + background: var(--sm-bg); + color: var(--sm-text); +} + +main, +header, +#pip-container { + background: transparent; + color: var(--sm-text); +} + +header.bg-base-100, +header.bg-base-200 { + background: transparent; +} + +main, +main.flex { + font-family: 'Noto Sans CJK JP', 'Hiragino Sans', system-ui, sans-serif; + padding: 0.5rem min(4vw, 2rem); + line-height: 1.7; + gap: 0; +} + +p, +p.cursor-pointer { + font-family: 'Noto Sans CJK JP', 'Hiragino Sans', system-ui, sans-serif; + font-size: clamp(18px, 2vw, 26px); + letter-spacing: 0.04em; + line-height: 1.65; + white-space: normal; + margin: 0; + padding: 0.65rem 1rem; + border: none; + border-bottom: 1px solid var(--sm-border); + border-radius: 0; + background: transparent; + transition: background 0.2s ease; +} + +p:hover, +p.cursor-pointer:hover { + background: var(--sm-hover-bg); +} + +p:last-child, +p.cursor-pointer:last-child { + border-bottom: none; +} + +p.cursor-pointer.whitespace-pre-wrap { + white-space: normal; +} + +p.cursor-pointer.my-2 { + margin: 0; +} + +p.cursor-pointer.py-4, +p.cursor-pointer.py-2, +p.cursor-pointer.px-2, +p.cursor-pointer.px-4 { + padding: 0.65rem 1rem; +} + +*::-webkit-scrollbar { + width: 4px; +} + +*::-webkit-scrollbar-track { + background: transparent; +} + +*::-webkit-scrollbar-thumb { + background: var(--sm-scrollbar); + border-radius: 2px; +} + +*::-webkit-scrollbar-thumb:hover { + background: var(--sm-scrollbar-hover); +} +/* SUBMINER_DEFAULT_STYLE_END */ +EOF + echo " - Added default SubMiner CSS block" +fi + +echo "Patching stores.ts defaults..." + +# Patch 4: Change default settings for title/whitespace/animation/reconnect +if grep -q "preserveWhitespace\\$: false" "$STORES_TS" && \ + grep -q "removeAllWhitespace\\$: true" "$STORES_TS" && \ + grep -q "enableLineAnimation\\$: true" "$STORES_TS" && \ + grep -q "continuousReconnect\\$: true" "$STORES_TS" && \ + grep -q "windowTitle\\$: 'SubMiner Texthooker'" "$STORES_TS"; then + echo " - Default settings already patched, skipping" +else + sed_in_place "s/windowTitle\\$: '',/windowTitle\\$: 'SubMiner Texthooker',/" "$STORES_TS" + sed_in_place 's/preserveWhitespace\$: true,/preserveWhitespace\$: false,/' "$STORES_TS" + sed_in_place 's/removeAllWhitespace\$: false,/removeAllWhitespace\$: true,/' "$STORES_TS" + sed_in_place 's/enableLineAnimation\$: false,/enableLineAnimation\$: true,/' "$STORES_TS" + sed_in_place 's/continuousReconnect\$: false,/continuousReconnect\$: true,/' "$STORES_TS" + echo " - Updated default settings (title/whitespace/animation/reconnect)" +fi + +echo "" +echo "texthooker-ui patching complete!" +echo "" +echo "Changes applied:" +echo " 1. socket.ts: Use ?? instead of || to preserve empty strings" +echo " 2. socket.ts: Skip emitting empty sentences" +echo " 3. app.css: Apply SubMiner default styling (without !important)" +echo " 4. stores.ts: Update default settings for title/whitespace/animation/reconnect" +echo "" +echo "To rebuild: cd vendor/texthooker-ui && pnpm build" diff --git a/scripts/patch-yomitan.sh b/scripts/patch-yomitan.sh new file mode 100755 index 0000000..a6e1570 --- /dev/null +++ b/scripts/patch-yomitan.sh @@ -0,0 +1,261 @@ +#!/bin/bash +# +# SubMiner - All-in-one sentence mining overlay +# Copyright (C) 2024 sudacode +# +# 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 . +# +# patch-yomitan.sh - Apply Electron compatibility patches to Yomitan +# +# This script applies the necessary patches to make Yomitan work in Electron +# after upgrading to a new version. Run this after extracting a fresh Yomitan release. +# +# Usage: ./patch-yomitan.sh [yomitan_dir] +# yomitan_dir: Path to the Yomitan directory (default: vendor/yomitan) +# + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +YOMITAN_DIR="${1:-$SCRIPT_DIR/../vendor/yomitan}" + +if [ ! -d "$YOMITAN_DIR" ]; then + echo "Error: Yomitan directory not found: $YOMITAN_DIR" + exit 1 +fi + +echo "Patching Yomitan in: $YOMITAN_DIR" + +PERMISSIONS_UTIL="$YOMITAN_DIR/js/data/permissions-util.js" + +if [ ! -f "$PERMISSIONS_UTIL" ]; then + echo "Error: permissions-util.js not found at $PERMISSIONS_UTIL" + exit 1 +fi + +echo "Patching permissions-util.js..." + +if grep -q "Electron workaround" "$PERMISSIONS_UTIL"; then + echo " - Already patched, skipping" +else + cat > "$PERMISSIONS_UTIL.tmp" << 'PATCH_EOF' +/* + * Copyright (C) 2023-2025 Yomitan Authors + * Copyright (C) 2021-2022 Yomichan Authors + * + * 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 . + */ + +import {getFieldMarkers} from './anki-util.js'; + +/** + * This function returns whether an Anki field marker might require clipboard permissions. + * This is speculative and may not guarantee that the field marker actually does require the permission, + * as the custom handlebars template is not deeply inspected. + * @param {string} marker + * @returns {boolean} + */ +function ankiFieldMarkerMayUseClipboard(marker) { + switch (marker) { + case 'clipboard-image': + case 'clipboard-text': + return true; + default: + return false; + } +} + +/** + * @param {chrome.permissions.Permissions} permissions + * @returns {Promise} + */ +export function hasPermissions(permissions) { + return new Promise((resolve, reject) => { + chrome.permissions.contains(permissions, (result) => { + const e = chrome.runtime.lastError; + if (e) { + reject(new Error(e.message)); + } else { + resolve(result); + } + }); + }); +} + +/** + * @param {chrome.permissions.Permissions} permissions + * @param {boolean} shouldHave + * @returns {Promise} + */ +export function setPermissionsGranted(permissions, shouldHave) { + return ( + shouldHave ? + new Promise((resolve, reject) => { + chrome.permissions.request(permissions, (result) => { + const e = chrome.runtime.lastError; + if (e) { + reject(new Error(e.message)); + } else { + resolve(result); + } + }); + }) : + new Promise((resolve, reject) => { + chrome.permissions.remove(permissions, (result) => { + const e = chrome.runtime.lastError; + if (e) { + reject(new Error(e.message)); + } else { + resolve(!result); + } + }); + }) + ); +} + +/** + * @returns {Promise} + */ +export function getAllPermissions() { + // Electron workaround - chrome.permissions.getAll() not available + return Promise.resolve({ + origins: [""], + permissions: ["clipboardWrite", "storage", "unlimitedStorage", "scripting", "contextMenus"] + }); +} + +/** + * @param {string} fieldValue + * @returns {string[]} + */ +export function getRequiredPermissionsForAnkiFieldValue(fieldValue) { + const markers = getFieldMarkers(fieldValue); + for (const marker of markers) { + if (ankiFieldMarkerMayUseClipboard(marker)) { + return ['clipboardRead']; + } + } + return []; +} + +/** + * @param {chrome.permissions.Permissions} permissions + * @param {import('settings').ProfileOptions} options + * @returns {boolean} + */ +export function hasRequiredPermissionsForOptions(permissions, options) { + const permissionsSet = new Set(permissions.permissions); + + if (!permissionsSet.has('nativeMessaging') && (options.parsing.enableMecabParser || options.general.enableYomitanApi)) { + return false; + } + + if (!permissionsSet.has('clipboardRead')) { + if (options.clipboard.enableBackgroundMonitor || options.clipboard.enableSearchPageMonitor) { + return false; + } + const fieldsList = options.anki.cardFormats.map((cardFormat) => cardFormat.fields); + + for (const fields of fieldsList) { + for (const {value: fieldValue} of Object.values(fields)) { + const markers = getFieldMarkers(fieldValue); + for (const marker of markers) { + if (ankiFieldMarkerMayUseClipboard(marker)) { + return false; + } + } + } + } + } + + return true; +} +PATCH_EOF + + mv "$PERMISSIONS_UTIL.tmp" "$PERMISSIONS_UTIL" + echo " - Patched successfully" +fi + +OPTIONS_SCHEMA="$YOMITAN_DIR/data/schemas/options-schema.json" + +if [ ! -f "$OPTIONS_SCHEMA" ]; then + echo "Error: options-schema.json not found at $OPTIONS_SCHEMA" + exit 1 +fi + +echo "Patching options-schema.json..." + +if grep -q '"selectText".*"default": true' "$OPTIONS_SCHEMA"; then + sed -i '/"selectText": {/,/"default":/{s/"default": true/"default": false/}' "$OPTIONS_SCHEMA" + echo " - Changed selectText default to false" +elif grep -q '"selectText".*"default": false' "$OPTIONS_SCHEMA"; then + echo " - selectText already set to false, skipping" +else + echo " - Warning: Could not find selectText setting" +fi + +if grep -q '"layoutAwareScan".*"default": true' "$OPTIONS_SCHEMA"; then + sed -i '/"layoutAwareScan": {/,/"default":/{s/"default": true/"default": false/}' "$OPTIONS_SCHEMA" + echo " - Changed layoutAwareScan default to false" +elif grep -q '"layoutAwareScan".*"default": false' "$OPTIONS_SCHEMA"; then + echo " - layoutAwareScan already set to false, skipping" +else + echo " - Warning: Could not find layoutAwareScan setting" +fi + +POPUP_JS="$YOMITAN_DIR/js/app/popup.js" + +if [ ! -f "$POPUP_JS" ]; then + echo "Error: popup.js not found at $POPUP_JS" + exit 1 +fi + +echo "Patching popup.js..." + +if grep -q "yomitan-popup-shown" "$POPUP_JS"; then + echo " - Already patched, skipping" +else + # Add the visibility event dispatch after the existing _onVisibleChange code + # We need to add it after: void this._invokeSafe('displayVisibilityChanged', {value}); + sed -i "/void this._invokeSafe('displayVisibilityChanged', {value});/a\\ +\\ + // Dispatch custom events for popup visibility (Electron integration)\\ + if (value) {\\ + window.dispatchEvent(new CustomEvent('yomitan-popup-shown'));\\ + } else {\\ + window.dispatchEvent(new CustomEvent('yomitan-popup-hidden'));\\ + }" "$POPUP_JS" + echo " - Added visibility events" +fi + +echo "" +echo "Yomitan patching complete!" +echo "" +echo "Changes applied:" +echo " 1. permissions-util.js: Hardcoded permissions (Electron workaround)" +echo " 2. options-schema.json: selectText=false, layoutAwareScan=false" +echo " 3. popup.js: Added yomitan-popup-shown/hidden events" +echo "" +echo "To verify: Run 'pnpm start --dev' and check for 'Yomitan extension loaded successfully'" diff --git a/src/anki-connect.ts b/src/anki-connect.ts new file mode 100644 index 0000000..2706a3c --- /dev/null +++ b/src/anki-connect.ts @@ -0,0 +1,228 @@ +/* + * SubMiner - Subtitle mining overlay for mpv + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +import axios, { AxiosInstance } from "axios"; +import http from "http"; +import https from "https"; +import { createLogger } from "./logger"; + +const log = createLogger("anki"); + +interface AnkiConnectRequest { + action: string; + version: number; + params: Record; +} + +interface AnkiConnectResponse { + result: unknown; + error: string | null; +} + +export class AnkiConnectClient { + private client: AxiosInstance; + private url: string; + private backoffMs = 200; + private maxBackoffMs = 5000; + private consecutiveFailures = 0; + private maxConsecutiveFailures = 5; + + constructor(url: string) { + this.url = url; + + const httpAgent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 1000, + maxSockets: 5, + maxFreeSockets: 2, + timeout: 10000, + }); + + const httpsAgent = new https.Agent({ + keepAlive: true, + keepAliveMsecs: 1000, + maxSockets: 5, + maxFreeSockets: 2, + timeout: 10000, + }); + + this.client = axios.create({ + baseURL: url, + timeout: 10000, + httpAgent, + httpsAgent, + }); + } + + private async sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); + } + + private isRetryableError(error: unknown): boolean { + if (!error || typeof error !== "object") return false; + + const code = (error as Record).code; + const message = + typeof (error as Record).message === "string" + ? ((error as Record).message as string).toLowerCase() + : ""; + + return ( + code === "ECONNRESET" || + code === "ETIMEDOUT" || + code === "ENOTFOUND" || + code === "ECONNREFUSED" || + code === "EPIPE" || + message.includes("socket hang up") || + message.includes("network error") || + message.includes("timeout") + ); + } + + async invoke( + action: string, + params: Record = {}, + options: { timeout?: number; maxRetries?: number } = {}, + ): Promise { + const maxRetries = options.maxRetries ?? 3; + let lastError: Error | null = null; + + const isMediaUpload = action === "storeMediaFile"; + const requestTimeout = options.timeout || (isMediaUpload ? 30000 : 10000); + + for (let attempt = 0; attempt <= maxRetries; attempt++) { + try { + if (attempt > 0) { + const delay = Math.min( + this.backoffMs * Math.pow(2, attempt - 1), + this.maxBackoffMs, + ); + log.info( + `AnkiConnect retry ${attempt}/${maxRetries} after ${delay}ms delay`, + ); + await this.sleep(delay); + } + + const response = await this.client.post( + "", + { + action, + version: 6, + params, + } as AnkiConnectRequest, + { + timeout: requestTimeout, + }, + ); + + this.consecutiveFailures = 0; + this.backoffMs = 200; + + if (response.data.error) { + throw new Error(response.data.error); + } + + return response.data.result; + } catch (error) { + lastError = error as Error; + this.consecutiveFailures++; + + if (!this.isRetryableError(error) || attempt === maxRetries) { + if (this.consecutiveFailures < this.maxConsecutiveFailures) { + log.error( + `AnkiConnect error (attempt ${this.consecutiveFailures}/${this.maxConsecutiveFailures}):`, + lastError.message, + ); + } else if (this.consecutiveFailures === this.maxConsecutiveFailures) { + log.error( + "AnkiConnect: Too many consecutive failures, suppressing further error logs", + ); + } + throw lastError; + } + } + } + + throw lastError || new Error("Unknown error"); + } + + async findNotes( + query: string, + options?: { maxRetries?: number }, + ): Promise { + const result = await this.invoke("findNotes", { query }, options); + return (result as number[]) || []; + } + + async notesInfo(noteIds: number[]): Promise[]> { + const result = await this.invoke("notesInfo", { notes: noteIds }); + return (result as Record[]) || []; + } + + async updateNoteFields( + noteId: number, + fields: Record, + ): Promise { + await this.invoke("updateNoteFields", { + note: { + id: noteId, + fields, + }, + }); + } + + async storeMediaFile(filename: string, data: Buffer): Promise { + const base64Data = data.toString("base64"); + const sizeKB = Math.round(base64Data.length / 1024); + log.info(`Uploading media file: ${filename} (${sizeKB}KB)`); + + await this.invoke( + "storeMediaFile", + { + filename, + data: base64Data, + }, + { timeout: 30000 }, + ); + } + + async addNote( + deckName: string, + modelName: string, + fields: Record, + ): Promise { + const result = await this.invoke("addNote", { + note: { deckName, modelName, fields }, + }); + return result as number; + } + + async deleteNotes(noteIds: number[]): Promise { + await this.invoke("deleteNotes", { notes: noteIds }); + } + + async retrieveMediaFile(filename: string): Promise { + const result = await this.invoke("retrieveMediaFile", { filename }); + return (result as string) || ""; + } + + resetBackoff(): void { + this.backoffMs = 200; + this.consecutiveFailures = 0; + } +} diff --git a/src/anki-integration.ts b/src/anki-integration.ts new file mode 100644 index 0000000..b7b578d --- /dev/null +++ b/src/anki-integration.ts @@ -0,0 +1,2679 @@ +/* + * SubMiner - Subtitle mining overlay for mpv + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +import { AnkiConnectClient } from "./anki-connect"; +import { SubtitleTimingTracker } from "./subtitle-timing-tracker"; +import { MediaGenerator } from "./media-generator"; +import * as path from "path"; +import axios from "axios"; +import { + AnkiConnectConfig, + KikuDuplicateCardInfo, + KikuFieldGroupingChoice, + KikuMergePreviewResponse, + MpvClient, + NotificationOptions, +} from "./types"; +import { DEFAULT_ANKI_CONNECT_CONFIG } from "./config"; +import { createLogger } from "./logger"; + +const log = createLogger("anki").child("integration"); + +interface NoteInfo { + noteId: number; + fields: Record; +} + +type CardKind = "sentence" | "audio"; + +export class AnkiIntegration { + private client: AnkiConnectClient; + private mediaGenerator: MediaGenerator; + private timingTracker: SubtitleTimingTracker; + private config: AnkiConnectConfig; + private pollingInterval: ReturnType | null = null; + private previousNoteIds = new Set(); + private initialized = false; + private backoffMs = 200; + private maxBackoffMs = 5000; + private nextPollTime = 0; + private mpvClient: MpvClient; + private osdCallback: ((text: string) => void) | null = null; + private notificationCallback: + | ((title: string, options: NotificationOptions) => void) + | null = null; + private updateInProgress = false; + private progressDepth = 0; + private progressTimer: ReturnType | null = null; + private progressMessage = ""; + private progressFrame = 0; + private parseWarningKeys = new Set(); + private readonly strictGroupingFieldDefaults = new Set([ + "picture", + "sentence", + "sentenceaudio", + "sentencefurigana", + "miscinfo", + ]); + private fieldGroupingCallback: + | ((data: { + original: KikuDuplicateCardInfo; + duplicate: KikuDuplicateCardInfo; + }) => Promise) + | null = null; + + constructor( + config: AnkiConnectConfig, + timingTracker: SubtitleTimingTracker, + mpvClient: MpvClient, + osdCallback?: (text: string) => void, + notificationCallback?: ( + title: string, + options: NotificationOptions, + ) => void, + fieldGroupingCallback?: (data: { + original: KikuDuplicateCardInfo; + duplicate: KikuDuplicateCardInfo; + }) => Promise, + ) { + this.config = { + ...DEFAULT_ANKI_CONNECT_CONFIG, + ...config, + fields: { + ...DEFAULT_ANKI_CONNECT_CONFIG.fields, + ...(config.fields ?? {}), + }, + ai: { + ...DEFAULT_ANKI_CONNECT_CONFIG.ai, + ...(config.openRouter ?? {}), + ...(config.ai ?? {}), + }, + media: { + ...DEFAULT_ANKI_CONNECT_CONFIG.media, + ...(config.media ?? {}), + }, + behavior: { + ...DEFAULT_ANKI_CONNECT_CONFIG.behavior, + ...(config.behavior ?? {}), + }, + metadata: { + ...DEFAULT_ANKI_CONNECT_CONFIG.metadata, + ...(config.metadata ?? {}), + }, + isLapis: { + ...DEFAULT_ANKI_CONNECT_CONFIG.isLapis, + ...(config.isLapis ?? {}), + }, + isKiku: { + ...DEFAULT_ANKI_CONNECT_CONFIG.isKiku, + ...(config.isKiku ?? {}), + }, + } as AnkiConnectConfig; + + this.client = new AnkiConnectClient(this.config.url!); + this.mediaGenerator = new MediaGenerator(); + this.timingTracker = timingTracker; + this.mpvClient = mpvClient; + this.osdCallback = osdCallback || null; + this.notificationCallback = notificationCallback || null; + this.fieldGroupingCallback = fieldGroupingCallback || null; + } + + private extractAiText(content: unknown): string { + if (typeof content === "string") { + return content.trim(); + } + if (!Array.isArray(content)) { + return ""; + } + const parts: string[] = []; + for (const item of content) { + if ( + item && + typeof item === "object" && + "type" in item && + (item as { type?: unknown }).type === "text" && + "text" in item && + typeof (item as { text?: unknown }).text === "string" + ) { + parts.push((item as { text: string }).text); + } + } + return parts.join("").trim(); + } + + private normalizeOpenAiBaseUrl(baseUrl: string): string { + const trimmed = baseUrl.trim().replace(/\/+$/, ""); + if (/\/v1$/i.test(trimmed)) { + return trimmed; + } + return `${trimmed}/v1`; + } + + private async translateSentenceWithAi( + sentence: string, + ): Promise { + const ai = this.config.ai ?? DEFAULT_ANKI_CONNECT_CONFIG.ai; + if (!ai) { + return null; + } + const apiKey = ai?.apiKey?.trim(); + if (!apiKey) { + return null; + } + + const baseUrl = this.normalizeOpenAiBaseUrl( + ai.baseUrl || "https://openrouter.ai/api", + ); + const model = ai.model || "openai/gpt-4o-mini"; + const targetLanguage = ai.targetLanguage || "English"; + const defaultSystemPrompt = + "You are a translation engine. Return only the translated text with no explanations."; + const systemPrompt = ai.systemPrompt?.trim() || defaultSystemPrompt; + + try { + const response = await axios.post( + `${baseUrl}/chat/completions`, + { + model, + temperature: 0, + messages: [ + { role: "system", content: systemPrompt }, + { + role: "user", + content: `Translate this text to ${targetLanguage}:\n\n${sentence}`, + }, + ], + }, + { + headers: { + Authorization: `Bearer ${apiKey}`, + "Content-Type": "application/json", + }, + timeout: 15000, + }, + ); + const content = (response.data as { choices?: unknown[] })?.choices?.[0] as + | { message?: { content?: unknown } } + | undefined; + const translated = this.extractAiText(content?.message?.content); + return translated || null; + } catch (error) { + const message = + error instanceof Error ? error.message : "Unknown translation error"; + log.warn("AI translation failed:", message); + return null; + } + } + + private getLapisConfig(): { + enabled: boolean; + sentenceCardModel?: string; + sentenceCardSentenceField?: string; + sentenceCardAudioField?: string; + } { + const lapis = this.config.isLapis; + return { + enabled: lapis?.enabled === true, + sentenceCardModel: lapis?.sentenceCardModel, + sentenceCardSentenceField: lapis?.sentenceCardSentenceField, + sentenceCardAudioField: lapis?.sentenceCardAudioField, + }; + } + + private getKikuConfig(): { + enabled: boolean; + fieldGrouping?: "auto" | "manual" | "disabled"; + deleteDuplicateInAuto?: boolean; + } { + const kiku = this.config.isKiku; + return { + enabled: kiku?.enabled === true, + fieldGrouping: kiku?.fieldGrouping, + deleteDuplicateInAuto: kiku?.deleteDuplicateInAuto, + }; + } + + private getEffectiveSentenceCardConfig(): { + model?: string; + sentenceField: string; + audioField: string; + lapisEnabled: boolean; + kikuEnabled: boolean; + kikuFieldGrouping: "auto" | "manual" | "disabled"; + kikuDeleteDuplicateInAuto: boolean; + } { + const lapis = this.getLapisConfig(); + const kiku = this.getKikuConfig(); + + return { + model: lapis.sentenceCardModel, + sentenceField: lapis.sentenceCardSentenceField || "Sentence", + audioField: lapis.sentenceCardAudioField || "SentenceAudio", + lapisEnabled: lapis.enabled, + kikuEnabled: kiku.enabled, + kikuFieldGrouping: (kiku.fieldGrouping || "disabled") as + | "auto" + | "manual" + | "disabled", + kikuDeleteDuplicateInAuto: kiku.deleteDuplicateInAuto !== false, + }; + } + + start(): void { + if (this.pollingInterval) { + this.stop(); + } + + log.info( + "Starting AnkiConnect integration with polling rate:", + this.config.pollingRate, + ); + this.poll(); + } + + stop(): void { + if (this.pollingInterval) { + clearInterval(this.pollingInterval); + this.pollingInterval = null; + } + log.info("Stopped AnkiConnect integration"); + } + + private poll(): void { + this.pollOnce(); + this.pollingInterval = setInterval(() => { + this.pollOnce(); + }, this.config.pollingRate); + } + + private async pollOnce(): Promise { + if (this.updateInProgress) return; + if (Date.now() < this.nextPollTime) return; + + this.updateInProgress = true; + try { + const query = this.config.deck + ? `"deck:${this.config.deck}" added:1` + : "added:1"; + const noteIds = (await this.client.findNotes(query, { + maxRetries: 0, + })) as number[]; + const currentNoteIds = new Set(noteIds); + + if (!this.initialized) { + this.previousNoteIds = currentNoteIds; + this.initialized = true; + log.info( + `AnkiConnect initialized with ${currentNoteIds.size} existing cards`, + ); + this.backoffMs = 200; + return; + } + + const newNoteIds = Array.from(currentNoteIds).filter( + (id) => !this.previousNoteIds.has(id), + ); + + if (newNoteIds.length > 0) { + log.info("Found new cards:", newNoteIds); + + for (const noteId of newNoteIds) { + this.previousNoteIds.add(noteId); + } + + if (this.config.behavior?.autoUpdateNewCards !== false) { + for (const noteId of newNoteIds) { + await this.processNewCard(noteId); + } + } else { + log.info( + "New card detected (auto-update disabled). Press Ctrl+V to update from clipboard.", + ); + } + } + + if (this.backoffMs > 200) { + log.info("AnkiConnect connection restored"); + } + this.backoffMs = 200; + } catch (error) { + const wasBackingOff = this.backoffMs > 200; + this.backoffMs = Math.min(this.backoffMs * 2, this.maxBackoffMs); + this.nextPollTime = Date.now() + this.backoffMs; + if (!wasBackingOff) { + log.warn("AnkiConnect polling failed, backing off..."); + this.showStatusNotification("AnkiConnect: unable to connect"); + } + } finally { + this.updateInProgress = false; + } + } + + private async processNewCard( + noteId: number, + options?: { skipKikuFieldGrouping?: boolean }, + ): Promise { + this.beginUpdateProgress("Updating card"); + try { + const notesInfoResult = await this.client.notesInfo([noteId]); + const notesInfo = notesInfoResult as unknown as NoteInfo[]; + if (!notesInfo || notesInfo.length === 0) { + log.warn("Card not found:", noteId); + return; + } + + const noteInfo = notesInfo[0]; + const fields = this.extractFields(noteInfo.fields); + + const expressionText = fields.expression || fields.word || ""; + if (!expressionText) { + log.warn("No expression/word field found in card:", noteId); + return; + } + + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + if ( + !options?.skipKikuFieldGrouping && + sentenceCardConfig.kikuEnabled && + sentenceCardConfig.kikuFieldGrouping !== "disabled" + ) { + const duplicateNoteId = await this.findDuplicateNote( + expressionText, + noteId, + noteInfo, + ); + if (duplicateNoteId !== null) { + if (sentenceCardConfig.kikuFieldGrouping === "auto") { + await this.handleFieldGroupingAuto( + duplicateNoteId, + noteId, + noteInfo, + expressionText, + ); + return; + } else if (sentenceCardConfig.kikuFieldGrouping === "manual") { + const handled = await this.handleFieldGroupingManual( + duplicateNoteId, + noteId, + noteInfo, + expressionText, + ); + if (handled) return; + } + } + } + + const updatedFields: Record = {}; + let updatePerformed = false; + let miscInfoFilename: string | null = null; + const sentenceField = sentenceCardConfig.sentenceField; + + if (sentenceField && this.mpvClient.currentSubText) { + const processedSentence = this.processSentence( + this.mpvClient.currentSubText, + fields, + ); + updatedFields[sentenceField] = processedSentence; + updatePerformed = true; + } + + if (this.config.media?.generateAudio && this.mpvClient) { + try { + const audioFilename = this.generateAudioFilename(); + const audioBuffer = await this.generateAudio(); + + if (audioBuffer) { + await this.client.storeMediaFile(audioFilename, audioBuffer); + const sentenceAudioField = + this.getResolvedSentenceAudioFieldName(noteInfo); + if (sentenceAudioField) { + const existingAudio = + noteInfo.fields[sentenceAudioField]?.value || ""; + updatedFields[sentenceAudioField] = this.mergeFieldValue( + existingAudio, + `[sound:${audioFilename}]`, + this.config.behavior?.overwriteAudio !== false, + ); + } + miscInfoFilename = audioFilename; + updatePerformed = true; + } + } catch (error) { + log.error("Failed to generate audio:", (error as Error).message); + this.showOsdNotification( + `Audio generation failed: ${(error as Error).message}`, + ); + } + } + + let imageBuffer: Buffer | null = null; + if (this.config.media?.generateImage && this.mpvClient) { + try { + const imageFilename = this.generateImageFilename(); + imageBuffer = await this.generateImage(); + + if (imageBuffer) { + await this.client.storeMediaFile(imageFilename, imageBuffer); + const imageFieldName = this.resolveConfiguredFieldName( + noteInfo, + this.config.fields?.image, + DEFAULT_ANKI_CONNECT_CONFIG.fields.image, + ); + if (!imageFieldName) { + log.warn("Image field not found on note, skipping image update"); + } else { + const existingImage = noteInfo.fields[imageFieldName]?.value || ""; + updatedFields[imageFieldName] = this.mergeFieldValue( + existingImage, + ``, + this.config.behavior?.overwriteImage !== false, + ); + miscInfoFilename = imageFilename; + updatePerformed = true; + } + } + } catch (error) { + log.error("Failed to generate image:", (error as Error).message); + this.showOsdNotification( + `Image generation failed: ${(error as Error).message}`, + ); + } + } + + if (this.config.fields?.miscInfo) { + const miscInfo = this.formatMiscInfoPattern( + miscInfoFilename || "", + this.mpvClient.currentSubStart, + ); + const miscInfoField = this.resolveConfiguredFieldName( + noteInfo, + this.config.fields?.miscInfo, + ); + if (miscInfo && miscInfoField) { + updatedFields[miscInfoField] = miscInfo; + updatePerformed = true; + } + } + + if (updatePerformed) { + await this.client.updateNoteFields(noteId, updatedFields); + log.info("Updated card fields for:", expressionText); + await this.showNotification(noteId, expressionText); + } + } catch (error) { + if ((error as Error).message.includes("note was not found")) { + log.warn("Card was deleted before update:", noteId); + } else { + log.error("Error processing new card:", (error as Error).message); + } + } finally { + this.endUpdateProgress(); + } + } + + private extractFields( + fields: Record, + ): Record { + const result: Record = {}; + for (const [key, value] of Object.entries(fields)) { + result[key.toLowerCase()] = value.value || ""; + } + return result; + } + + private processSentence( + mpvSentence: string, + noteFields: Record, + ): string { + if (this.config.behavior?.highlightWord === false) { + return mpvSentence; + } + + const sentenceFieldName = + this.config.fields?.sentence?.toLowerCase() || "sentence"; + const existingSentence = noteFields[sentenceFieldName] || ""; + + const highlightMatch = existingSentence.match(/(.*?)<\/b>/); + if (!highlightMatch || !highlightMatch[1]) { + return mpvSentence; + } + + const highlightedText = highlightMatch[1]; + const index = mpvSentence.indexOf(highlightedText); + + if (index === -1) { + return mpvSentence; + } + + const prefix = mpvSentence.substring(0, index); + const suffix = mpvSentence.substring(index + highlightedText.length); + return `${prefix}${highlightedText}${suffix}`; + } + + private async generateAudio(): Promise { + const mpvClient = this.mpvClient; + if (!mpvClient || !mpvClient.currentVideoPath) { + return null; + } + + const videoPath = mpvClient.currentVideoPath; + let startTime = mpvClient.currentSubStart; + let endTime = mpvClient.currentSubEnd; + + if (startTime === undefined || endTime === undefined) { + const currentTime = mpvClient.currentTimePos || 0; + const fallback = this.getFallbackDurationSeconds() / 2; + startTime = currentTime - fallback; + endTime = currentTime + fallback; + } + + return this.mediaGenerator.generateAudio( + videoPath, + startTime, + endTime, + this.config.media?.audioPadding, + this.mpvClient.currentAudioStreamIndex, + ); + } + + private async generateImage(): Promise { + if (!this.mpvClient || !this.mpvClient.currentVideoPath) { + return null; + } + + const videoPath = this.mpvClient.currentVideoPath; + const timestamp = this.mpvClient.currentTimePos || 0; + + if (this.config.media?.imageType === "avif") { + let startTime = this.mpvClient.currentSubStart; + let endTime = this.mpvClient.currentSubEnd; + + if (startTime === undefined || endTime === undefined) { + const fallback = this.getFallbackDurationSeconds() / 2; + startTime = timestamp - fallback; + endTime = timestamp + fallback; + } + + return this.mediaGenerator.generateAnimatedImage( + videoPath, + startTime, + endTime, + this.config.media?.audioPadding, + { + fps: this.config.media?.animatedFps, + maxWidth: this.config.media?.animatedMaxWidth, + maxHeight: this.config.media?.animatedMaxHeight, + crf: this.config.media?.animatedCrf, + }, + ); + } else { + return this.mediaGenerator.generateScreenshot(videoPath, timestamp, { + format: this.config.media?.imageFormat as "jpg" | "png" | "webp", + quality: this.config.media?.imageQuality, + maxWidth: this.config.media?.imageMaxWidth, + maxHeight: this.config.media?.imageMaxHeight, + }); + } + } + + private formatMiscInfoPattern( + fallbackFilename: string, + startTimeSeconds?: number, + ): string { + if (!this.config.metadata?.pattern) { + return ""; + } + + const currentVideoPath = this.mpvClient.currentVideoPath || ""; + const videoFilename = currentVideoPath + ? path.basename(currentVideoPath) + : ""; + const filenameWithExt = videoFilename || fallbackFilename; + const filenameWithoutExt = filenameWithExt.replace(/\.[^.]+$/, ""); + + const currentTimePos = + typeof startTimeSeconds === "number" && Number.isFinite(startTimeSeconds) + ? startTimeSeconds + : this.mpvClient.currentTimePos; + let totalMilliseconds = 0; + if (Number.isFinite(currentTimePos) && currentTimePos >= 0) { + totalMilliseconds = Math.floor(currentTimePos * 1000); + } else { + const now = new Date(); + totalMilliseconds = + now.getHours() * 3600000 + + now.getMinutes() * 60000 + + now.getSeconds() * 1000 + + now.getMilliseconds(); + } + + const totalSeconds = Math.floor(totalMilliseconds / 1000); + const hours = String(Math.floor(totalSeconds / 3600)).padStart(2, "0"); + const minutes = String(Math.floor((totalSeconds % 3600) / 60)).padStart( + 2, + "0", + ); + const seconds = String(totalSeconds % 60).padStart(2, "0"); + const milliseconds = String(totalMilliseconds % 1000).padStart(3, "0"); + + let result = this.config.metadata?.pattern + .replace(/%f/g, filenameWithoutExt) + .replace(/%F/g, filenameWithExt) + .replace(/%t/g, `${hours}:${minutes}:${seconds}`) + .replace(/%T/g, `${hours}:${minutes}:${seconds}:${milliseconds}`) + .replace(/
/g, "\n"); + + return result; + } + + private getFallbackDurationSeconds(): number { + const configured = this.config.media?.fallbackDuration; + if ( + typeof configured === "number" && + Number.isFinite(configured) && + configured > 0 + ) { + return configured; + } + return DEFAULT_ANKI_CONNECT_CONFIG.media.fallbackDuration; + } + + private generateAudioFilename(): string { + const timestamp = Date.now(); + return `audio_${timestamp}.mp3`; + } + + private generateImageFilename(): string { + const timestamp = Date.now(); + const ext = + this.config.media?.imageType === "avif" ? "avif" : this.config.media?.imageFormat; + return `image_${timestamp}.${ext}`; + } + + private showStatusNotification(message: string): void { + const type = this.config.behavior?.notificationType || "osd"; + + if (type === "osd" || type === "both") { + this.showOsdNotification(message); + } + + if ((type === "system" || type === "both") && this.notificationCallback) { + this.notificationCallback("SubMiner", { body: message }); + } + } + + private beginUpdateProgress(initialMessage: string): void { + this.progressDepth += 1; + if (this.progressDepth > 1) return; + + this.progressMessage = initialMessage; + this.progressFrame = 0; + this.showProgressTick(); + this.progressTimer = setInterval(() => { + this.showProgressTick(); + }, 180); + } + + private endUpdateProgress(): void { + this.progressDepth = Math.max(0, this.progressDepth - 1); + if (this.progressDepth > 0) return; + + if (this.progressTimer) { + clearInterval(this.progressTimer); + this.progressTimer = null; + } + this.progressMessage = ""; + this.progressFrame = 0; + } + + private showProgressTick(): void { + if (!this.progressMessage) return; + const frames = ["|", "/", "-", "\\"]; + const frame = frames[this.progressFrame % frames.length]; + this.progressFrame += 1; + this.showOsdNotification(`${this.progressMessage} ${frame}`); + } + + private async withUpdateProgress( + initialMessage: string, + action: () => Promise, + ): Promise { + this.beginUpdateProgress(initialMessage); + this.updateInProgress = true; + try { + return await action(); + } finally { + this.updateInProgress = false; + this.endUpdateProgress(); + } + } + + private showOsdNotification(text: string): void { + if (this.osdCallback) { + this.osdCallback(text); + } else if (this.mpvClient && this.mpvClient.send) { + this.mpvClient.send({ + command: ["show-text", text, "3000"], + }); + } + } + + private resolveFieldName( + availableFieldNames: string[], + preferredName: string, + ): string | null { + const exact = availableFieldNames.find((name) => name === preferredName); + if (exact) return exact; + + const lower = preferredName.toLowerCase(); + const ci = availableFieldNames.find((name) => name.toLowerCase() === lower); + return ci || null; + } + + private resolveNoteFieldName( + noteInfo: NoteInfo, + preferredName?: string, + ): string | null { + if (!preferredName) return null; + return this.resolveFieldName(Object.keys(noteInfo.fields), preferredName); + } + + private resolveConfiguredFieldName( + noteInfo: NoteInfo, + ...preferredNames: (string | undefined)[] + ): string | null { + for (const preferredName of preferredNames) { + const resolved = this.resolveNoteFieldName(noteInfo, preferredName); + if (resolved) return resolved; + } + return null; + } + + private warnFieldParseOnce( + fieldName: string, + reason: string, + detail?: string, + ): void { + const key = `${fieldName.toLowerCase()}::${reason}`; + if (this.parseWarningKeys.has(key)) return; + this.parseWarningKeys.add(key); + const suffix = detail ? ` (${detail})` : ""; + log.warn( + `Field grouping parse warning [${fieldName}] ${reason}${suffix}`, + ); + } + + private setCardTypeFields( + updatedFields: Record, + availableFieldNames: string[], + cardKind: CardKind, + ): void { + const audioFlagNames = ["IsAudioCard"]; + + if (cardKind === "sentence") { + const sentenceFlag = this.resolveFieldName( + availableFieldNames, + "IsSentenceCard", + ); + if (sentenceFlag) { + updatedFields[sentenceFlag] = "x"; + } + + for (const audioFlagName of audioFlagNames) { + const resolved = this.resolveFieldName( + availableFieldNames, + audioFlagName, + ); + if (resolved && resolved !== sentenceFlag) { + updatedFields[resolved] = ""; + } + } + + const wordAndSentenceFlag = this.resolveFieldName( + availableFieldNames, + "IsWordAndSentenceCard", + ); + if (wordAndSentenceFlag && wordAndSentenceFlag !== sentenceFlag) { + updatedFields[wordAndSentenceFlag] = ""; + } + return; + } + + const resolvedAudioFlags = Array.from( + new Set( + audioFlagNames + .map((name) => this.resolveFieldName(availableFieldNames, name)) + .filter((name): name is string => Boolean(name)), + ), + ); + const audioFlagName = resolvedAudioFlags[0] || null; + if (audioFlagName) { + updatedFields[audioFlagName] = "x"; + } + for (const extraAudioFlag of resolvedAudioFlags.slice(1)) { + updatedFields[extraAudioFlag] = ""; + } + + const sentenceFlag = this.resolveFieldName( + availableFieldNames, + "IsSentenceCard", + ); + if (sentenceFlag && sentenceFlag !== audioFlagName) { + updatedFields[sentenceFlag] = ""; + } + + const wordAndSentenceFlag = this.resolveFieldName( + availableFieldNames, + "IsWordAndSentenceCard", + ); + if (wordAndSentenceFlag && wordAndSentenceFlag !== audioFlagName) { + updatedFields[wordAndSentenceFlag] = ""; + } + } + + private async showNotification( + noteId: number, + label: string | number, + errorSuffix?: string, + ): Promise { + const message = errorSuffix + ? `Updated card: ${label} (${errorSuffix})` + : `Updated card: ${label}`; + + const type = this.config.behavior?.notificationType || "osd"; + + if (type === "osd" || type === "both") { + this.showOsdNotification(message); + } + + if ((type === "system" || type === "both") && this.notificationCallback) { + let notificationIconPath: string | undefined; + + if (this.mpvClient && this.mpvClient.currentVideoPath) { + try { + const timestamp = this.mpvClient.currentTimePos || 0; + const iconBuffer = await this.mediaGenerator.generateNotificationIcon( + this.mpvClient.currentVideoPath, + timestamp, + ); + if (iconBuffer && iconBuffer.length > 0) { + notificationIconPath = + this.mediaGenerator.writeNotificationIconToFile( + iconBuffer, + noteId, + ); + } + } catch (err) { + log.warn( + "Failed to generate notification icon:", + (err as Error).message, + ); + } + } + + this.notificationCallback("Anki Card Updated", { + body: message, + icon: notificationIconPath, + }); + + if (notificationIconPath) { + this.mediaGenerator.scheduleNotificationIconCleanup( + notificationIconPath, + ); + } + } + } + + private mergeFieldValue( + existing: string, + newValue: string, + overwrite: boolean, + ): string { + if (overwrite || !existing.trim()) { + return newValue; + } + if (this.config.behavior?.mediaInsertMode === "prepend") { + return newValue + existing; + } + return existing + newValue; + } + + /** + * Update the last added Anki card using subtitle blocks from clipboard. + * This is the manual update flow (animecards-style) when auto-update is disabled. + */ + async updateLastAddedFromClipboard(clipboardText: string): Promise { + try { + if (!clipboardText || !clipboardText.trim()) { + this.showOsdNotification("Clipboard is empty"); + return; + } + + if (!this.mpvClient || !this.mpvClient.currentVideoPath) { + this.showOsdNotification("No video loaded"); + return; + } + + // Parse clipboard into blocks (separated by blank lines) + const blocks = clipboardText + .split(/\n\s*\n/) + .map((b) => b.trim()) + .filter((b) => b.length > 0); + + if (blocks.length === 0) { + this.showOsdNotification("No subtitle blocks found in clipboard"); + return; + } + + // Lookup timings for each block + const timings: { startTime: number; endTime: number }[] = []; + for (const block of blocks) { + const timing = this.timingTracker.findTiming(block); + if (timing) { + timings.push(timing); + } + } + + if (timings.length === 0) { + this.showOsdNotification( + "Subtitle timing not found; copy again while playing", + ); + return; + } + + // Compute range from all matched timings + const rangeStart = Math.min(...timings.map((t) => t.startTime)); + let rangeEnd = Math.max(...timings.map((t) => t.endTime)); + + const maxMediaDuration = this.config.media?.maxMediaDuration ?? 30; + if (maxMediaDuration > 0 && rangeEnd - rangeStart > maxMediaDuration) { + log.warn( + `Media range ${(rangeEnd - rangeStart).toFixed(1)}s exceeds cap of ${maxMediaDuration}s, clamping`, + ); + rangeEnd = rangeStart + maxMediaDuration; + } + + this.showOsdNotification("Updating card from clipboard..."); + this.beginUpdateProgress("Updating card from clipboard"); + this.updateInProgress = true; + + try { + // Get last added note + const query = this.config.deck + ? `"deck:${this.config.deck}" added:1` + : "added:1"; + const noteIds = (await this.client.findNotes(query)) as number[]; + if (!noteIds || noteIds.length === 0) { + this.showOsdNotification("No recently added cards found"); + return; + } + + // Get max note ID (most recent) + const noteId = Math.max(...noteIds); + + // Get note info for expression + const notesInfoResult = await this.client.notesInfo([noteId]); + const notesInfo = notesInfoResult as unknown as NoteInfo[]; + if (!notesInfo || notesInfo.length === 0) { + this.showOsdNotification("Card not found"); + return; + } + + const noteInfo = notesInfo[0]; + const fields = this.extractFields(noteInfo.fields); + const expressionText = fields.expression || fields.word || ""; + const sentenceAudioField = + this.getResolvedSentenceAudioFieldName(noteInfo); + const sentenceField = + this.getEffectiveSentenceCardConfig().sentenceField; + + // Build sentence from blocks (join with spaces between blocks) + const sentence = blocks.join(" "); + const updatedFields: Record = {}; + let updatePerformed = false; + const errors: string[] = []; + let miscInfoFilename: string | null = null; + + // Add sentence field + if (sentenceField) { + const processedSentence = this.processSentence(sentence, fields); + updatedFields[sentenceField] = processedSentence; + updatePerformed = true; + } + + log.info( + `Clipboard update: timing range ${rangeStart.toFixed(2)}s - ${rangeEnd.toFixed(2)}s`, + ); + + // Generate and upload audio + if (this.config.media?.generateAudio) { + try { + const audioFilename = this.generateAudioFilename(); + const audioBuffer = await this.mediaGenerator.generateAudio( + this.mpvClient.currentVideoPath, + rangeStart, + rangeEnd, + this.config.media?.audioPadding, + this.mpvClient.currentAudioStreamIndex, + ); + + if (audioBuffer) { + await this.client.storeMediaFile(audioFilename, audioBuffer); + if (sentenceAudioField) { + const existingAudio = + noteInfo.fields[sentenceAudioField]?.value || ""; + updatedFields[sentenceAudioField] = this.mergeFieldValue( + existingAudio, + `[sound:${audioFilename}]`, + this.config.behavior?.overwriteAudio !== false, + ); + } + miscInfoFilename = audioFilename; + updatePerformed = true; + } + } catch (error) { + log.error( + "Failed to generate audio:", + (error as Error).message, + ); + errors.push("audio"); + } + } + + // Generate and upload image + if (this.config.media?.generateImage) { + try { + const imageFilename = this.generateImageFilename(); + let imageBuffer: Buffer | null = null; + + if (this.config.media?.imageType === "avif") { + imageBuffer = await this.mediaGenerator.generateAnimatedImage( + this.mpvClient.currentVideoPath, + rangeStart, + rangeEnd, + this.config.media?.audioPadding, + { + fps: this.config.media?.animatedFps, + maxWidth: this.config.media?.animatedMaxWidth, + maxHeight: this.config.media?.animatedMaxHeight, + crf: this.config.media?.animatedCrf, + }, + ); + } else { + const timestamp = this.mpvClient.currentTimePos || 0; + imageBuffer = await this.mediaGenerator.generateScreenshot( + this.mpvClient.currentVideoPath, + timestamp, + { + format: this.config.media?.imageFormat as "jpg" | "png" | "webp", + quality: this.config.media?.imageQuality, + maxWidth: this.config.media?.imageMaxWidth, + maxHeight: this.config.media?.imageMaxHeight, + }, + ); + } + + if (imageBuffer) { + await this.client.storeMediaFile(imageFilename, imageBuffer); + const imageFieldName = this.resolveConfiguredFieldName( + noteInfo, + this.config.fields?.image, + DEFAULT_ANKI_CONNECT_CONFIG.fields.image, + ); + if (!imageFieldName) { + log.warn("Image field not found on note, skipping image update"); + } else { + const existingImage = noteInfo.fields[imageFieldName]?.value || ""; + updatedFields[imageFieldName] = this.mergeFieldValue( + existingImage, + ``, + this.config.behavior?.overwriteImage !== false, + ); + miscInfoFilename = imageFilename; + updatePerformed = true; + } + } + } catch (error) { + log.error( + "Failed to generate image:", + (error as Error).message, + ); + errors.push("image"); + } + } + + if (this.config.fields?.miscInfo) { + const miscInfo = this.formatMiscInfoPattern( + miscInfoFilename || "", + rangeStart, + ); + const miscInfoField = this.resolveConfiguredFieldName( + noteInfo, + this.config.fields?.miscInfo, + ); + if (miscInfo && miscInfoField) { + updatedFields[miscInfoField] = miscInfo; + updatePerformed = true; + } + } + + if (updatePerformed) { + await this.client.updateNoteFields(noteId, updatedFields); + const label = expressionText || noteId; + log.info("Updated card from clipboard:", label); + const errorSuffix = + errors.length > 0 ? `${errors.join(", ")} failed` : undefined; + await this.showNotification(noteId, label, errorSuffix); + } + } finally { + this.updateInProgress = false; + this.endUpdateProgress(); + } + } catch (error) { + log.error( + "Error updating card from clipboard:", + (error as Error).message, + ); + this.showOsdNotification(`Update failed: ${(error as Error).message}`); + } + } + + async triggerFieldGroupingForLastAddedCard(): Promise { + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + if (!sentenceCardConfig.kikuEnabled) { + this.showOsdNotification("Kiku mode is not enabled"); + return; + } + if (sentenceCardConfig.kikuFieldGrouping === "disabled") { + this.showOsdNotification("Kiku field grouping is disabled"); + return; + } + + if (this.updateInProgress) { + this.showOsdNotification("Anki update already in progress"); + return; + } + + try { + await this.withUpdateProgress("Grouping duplicate cards", async () => { + const query = this.config.deck + ? `"deck:${this.config.deck}" added:1` + : "added:1"; + const noteIds = (await this.client.findNotes(query)) as number[]; + if (!noteIds || noteIds.length === 0) { + this.showOsdNotification("No recently added cards found"); + return; + } + + const noteId = Math.max(...noteIds); + const notesInfoResult = await this.client.notesInfo([noteId]); + const notesInfo = notesInfoResult as unknown as NoteInfo[]; + if (!notesInfo || notesInfo.length === 0) { + this.showOsdNotification("Card not found"); + return; + } + const noteInfoBeforeUpdate = notesInfo[0]; + const fields = this.extractFields(noteInfoBeforeUpdate.fields); + const expressionText = fields.expression || fields.word || ""; + if (!expressionText) { + this.showOsdNotification("No expression/word field found"); + return; + } + + const duplicateNoteId = await this.findDuplicateNote( + expressionText, + noteId, + noteInfoBeforeUpdate, + ); + if (duplicateNoteId === null) { + this.showOsdNotification("No duplicate card found"); + return; + } + + // Only do card update work when we already know a merge candidate exists. + if ( + !this.hasAllConfiguredFields(noteInfoBeforeUpdate, [ + this.config.fields?.image, + ]) + ) { + await this.processNewCard(noteId, { skipKikuFieldGrouping: true }); + } + + const refreshedInfoResult = await this.client.notesInfo([noteId]); + const refreshedInfo = refreshedInfoResult as unknown as NoteInfo[]; + if (!refreshedInfo || refreshedInfo.length === 0) { + this.showOsdNotification("Card not found"); + return; + } + + const noteInfo = refreshedInfo[0]; + + if (sentenceCardConfig.kikuFieldGrouping === "auto") { + await this.handleFieldGroupingAuto( + duplicateNoteId, + noteId, + noteInfo, + expressionText, + ); + return; + } + const handled = await this.handleFieldGroupingManual( + duplicateNoteId, + noteId, + noteInfo, + expressionText, + ); + if (!handled) { + this.showOsdNotification("Field grouping cancelled"); + } + }); + } catch (error) { + log.error( + "Error triggering field grouping:", + (error as Error).message, + ); + this.showOsdNotification( + `Field grouping failed: ${(error as Error).message}`, + ); + } + } + + async markLastCardAsAudioCard(): Promise { + if (this.updateInProgress) { + this.showOsdNotification("Anki update already in progress"); + return; + } + + try { + if (!this.mpvClient || !this.mpvClient.currentVideoPath) { + this.showOsdNotification("No video loaded"); + return; + } + + if (!this.mpvClient.currentSubText) { + this.showOsdNotification("No current subtitle"); + return; + } + + let startTime = this.mpvClient.currentSubStart; + let endTime = this.mpvClient.currentSubEnd; + + if (startTime === undefined || endTime === undefined) { + const currentTime = this.mpvClient.currentTimePos || 0; + const fallback = this.getFallbackDurationSeconds() / 2; + startTime = currentTime - fallback; + endTime = currentTime + fallback; + } + + const maxMediaDuration = this.config.media?.maxMediaDuration ?? 30; + if (maxMediaDuration > 0 && endTime - startTime > maxMediaDuration) { + endTime = startTime + maxMediaDuration; + } + + this.showOsdNotification("Marking card as audio card..."); + await this.withUpdateProgress("Marking audio card", async () => { + const query = this.config.deck + ? `"deck:${this.config.deck}" added:1` + : "added:1"; + const noteIds = (await this.client.findNotes(query)) as number[]; + if (!noteIds || noteIds.length === 0) { + this.showOsdNotification("No recently added cards found"); + return; + } + + const noteId = Math.max(...noteIds); + + const notesInfoResult = await this.client.notesInfo([noteId]); + const notesInfo = notesInfoResult as unknown as NoteInfo[]; + if (!notesInfo || notesInfo.length === 0) { + this.showOsdNotification("Card not found"); + return; + } + + const noteInfo = notesInfo[0]; + const fields = this.extractFields(noteInfo.fields); + const expressionText = fields.expression || fields.word || ""; + + const updatedFields: Record = {}; + const errors: string[] = []; + let miscInfoFilename: string | null = null; + + this.setCardTypeFields( + updatedFields, + Object.keys(noteInfo.fields), + "audio", + ); + + if (this.config.fields?.sentence) { + const processedSentence = this.processSentence( + this.mpvClient.currentSubText, + fields, + ); + updatedFields[this.config.fields?.sentence] = processedSentence; + } + + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + const audioFieldName = sentenceCardConfig.audioField; + try { + const audioFilename = this.generateAudioFilename(); + const audioBuffer = await this.mediaGenerator.generateAudio( + this.mpvClient.currentVideoPath, + startTime, + endTime, + this.config.media?.audioPadding, + this.mpvClient.currentAudioStreamIndex, + ); + + if (audioBuffer) { + await this.client.storeMediaFile(audioFilename, audioBuffer); + updatedFields[audioFieldName] = `[sound:${audioFilename}]`; + miscInfoFilename = audioFilename; + } + } catch (error) { + log.error( + "Failed to generate audio for audio card:", + (error as Error).message, + ); + errors.push("audio"); + } + + if (this.config.media?.generateImage) { + try { + const imageFilename = this.generateImageFilename(); + let imageBuffer: Buffer | null = null; + + if (this.config.media?.imageType === "avif") { + imageBuffer = await this.mediaGenerator.generateAnimatedImage( + this.mpvClient.currentVideoPath, + startTime, + endTime, + this.config.media?.audioPadding, + { + fps: this.config.media?.animatedFps, + maxWidth: this.config.media?.animatedMaxWidth, + maxHeight: this.config.media?.animatedMaxHeight, + crf: this.config.media?.animatedCrf, + }, + ); + } else { + const timestamp = this.mpvClient.currentTimePos || 0; + imageBuffer = await this.mediaGenerator.generateScreenshot( + this.mpvClient.currentVideoPath, + timestamp, + { + format: this.config.media?.imageFormat as "jpg" | "png" | "webp", + quality: this.config.media?.imageQuality, + maxWidth: this.config.media?.imageMaxWidth, + maxHeight: this.config.media?.imageMaxHeight, + }, + ); + } + + if (imageBuffer && this.config.fields?.image) { + await this.client.storeMediaFile(imageFilename, imageBuffer); + updatedFields[this.config.fields?.image] = + ``; + miscInfoFilename = imageFilename; + } + } catch (error) { + log.error( + "Failed to generate image for audio card:", + (error as Error).message, + ); + errors.push("image"); + } + } + + if (this.config.fields?.miscInfo) { + const miscInfo = this.formatMiscInfoPattern( + miscInfoFilename || "", + startTime, + ); + const miscInfoField = this.resolveConfiguredFieldName( + noteInfo, + this.config.fields?.miscInfo, + ); + if (miscInfo && miscInfoField) { + updatedFields[miscInfoField] = miscInfo; + } + } + + await this.client.updateNoteFields(noteId, updatedFields); + const label = expressionText || noteId; + log.info("Marked card as audio card:", label); + const errorSuffix = + errors.length > 0 ? `${errors.join(", ")} failed` : undefined; + await this.showNotification(noteId, label, errorSuffix); + }); + } catch (error) { + log.error( + "Error marking card as audio card:", + (error as Error).message, + ); + this.showOsdNotification( + `Audio card failed: ${(error as Error).message}`, + ); + } + } + + async createSentenceCard( + sentence: string, + startTime: number, + endTime: number, + secondarySubText?: string, + ): Promise { + if (this.updateInProgress) { + this.showOsdNotification("Anki update already in progress"); + return; + } + + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + const sentenceCardModel = sentenceCardConfig.model; + if (!sentenceCardModel) { + this.showOsdNotification("sentenceCardModel not configured"); + return; + } + + if (!this.mpvClient || !this.mpvClient.currentVideoPath) { + this.showOsdNotification("No video loaded"); + return; + } + + const maxMediaDuration = this.config.media?.maxMediaDuration ?? 30; + if (maxMediaDuration > 0 && endTime - startTime > maxMediaDuration) { + log.warn( + `Sentence card media range ${(endTime - startTime).toFixed(1)}s exceeds cap of ${maxMediaDuration}s, clamping`, + ); + endTime = startTime + maxMediaDuration; + } + + this.showOsdNotification("Creating sentence card..."); + await this.withUpdateProgress("Creating sentence card", async () => { + const videoPath = this.mpvClient.currentVideoPath; + const fields: Record = {}; + const errors: string[] = []; + let miscInfoFilename: string | null = null; + + const sentenceField = sentenceCardConfig.sentenceField; + const audioFieldName = sentenceCardConfig.audioField || "SentenceAudio"; + const translationField = this.config.fields?.translation || "SelectionText"; + let resolvedMiscInfoField: string | null = null; + let resolvedSentenceAudioField: string = audioFieldName; + let resolvedExpressionAudioField: string | null = null; + + fields[sentenceField] = sentence; + + const hasSecondarySub = Boolean(secondarySubText?.trim()); + let backText = secondarySubText?.trim() || ""; + const aiConfig = this.config.ai ?? DEFAULT_ANKI_CONNECT_CONFIG.ai; + const aiEnabled = aiConfig?.enabled === true; + const alwaysUseAiTranslation = + aiConfig?.alwaysUseAiTranslation === true; + const shouldAttemptAiTranslation = + aiEnabled && (alwaysUseAiTranslation || !hasSecondarySub); + if (shouldAttemptAiTranslation) { + const translated = await this.translateSentenceWithAi(sentence); + if (translated) { + backText = translated; + } else if (!hasSecondarySub) { + backText = sentence; + } + } + if (backText) { + fields[translationField] = backText; + } + + if (sentenceCardConfig.lapisEnabled || sentenceCardConfig.kikuEnabled) { + fields["IsSentenceCard"] = "x"; + fields["Expression"] = sentence; + } + + const deck = this.config.deck || "Default"; + let noteId: number; + try { + noteId = await this.client.addNote( + deck, + sentenceCardModel, + fields, + ); + log.info("Created sentence card:", noteId); + this.previousNoteIds.add(noteId); + } catch (error) { + log.error( + "Failed to create sentence card:", + (error as Error).message, + ); + this.showOsdNotification( + `Sentence card failed: ${(error as Error).message}`, + ); + return; + } + + try { + const noteInfoResult = await this.client.notesInfo([noteId]); + const noteInfos = noteInfoResult as unknown as NoteInfo[]; + if (noteInfos.length > 0) { + const createdNoteInfo = noteInfos[0]; + resolvedSentenceAudioField = + this.resolveNoteFieldName(createdNoteInfo, audioFieldName) || + audioFieldName; + resolvedExpressionAudioField = this.resolveConfiguredFieldName( + createdNoteInfo, + this.config.fields?.audio || "ExpressionAudio", + "ExpressionAudio", + ); + resolvedMiscInfoField = this.resolveConfiguredFieldName( + createdNoteInfo, + this.config.fields?.miscInfo, + ); + const cardTypeFields: Record = {}; + this.setCardTypeFields( + cardTypeFields, + Object.keys(createdNoteInfo.fields), + "sentence", + ); + if (Object.keys(cardTypeFields).length > 0) { + await this.client.updateNoteFields(noteId, cardTypeFields); + } + } + } catch (error) { + log.error( + "Failed to normalize sentence card type fields:", + (error as Error).message, + ); + errors.push("card type fields"); + } + + const mediaFields: Record = {}; + + try { + const audioFilename = this.generateAudioFilename(); + const audioBuffer = await this.mediaGenerator.generateAudio( + videoPath, + startTime, + endTime, + this.config.media?.audioPadding, + this.mpvClient.currentAudioStreamIndex, + ); + + if (audioBuffer) { + await this.client.storeMediaFile(audioFilename, audioBuffer); + const audioValue = `[sound:${audioFilename}]`; + mediaFields[resolvedSentenceAudioField] = audioValue; + if ( + resolvedExpressionAudioField && + resolvedExpressionAudioField !== resolvedSentenceAudioField + ) { + mediaFields[resolvedExpressionAudioField] = audioValue; + } + miscInfoFilename = audioFilename; + } + } catch (error) { + log.error( + "Failed to generate sentence audio:", + (error as Error).message, + ); + errors.push("audio"); + } + + try { + const imageFilename = this.generateImageFilename(); + let imageBuffer: Buffer | null = null; + + if (this.config.media?.imageType === "avif") { + imageBuffer = await this.mediaGenerator.generateAnimatedImage( + videoPath, + startTime, + endTime, + this.config.media?.audioPadding, + { + fps: this.config.media?.animatedFps, + maxWidth: this.config.media?.animatedMaxWidth, + maxHeight: this.config.media?.animatedMaxHeight, + crf: this.config.media?.animatedCrf, + }, + ); + } else { + const timestamp = this.mpvClient.currentTimePos || 0; + imageBuffer = await this.mediaGenerator.generateScreenshot( + videoPath, + timestamp, + { + format: this.config.media?.imageFormat as "jpg" | "png" | "webp", + quality: this.config.media?.imageQuality, + maxWidth: this.config.media?.imageMaxWidth, + maxHeight: this.config.media?.imageMaxHeight, + }, + ); + } + + if (imageBuffer && this.config.fields?.image) { + await this.client.storeMediaFile(imageFilename, imageBuffer); + mediaFields[this.config.fields?.image] = ``; + miscInfoFilename = imageFilename; + } + } catch (error) { + log.error( + "Failed to generate sentence image:", + (error as Error).message, + ); + errors.push("image"); + } + + if (this.config.fields?.miscInfo) { + const miscInfo = this.formatMiscInfoPattern( + miscInfoFilename || "", + startTime, + ); + if (miscInfo && resolvedMiscInfoField) { + mediaFields[resolvedMiscInfoField] = miscInfo; + } + } + + if (Object.keys(mediaFields).length > 0) { + try { + await this.client.updateNoteFields(noteId, mediaFields); + } catch (error) { + log.error( + "Failed to update sentence card media:", + (error as Error).message, + ); + errors.push("media update"); + } + } + + const label = + sentence.length > 30 ? sentence.substring(0, 30) + "..." : sentence; + const errorSuffix = + errors.length > 0 ? `${errors.join(", ")} failed` : undefined; + await this.showNotification(noteId, label, errorSuffix); + }); + } + + private async findDuplicateNote( + expression: string, + excludeNoteId: number, + noteInfo: NoteInfo, + ): Promise { + let fieldName = ""; + for (const name of Object.keys(noteInfo.fields)) { + if ( + ["word", "expression"].includes(name.toLowerCase()) && + noteInfo.fields[name].value + ) { + fieldName = name; + break; + } + } + if (!fieldName) return null; + + const escapedFieldName = this.escapeAnkiSearchValue(fieldName); + const escapedExpression = this.escapeAnkiSearchValue(expression); + const deckPrefix = this.config.deck + ? `"deck:${this.escapeAnkiSearchValue(this.config.deck)}" ` + : ""; + const query = `${deckPrefix}"${escapedFieldName}:${escapedExpression}"`; + + try { + const noteIds = (await this.client.findNotes(query)) as number[]; + return await this.findFirstExactDuplicateNoteId( + noteIds, + excludeNoteId, + fieldName, + expression, + ); + } catch (error) { + log.warn("Duplicate search failed:", (error as Error).message); + return null; + } + } + + private escapeAnkiSearchValue(value: string): string { + return value + .replace(/\\/g, "\\\\") + .replace(/"/g, '\\"') + .replace(/([:*?()[\]{}])/g, "\\$1"); + } + + private normalizeDuplicateValue(value: string): string { + return value.replace(/\s+/g, " ").trim(); + } + + private async findFirstExactDuplicateNoteId( + candidateNoteIds: number[], + excludeNoteId: number, + fieldName: string, + expression: string, + ): Promise { + const candidates = candidateNoteIds.filter((id) => id !== excludeNoteId); + if (candidates.length === 0) return null; + + const normalizedExpression = this.normalizeDuplicateValue(expression); + const chunkSize = 50; + for (let i = 0; i < candidates.length; i += chunkSize) { + const chunk = candidates.slice(i, i + chunkSize); + const notesInfoResult = await this.client.notesInfo(chunk); + const notesInfo = notesInfoResult as unknown as NoteInfo[]; + for (const noteInfo of notesInfo) { + const resolvedField = this.resolveNoteFieldName(noteInfo, fieldName); + if (!resolvedField) continue; + const candidateValue = noteInfo.fields[resolvedField]?.value || ""; + if ( + this.normalizeDuplicateValue(candidateValue) === normalizedExpression + ) { + return noteInfo.noteId; + } + } + } + + return null; + } + + private getGroupableFieldNames(): string[] { + const fields: string[] = []; + fields.push("Sentence"); + fields.push("SentenceAudio"); + fields.push("Picture"); + if (this.config.fields?.image) fields.push(this.config.fields?.image); + if (this.config.fields?.sentence) fields.push(this.config.fields?.sentence); + if ( + this.config.fields?.audio && + this.config.fields?.audio.toLowerCase() !== "expressionaudio" + ) { + fields.push(this.config.fields?.audio); + } + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + const sentenceAudioField = sentenceCardConfig.audioField; + if (!fields.includes(sentenceAudioField)) fields.push(sentenceAudioField); + if (this.config.fields?.miscInfo) fields.push(this.config.fields?.miscInfo); + fields.push("SentenceFurigana"); + return fields; + } + + private getPreferredSentenceAudioFieldName(): string { + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + return sentenceCardConfig.audioField || "SentenceAudio"; + } + + private getResolvedSentenceAudioFieldName(noteInfo: NoteInfo): string | null { + return ( + this.resolveNoteFieldName( + noteInfo, + this.getPreferredSentenceAudioFieldName(), + ) || this.resolveConfiguredFieldName(noteInfo, this.config.fields?.audio) + ); + } + + private extractUngroupedValue(value: string): string { + const groupedSpanRegex = /[\s\S]*?<\/span>/gi; + const ungrouped = value.replace(groupedSpanRegex, "").trim(); + if (ungrouped) return ungrouped; + return value.trim(); + } + + private extractLastSoundTag(value: string): string { + const matches = value.match(/\[sound:[^\]]+\]/g); + if (!matches || matches.length === 0) return ""; + return matches[matches.length - 1]; + } + + private extractLastImageTag(value: string): string { + const matches = value.match(/]*>/gi); + if (!matches || matches.length === 0) return ""; + return matches[matches.length - 1]; + } + + private extractImageTags(value: string): string[] { + const matches = value.match(/]*>/gi); + return matches || []; + } + + private ensureImageGroupId(imageTag: string, groupId: number): string { + if (!imageTag) return ""; + if (/data-group-id=/i.test(imageTag)) { + return imageTag.replace( + /data-group-id="[^"]*"/i, + `data-group-id="${groupId}"`, + ); + } + return imageTag.replace(/]*data-group-id="([^"]*)"[^>]*>/gi; + let malformed; + while ((malformed = malformedIdRegex.exec(value)) !== null) { + const rawId = malformed[1]; + const groupId = Number(rawId); + if (!Number.isFinite(groupId) || groupId <= 0) { + this.warnFieldParseOnce(fieldName, "invalid-group-id", rawId); + } + } + + const spanRegex = /]*>([\s\S]*?)<\/span>/gi; + let match; + while ((match = spanRegex.exec(value)) !== null) { + const groupId = Number(match[1]); + if (!Number.isFinite(groupId) || groupId <= 0) continue; + const content = this.normalizeStrictGroupedValue( + match[2] || "", + fieldName, + ); + if (!content) { + this.warnFieldParseOnce(fieldName, "empty-group-content"); + log.debug("Skipping span with empty normalized content", { + fieldName, + rawContent: (match[2] || "").slice(0, 120), + }); + continue; + } + entries.push({ groupId, content }); + } + if (entries.length === 0 && /(); + for (const entry of entries) { + const key = `${entry.groupId}::${entry.content}`; + if (seen.has(key)) continue; + seen.add(key); + unique.push(entry); + } + return unique; + } + + private parsePictureEntries( + value: string, + fallbackGroupId: number, + ): { groupId: number; tag: string }[] { + const tags = this.extractImageTags(value); + const result: { groupId: number; tag: string }[] = []; + for (const tag of tags) { + const idMatch = tag.match(/data-group-id="(\d+)"/i); + let groupId = fallbackGroupId; + if (idMatch) { + const parsed = Number(idMatch[1]); + if (!Number.isFinite(parsed) || parsed <= 0) { + this.warnFieldParseOnce("Picture", "invalid-group-id", idMatch[1]); + } else { + groupId = parsed; + } + } + const normalizedTag = this.ensureImageGroupId(tag, groupId); + if (!normalizedTag) { + this.warnFieldParseOnce("Picture", "empty-image-tag"); + continue; + } + result.push({ groupId, tag: normalizedTag }); + } + return result; + } + + private normalizeStrictGroupedValue( + value: string, + fieldName: string, + ): string { + const ungrouped = this.extractUngroupedValue(value); + if (!ungrouped) return ""; + + const normalizedField = fieldName.toLowerCase(); + if ( + normalizedField === "sentenceaudio" || + normalizedField === "expressionaudio" + ) { + const lastSoundTag = this.extractLastSoundTag(ungrouped); + if (!lastSoundTag) { + this.warnFieldParseOnce(fieldName, "missing-sound-tag"); + } + return lastSoundTag || ungrouped; + } + + if (normalizedField === "picture") { + const lastImageTag = this.extractLastImageTag(ungrouped); + if (!lastImageTag) { + this.warnFieldParseOnce(fieldName, "missing-image-tag"); + } + return lastImageTag || ungrouped; + } + + return ungrouped; + } + + private getStrictSpanGroupingFields(): Set { + const strictFields = new Set(this.strictGroupingFieldDefaults); + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + strictFields.add((sentenceCardConfig.sentenceField || "sentence").toLowerCase()); + strictFields.add((sentenceCardConfig.audioField || "sentenceaudio").toLowerCase()); + if (this.config.fields?.image) strictFields.add(this.config.fields.image.toLowerCase()); + if (this.config.fields?.miscInfo) strictFields.add(this.config.fields.miscInfo.toLowerCase()); + return strictFields; + } + + private shouldUseStrictSpanGrouping(fieldName: string): boolean { + const normalized = fieldName.toLowerCase(); + return this.getStrictSpanGroupingFields().has(normalized); + } + + private applyFieldGrouping( + existingValue: string, + newValue: string, + keepGroupId: number, + sourceGroupId: number, + fieldName: string, + ): string { + if (this.shouldUseStrictSpanGrouping(fieldName)) { + if (fieldName.toLowerCase() === "picture") { + const keepEntries = this.parsePictureEntries( + existingValue, + keepGroupId, + ); + const sourceEntries = this.parsePictureEntries(newValue, sourceGroupId); + if (keepEntries.length === 0 && sourceEntries.length === 0) { + return existingValue || newValue; + } + const mergedTags = keepEntries.map((entry) => + this.ensureImageGroupId(entry.tag, entry.groupId), + ); + const seen = new Set(mergedTags); + for (const entry of sourceEntries) { + const normalized = this.ensureImageGroupId(entry.tag, entry.groupId); + if (seen.has(normalized)) continue; + seen.add(normalized); + mergedTags.push(normalized); + } + return mergedTags.join(""); + } + + const keepEntries = this.parseStrictEntries( + existingValue, + keepGroupId, + fieldName, + ); + const sourceEntries = this.parseStrictEntries( + newValue, + sourceGroupId, + fieldName, + ); + if (keepEntries.length === 0 && sourceEntries.length === 0) { + return existingValue || newValue; + } + if (sourceEntries.length === 0) { + return keepEntries + .map( + (entry) => + `${entry.content}`, + ) + .join(""); + } + const merged = [...keepEntries]; + const seen = new Set( + keepEntries.map((entry) => `${entry.groupId}::${entry.content}`), + ); + for (const entry of sourceEntries) { + const key = `${entry.groupId}::${entry.content}`; + if (seen.has(key)) continue; + seen.add(key); + merged.push(entry); + } + if (merged.length === 0) return existingValue; + return merged + .map( + (entry) => + `${entry.content}`, + ) + .join(""); + } + + if (!existingValue.trim()) return newValue; + if (!newValue.trim()) return existingValue; + + const hasGroups = /data-group-id/.test(existingValue); + + if (!hasGroups) { + return ( + `${existingValue}\n` + + newValue + ); + } + + const groupedSpanRegex = /[\s\S]*?<\/span>/g; + let lastEnd = 0; + let result = ""; + let match; + + while ((match = groupedSpanRegex.exec(existingValue)) !== null) { + const before = existingValue.slice(lastEnd, match.index); + if (before.trim()) { + result += `${before.trim()}\n`; + } + result += match[0] + "\n"; + lastEnd = match.index + match[0].length; + } + + const after = existingValue.slice(lastEnd); + if (after.trim()) { + result += `\n${after.trim()}`; + } + + return result + "\n" + newValue; + } + + private async generateMediaForMerge(): Promise<{ + audioField?: string; + audioValue?: string; + imageField?: string; + imageValue?: string; + miscInfoValue?: string; + }> { + const result: { + audioField?: string; + audioValue?: string; + imageField?: string; + imageValue?: string; + miscInfoValue?: string; + } = {}; + + if (this.config.media?.generateAudio && this.mpvClient?.currentVideoPath) { + try { + const audioFilename = this.generateAudioFilename(); + const audioBuffer = await this.generateAudio(); + if (audioBuffer) { + await this.client.storeMediaFile(audioFilename, audioBuffer); + result.audioField = this.getPreferredSentenceAudioFieldName(); + result.audioValue = `[sound:${audioFilename}]`; + if (this.config.fields?.miscInfo) { + result.miscInfoValue = this.formatMiscInfoPattern( + audioFilename, + this.mpvClient.currentSubStart, + ); + } + } + } catch (error) { + log.error( + "Failed to generate audio for merge:", + (error as Error).message, + ); + } + } + + if (this.config.media?.generateImage && this.mpvClient?.currentVideoPath) { + try { + const imageFilename = this.generateImageFilename(); + const imageBuffer = await this.generateImage(); + if (imageBuffer) { + await this.client.storeMediaFile(imageFilename, imageBuffer); + result.imageField = + this.config.fields?.image || DEFAULT_ANKI_CONNECT_CONFIG.fields.image; + result.imageValue = ``; + if (this.config.fields?.miscInfo && !result.miscInfoValue) { + result.miscInfoValue = this.formatMiscInfoPattern( + imageFilename, + this.mpvClient.currentSubStart, + ); + } + } + } catch (error) { + log.error( + "Failed to generate image for merge:", + (error as Error).message, + ); + } + } + + return result; + } + + private getResolvedFieldValue( + noteInfo: NoteInfo, + preferredFieldName?: string, + ): string { + if (!preferredFieldName) return ""; + const resolved = this.resolveNoteFieldName(noteInfo, preferredFieldName); + if (!resolved) return ""; + return noteInfo.fields[resolved]?.value || ""; + } + + private async computeFieldGroupingMergedFields( + keepNoteId: number, + deleteNoteId: number, + keepNoteInfo: NoteInfo, + deleteNoteInfo: NoteInfo, + includeGeneratedMedia: boolean, + ): Promise> { + const groupableFields = this.getGroupableFieldNames(); + const keepFieldNames = Object.keys(keepNoteInfo.fields); + const sourceFields: Record = {}; + const resolvedKeepFieldByPreferred = new Map(); + for (const preferredFieldName of groupableFields) { + sourceFields[preferredFieldName] = this.getResolvedFieldValue( + deleteNoteInfo, + preferredFieldName, + ); + const keepResolved = this.resolveFieldName( + keepFieldNames, + preferredFieldName, + ); + if (keepResolved) { + resolvedKeepFieldByPreferred.set(preferredFieldName, keepResolved); + } + } + + if (!sourceFields["SentenceFurigana"] && sourceFields["Sentence"]) { + sourceFields["SentenceFurigana"] = sourceFields["Sentence"]; + } + if (!sourceFields["Sentence"] && sourceFields["SentenceFurigana"]) { + sourceFields["Sentence"] = sourceFields["SentenceFurigana"]; + } + if (!sourceFields["Expression"] && sourceFields["Word"]) { + sourceFields["Expression"] = sourceFields["Word"]; + } + if (!sourceFields["Word"] && sourceFields["Expression"]) { + sourceFields["Word"] = sourceFields["Expression"]; + } + if (!sourceFields["SentenceAudio"] && sourceFields["ExpressionAudio"]) { + sourceFields["SentenceAudio"] = sourceFields["ExpressionAudio"]; + } + if (!sourceFields["ExpressionAudio"] && sourceFields["SentenceAudio"]) { + sourceFields["ExpressionAudio"] = sourceFields["SentenceAudio"]; + } + + if ( + this.config.fields?.sentence && + !sourceFields[this.config.fields?.sentence] && + this.mpvClient.currentSubText + ) { + const deleteFields = this.extractFields(deleteNoteInfo.fields); + sourceFields[this.config.fields?.sentence] = this.processSentence( + this.mpvClient.currentSubText, + deleteFields, + ); + } + + if (includeGeneratedMedia) { + const media = await this.generateMediaForMerge(); + if ( + media.audioField && + media.audioValue && + !sourceFields[media.audioField] + ) { + sourceFields[media.audioField] = media.audioValue; + } + if ( + media.imageField && + media.imageValue && + !sourceFields[media.imageField] + ) { + sourceFields[media.imageField] = media.imageValue; + } + if ( + this.config.fields?.miscInfo && + media.miscInfoValue && + !sourceFields[this.config.fields?.miscInfo] + ) { + sourceFields[this.config.fields?.miscInfo] = media.miscInfoValue; + } + } + + const mergedFields: Record = {}; + for (const preferredFieldName of groupableFields) { + const keepFieldName = + resolvedKeepFieldByPreferred.get(preferredFieldName); + if (!keepFieldName) continue; + + const keepFieldNormalized = keepFieldName.toLowerCase(); + if ( + keepFieldNormalized === "expression" || + keepFieldNormalized === "expressionfurigana" || + keepFieldNormalized === "expressionreading" || + keepFieldNormalized === "expressionaudio" + ) { + continue; + } + + const existingValue = keepNoteInfo.fields[keepFieldName]?.value || ""; + const newValue = sourceFields[preferredFieldName] || ""; + const isStrictField = this.shouldUseStrictSpanGrouping(keepFieldName); + if (!existingValue.trim() && !newValue.trim()) continue; + + if (isStrictField) { + mergedFields[keepFieldName] = this.applyFieldGrouping( + existingValue, + newValue, + keepNoteId, + deleteNoteId, + keepFieldName, + ); + } else if (existingValue.trim() && newValue.trim()) { + mergedFields[keepFieldName] = this.applyFieldGrouping( + existingValue, + newValue, + keepNoteId, + deleteNoteId, + keepFieldName, + ); + } else { + if (!newValue.trim()) continue; + mergedFields[keepFieldName] = newValue; + } + } + + // Keep sentence/expression audio fields aligned after grouping. Otherwise a + // kept note can retain stale ExpressionAudio while SentenceAudio is merged. + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + const resolvedSentenceAudioField = this.resolveFieldName( + keepFieldNames, + sentenceCardConfig.audioField || "SentenceAudio", + ); + const resolvedExpressionAudioField = this.resolveFieldName( + keepFieldNames, + this.config.fields?.audio || "ExpressionAudio", + ); + if ( + resolvedSentenceAudioField && + resolvedExpressionAudioField && + resolvedExpressionAudioField !== resolvedSentenceAudioField + ) { + const mergedSentenceAudioValue = + mergedFields[resolvedSentenceAudioField] || + keepNoteInfo.fields[resolvedSentenceAudioField]?.value || + ""; + if (mergedSentenceAudioValue.trim()) { + mergedFields[resolvedExpressionAudioField] = mergedSentenceAudioValue; + } + } + + return mergedFields; + } + + private getNoteFieldMap(noteInfo: NoteInfo): Record { + const fields: Record = {}; + for (const [name, field] of Object.entries(noteInfo.fields)) { + fields[name] = field?.value || ""; + } + return fields; + } + + async buildFieldGroupingPreview( + keepNoteId: number, + deleteNoteId: number, + deleteDuplicate: boolean, + ): Promise { + try { + const notesInfoResult = await this.client.notesInfo([ + keepNoteId, + deleteNoteId, + ]); + const notesInfo = notesInfoResult as unknown as NoteInfo[]; + const keepNoteInfo = notesInfo.find((note) => note.noteId === keepNoteId); + const deleteNoteInfo = notesInfo.find( + (note) => note.noteId === deleteNoteId, + ); + + if (!keepNoteInfo || !deleteNoteInfo) { + return { ok: false, error: "Could not load selected notes" }; + } + + const mergedFields = await this.computeFieldGroupingMergedFields( + keepNoteId, + deleteNoteId, + keepNoteInfo, + deleteNoteInfo, + false, + ); + const keepBefore = this.getNoteFieldMap(keepNoteInfo); + const keepAfter = { ...keepBefore, ...mergedFields }; + const sourceBefore = this.getNoteFieldMap(deleteNoteInfo); + + const compactFields: Record = {}; + for (const fieldName of [ + "Sentence", + "SentenceFurigana", + "SentenceAudio", + "Picture", + "MiscInfo", + ]) { + const resolved = this.resolveFieldName( + Object.keys(keepAfter), + fieldName, + ); + if (!resolved) continue; + compactFields[fieldName] = keepAfter[resolved] || ""; + } + + return { + ok: true, + compact: { + action: { + keepNoteId, + deleteNoteId, + deleteDuplicate, + }, + mergedFields: compactFields, + }, + full: { + keepNote: { + id: keepNoteId, + fieldsBefore: keepBefore, + }, + sourceNote: { + id: deleteNoteId, + fieldsBefore: sourceBefore, + }, + result: { + fieldsAfter: keepAfter, + wouldDeleteNoteId: deleteDuplicate ? deleteNoteId : null, + }, + }, + }; + } catch (error) { + return { + ok: false, + error: `Failed to build preview: ${(error as Error).message}`, + }; + } + } + + private async performFieldGroupingMerge( + keepNoteId: number, + deleteNoteId: number, + deleteNoteInfo: NoteInfo, + expression: string, + deleteDuplicate = true, + ): Promise { + const keepNotesInfoResult = await this.client.notesInfo([keepNoteId]); + const keepNotesInfo = keepNotesInfoResult as unknown as NoteInfo[]; + if (!keepNotesInfo || keepNotesInfo.length === 0) { + log.warn("Keep note not found:", keepNoteId); + return; + } + const keepNoteInfo = keepNotesInfo[0]; + const mergedFields = await this.computeFieldGroupingMergedFields( + keepNoteId, + deleteNoteId, + keepNoteInfo, + deleteNoteInfo, + true, + ); + + if (Object.keys(mergedFields).length > 0) { + await this.client.updateNoteFields(keepNoteId, mergedFields); + } + + if (deleteDuplicate) { + await this.client.deleteNotes([deleteNoteId]); + this.previousNoteIds.delete(deleteNoteId); + } + + log.info("Merged duplicate card:", expression, "into note:", keepNoteId); + this.showStatusNotification( + deleteDuplicate + ? `Merged duplicate: ${expression}` + : `Grouped duplicate (kept both): ${expression}`, + ); + await this.showNotification(keepNoteId, expression); + } + + private async handleFieldGroupingAuto( + originalNoteId: number, + newNoteId: number, + newNoteInfo: NoteInfo, + expression: string, + ): Promise { + try { + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + await this.performFieldGroupingMerge( + originalNoteId, + newNoteId, + newNoteInfo, + expression, + sentenceCardConfig.kikuDeleteDuplicateInAuto, + ); + } catch (error) { + log.error( + "Field grouping auto merge failed:", + (error as Error).message, + ); + this.showOsdNotification( + `Field grouping failed: ${(error as Error).message}`, + ); + } + } + + private async handleFieldGroupingManual( + originalNoteId: number, + newNoteId: number, + newNoteInfo: NoteInfo, + expression: string, + ): Promise { + if (!this.fieldGroupingCallback) { + log.warn( + "No field grouping callback registered, skipping manual mode", + ); + this.showOsdNotification("Field grouping UI unavailable"); + return false; + } + + try { + const originalNotesInfoResult = await this.client.notesInfo([ + originalNoteId, + ]); + const originalNotesInfo = + originalNotesInfoResult as unknown as NoteInfo[]; + if (!originalNotesInfo || originalNotesInfo.length === 0) { + return false; + } + const originalNoteInfo = originalNotesInfo[0]; + const sentenceCardConfig = this.getEffectiveSentenceCardConfig(); + + const originalFields = this.extractFields(originalNoteInfo.fields); + const newFields = this.extractFields(newNoteInfo.fields); + + const originalCard: KikuDuplicateCardInfo = { + noteId: originalNoteId, + expression: + originalFields.expression || originalFields.word || expression, + sentencePreview: this.truncateSentence( + originalFields[ + (sentenceCardConfig.sentenceField || "sentence").toLowerCase() + ] || "", + ), + hasAudio: + this.hasFieldValue(originalNoteInfo, this.config.fields?.audio) || + this.hasFieldValue(originalNoteInfo, sentenceCardConfig.audioField), + hasImage: this.hasFieldValue(originalNoteInfo, this.config.fields?.image), + isOriginal: true, + }; + + const newCard: KikuDuplicateCardInfo = { + noteId: newNoteId, + expression: newFields.expression || newFields.word || expression, + sentencePreview: this.truncateSentence( + newFields[ + (sentenceCardConfig.sentenceField || "sentence").toLowerCase() + ] || + this.mpvClient.currentSubText || + "", + ), + hasAudio: + this.hasFieldValue(newNoteInfo, this.config.fields?.audio) || + this.hasFieldValue(newNoteInfo, sentenceCardConfig.audioField), + hasImage: this.hasFieldValue(newNoteInfo, this.config.fields?.image), + isOriginal: false, + }; + + const choice = await this.fieldGroupingCallback({ + original: originalCard, + duplicate: newCard, + }); + + if (choice.cancelled) { + this.showOsdNotification("Field grouping cancelled"); + return false; + } + + const keepNoteId = choice.keepNoteId; + const deleteNoteId = choice.deleteNoteId; + const deleteNoteInfo = + deleteNoteId === newNoteId ? newNoteInfo : originalNoteInfo; + + await this.performFieldGroupingMerge( + keepNoteId, + deleteNoteId, + deleteNoteInfo, + expression, + choice.deleteDuplicate, + ); + return true; + } catch (error) { + log.error( + "Field grouping manual merge failed:", + (error as Error).message, + ); + this.showOsdNotification( + `Field grouping failed: ${(error as Error).message}`, + ); + return false; + } + } + + private truncateSentence(sentence: string): string { + const clean = sentence.replace(/<[^>]*>/g, "").trim(); + if (clean.length <= 100) return clean; + return clean.substring(0, 100) + "..."; + } + + private hasFieldValue( + noteInfo: NoteInfo, + preferredFieldName?: string, + ): boolean { + const resolved = this.resolveNoteFieldName(noteInfo, preferredFieldName); + if (!resolved) return false; + return Boolean(noteInfo.fields[resolved]?.value); + } + + private hasAllConfiguredFields( + noteInfo: NoteInfo, + configuredFieldNames: (string | undefined)[], + ): boolean { + const requiredFields = configuredFieldNames.filter( + (fieldName): fieldName is string => Boolean(fieldName), + ); + if (requiredFields.length === 0) return true; + return requiredFields.every((fieldName) => + this.hasFieldValue(noteInfo, fieldName), + ); + } + + private async refreshMiscInfoField( + noteId: number, + noteInfo: NoteInfo, + ): Promise { + if (!this.config.fields?.miscInfo || !this.config.metadata?.pattern) return; + + const resolvedMiscField = this.resolveNoteFieldName( + noteInfo, + this.config.fields?.miscInfo, + ); + if (!resolvedMiscField) return; + + const nextValue = this.formatMiscInfoPattern( + "", + this.mpvClient.currentSubStart, + ); + if (!nextValue) return; + + const currentValue = noteInfo.fields[resolvedMiscField]?.value || ""; + if (currentValue === nextValue) return; + + await this.client.updateNoteFields(noteId, { + [resolvedMiscField]: nextValue, + }); + } + + applyRuntimeConfigPatch(patch: Partial): void { + const previousPollingRate = this.config.pollingRate; + this.config = { + ...this.config, + ...patch, + fields: + patch.fields !== undefined + ? { ...this.config.fields, ...patch.fields } + : this.config.fields, + media: + patch.media !== undefined + ? { ...this.config.media, ...patch.media } + : this.config.media, + behavior: + patch.behavior !== undefined + ? { ...this.config.behavior, ...patch.behavior } + : this.config.behavior, + metadata: + patch.metadata !== undefined + ? { ...this.config.metadata, ...patch.metadata } + : this.config.metadata, + isLapis: + patch.isLapis !== undefined + ? { ...this.config.isLapis, ...patch.isLapis } + : this.config.isLapis, + isKiku: + patch.isKiku !== undefined + ? { ...this.config.isKiku, ...patch.isKiku } + : this.config.isKiku, + }; + + if ( + patch.pollingRate !== undefined && + previousPollingRate !== this.config.pollingRate && + this.pollingInterval + ) { + this.stop(); + this.poll(); + } + } + + + destroy(): void { + this.stop(); + this.mediaGenerator.cleanup(); + } +} diff --git a/src/config/config.test.ts b/src/config/config.test.ts new file mode 100644 index 0000000..c5adcfd --- /dev/null +++ b/src/config/config.test.ts @@ -0,0 +1,79 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { ConfigService } from "./service"; +import { DEFAULT_CONFIG, RUNTIME_OPTION_REGISTRY } from "./definitions"; +import { generateConfigTemplate } from "./template"; + +function makeTempDir(): string { + return fs.mkdtempSync(path.join(os.tmpdir(), "subminer-config-test-")); +} + +test("loads defaults when config is missing", () => { + const dir = makeTempDir(); + const service = new ConfigService(dir); + const config = service.getConfig(); + assert.equal(config.websocket.port, DEFAULT_CONFIG.websocket.port); + assert.equal(config.ankiConnect.behavior.autoUpdateNewCards, true); +}); + +test("parses jsonc and warns/falls back on invalid value", () => { + const dir = makeTempDir(); + fs.writeFileSync( + path.join(dir, "config.jsonc"), + `{ + // invalid websocket port + "websocket": { "port": "bad" } + }`, + "utf-8", + ); + + const service = new ConfigService(dir); + const config = service.getConfig(); + assert.equal(config.websocket.port, DEFAULT_CONFIG.websocket.port); + assert.ok(service.getWarnings().some((w) => w.path === "websocket.port")); +}); + +test("parses invisible overlay config and new global shortcuts", () => { + const dir = makeTempDir(); + fs.writeFileSync( + path.join(dir, "config.jsonc"), + `{ + "shortcuts": { + "toggleVisibleOverlayGlobal": "Alt+Shift+U", + "toggleInvisibleOverlayGlobal": "Alt+Shift+I" + }, + "invisibleOverlay": { + "startupVisibility": "hidden" + }, + "bind_visible_overlay_to_mpv_sub_visibility": false, + "youtubeSubgen": { + "primarySubLanguages": ["ja", "jpn", "jp"] + } + }`, + "utf-8", + ); + + const service = new ConfigService(dir); + const config = service.getConfig(); + assert.equal(config.shortcuts.toggleVisibleOverlayGlobal, "Alt+Shift+U"); + assert.equal(config.shortcuts.toggleInvisibleOverlayGlobal, "Alt+Shift+I"); + assert.equal(config.invisibleOverlay.startupVisibility, "hidden"); + assert.equal(config.bind_visible_overlay_to_mpv_sub_visibility, false); + assert.deepEqual(config.youtubeSubgen.primarySubLanguages, ["ja", "jpn", "jp"]); +}); + +test("runtime options registry is centralized", () => { + const ids = RUNTIME_OPTION_REGISTRY.map((entry) => entry.id); + assert.deepEqual(ids, ["anki.autoUpdateNewCards", "anki.kikuFieldGrouping"]); +}); + +test("template generator includes known keys", () => { + const output = generateConfigTemplate(DEFAULT_CONFIG); + assert.match(output, /"ankiConnect":/); + assert.match(output, /"websocket":/); + assert.match(output, /"youtubeSubgen":/); + assert.match(output, /auto-generated from src\/config\/definitions.ts/); +}); diff --git a/src/config/definitions.ts b/src/config/definitions.ts new file mode 100644 index 0000000..8e31e6c --- /dev/null +++ b/src/config/definitions.ts @@ -0,0 +1,474 @@ +import { + AnkiConnectConfig, + Config, + RawConfig, + ResolvedConfig, + RuntimeOptionId, + RuntimeOptionScope, + RuntimeOptionValue, + RuntimeOptionValueType, +} from "../types"; + +export type ConfigValueKind = + | "boolean" + | "number" + | "string" + | "enum" + | "array" + | "object"; + +export interface RuntimeOptionRegistryEntry { + id: RuntimeOptionId; + path: string; + label: string; + scope: RuntimeOptionScope; + valueType: RuntimeOptionValueType; + allowedValues: RuntimeOptionValue[]; + defaultValue: RuntimeOptionValue; + requiresRestart: boolean; + formatValueForOsd: (value: RuntimeOptionValue) => string; + toAnkiPatch: (value: RuntimeOptionValue) => Partial; +} + +export interface ConfigOptionRegistryEntry { + path: string; + kind: ConfigValueKind; + defaultValue: unknown; + description: string; + enumValues?: readonly string[]; + runtime?: RuntimeOptionRegistryEntry; +} + +export interface ConfigTemplateSection { + title: string; + description: string[]; + key: keyof ResolvedConfig; + notes?: string[]; +} + +export const SPECIAL_COMMANDS = { + SUBSYNC_TRIGGER: "__subsync-trigger", + RUNTIME_OPTIONS_OPEN: "__runtime-options-open", + RUNTIME_OPTION_CYCLE_PREFIX: "__runtime-option-cycle:", + REPLAY_SUBTITLE: "__replay-subtitle", + PLAY_NEXT_SUBTITLE: "__play-next-subtitle", +} as const; + +export const DEFAULT_KEYBINDINGS: NonNullable = [ + { key: "Space", command: ["cycle", "pause"] }, + { key: "ArrowRight", command: ["seek", 5] }, + { key: "ArrowLeft", command: ["seek", -5] }, + { key: "ArrowUp", command: ["seek", 60] }, + { key: "ArrowDown", command: ["seek", -60] }, + { key: "Shift+KeyH", command: ["sub-seek", -1] }, + { key: "Shift+KeyL", command: ["sub-seek", 1] }, + { key: "Ctrl+Shift+KeyH", command: [SPECIAL_COMMANDS.REPLAY_SUBTITLE] }, + { key: "Ctrl+Shift+KeyL", command: [SPECIAL_COMMANDS.PLAY_NEXT_SUBTITLE] }, + { key: "KeyQ", command: ["quit"] }, + { key: "Ctrl+KeyW", command: ["quit"] }, +]; + +export const DEFAULT_CONFIG: ResolvedConfig = { + subtitlePosition: { yPercent: 10 }, + keybindings: [], + websocket: { + enabled: "auto", + port: 6677, + }, + texthooker: { + openBrowser: true, + }, + ankiConnect: { + enabled: false, + url: "http://127.0.0.1:8765", + pollingRate: 3000, + fields: { + audio: "ExpressionAudio", + image: "Picture", + sentence: "Sentence", + miscInfo: "MiscInfo", + translation: "SelectionText", + }, + ai: { + enabled: false, + alwaysUseAiTranslation: false, + apiKey: "", + model: "openai/gpt-4o-mini", + baseUrl: "https://openrouter.ai/api", + targetLanguage: "English", + systemPrompt: + "You are a translation engine. Return only the translated text with no explanations.", + }, + media: { + generateAudio: true, + generateImage: true, + imageType: "static", + imageFormat: "jpg", + imageQuality: 92, + imageMaxWidth: undefined, + imageMaxHeight: undefined, + animatedFps: 10, + animatedMaxWidth: 640, + animatedMaxHeight: undefined, + animatedCrf: 35, + audioPadding: 0.5, + fallbackDuration: 3.0, + maxMediaDuration: 30, + }, + behavior: { + overwriteAudio: true, + overwriteImage: true, + mediaInsertMode: "append", + highlightWord: true, + notificationType: "osd", + autoUpdateNewCards: true, + }, + metadata: { + pattern: "[SubMiner] %f (%t)", + }, + isLapis: { + enabled: false, + sentenceCardModel: "Japanese sentences", + sentenceCardSentenceField: "Sentence", + sentenceCardAudioField: "SentenceAudio", + }, + isKiku: { + enabled: false, + fieldGrouping: "disabled", + deleteDuplicateInAuto: true, + }, + }, + shortcuts: { + toggleVisibleOverlayGlobal: "Alt+Shift+O", + toggleInvisibleOverlayGlobal: "Alt+Shift+I", + copySubtitle: "CommandOrControl+C", + copySubtitleMultiple: "CommandOrControl+Shift+C", + updateLastCardFromClipboard: "CommandOrControl+V", + triggerFieldGrouping: "CommandOrControl+G", + triggerSubsync: "Ctrl+Alt+S", + mineSentence: "CommandOrControl+S", + mineSentenceMultiple: "CommandOrControl+Shift+S", + multiCopyTimeoutMs: 3000, + toggleSecondarySub: "CommandOrControl+Shift+V", + markAudioCard: "CommandOrControl+Shift+A", + openRuntimeOptions: "CommandOrControl+Shift+O", + }, + secondarySub: { + secondarySubLanguages: [], + autoLoadSecondarySub: false, + defaultMode: "hover", + }, + subsync: { + defaultMode: "auto", + alass_path: "", + ffsubsync_path: "", + ffmpeg_path: "", + }, + subtitleStyle: { + fontFamily: + "Noto Sans CJK JP Regular, Noto Sans CJK JP, Arial Unicode MS, Arial, sans-serif", + fontSize: 35, + fontColor: "#cad3f5", + fontWeight: "normal", + fontStyle: "normal", + backgroundColor: "rgba(54, 58, 79, 0.5)", + secondary: { + fontSize: 24, + fontColor: "#ffffff", + backgroundColor: "transparent", + fontWeight: "normal", + fontStyle: "normal", + fontFamily: + "Noto Sans CJK JP Regular, Noto Sans CJK JP, Arial Unicode MS, Arial, sans-serif", + }, + }, + auto_start_overlay: false, + bind_visible_overlay_to_mpv_sub_visibility: true, + jimaku: { + apiBaseUrl: "https://jimaku.cc", + languagePreference: "ja", + maxEntryResults: 10, + }, + youtubeSubgen: { + mode: "automatic", + whisperBin: "", + whisperModel: "", + primarySubLanguages: ["ja", "jpn"], + }, + invisibleOverlay: { + startupVisibility: "platform-default", + }, +}; + +export const DEFAULT_ANKI_CONNECT_CONFIG = DEFAULT_CONFIG.ankiConnect; + +export const RUNTIME_OPTION_REGISTRY: RuntimeOptionRegistryEntry[] = [ + { + id: "anki.autoUpdateNewCards", + path: "ankiConnect.behavior.autoUpdateNewCards", + label: "Auto Update New Cards", + scope: "ankiConnect", + valueType: "boolean", + allowedValues: [true, false], + defaultValue: DEFAULT_CONFIG.ankiConnect.behavior.autoUpdateNewCards, + requiresRestart: false, + formatValueForOsd: (value) => (value === true ? "On" : "Off"), + toAnkiPatch: (value) => ({ + behavior: { autoUpdateNewCards: value === true }, + }), + }, + { + id: "anki.kikuFieldGrouping", + path: "ankiConnect.isKiku.fieldGrouping", + label: "Kiku Field Grouping", + scope: "ankiConnect", + valueType: "enum", + allowedValues: ["auto", "manual", "disabled"], + defaultValue: "disabled", + requiresRestart: false, + formatValueForOsd: (value) => String(value), + toAnkiPatch: (value) => ({ + isKiku: { + fieldGrouping: + value === "auto" || value === "manual" || value === "disabled" + ? value + : "disabled", + }, + }), + }, +]; + +export const CONFIG_OPTION_REGISTRY: ConfigOptionRegistryEntry[] = [ + { + path: "websocket.enabled", + kind: "enum", + enumValues: ["auto", "true", "false"], + defaultValue: DEFAULT_CONFIG.websocket.enabled, + description: "Built-in subtitle websocket server mode.", + }, + { + path: "websocket.port", + kind: "number", + defaultValue: DEFAULT_CONFIG.websocket.port, + description: "Built-in subtitle websocket server port.", + }, + { + path: "ankiConnect.enabled", + kind: "boolean", + defaultValue: DEFAULT_CONFIG.ankiConnect.enabled, + description: "Enable AnkiConnect integration.", + }, + { + path: "ankiConnect.pollingRate", + kind: "number", + defaultValue: DEFAULT_CONFIG.ankiConnect.pollingRate, + description: "Polling interval in milliseconds.", + }, + { + path: "ankiConnect.behavior.autoUpdateNewCards", + kind: "boolean", + defaultValue: DEFAULT_CONFIG.ankiConnect.behavior.autoUpdateNewCards, + description: "Automatically update newly added cards.", + runtime: RUNTIME_OPTION_REGISTRY[0], + }, + { + path: "ankiConnect.isKiku.fieldGrouping", + kind: "enum", + enumValues: ["auto", "manual", "disabled"], + defaultValue: DEFAULT_CONFIG.ankiConnect.isKiku.fieldGrouping, + description: "Kiku duplicate-card field grouping mode.", + runtime: RUNTIME_OPTION_REGISTRY[1], + }, + { + path: "subsync.defaultMode", + kind: "enum", + enumValues: ["auto", "manual"], + defaultValue: DEFAULT_CONFIG.subsync.defaultMode, + description: "Subsync default mode.", + }, + { + path: "shortcuts.multiCopyTimeoutMs", + kind: "number", + defaultValue: DEFAULT_CONFIG.shortcuts.multiCopyTimeoutMs, + description: "Timeout for multi-copy/mine modes.", + }, + { + path: "bind_visible_overlay_to_mpv_sub_visibility", + kind: "boolean", + defaultValue: DEFAULT_CONFIG.bind_visible_overlay_to_mpv_sub_visibility, + description: + "Link visible overlay toggles to MPV subtitle visibility (primary and secondary).", + }, + { + path: "jimaku.languagePreference", + kind: "enum", + enumValues: ["ja", "en", "none"], + defaultValue: DEFAULT_CONFIG.jimaku.languagePreference, + description: "Preferred language used in Jimaku search.", + }, + { + path: "jimaku.maxEntryResults", + kind: "number", + defaultValue: DEFAULT_CONFIG.jimaku.maxEntryResults, + description: "Maximum Jimaku search results returned.", + }, + { + path: "youtubeSubgen.mode", + kind: "enum", + enumValues: ["automatic", "preprocess", "off"], + defaultValue: DEFAULT_CONFIG.youtubeSubgen.mode, + description: "YouTube subtitle generation mode for the launcher script.", + }, + { + path: "youtubeSubgen.whisperBin", + kind: "string", + defaultValue: DEFAULT_CONFIG.youtubeSubgen.whisperBin, + description: "Path to whisper.cpp CLI used as fallback transcription engine.", + }, + { + path: "youtubeSubgen.whisperModel", + kind: "string", + defaultValue: DEFAULT_CONFIG.youtubeSubgen.whisperModel, + description: "Path to whisper model used for fallback transcription.", + }, + { + path: "youtubeSubgen.primarySubLanguages", + kind: "string", + defaultValue: DEFAULT_CONFIG.youtubeSubgen.primarySubLanguages.join(","), + description: + "Comma-separated primary subtitle language priority used by the launcher.", + }, +]; + +export const CONFIG_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [ + { + title: "Overlay Auto-Start", + description: [ + "When overlay connects to mpv, automatically show overlay and hide mpv subtitles.", + ], + key: "auto_start_overlay", + }, + { + title: "Visible Overlay Subtitle Binding", + description: [ + "Control whether visible overlay toggles also toggle MPV subtitle visibility.", + "When enabled, visible overlay hides MPV subtitles; when disabled, MPV subtitles are left unchanged.", + ], + key: "bind_visible_overlay_to_mpv_sub_visibility", + }, + { + title: "Texthooker Server", + description: [ + "Control whether browser opens automatically for texthooker.", + ], + key: "texthooker", + }, + { + title: "WebSocket Server", + description: [ + "Built-in WebSocket server broadcasts subtitle text to connected clients.", + "Auto mode disables built-in server if mpv_websocket is detected.", + ], + key: "websocket", + }, + { + title: "AnkiConnect Integration", + description: ["Automatic Anki updates and media generation options."], + key: "ankiConnect", + }, + { + title: "Keyboard Shortcuts", + description: [ + "Overlay keyboard shortcuts. Set a shortcut to null to disable.", + ], + key: "shortcuts", + }, + { + title: "Invisible Overlay", + description: [ + "Startup behavior for the invisible interactive subtitle mining layer.", + ], + key: "invisibleOverlay", + }, + { + title: "Keybindings (MPV Commands)", + description: [ + "Extra keybindings that are merged with built-in defaults.", + "Set command to null to disable a default keybinding.", + ], + key: "keybindings", + }, + { + title: "Subtitle Appearance", + description: ["Primary and secondary subtitle styling."], + key: "subtitleStyle", + }, + { + title: "Secondary Subtitles", + description: [ + "Dual subtitle track options.", + "Used by subminer YouTube subtitle generation as secondary language preferences.", + ], + key: "secondarySub", + }, + { + title: "Auto Subtitle Sync", + description: ["Subsync engine and executable paths."], + key: "subsync", + }, + { + title: "Subtitle Position", + description: ["Initial vertical subtitle position from the bottom."], + key: "subtitlePosition", + }, + { + title: "Jimaku", + description: ["Jimaku API configuration and defaults."], + key: "jimaku", + }, + { + title: "YouTube Subtitle Generation", + description: [ + "Defaults for subminer YouTube subtitle extraction/transcription mode.", + ], + key: "youtubeSubgen", + }, +]; + +export function deepCloneConfig(config: ResolvedConfig): ResolvedConfig { + return JSON.parse(JSON.stringify(config)) as ResolvedConfig; +} + +export function deepMergeRawConfig( + base: RawConfig, + patch: RawConfig, +): RawConfig { + const clone = JSON.parse(JSON.stringify(base)) as Record; + const patchObject = patch as Record; + + const mergeInto = ( + target: Record, + source: Record, + ): void => { + for (const [key, value] of Object.entries(source)) { + if ( + value !== null && + typeof value === "object" && + !Array.isArray(value) && + typeof target[key] === "object" && + target[key] !== null && + !Array.isArray(target[key]) + ) { + mergeInto( + target[key] as Record, + value as Record, + ); + } else { + target[key] = value; + } + } + }; + + mergeInto(clone, patchObject); + return clone as RawConfig; +} diff --git a/src/config/index.ts b/src/config/index.ts new file mode 100644 index 0000000..ba93d2c --- /dev/null +++ b/src/config/index.ts @@ -0,0 +1,3 @@ +export * from "./definitions"; +export * from "./service"; +export * from "./template"; diff --git a/src/config/service.ts b/src/config/service.ts new file mode 100644 index 0000000..5977181 --- /dev/null +++ b/src/config/service.ts @@ -0,0 +1,600 @@ +import * as fs from "fs"; +import * as path from "path"; +import { parse as parseJsonc } from "jsonc-parser"; +import { + Config, + ConfigValidationWarning, + RawConfig, + ResolvedConfig, +} from "../types"; +import { + DEFAULT_CONFIG, + deepCloneConfig, + deepMergeRawConfig, +} from "./definitions"; + +interface LoadResult { + config: RawConfig; + path: string; +} + +function isObject(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function asNumber(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) + ? value + : undefined; +} + +function asString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function asBoolean(value: unknown): boolean | undefined { + return typeof value === "boolean" ? value : undefined; +} + +export class ConfigService { + private readonly configDir: string; + private readonly configFileJsonc: string; + private readonly configFileJson: string; + private rawConfig: RawConfig = {}; + private resolvedConfig: ResolvedConfig = deepCloneConfig(DEFAULT_CONFIG); + private warnings: ConfigValidationWarning[] = []; + private configPathInUse: string; + + constructor(configDir: string) { + this.configDir = configDir; + this.configFileJsonc = path.join(configDir, "config.jsonc"); + this.configFileJson = path.join(configDir, "config.json"); + this.configPathInUse = this.configFileJsonc; + this.reloadConfig(); + } + + getConfigPath(): string { + return this.configPathInUse; + } + + getConfig(): ResolvedConfig { + return deepCloneConfig(this.resolvedConfig); + } + + getRawConfig(): RawConfig { + return JSON.parse(JSON.stringify(this.rawConfig)) as RawConfig; + } + + getWarnings(): ConfigValidationWarning[] { + return [...this.warnings]; + } + + reloadConfig(): ResolvedConfig { + const { config, path: configPath } = this.loadRawConfig(); + this.rawConfig = config; + this.configPathInUse = configPath; + const { resolved, warnings } = this.resolveConfig(config); + this.resolvedConfig = resolved; + this.warnings = warnings; + return this.getConfig(); + } + + saveRawConfig(config: RawConfig): void { + if (!fs.existsSync(this.configDir)) { + fs.mkdirSync(this.configDir, { recursive: true }); + } + const targetPath = this.configPathInUse.endsWith(".json") + ? this.configPathInUse + : this.configFileJsonc; + fs.writeFileSync(targetPath, JSON.stringify(config, null, 2)); + this.rawConfig = config; + this.configPathInUse = targetPath; + const { resolved, warnings } = this.resolveConfig(config); + this.resolvedConfig = resolved; + this.warnings = warnings; + } + + patchRawConfig(patch: RawConfig): void { + const merged = deepMergeRawConfig(this.getRawConfig(), patch); + this.saveRawConfig(merged); + } + + private loadRawConfig(): LoadResult { + const configPath = fs.existsSync(this.configFileJsonc) + ? this.configFileJsonc + : fs.existsSync(this.configFileJson) + ? this.configFileJson + : this.configFileJsonc; + + if (!fs.existsSync(configPath)) { + return { config: {}, path: configPath }; + } + + try { + const data = fs.readFileSync(configPath, "utf-8"); + const parsed = configPath.endsWith(".jsonc") + ? parseJsonc(data) + : JSON.parse(data); + return { + config: isObject(parsed) ? (parsed as Config) : {}, + path: configPath, + }; + } catch { + return { config: {}, path: configPath }; + } + } + + private resolveConfig(raw: RawConfig): { + resolved: ResolvedConfig; + warnings: ConfigValidationWarning[]; + } { + const warnings: ConfigValidationWarning[] = []; + const resolved = deepCloneConfig(DEFAULT_CONFIG); + + const warn = ( + path: string, + value: unknown, + fallback: unknown, + message: string, + ): void => { + warnings.push({ + path, + value, + fallback, + message, + }); + }; + + const src = isObject(raw) ? raw : {}; + + if (isObject(src.texthooker)) { + const openBrowser = asBoolean(src.texthooker.openBrowser); + if (openBrowser !== undefined) { + resolved.texthooker.openBrowser = openBrowser; + } else if (src.texthooker.openBrowser !== undefined) { + warn( + "texthooker.openBrowser", + src.texthooker.openBrowser, + resolved.texthooker.openBrowser, + "Expected boolean.", + ); + } + } + + if (isObject(src.websocket)) { + const enabled = src.websocket.enabled; + if (enabled === "auto" || enabled === true || enabled === false) { + resolved.websocket.enabled = enabled; + } else if (enabled !== undefined) { + warn( + "websocket.enabled", + enabled, + resolved.websocket.enabled, + "Expected true, false, or 'auto'.", + ); + } + + const port = asNumber(src.websocket.port); + if (port !== undefined && port > 0 && port <= 65535) { + resolved.websocket.port = Math.floor(port); + } else if (src.websocket.port !== undefined) { + warn( + "websocket.port", + src.websocket.port, + resolved.websocket.port, + "Expected integer between 1 and 65535.", + ); + } + } + + if (Array.isArray(src.keybindings)) { + resolved.keybindings = src.keybindings.filter( + ( + entry, + ): entry is { key: string; command: (string | number)[] | null } => { + if (!isObject(entry)) return false; + if (typeof entry.key !== "string") return false; + if (entry.command === null) return true; + return Array.isArray(entry.command); + }, + ); + } + + if (isObject(src.shortcuts)) { + const shortcutKeys = [ + "toggleVisibleOverlayGlobal", + "toggleInvisibleOverlayGlobal", + "copySubtitle", + "copySubtitleMultiple", + "updateLastCardFromClipboard", + "triggerFieldGrouping", + "triggerSubsync", + "mineSentence", + "mineSentenceMultiple", + "toggleSecondarySub", + "markAudioCard", + "openRuntimeOptions", + ] as const; + + for (const key of shortcutKeys) { + const value = src.shortcuts[key]; + if (typeof value === "string" || value === null) { + resolved.shortcuts[key] = + value as (typeof resolved.shortcuts)[typeof key]; + } else if (value !== undefined) { + warn( + `shortcuts.${key}`, + value, + resolved.shortcuts[key], + "Expected string or null.", + ); + } + } + + const timeout = asNumber(src.shortcuts.multiCopyTimeoutMs); + if (timeout !== undefined && timeout > 0) { + resolved.shortcuts.multiCopyTimeoutMs = Math.floor(timeout); + } else if (src.shortcuts.multiCopyTimeoutMs !== undefined) { + warn( + "shortcuts.multiCopyTimeoutMs", + src.shortcuts.multiCopyTimeoutMs, + resolved.shortcuts.multiCopyTimeoutMs, + "Expected positive number.", + ); + } + } + + if (isObject(src.invisibleOverlay)) { + const startupVisibility = src.invisibleOverlay.startupVisibility; + if ( + startupVisibility === "platform-default" || + startupVisibility === "visible" || + startupVisibility === "hidden" + ) { + resolved.invisibleOverlay.startupVisibility = startupVisibility; + } else if (startupVisibility !== undefined) { + warn( + "invisibleOverlay.startupVisibility", + startupVisibility, + resolved.invisibleOverlay.startupVisibility, + "Expected platform-default, visible, or hidden.", + ); + } + } + + if (isObject(src.secondarySub)) { + if (Array.isArray(src.secondarySub.secondarySubLanguages)) { + resolved.secondarySub.secondarySubLanguages = + src.secondarySub.secondarySubLanguages.filter( + (item): item is string => typeof item === "string", + ); + } + const autoLoad = asBoolean(src.secondarySub.autoLoadSecondarySub); + if (autoLoad !== undefined) { + resolved.secondarySub.autoLoadSecondarySub = autoLoad; + } + const defaultMode = src.secondarySub.defaultMode; + if ( + defaultMode === "hidden" || + defaultMode === "visible" || + defaultMode === "hover" + ) { + resolved.secondarySub.defaultMode = defaultMode; + } else if (defaultMode !== undefined) { + warn( + "secondarySub.defaultMode", + defaultMode, + resolved.secondarySub.defaultMode, + "Expected hidden, visible, or hover.", + ); + } + } + + if (isObject(src.subsync)) { + const mode = src.subsync.defaultMode; + if (mode === "auto" || mode === "manual") { + resolved.subsync.defaultMode = mode; + } else if (mode !== undefined) { + warn( + "subsync.defaultMode", + mode, + resolved.subsync.defaultMode, + "Expected auto or manual.", + ); + } + + const alass = asString(src.subsync.alass_path); + if (alass !== undefined) resolved.subsync.alass_path = alass; + const ffsubsync = asString(src.subsync.ffsubsync_path); + if (ffsubsync !== undefined) resolved.subsync.ffsubsync_path = ffsubsync; + const ffmpeg = asString(src.subsync.ffmpeg_path); + if (ffmpeg !== undefined) resolved.subsync.ffmpeg_path = ffmpeg; + } + + if (isObject(src.subtitlePosition)) { + const y = asNumber(src.subtitlePosition.yPercent); + if (y !== undefined) { + resolved.subtitlePosition.yPercent = y; + } + } + + if (isObject(src.jimaku)) { + const apiKey = asString(src.jimaku.apiKey); + if (apiKey !== undefined) resolved.jimaku.apiKey = apiKey; + const apiKeyCommand = asString(src.jimaku.apiKeyCommand); + if (apiKeyCommand !== undefined) + resolved.jimaku.apiKeyCommand = apiKeyCommand; + const apiBaseUrl = asString(src.jimaku.apiBaseUrl); + if (apiBaseUrl !== undefined) resolved.jimaku.apiBaseUrl = apiBaseUrl; + + const lang = src.jimaku.languagePreference; + if (lang === "ja" || lang === "en" || lang === "none") { + resolved.jimaku.languagePreference = lang; + } else if (lang !== undefined) { + warn( + "jimaku.languagePreference", + lang, + resolved.jimaku.languagePreference, + "Expected ja, en, or none.", + ); + } + + const maxEntryResults = asNumber(src.jimaku.maxEntryResults); + if (maxEntryResults !== undefined && maxEntryResults > 0) { + resolved.jimaku.maxEntryResults = Math.floor(maxEntryResults); + } else if (src.jimaku.maxEntryResults !== undefined) { + warn( + "jimaku.maxEntryResults", + src.jimaku.maxEntryResults, + resolved.jimaku.maxEntryResults, + "Expected positive number.", + ); + } + } + + if (isObject(src.youtubeSubgen)) { + const mode = src.youtubeSubgen.mode; + if (mode === "automatic" || mode === "preprocess" || mode === "off") { + resolved.youtubeSubgen.mode = mode; + } else if (mode !== undefined) { + warn( + "youtubeSubgen.mode", + mode, + resolved.youtubeSubgen.mode, + "Expected automatic, preprocess, or off.", + ); + } + + const whisperBin = asString(src.youtubeSubgen.whisperBin); + if (whisperBin !== undefined) { + resolved.youtubeSubgen.whisperBin = whisperBin; + } else if (src.youtubeSubgen.whisperBin !== undefined) { + warn( + "youtubeSubgen.whisperBin", + src.youtubeSubgen.whisperBin, + resolved.youtubeSubgen.whisperBin, + "Expected string.", + ); + } + + const whisperModel = asString(src.youtubeSubgen.whisperModel); + if (whisperModel !== undefined) { + resolved.youtubeSubgen.whisperModel = whisperModel; + } else if (src.youtubeSubgen.whisperModel !== undefined) { + warn( + "youtubeSubgen.whisperModel", + src.youtubeSubgen.whisperModel, + resolved.youtubeSubgen.whisperModel, + "Expected string.", + ); + } + + if (Array.isArray(src.youtubeSubgen.primarySubLanguages)) { + resolved.youtubeSubgen.primarySubLanguages = + src.youtubeSubgen.primarySubLanguages.filter( + (item): item is string => typeof item === "string", + ); + } else if (src.youtubeSubgen.primarySubLanguages !== undefined) { + warn( + "youtubeSubgen.primarySubLanguages", + src.youtubeSubgen.primarySubLanguages, + resolved.youtubeSubgen.primarySubLanguages, + "Expected string array.", + ); + } + } + + if (asBoolean(src.auto_start_overlay) !== undefined) { + resolved.auto_start_overlay = src.auto_start_overlay as boolean; + } + + if (asBoolean(src.bind_visible_overlay_to_mpv_sub_visibility) !== undefined) { + resolved.bind_visible_overlay_to_mpv_sub_visibility = + src.bind_visible_overlay_to_mpv_sub_visibility as boolean; + } else if (src.bind_visible_overlay_to_mpv_sub_visibility !== undefined) { + warn( + "bind_visible_overlay_to_mpv_sub_visibility", + src.bind_visible_overlay_to_mpv_sub_visibility, + resolved.bind_visible_overlay_to_mpv_sub_visibility, + "Expected boolean.", + ); + } + + if (isObject(src.subtitleStyle)) { + resolved.subtitleStyle = { + ...resolved.subtitleStyle, + ...(src.subtitleStyle as ResolvedConfig["subtitleStyle"]), + secondary: { + ...resolved.subtitleStyle.secondary, + ...(isObject(src.subtitleStyle.secondary) + ? (src.subtitleStyle + .secondary as ResolvedConfig["subtitleStyle"]["secondary"]) + : {}), + }, + }; + } + + if (isObject(src.ankiConnect)) { + const ac = src.ankiConnect; + const aiSource = isObject(ac.ai) + ? ac.ai + : isObject(ac.openRouter) + ? ac.openRouter + : {}; + resolved.ankiConnect = { + ...resolved.ankiConnect, + ...(isObject(ac) ? (ac as Partial) : {}), + fields: { + ...resolved.ankiConnect.fields, + ...(isObject(ac.fields) + ? (ac.fields as ResolvedConfig["ankiConnect"]["fields"]) + : {}), + }, + ai: { + ...resolved.ankiConnect.ai, + ...(aiSource as ResolvedConfig["ankiConnect"]["ai"]), + }, + media: { + ...resolved.ankiConnect.media, + ...(isObject(ac.media) + ? (ac.media as ResolvedConfig["ankiConnect"]["media"]) + : {}), + }, + behavior: { + ...resolved.ankiConnect.behavior, + ...(isObject(ac.behavior) + ? (ac.behavior as ResolvedConfig["ankiConnect"]["behavior"]) + : {}), + }, + metadata: { + ...resolved.ankiConnect.metadata, + ...(isObject(ac.metadata) + ? (ac.metadata as ResolvedConfig["ankiConnect"]["metadata"]) + : {}), + }, + isLapis: { + ...resolved.ankiConnect.isLapis, + ...(isObject(ac.isLapis) + ? (ac.isLapis as ResolvedConfig["ankiConnect"]["isLapis"]) + : {}), + }, + isKiku: { + ...resolved.ankiConnect.isKiku, + ...(isObject(ac.isKiku) + ? (ac.isKiku as ResolvedConfig["ankiConnect"]["isKiku"]) + : {}), + }, + }; + + const legacy = ac as Record; + const mapLegacy = ( + key: string, + apply: (value: unknown) => void, + ): void => { + if (legacy[key] !== undefined) apply(legacy[key]); + }; + + mapLegacy("audioField", (value) => { + resolved.ankiConnect.fields.audio = value as string; + }); + mapLegacy("imageField", (value) => { + resolved.ankiConnect.fields.image = value as string; + }); + mapLegacy("sentenceField", (value) => { + resolved.ankiConnect.fields.sentence = value as string; + }); + mapLegacy("miscInfoField", (value) => { + resolved.ankiConnect.fields.miscInfo = value as string; + }); + mapLegacy("miscInfoPattern", (value) => { + resolved.ankiConnect.metadata.pattern = value as string; + }); + mapLegacy("generateAudio", (value) => { + resolved.ankiConnect.media.generateAudio = value as boolean; + }); + mapLegacy("generateImage", (value) => { + resolved.ankiConnect.media.generateImage = value as boolean; + }); + mapLegacy("imageType", (value) => { + resolved.ankiConnect.media.imageType = value as "static" | "avif"; + }); + mapLegacy("imageFormat", (value) => { + resolved.ankiConnect.media.imageFormat = value as + | "jpg" + | "png" + | "webp"; + }); + mapLegacy("imageQuality", (value) => { + resolved.ankiConnect.media.imageQuality = value as number; + }); + mapLegacy("imageMaxWidth", (value) => { + resolved.ankiConnect.media.imageMaxWidth = value as number; + }); + mapLegacy("imageMaxHeight", (value) => { + resolved.ankiConnect.media.imageMaxHeight = value as number; + }); + mapLegacy("animatedFps", (value) => { + resolved.ankiConnect.media.animatedFps = value as number; + }); + mapLegacy("animatedMaxWidth", (value) => { + resolved.ankiConnect.media.animatedMaxWidth = value as number; + }); + mapLegacy("animatedMaxHeight", (value) => { + resolved.ankiConnect.media.animatedMaxHeight = value as number; + }); + mapLegacy("animatedCrf", (value) => { + resolved.ankiConnect.media.animatedCrf = value as number; + }); + mapLegacy("audioPadding", (value) => { + resolved.ankiConnect.media.audioPadding = value as number; + }); + mapLegacy("fallbackDuration", (value) => { + resolved.ankiConnect.media.fallbackDuration = value as number; + }); + mapLegacy("maxMediaDuration", (value) => { + resolved.ankiConnect.media.maxMediaDuration = value as number; + }); + mapLegacy("overwriteAudio", (value) => { + resolved.ankiConnect.behavior.overwriteAudio = value as boolean; + }); + mapLegacy("overwriteImage", (value) => { + resolved.ankiConnect.behavior.overwriteImage = value as boolean; + }); + mapLegacy("mediaInsertMode", (value) => { + resolved.ankiConnect.behavior.mediaInsertMode = value as + | "append" + | "prepend"; + }); + mapLegacy("highlightWord", (value) => { + resolved.ankiConnect.behavior.highlightWord = value as boolean; + }); + mapLegacy("notificationType", (value) => { + resolved.ankiConnect.behavior.notificationType = value as + | "osd" + | "system" + | "both" + | "none"; + }); + mapLegacy("autoUpdateNewCards", (value) => { + resolved.ankiConnect.behavior.autoUpdateNewCards = value as boolean; + }); + + if ( + resolved.ankiConnect.isKiku.fieldGrouping !== "auto" && + resolved.ankiConnect.isKiku.fieldGrouping !== "manual" && + resolved.ankiConnect.isKiku.fieldGrouping !== "disabled" + ) { + warn( + "ankiConnect.isKiku.fieldGrouping", + resolved.ankiConnect.isKiku.fieldGrouping, + DEFAULT_CONFIG.ankiConnect.isKiku.fieldGrouping, + "Expected auto, manual, or disabled.", + ); + resolved.ankiConnect.isKiku.fieldGrouping = + DEFAULT_CONFIG.ankiConnect.isKiku.fieldGrouping; + } + } + + return { resolved, warnings }; + } +} diff --git a/src/config/template.ts b/src/config/template.ts new file mode 100644 index 0000000..7099f3a --- /dev/null +++ b/src/config/template.ts @@ -0,0 +1,78 @@ +import { ResolvedConfig } from "../types"; +import { + CONFIG_TEMPLATE_SECTIONS, + DEFAULT_CONFIG, + deepCloneConfig, +} from "./definitions"; + +function renderValue(value: unknown, indent = 0): string { + const pad = " ".repeat(indent); + const nextPad = " ".repeat(indent + 2); + + if (value === null) return "null"; + if (typeof value === "string") return JSON.stringify(value); + if (typeof value === "number" || typeof value === "boolean") return String(value); + + if (Array.isArray(value)) { + if (value.length === 0) return "[]"; + const items = value.map((item) => `${nextPad}${renderValue(item, indent + 2)}`); + return `\n${items.join(",\n")}\n${pad}`.replace(/^/, "[").concat("]"); + } + + if (typeof value === "object") { + const entries = Object.entries(value as Record).filter( + ([, child]) => child !== undefined, + ); + if (entries.length === 0) return "{}"; + const lines = entries.map( + ([key, child]) => `${nextPad}${JSON.stringify(key)}: ${renderValue(child, indent + 2)}`, + ); + return `\n${lines.join(",\n")}\n${pad}`.replace(/^/, "{").concat("}"); + } + + return "null"; +} + +function renderSection( + key: keyof ResolvedConfig, + value: unknown, + isLast: boolean, + comments: string[], +): string { + const lines: string[] = []; + lines.push(" // =========================================="); + for (const comment of comments) { + lines.push(` // ${comment}`); + } + lines.push(" // =========================================="); + lines.push(` ${JSON.stringify(key)}: ${renderValue(value, 2)}${isLast ? "" : ","}`); + return lines.join("\n"); +} + +export function generateConfigTemplate(config: ResolvedConfig = deepCloneConfig(DEFAULT_CONFIG)): string { + const lines: string[] = []; + lines.push("/**"); + lines.push(" * SubMiner Example Configuration File"); + lines.push(" *"); + lines.push(" * This file is auto-generated from src/config/definitions.ts."); + lines.push(" * Copy to ~/.config/SubMiner/config.jsonc and edit as needed."); + lines.push(" */"); + lines.push("{"); + + CONFIG_TEMPLATE_SECTIONS.forEach((section, index) => { + lines.push(""); + const comments = [section.title, ...section.description, ...(section.notes ?? [])]; + lines.push( + renderSection( + section.key, + config[section.key], + index === CONFIG_TEMPLATE_SECTIONS.length - 1, + comments, + ), + ); + }); + + lines.push("}"); + lines.push(""); + return lines.join("\n"); +} diff --git a/src/generate-config-example.ts b/src/generate-config-example.ts new file mode 100644 index 0000000..b9e8856 --- /dev/null +++ b/src/generate-config-example.ts @@ -0,0 +1,12 @@ +import * as fs from "fs"; +import * as path from "path"; +import { DEFAULT_CONFIG, generateConfigTemplate } from "./config"; + +function main(): void { + const outputPath = path.join(process.cwd(), "config.example.jsonc"); + const template = generateConfigTemplate(DEFAULT_CONFIG); + fs.writeFileSync(outputPath, template, "utf-8"); + console.log(`Generated ${outputPath}`); +} + +main(); diff --git a/src/logger.ts b/src/logger.ts new file mode 100644 index 0000000..1e0b791 --- /dev/null +++ b/src/logger.ts @@ -0,0 +1,150 @@ +export type LogLevel = "debug" | "info" | "warn" | "error"; + +type LogMethod = (message: string, ...meta: unknown[]) => void; + +type Logger = { + debug: LogMethod; + info: LogMethod; + warn: LogMethod; + error: LogMethod; + child: (childScope: string) => Logger; +}; + +const LOG_LEVELS: LogLevel[] = ["debug", "info", "warn", "error"]; +const LEVEL_PRIORITY: Record = { + debug: 10, + info: 20, + warn: 30, + error: 40, +}; + +function pad(value: number): string { + return String(value).padStart(2, "0"); +} + +function formatTimestamp(date: Date): string { + const year = date.getFullYear(); + const month = pad(date.getMonth() + 1); + const day = pad(date.getDate()); + const hour = pad(date.getHours()); + const minute = pad(date.getMinutes()); + const second = pad(date.getSeconds()); + return `${year}-${month}-${day} ${hour}:${minute}:${second}`; +} + +function resolveMinLevel(): LogLevel { + const raw = + typeof process !== "undefined" && process?.env + ? process.env.SUBMINER_LOG_LEVEL + : undefined; + const normalized = (raw || "").toLowerCase() as LogLevel; + if (LOG_LEVELS.includes(normalized)) { + return normalized; + } + return "info"; +} + +function normalizeError(error: Error): { message: string; stack?: string } { + return { + message: error.message, + ...(error.stack ? { stack: error.stack } : {}), + }; +} + +function sanitizeMeta(value: unknown): unknown { + if (value instanceof Error) { + return normalizeError(value); + } + if (typeof value === "bigint") { + return value.toString(); + } + return value; +} + +function safeStringify(value: unknown): string { + if (typeof value === "string") { + return value; + } + if ( + typeof value === "number" || + typeof value === "boolean" || + typeof value === "undefined" || + value === null + ) { + return String(value); + } + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} + +function emit( + level: LogLevel, + scope: string, + message: string, + meta: unknown[], +): void { + const minLevel = resolveMinLevel(); + if (LEVEL_PRIORITY[level] < LEVEL_PRIORITY[minLevel]) { + return; + } + + const timestamp = formatTimestamp(new Date()); + const prefix = `[subminer] - ${timestamp} - ${level.toUpperCase()} - [${scope}] ${message}`; + const normalizedMeta = meta.map(sanitizeMeta); + + if (normalizedMeta.length === 0) { + if (level === "error") { + console.error(prefix); + } else if (level === "warn") { + console.warn(prefix); + } else if (level === "debug") { + console.debug(prefix); + } else { + console.info(prefix); + } + return; + } + + const serialized = normalizedMeta.map(safeStringify).join(" "); + const finalMessage = `${prefix} ${serialized}`; + + if (level === "error") { + console.error(finalMessage); + } else if (level === "warn") { + console.warn(finalMessage); + } else if (level === "debug") { + console.debug(finalMessage); + } else { + console.info(finalMessage); + } +} + +export function createLogger(scope: string): Logger { + const baseScope = scope.trim(); + if (!baseScope) { + throw new Error("Logger scope is required"); + } + + const logAt = (level: LogLevel): LogMethod => { + return (message: string, ...meta: unknown[]) => { + emit(level, baseScope, message, meta); + }; + }; + + return { + debug: logAt("debug"), + info: logAt("info"), + warn: logAt("warn"), + error: logAt("error"), + child: (childScope: string): Logger => { + const normalizedChild = childScope.trim(); + if (!normalizedChild) { + throw new Error("Child logger scope is required"); + } + return createLogger(`${baseScope}:${normalizedChild}`); + }, + }; +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..316beff --- /dev/null +++ b/src/main.ts @@ -0,0 +1,5003 @@ +/* + SubMiner - All-in-one sentence mining overlay + Copyright (C) 2024 sudacode + + 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 . +*/ +import { + app, + BrowserWindow, + session, + ipcMain, + globalShortcut, + clipboard, + shell, + protocol, + screen, + IpcMainEvent, + Extension, + Notification, + nativeImage, +} from "electron"; + +protocol.registerSchemesAsPrivileged([ + { + scheme: "chrome-extension", + privileges: { + standard: true, + secure: true, + supportFetchAPI: true, + corsEnabled: true, + bypassCSP: true, + }, + }, +]); + +import * as path from "path"; +import * as net from "net"; +import * as http from "http"; +import * as https from "https"; +import * as os from "os"; +import * as fs from "fs"; +import * as crypto from "crypto"; +import * as readline from "readline"; +import * as childProcess from "child_process"; +import WebSocket from "ws"; +import { MecabTokenizer } from "./mecab-tokenizer"; +import { mergeTokens } from "./token-merger"; +import { createWindowTracker, BaseWindowTracker } from "./window-trackers"; +import { + Config, + JimakuApiResponse, + JimakuDownloadResult, + JimakuEntry, + JimakuFileEntry, + JimakuFilesQuery, + JimakuMediaInfo, + JimakuSearchQuery, + JimakuDownloadQuery, + JimakuConfig, + JimakuLanguagePreference, + SubtitleData, + SubtitlePosition, + Keybinding, + WindowGeometry, + SecondarySubMode, + MpvClient, + SubsyncConfig, + SubsyncMode, + SubsyncManualPayload, + SubsyncManualRunRequest, + SubsyncResult, + KikuFieldGroupingRequestData, + KikuFieldGroupingChoice, + KikuMergePreviewRequest, + KikuMergePreviewResponse, + RuntimeOptionApplyResult, + RuntimeOptionId, + RuntimeOptionState, + RuntimeOptionValue, + MpvSubtitleRenderMetrics, +} from "./types"; +import { SubtitleTimingTracker } from "./subtitle-timing-tracker"; +import { AnkiIntegration } from "./anki-integration"; +import { RuntimeOptionsManager } from "./runtime-options"; +import { + ConfigService, + DEFAULT_CONFIG, + DEFAULT_KEYBINDINGS, + generateConfigTemplate, + SPECIAL_COMMANDS, +} from "./config"; + +if (process.platform === "linux") { + // Wayland requires the portal backend for reliable globalShortcut support. + app.commandLine.appendSwitch("enable-features", "GlobalShortcutsPortal"); +} + +const DEFAULT_TEXTHOOKER_PORT = 5174; +let texthookerServer: http.Server | null = null; +let subtitleWebSocketServer: WebSocket.Server | null = null; +const CONFIG_DIR = path.join(os.homedir(), ".config", "SubMiner"); +const USER_DATA_PATH = CONFIG_DIR; +const configService = new ConfigService(CONFIG_DIR); +const isDev = + process.argv.includes("--dev") || process.argv.includes("--debug"); + +function getDefaultSocketPath(): string { + if (process.platform === "win32") { + return "\\\\.\\pipe\\subminer-socket"; + } + return "/tmp/subminer-socket"; +} + +interface CliArgs { + start: boolean; + stop: boolean; + toggle: boolean; + toggleVisibleOverlay: boolean; + toggleInvisibleOverlay: boolean; + settings: boolean; + show: boolean; + hide: boolean; + showVisibleOverlay: boolean; + hideVisibleOverlay: boolean; + showInvisibleOverlay: boolean; + hideInvisibleOverlay: boolean; + copySubtitle: boolean; + copySubtitleMultiple: boolean; + mineSentence: boolean; + mineSentenceMultiple: boolean; + updateLastCardFromClipboard: boolean; + toggleSecondarySub: boolean; + triggerFieldGrouping: boolean; + triggerSubsync: boolean; + markAudioCard: boolean; + openRuntimeOptions: boolean; + texthooker: boolean; + help: boolean; + autoStartOverlay: boolean; + generateConfig: boolean; + configPath?: string; + backupOverwrite: boolean; + socketPath?: string; + backend?: string; + texthookerPort?: number; + verbose: boolean; + logLevel?: "debug" | "info" | "warn" | "error"; +} + +type CliCommandSource = "initial" | "second-instance"; + +function parseArgs(argv: string[]): CliArgs { + const args: CliArgs = { + start: false, + stop: false, + toggle: false, + toggleVisibleOverlay: false, + toggleInvisibleOverlay: false, + settings: false, + show: false, + hide: false, + showVisibleOverlay: false, + hideVisibleOverlay: false, + showInvisibleOverlay: false, + hideInvisibleOverlay: false, + copySubtitle: false, + copySubtitleMultiple: false, + mineSentence: false, + mineSentenceMultiple: false, + updateLastCardFromClipboard: false, + toggleSecondarySub: false, + triggerFieldGrouping: false, + triggerSubsync: false, + markAudioCard: false, + openRuntimeOptions: false, + texthooker: false, + help: false, + autoStartOverlay: false, + generateConfig: false, + backupOverwrite: false, + verbose: false, + }; + + const readValue = (value?: string): string | undefined => { + if (!value) return undefined; + if (value.startsWith("--")) return undefined; + return value; + }; + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (!arg.startsWith("--")) continue; + + if (arg === "--start") args.start = true; + else if (arg === "--stop") args.stop = true; + else if (arg === "--toggle") args.toggle = true; + else if (arg === "--toggle-visible-overlay") + args.toggleVisibleOverlay = true; + else if (arg === "--toggle-invisible-overlay") + args.toggleInvisibleOverlay = true; + else if (arg === "--settings" || arg === "--yomitan") args.settings = true; + else if (arg === "--show") args.show = true; + else if (arg === "--hide") args.hide = true; + else if (arg === "--show-visible-overlay") args.showVisibleOverlay = true; + else if (arg === "--hide-visible-overlay") args.hideVisibleOverlay = true; + else if (arg === "--show-invisible-overlay") + args.showInvisibleOverlay = true; + else if (arg === "--hide-invisible-overlay") + args.hideInvisibleOverlay = true; + else if (arg === "--copy-subtitle") args.copySubtitle = true; + else if (arg === "--copy-subtitle-multiple") args.copySubtitleMultiple = true; + else if (arg === "--mine-sentence") args.mineSentence = true; + else if (arg === "--mine-sentence-multiple") args.mineSentenceMultiple = true; + else if (arg === "--update-last-card-from-clipboard") + args.updateLastCardFromClipboard = true; + else if (arg === "--toggle-secondary-sub") args.toggleSecondarySub = true; + else if (arg === "--trigger-field-grouping") + args.triggerFieldGrouping = true; + else if (arg === "--trigger-subsync") args.triggerSubsync = true; + else if (arg === "--mark-audio-card") args.markAudioCard = true; + else if (arg === "--open-runtime-options") args.openRuntimeOptions = true; + else if (arg === "--texthooker") args.texthooker = true; + else if (arg === "--auto-start-overlay") args.autoStartOverlay = true; + else if (arg === "--generate-config") args.generateConfig = true; + else if (arg === "--backup-overwrite") args.backupOverwrite = true; + else if (arg === "--help") args.help = true; + else if (arg === "--verbose") args.verbose = true; + else if (arg.startsWith("--log-level=")) { + const value = arg.split("=", 2)[1]?.toLowerCase(); + if ( + value === "debug" || + value === "info" || + value === "warn" || + value === "error" + ) { + args.logLevel = value; + } + } else if (arg === "--log-level") { + const value = readValue(argv[i + 1])?.toLowerCase(); + if ( + value === "debug" || + value === "info" || + value === "warn" || + value === "error" + ) { + args.logLevel = value; + } + } else if (arg.startsWith("--config-path=")) { + const value = arg.split("=", 2)[1]; + if (value) args.configPath = value; + } else if (arg === "--config-path") { + const value = readValue(argv[i + 1]); + if (value) args.configPath = value; + } else if (arg.startsWith("--socket=")) { + const value = arg.split("=", 2)[1]; + if (value) args.socketPath = value; + } else if (arg === "--socket") { + const value = readValue(argv[i + 1]); + if (value) args.socketPath = value; + } else if (arg.startsWith("--backend=")) { + const value = arg.split("=", 2)[1]; + if (value) args.backend = value; + } else if (arg === "--backend") { + const value = readValue(argv[i + 1]); + if (value) args.backend = value; + } else if (arg.startsWith("--port=")) { + const value = Number(arg.split("=", 2)[1]); + if (!Number.isNaN(value)) args.texthookerPort = value; + } else if (arg === "--port") { + const value = Number(readValue(argv[i + 1])); + if (!Number.isNaN(value)) args.texthookerPort = value; + } + } + + return args; +} + +function printHelp(): void { + console.log(` +SubMiner CLI commands: + --start Start MPV IPC connection and overlay control loop + --stop Stop the running overlay app + --toggle Toggle visible subtitle overlay visibility (legacy alias) + --toggle-visible-overlay Toggle visible subtitle overlay visibility + --toggle-invisible-overlay Toggle invisible interactive overlay visibility + --settings Open Yomitan settings window + --texthooker Launch texthooker only (no overlay window) + --show Force show visible overlay (legacy alias) + --hide Force hide visible overlay (legacy alias) + --show-visible-overlay Force show visible subtitle overlay + --hide-visible-overlay Force hide visible subtitle overlay + --show-invisible-overlay Force show invisible interactive overlay + --hide-invisible-overlay Force hide invisible interactive overlay + --copy-subtitle Copy current subtitle text + --copy-subtitle-multiple Start multi-copy mode + --mine-sentence Mine sentence card from current subtitle + --mine-sentence-multiple Start multi-mine sentence mode + --update-last-card-from-clipboard Update last card from clipboard + --toggle-secondary-sub Cycle secondary subtitle mode + --trigger-field-grouping Trigger Kiku field grouping + --trigger-subsync Run subtitle sync + --mark-audio-card Mark last card as audio card + --open-runtime-options Open runtime options palette + --auto-start-overlay Auto-hide mpv subtitles on connect (show overlay) + --socket PATH Override MPV IPC socket/pipe path + --backend BACKEND Override window tracker backend (auto, hyprland, sway, x11, macos) + --port PORT Texthooker server port (default: ${DEFAULT_TEXTHOOKER_PORT}) + --verbose Enable debug logging (equivalent to --log-level debug) + --log-level LEVEL Set log level: debug, info, warn, error + --generate-config Generate default config.jsonc from centralized config registry + --config-path PATH Target config path for --generate-config + --backup-overwrite With --generate-config, backup and overwrite existing file + --dev Run in development mode + --debug Alias for --dev + --help Show this help +`); +} + +function hasExplicitCommand(args: CliArgs): boolean { + return ( + args.start || + args.stop || + args.toggle || + args.toggleVisibleOverlay || + args.toggleInvisibleOverlay || + args.settings || + args.show || + args.hide || + args.showVisibleOverlay || + args.hideVisibleOverlay || + args.showInvisibleOverlay || + args.hideInvisibleOverlay || + args.copySubtitle || + args.copySubtitleMultiple || + args.mineSentence || + args.mineSentenceMultiple || + args.updateLastCardFromClipboard || + args.toggleSecondarySub || + args.triggerFieldGrouping || + args.triggerSubsync || + args.markAudioCard || + args.openRuntimeOptions || + args.texthooker || + args.generateConfig || + args.help + ); +} + +function shouldStartApp(args: CliArgs): boolean { + if (args.stop && !args.start) return false; + if ( + args.start || + args.toggle || + args.toggleVisibleOverlay || + args.toggleInvisibleOverlay || + args.copySubtitle || + args.copySubtitleMultiple || + args.mineSentence || + args.mineSentenceMultiple || + args.updateLastCardFromClipboard || + args.toggleSecondarySub || + args.triggerFieldGrouping || + args.triggerSubsync || + args.markAudioCard || + args.openRuntimeOptions || + args.texthooker + ) { + return true; + } + return false; +} + +function formatBackupTimestamp(date = new Date()): string { + const pad = (v: number): string => String(v).padStart(2, "0"); + return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`; +} + +function promptYesNo(question: string): Promise { + return new Promise((resolve) => { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + rl.question(question, (answer) => { + rl.close(); + const normalized = answer.trim().toLowerCase(); + resolve(normalized === "y" || normalized === "yes"); + }); + }); +} + +async function generateDefaultConfigFile(args: CliArgs): Promise { + const targetPath = args.configPath + ? path.resolve(args.configPath) + : path.join(CONFIG_DIR, "config.jsonc"); + const template = generateConfigTemplate(DEFAULT_CONFIG); + + if (fs.existsSync(targetPath)) { + if (args.backupOverwrite) { + const backupPath = `${targetPath}.bak.${formatBackupTimestamp()}`; + fs.copyFileSync(targetPath, backupPath); + fs.writeFileSync(targetPath, template, "utf-8"); + console.log(`Backed up existing config to ${backupPath}`); + console.log(`Generated config at ${targetPath}`); + return 0; + } + + if (!process.stdin.isTTY || !process.stdout.isTTY) { + console.error( + `Config exists at ${targetPath}. Re-run with --backup-overwrite to back up and overwrite.`, + ); + return 1; + } + + const confirmed = await promptYesNo( + `Config exists at ${targetPath}. Back up and overwrite? [y/N] `, + ); + if (!confirmed) { + console.log("Config generation cancelled."); + return 0; + } + + const backupPath = `${targetPath}.bak.${formatBackupTimestamp()}`; + fs.copyFileSync(targetPath, backupPath); + fs.writeFileSync(targetPath, template, "utf-8"); + console.log(`Backed up existing config to ${backupPath}`); + console.log(`Generated config at ${targetPath}`); + return 0; + } + + const parentDir = path.dirname(targetPath); + if (!fs.existsSync(parentDir)) { + fs.mkdirSync(parentDir, { recursive: true }); + } + fs.writeFileSync(targetPath, template, "utf-8"); + console.log(`Generated config at ${targetPath}`); + return 0; +} + +if (!fs.existsSync(USER_DATA_PATH)) { + fs.mkdirSync(USER_DATA_PATH, { recursive: true }); +} +app.setPath("userData", USER_DATA_PATH); + +process.on("SIGINT", () => { + app.quit(); +}); +process.on("SIGTERM", () => { + app.quit(); +}); + +let mainWindow: BrowserWindow | null = null; +let invisibleWindow: BrowserWindow | null = null; +let yomitanExt: Extension | null = null; +let yomitanSettingsWindow: BrowserWindow | null = null; +let mpvClient: MpvIpcClient | null = null; +let reconnectTimer: ReturnType | null = null; +let currentSubText = ""; +let currentSubAssText = ""; +let visibleOverlayVisible = false; +let invisibleOverlayVisible = false; +let windowTracker: BaseWindowTracker | null = null; +let subtitlePosition: SubtitlePosition | null = null; +let currentMediaPath: string | null = null; +let pendingSubtitlePosition: SubtitlePosition | null = null; +let mecabTokenizer: MecabTokenizer | null = null; +let keybindings: Keybinding[] = []; +let subtitleTimingTracker: SubtitleTimingTracker | null = null; +let ankiIntegration: AnkiIntegration | null = null; +let secondarySubMode: SecondarySubMode = "hover"; +let lastSecondarySubToggleAtMs = 0; +let previousSecondarySubVisibility: boolean | null = null; +const DEFAULT_MPV_SUBTITLE_RENDER_METRICS: MpvSubtitleRenderMetrics = { + subPos: 100, + subFontSize: 38, + subScale: 1, + subMarginY: 34, + subMarginX: 19, + subFont: "sans-serif", + subSpacing: 0, + subBold: false, + subItalic: false, + subBorderSize: 2.5, + subShadowOffset: 0, + subAssOverride: "yes", + subScaleByWindow: true, + subUseMargins: true, + osdHeight: 720, + osdDimensions: null, +}; +let mpvSubtitleRenderMetrics: MpvSubtitleRenderMetrics = { + ...DEFAULT_MPV_SUBTITLE_RENDER_METRICS, +}; + +// Shortcut state tracking +let shortcutsRegistered = false; +let pendingMultiCopy = false; +let pendingMultiCopyTimeout: ReturnType | null = null; +let multiCopyDigitShortcuts: string[] = []; +let multiCopyEscapeShortcut: string | null = null; +let pendingMineSentenceMultiple = false; +let pendingMineSentenceMultipleTimeout: ReturnType | null = + null; +let overlayRuntimeInitialized = false; +let mineSentenceDigitShortcuts: string[] = []; +let mineSentenceEscapeShortcut: string | null = null; +let fieldGroupingResolver: ((choice: KikuFieldGroupingChoice) => void) | null = + null; +let runtimeOptionsManager: RuntimeOptionsManager | null = null; +let trackerNotReadyWarningShown = false; +let overlayDebugVisualizationEnabled = false; +type OverlayHostedModal = "runtime-options" | "subsync"; +const restoreVisibleOverlayOnModalClose = new Set(); + +const SUBTITLE_POSITIONS_DIR = path.join(CONFIG_DIR, "subtitle-positions"); + +interface LoadConfigResult { + success: boolean; + config: Config; +} + +function loadConfig(): LoadConfigResult { + const config = configService.getRawConfig(); + return { success: true, config }; +} + +function saveConfig(config: Config): void { + try { + configService.saveRawConfig(config); + configService.reloadConfig(); + } catch (err) { + console.error("Failed to save config:", (err as Error).message); + } +} + +function getRuntimeOptionsState(): RuntimeOptionState[] { + if (!runtimeOptionsManager) return []; + return runtimeOptionsManager.listOptions(); +} + +function getOverlayWindows(): BrowserWindow[] { + const windows: BrowserWindow[] = []; + if (mainWindow && !mainWindow.isDestroyed()) { + windows.push(mainWindow); + } + if (invisibleWindow && !invisibleWindow.isDestroyed()) { + windows.push(invisibleWindow); + } + return windows; +} + +function broadcastToOverlayWindows(channel: string, ...args: unknown[]): void { + for (const window of getOverlayWindows()) { + window.webContents.send(channel, ...args); + } +} + +function broadcastRuntimeOptionsChanged(): void { + broadcastToOverlayWindows( + "runtime-options:changed", + getRuntimeOptionsState(), + ); +} + +function setOverlayDebugVisualizationEnabled(enabled: boolean): void { + if (overlayDebugVisualizationEnabled === enabled) return; + overlayDebugVisualizationEnabled = enabled; + broadcastToOverlayWindows( + "overlay-debug-visualization:set", + overlayDebugVisualizationEnabled, + ); +} + +function applyRuntimeOptionResult( + result: RuntimeOptionApplyResult, +): RuntimeOptionApplyResult { + if (result.ok && result.osdMessage) { + showMpvOsd(result.osdMessage); + } + return result; +} + +function openRuntimeOptionsPalette(): void { + sendToVisibleOverlay("runtime-options:open", undefined, { + restoreOnModalClose: "runtime-options", + }); +} + +function getResolvedConfig() { + return configService.getConfig(); +} + +function getInitialInvisibleOverlayVisibility(): boolean { + const visibility = getResolvedConfig().invisibleOverlay.startupVisibility; + if (visibility === "visible") return true; + if (visibility === "hidden") return false; + if (process.platform === "linux") return false; + return true; +} + +function shouldAutoInitializeOverlayRuntimeFromConfig(): boolean { + const config = getResolvedConfig(); + if (config.auto_start_overlay === true) return true; + if (config.invisibleOverlay.startupVisibility === "visible") return true; + return false; +} + +function shouldBindVisibleOverlayToMpvSubVisibility(): boolean { + return getResolvedConfig().bind_visible_overlay_to_mpv_sub_visibility; +} + +function commandNeedsOverlayRuntime(args: CliArgs): boolean { + return ( + args.toggle || + args.toggleVisibleOverlay || + args.toggleInvisibleOverlay || + args.show || + args.hide || + args.showVisibleOverlay || + args.hideVisibleOverlay || + args.showInvisibleOverlay || + args.hideInvisibleOverlay || + args.copySubtitle || + args.copySubtitleMultiple || + args.mineSentence || + args.mineSentenceMultiple || + args.updateLastCardFromClipboard || + args.toggleSecondarySub || + args.triggerFieldGrouping || + args.triggerSubsync || + args.markAudioCard || + args.openRuntimeOptions + ); +} + +function isAutoUpdateEnabledRuntime(): boolean { + const value = runtimeOptionsManager?.getOptionValue( + "anki.autoUpdateNewCards", + ); + if (typeof value === "boolean") return value; + const config = getResolvedConfig(); + return config.ankiConnect?.behavior?.autoUpdateNewCards !== false; +} + +function getJimakuConfig(): JimakuConfig { + const config = getResolvedConfig(); + return config.jimaku ?? {}; +} + +function getJimakuBaseUrl(): string { + const config = getJimakuConfig(); + return config.apiBaseUrl || DEFAULT_CONFIG.jimaku.apiBaseUrl; +} + +function getJimakuLanguagePreference(): JimakuLanguagePreference { + const config = getJimakuConfig(); + return config.languagePreference || DEFAULT_CONFIG.jimaku.languagePreference; +} + +function getJimakuMaxEntryResults(): number { + const config = getJimakuConfig(); + const value = config.maxEntryResults; + if (typeof value === "number" && Number.isFinite(value) && value > 0) { + return Math.floor(value); + } + return DEFAULT_CONFIG.jimaku.maxEntryResults; +} + +function execCommand( + command: string, +): Promise<{ stdout: string; stderr: string }> { + return new Promise((resolve, reject) => { + childProcess.exec(command, { timeout: 10000 }, (err, stdout, stderr) => { + if (err) { + reject(err); + return; + } + resolve({ stdout, stderr }); + }); + }); +} + +async function resolveJimakuApiKey(): Promise { + const config = getJimakuConfig(); + if (config.apiKey && config.apiKey.trim()) { + console.log("[jimaku] API key found in config"); + return config.apiKey.trim(); + } + if (config.apiKeyCommand && config.apiKeyCommand.trim()) { + try { + const { stdout } = await execCommand(config.apiKeyCommand); + const key = stdout.trim(); + console.log( + `[jimaku] apiKeyCommand result: ${key.length > 0 ? "key obtained" : "empty output"}`, + ); + return key.length > 0 ? key : null; + } catch (err) { + console.error( + "Failed to run jimaku.apiKeyCommand:", + (err as Error).message, + ); + return null; + } + } + console.log( + "[jimaku] No API key configured (neither apiKey nor apiKeyCommand set)", + ); + return null; +} + +function getRetryAfter(headers: http.IncomingHttpHeaders): number | undefined { + const value = headers["x-ratelimit-reset-after"]; + if (!value) return undefined; + const raw = Array.isArray(value) ? value[0] : value; + const parsed = Number.parseFloat(raw); + if (!Number.isFinite(parsed)) return undefined; + return parsed; +} + +async function jimakuFetchJson( + endpoint: string, + query: Record = {}, +): Promise> { + const apiKey = await resolveJimakuApiKey(); + if (!apiKey) { + return { + ok: false, + error: { + error: + "Jimaku API key not set. Configure jimaku.apiKey or jimaku.apiKeyCommand.", + code: 401, + }, + }; + } + + const baseUrl = getJimakuBaseUrl(); + const url = new URL(endpoint, baseUrl); + for (const [key, value] of Object.entries(query)) { + if (value === null || value === undefined) continue; + url.searchParams.set(key, String(value)); + } + + console.log(`[jimaku] GET ${url.toString()}`); + const transport = url.protocol === "https:" ? https : http; + + return new Promise((resolve) => { + const req = transport.request( + url, + { + method: "GET", + headers: { + Authorization: apiKey, + "User-Agent": "SubMiner", + }, + }, + (res) => { + let data = ""; + res.on("data", (chunk) => { + data += chunk.toString(); + }); + res.on("end", () => { + const status = res.statusCode || 0; + console.log(`[jimaku] Response HTTP ${status} for ${endpoint}`); + if (status >= 200 && status < 300) { + try { + const parsed = JSON.parse(data) as T; + resolve({ ok: true, data: parsed }); + } catch (err) { + console.error(`[jimaku] JSON parse error: ${data.slice(0, 200)}`); + resolve({ + ok: false, + error: { error: "Failed to parse Jimaku response JSON." }, + }); + } + return; + } + + let errorMessage = `Jimaku API error (HTTP ${status})`; + try { + const parsed = JSON.parse(data) as { error?: string }; + if (parsed && parsed.error) { + errorMessage = parsed.error; + } + } catch (err) { + // Ignore parse errors. + } + console.error(`[jimaku] API error: ${errorMessage}`); + + resolve({ + ok: false, + error: { + error: errorMessage, + code: status || undefined, + retryAfter: + status === 429 ? getRetryAfter(res.headers) : undefined, + }, + }); + }); + }, + ); + + req.on("error", (err) => { + console.error(`[jimaku] Network error: ${(err as Error).message}`); + resolve({ + ok: false, + error: { error: `Jimaku request failed: ${(err as Error).message}` }, + }); + }); + + req.end(); + }); +} + +function matchEpisodeFromName(name: string): { + season: number | null; + episode: number | null; + index: number | null; + confidence: "high" | "medium" | "low"; +} { + const seasonEpisode = name.match(/S(\d{1,2})E(\d{1,3})/i); + if (seasonEpisode && seasonEpisode.index !== undefined) { + return { + season: Number.parseInt(seasonEpisode[1], 10), + episode: Number.parseInt(seasonEpisode[2], 10), + index: seasonEpisode.index, + confidence: "high", + }; + } + + const alt = name.match(/(\d{1,2})x(\d{1,3})/i); + if (alt && alt.index !== undefined) { + return { + season: Number.parseInt(alt[1], 10), + episode: Number.parseInt(alt[2], 10), + index: alt.index, + confidence: "high", + }; + } + + const epOnly = name.match(/(?:^|[\s._-])E(?:P)?(\d{1,3})(?:\b|[\s._-])/i); + if (epOnly && epOnly.index !== undefined) { + return { + season: null, + episode: Number.parseInt(epOnly[1], 10), + index: epOnly.index, + confidence: "medium", + }; + } + + const numeric = name.match(/(?:^|[-–—]\s*)(\d{1,3})\s*[-–—]/); + if (numeric && numeric.index !== undefined) { + return { + season: null, + episode: Number.parseInt(numeric[1], 10), + index: numeric.index, + confidence: "medium", + }; + } + + return { season: null, episode: null, index: null, confidence: "low" }; +} + +function detectSeasonFromDir(mediaPath: string): number | null { + const parent = path.basename(path.dirname(mediaPath)); + const match = parent.match(/(?:Season|S)\s*(\d{1,2})/i); + if (!match) return null; + const parsed = Number.parseInt(match[1], 10); + return Number.isFinite(parsed) ? parsed : null; +} + +function cleanupTitle(value: string): string { + return value + .replace(/^[\s-–—]+/, "") + .replace(/[\s-–—]+$/, "") + .replace(/\s+/g, " ") + .trim(); +} + +function parseMediaInfo(mediaPath: string | null): JimakuMediaInfo { + if (!mediaPath) { + return { + title: "", + season: null, + episode: null, + confidence: "low", + filename: "", + rawTitle: "", + }; + } + + const filename = path.basename(mediaPath); + let name = filename.replace(/\.[^/.]+$/, ""); + name = name.replace(/\[[^\]]*]/g, " "); + name = name.replace(/\(\d{4}\)/g, " "); + name = name.replace(/[._]/g, " "); + name = name.replace(/[–—]/g, "-"); + name = name.replace(/\s+/g, " ").trim(); + + const parsed = matchEpisodeFromName(name); + let titlePart = name; + if (parsed.index !== null) { + titlePart = name.slice(0, parsed.index); + } + + const seasonFromDir = parsed.season ?? detectSeasonFromDir(mediaPath); + const title = cleanupTitle(titlePart || name); + + return { + title, + season: seasonFromDir, + episode: parsed.episode, + confidence: parsed.confidence, + filename, + rawTitle: name, + }; +} + +function getSubtitlePositionFilePath(mediaPath: string): string { + const key = normalizeMediaPathForSubtitlePosition(mediaPath); + const hash = crypto.createHash("sha256").update(key).digest("hex"); + return path.join(SUBTITLE_POSITIONS_DIR, `${hash}.json`); +} + +function normalizeMediaPathForSubtitlePosition(mediaPath: string): string { + const trimmed = mediaPath.trim(); + if (!trimmed) return trimmed; + + // Keep URL-like targets as-is; local files are normalized to stable absolute paths. + if ( + /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed) || + /^ytsearch:/.test(trimmed) + ) { + return trimmed; + } + + const resolved = path.resolve(trimmed); + let normalized = resolved; + try { + if (fs.existsSync(resolved)) { + normalized = fs.realpathSync(resolved); + } + } catch { + normalized = resolved; + } + + if (process.platform === "win32") { + normalized = normalized.toLowerCase(); + } + + return normalized; +} + +function persistSubtitlePosition(position: SubtitlePosition): void { + if (!currentMediaPath) return; + if (!fs.existsSync(SUBTITLE_POSITIONS_DIR)) { + fs.mkdirSync(SUBTITLE_POSITIONS_DIR, { recursive: true }); + } + const positionPath = getSubtitlePositionFilePath(currentMediaPath); + fs.writeFileSync(positionPath, JSON.stringify(position, null, 2)); +} + +function loadSubtitlePosition(): SubtitlePosition | null { + const fallbackPosition = getResolvedConfig().subtitlePosition; + if (!currentMediaPath) { + subtitlePosition = fallbackPosition; + return subtitlePosition; + } + + try { + const positionPath = getSubtitlePositionFilePath(currentMediaPath); + if (!fs.existsSync(positionPath)) { + subtitlePosition = fallbackPosition; + return subtitlePosition; + } + + const data = fs.readFileSync(positionPath, "utf-8"); + const parsed = JSON.parse(data) as Partial; + if ( + parsed && + typeof parsed.yPercent === "number" && + Number.isFinite(parsed.yPercent) + ) { + subtitlePosition = { yPercent: parsed.yPercent }; + } else { + subtitlePosition = fallbackPosition; + } + } catch (err) { + console.error("Failed to load subtitle position:", (err as Error).message); + subtitlePosition = fallbackPosition; + } + + return subtitlePosition; +} + +function saveSubtitlePosition(position: SubtitlePosition): void { + subtitlePosition = position; + if (!currentMediaPath) { + pendingSubtitlePosition = position; + console.warn("Queued subtitle position save - no media path yet"); + return; + } + + try { + persistSubtitlePosition(position); + pendingSubtitlePosition = null; + } catch (err) { + console.error("Failed to save subtitle position:", (err as Error).message); + } +} + +function updateCurrentMediaPath(mediaPath: unknown): void { + const nextPath = + typeof mediaPath === "string" && mediaPath.trim().length > 0 + ? mediaPath + : null; + if (nextPath === currentMediaPath) return; + currentMediaPath = nextPath; + + if (currentMediaPath && pendingSubtitlePosition) { + try { + persistSubtitlePosition(pendingSubtitlePosition); + subtitlePosition = pendingSubtitlePosition; + pendingSubtitlePosition = null; + } catch (err) { + console.error( + "Failed to persist queued subtitle position:", + (err as Error).message, + ); + } + } + + const position = loadSubtitlePosition(); + broadcastToOverlayWindows("subtitle-position:set", position); +} + +function getTexthookerPath(): string | null { + const searchPaths = [ + path.join(__dirname, "..", "vendor", "texthooker-ui", "docs"), + path.join(process.resourcesPath, "app", "vendor", "texthooker-ui", "docs"), + ]; + for (const p of searchPaths) { + if (fs.existsSync(path.join(p, "index.html"))) { + return p; + } + } + return null; +} + +function startTexthookerServer(port: number): http.Server | null { + const texthookerPath = getTexthookerPath(); + if (!texthookerPath) { + console.error("texthooker-ui not found"); + return null; + } + + texthookerServer = http.createServer((req, res) => { + let urlPath = (req.url || "/").split("?")[0]; + let filePath = path.join( + texthookerPath, + urlPath === "/" ? "index.html" : urlPath, + ); + + const ext = path.extname(filePath); + const mimeTypes: Record = { + ".html": "text/html", + ".js": "application/javascript", + ".css": "text/css", + ".json": "application/json", + ".png": "image/png", + ".svg": "image/svg+xml", + ".ttf": "font/ttf", + ".woff": "font/woff", + ".woff2": "font/woff2", + }; + + fs.readFile(filePath, (err, data) => { + if (err) { + res.writeHead(404); + res.end("Not found"); + return; + } + res.writeHead(200, { "Content-Type": mimeTypes[ext] || "text/plain" }); + res.end(data); + }); + }); + + texthookerServer.listen(port, "127.0.0.1", () => { + console.log(`Texthooker server running at http://127.0.0.1:${port}`); + }); + + return texthookerServer; +} + +function stopTexthookerServer(): void { + if (texthookerServer) { + texthookerServer.close(); + texthookerServer = null; + } +} + +function hasMpvWebsocket(): boolean { + const mpvWebsocketPath = path.join( + os.homedir(), + ".config", + "mpv", + "mpv_websocket", + ); + return fs.existsSync(mpvWebsocketPath); +} + +function startSubtitleWebSocketServer(port: number): void { + subtitleWebSocketServer = new WebSocket.Server({ port, host: "127.0.0.1" }); + + subtitleWebSocketServer.on("connection", (ws: WebSocket) => { + console.log("WebSocket client connected"); + if (currentSubText) { + ws.send(JSON.stringify({ sentence: currentSubText })); + } + }); + + subtitleWebSocketServer.on("error", (err: Error) => { + console.error("WebSocket server error:", err.message); + }); + + console.log(`Subtitle WebSocket server running on ws://127.0.0.1:${port}`); +} + +function broadcastSubtitle(text: string): void { + if (!subtitleWebSocketServer) return; + const message = JSON.stringify({ sentence: text }); + for (const client of subtitleWebSocketServer.clients) { + if (client.readyState === WebSocket.OPEN) { + client.send(message); + } + } +} + +function stopSubtitleWebSocketServer(): void { + if (subtitleWebSocketServer) { + subtitleWebSocketServer.close(); + subtitleWebSocketServer = null; + } +} + +interface MpvTrack { + id?: number; + type?: string; + selected?: boolean; + external?: boolean; + lang?: string; + title?: string; + codec?: string; + "ff-index"?: number; + "external-filename"?: string; +} + +interface SubsyncResolvedConfig { + defaultMode: SubsyncMode; + alassPath: string; + ffsubsyncPath: string; + ffmpegPath: string; +} + +const DEFAULT_SUBSYNC_EXECUTABLE_PATHS = { + alass: "/usr/bin/alass", + ffsubsync: "/usr/bin/ffsubsync", + ffmpeg: "/usr/bin/ffmpeg", +} as const; + +interface SubsyncContext { + videoPath: string; + primaryTrack: MpvTrack; + secondaryTrack: MpvTrack | null; + sourceTracks: MpvTrack[]; + audioStreamIndex: number | null; +} + +interface CommandResult { + ok: boolean; + code: number | null; + stderr: string; + stdout: string; + error?: string; +} + +const AUTOSUBSYNC_SPINNER_FRAMES = ["|", "/", "-", "\\"]; +let subsyncInProgress = false; + +async function runWithSubsyncSpinner( + task: () => Promise, + label = "Subsync: syncing", +): Promise { + let frame = 0; + showMpvOsd(`${label} ${AUTOSUBSYNC_SPINNER_FRAMES[0]}`); + const timer = setInterval(() => { + frame = (frame + 1) % AUTOSUBSYNC_SPINNER_FRAMES.length; + showMpvOsd(`${label} ${AUTOSUBSYNC_SPINNER_FRAMES[frame]}`); + }, 150); + + try { + return await task(); + } finally { + clearInterval(timer); + } +} + +interface FileExtractionResult { + path: string; + temporary: boolean; +} + +function getSubsyncConfig( + config: SubsyncConfig | undefined, +): SubsyncResolvedConfig { + const resolvePath = (value: string | undefined, fallback: string): string => { + const trimmed = value?.trim(); + return trimmed && trimmed.length > 0 ? trimmed : fallback; + }; + + return { + defaultMode: config?.defaultMode ?? DEFAULT_CONFIG.subsync.defaultMode, + alassPath: resolvePath( + config?.alass_path, + DEFAULT_SUBSYNC_EXECUTABLE_PATHS.alass, + ), + ffsubsyncPath: resolvePath( + config?.ffsubsync_path, + DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffsubsync, + ), + ffmpegPath: resolvePath( + config?.ffmpeg_path, + DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffmpeg, + ), + }; +} + +function hasPathSeparators(value: string): boolean { + return value.includes("/") || value.includes("\\"); +} + +function fileExists(pathOrEmpty: string): boolean { + if (!pathOrEmpty) return false; + try { + return fs.existsSync(pathOrEmpty); + } catch { + return false; + } +} + +function formatTrackLabel(track: MpvTrack): string { + const trackId = typeof track.id === "number" ? track.id : -1; + const source = track.external ? "External" : "Internal"; + const lang = track.lang || track.title || "unknown"; + const active = track.selected ? " (active)" : ""; + return `${source} #${trackId} - ${lang}${active}`; +} + +function getTrackById( + tracks: MpvTrack[], + trackId: number | null, +): MpvTrack | null { + if (trackId === null) return null; + return tracks.find((track) => track.id === trackId) ?? null; +} + +function codecToExtension(codec: string | undefined): string | null { + if (!codec) return null; + const normalized = codec.toLowerCase(); + if (normalized === "subrip" || normalized === "srt") return "srt"; + if (normalized === "ass" || normalized === "ssa") return "ass"; + return null; +} + +function runCommand( + executable: string, + args: string[], + timeoutMs = 120000, +): Promise { + return new Promise((resolve) => { + const child = childProcess.spawn(executable, args, { + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + const timeout = setTimeout(() => { + child.kill("SIGKILL"); + }, timeoutMs); + + child.stdout.on("data", (chunk: Buffer) => { + stdout += chunk.toString(); + }); + child.stderr.on("data", (chunk: Buffer) => { + stderr += chunk.toString(); + }); + child.on("error", (error: Error) => { + clearTimeout(timeout); + resolve({ + ok: false, + code: null, + stderr, + stdout, + error: error.message, + }); + }); + child.on("close", (code: number | null) => { + clearTimeout(timeout); + resolve({ + ok: code === 0, + code, + stderr, + stdout, + }); + }); + }); +} + +function loadKeybindings(): Keybinding[] { + const config = getResolvedConfig(); + const userBindings = config.keybindings || []; + + const bindingMap = new Map(); + + for (const binding of DEFAULT_KEYBINDINGS) { + bindingMap.set(binding.key, binding.command); + } + + for (const binding of userBindings) { + if (binding.command === null) { + bindingMap.delete(binding.key); + } else { + bindingMap.set(binding.key, binding.command); + } + } + + keybindings = []; + for (const [key, command] of bindingMap) { + if (command !== null) { + keybindings.push({ key, command }); + } + } + + return keybindings; +} + +const initialArgs = parseArgs(process.argv); +if (initialArgs.logLevel) { + process.env.SUBMINER_LOG_LEVEL = initialArgs.logLevel; +} else if (initialArgs.verbose) { + process.env.SUBMINER_LOG_LEVEL = "debug"; +} + +function getElectronOzonePlatformHint(): string | null { + const hint = process.env.ELECTRON_OZONE_PLATFORM_HINT?.trim().toLowerCase(); + if (hint) return hint; + const ozone = process.env.OZONE_PLATFORM?.trim().toLowerCase(); + if (ozone) return ozone; + return null; +} + +function enforceUnsupportedWaylandMode(args: CliArgs): void { + if (process.platform !== "linux") return; + if (!shouldStartApp(args)) return; + const hint = getElectronOzonePlatformHint(); + if (hint !== "wayland") return; + + const message = + "Unsupported Electron backend: Wayland. Set ELECTRON_OZONE_PLATFORM_HINT=x11 and restart SubMiner."; + console.error(message); + throw new Error(message); +} + +enforceUnsupportedWaylandMode(initialArgs); + +let mpvSocketPath = initialArgs.socketPath ?? getDefaultSocketPath(); +let texthookerPort = initialArgs.texthookerPort ?? DEFAULT_TEXTHOOKER_PORT; +const backendOverride = initialArgs.backend ?? null; +const autoStartOverlay = initialArgs.autoStartOverlay; +const texthookerOnlyMode = initialArgs.texthooker; + +if (initialArgs.generateConfig && !shouldStartApp(initialArgs)) { + generateDefaultConfigFile(initialArgs) + .then((exitCode) => { + process.exitCode = exitCode; + app.quit(); + }) + .catch((error: Error) => { + console.error(`Failed to generate config: ${error.message}`); + process.exitCode = 1; + app.quit(); + }); +} else { + const gotTheLock = app.requestSingleInstanceLock(); + + if (!gotTheLock) { + app.quit(); + } else { + app.on("second-instance", (_event, argv) => { + handleCliCommand(parseArgs(argv), "second-instance"); + }); + if (initialArgs.help && !shouldStartApp(initialArgs)) { + printHelp(); + app.quit(); + } else if (!shouldStartApp(initialArgs)) { + if (initialArgs.stop && !initialArgs.start) { + app.quit(); + } else { + console.error("No running instance. Use --start to launch the app."); + app.quit(); + } + } else { + app.whenReady().then(async () => { + loadSubtitlePosition(); + loadKeybindings(); + + mpvClient = new MpvIpcClient(mpvSocketPath); + + configService.reloadConfig(); + const config = getResolvedConfig(); + for (const warning of configService.getWarnings()) { + console.warn( + `[config] ${warning.path}: ${warning.message} value=${JSON.stringify(warning.value)} fallback=${JSON.stringify(warning.fallback)}`, + ); + } + runtimeOptionsManager = new RuntimeOptionsManager( + () => configService.getConfig().ankiConnect, + { + applyAnkiPatch: (patch) => { + if (ankiIntegration) { + ankiIntegration.applyRuntimeConfigPatch(patch); + } + }, + onOptionsChanged: () => { + broadcastRuntimeOptionsChanged(); + refreshOverlayShortcuts(); + }, + }, + ); + secondarySubMode = config.secondarySub?.defaultMode ?? "hover"; + const wsConfig = config.websocket || {}; + const wsEnabled = wsConfig.enabled ?? "auto"; + const wsPort = wsConfig.port || DEFAULT_CONFIG.websocket.port; + + if ( + wsEnabled === true || + (wsEnabled === "auto" && !hasMpvWebsocket()) + ) { + startSubtitleWebSocketServer(wsPort); + } else if (wsEnabled === "auto") { + console.log( + "mpv_websocket detected, skipping built-in WebSocket server", + ); + } + + mecabTokenizer = new MecabTokenizer(); + await mecabTokenizer.checkAvailability(); + + subtitleTimingTracker = new SubtitleTimingTracker(); + + await loadYomitanExtension(); + if (texthookerOnlyMode) { + console.log("Texthooker-only mode enabled; skipping overlay window."); + } else if (shouldAutoInitializeOverlayRuntimeFromConfig()) { + initializeOverlayRuntime(); + } else { + console.log( + "Overlay runtime deferred: waiting for explicit overlay command.", + ); + } + + handleInitialArgs(); + }); + + app.on("window-all-closed", () => { + if (process.platform !== "darwin") { + app.quit(); + } + }); + + app.on("will-quit", () => { + globalShortcut.unregisterAll(); + stopSubtitleWebSocketServer(); + stopTexthookerServer(); + if (windowTracker) { + windowTracker.stop(); + } + if (mpvClient && mpvClient.socket) { + mpvClient.socket.destroy(); + } + if (reconnectTimer) { + clearTimeout(reconnectTimer); + } + if (subtitleTimingTracker) { + subtitleTimingTracker.destroy(); + } + if (ankiIntegration) { + ankiIntegration.destroy(); + } + }); + + app.on("activate", () => { + if ( + overlayRuntimeInitialized && + BrowserWindow.getAllWindows().length === 0 + ) { + createMainWindow(); + createInvisibleWindow(); + updateVisibleOverlayVisibility(); + updateInvisibleOverlayVisibility(); + } + }); + } + } +} + +function handleCliCommand( + args: CliArgs, + source: CliCommandSource = "initial", +): void { + const hasNonStartAction = + args.stop || + args.toggle || + args.toggleVisibleOverlay || + args.toggleInvisibleOverlay || + args.settings || + args.show || + args.hide || + args.showVisibleOverlay || + args.hideVisibleOverlay || + args.showInvisibleOverlay || + args.hideInvisibleOverlay || + args.copySubtitle || + args.copySubtitleMultiple || + args.mineSentence || + args.mineSentenceMultiple || + args.updateLastCardFromClipboard || + args.toggleSecondarySub || + args.triggerFieldGrouping || + args.triggerSubsync || + args.markAudioCard || + args.openRuntimeOptions || + args.texthooker || + args.help; + const ignoreStart = source === "second-instance" && args.start; + if (ignoreStart && !hasNonStartAction) { + console.log("Ignoring --start because SubMiner is already running."); + return; + } + const shouldStart = + !ignoreStart && + (args.start || + (source === "initial" && + (args.toggle || + args.toggleVisibleOverlay || + args.toggleInvisibleOverlay))); + const needsOverlayRuntime = commandNeedsOverlayRuntime(args); + + if (args.socketPath !== undefined) { + mpvSocketPath = args.socketPath; + if (mpvClient) { + mpvClient.setSocketPath(mpvSocketPath); + } + } + if (args.texthookerPort !== undefined) { + if (texthookerServer) { + console.warn( + "Ignoring --port override because the texthooker server is already running.", + ); + } else { + texthookerPort = args.texthookerPort; + } + } + + if (args.stop) { + console.log("Stopping SubMiner..."); + app.quit(); + return; + } + + if (needsOverlayRuntime && !overlayRuntimeInitialized) { + initializeOverlayRuntime(); + } + + if (shouldStart && mpvClient) { + mpvClient.setSocketPath(mpvSocketPath); + mpvClient.connect(); + console.log(`Starting MPV IPC connection on socket: ${mpvSocketPath}`); + } + + if (args.toggle || args.toggleVisibleOverlay) { + toggleVisibleOverlay(); + } else if (args.toggleInvisibleOverlay) { + toggleInvisibleOverlay(); + } else if (args.settings) { + setTimeout(() => { + openYomitanSettings(); + }, 1000); + } else if (args.show || args.showVisibleOverlay) { + setVisibleOverlayVisible(true); + } else if (args.hide || args.hideVisibleOverlay) { + setVisibleOverlayVisible(false); + } else if (args.showInvisibleOverlay) { + setInvisibleOverlayVisible(true); + } else if (args.hideInvisibleOverlay) { + setInvisibleOverlayVisible(false); + } else if (args.copySubtitle) { + copyCurrentSubtitle(); + } else if (args.copySubtitleMultiple) { + startPendingMultiCopy(getConfiguredShortcuts().multiCopyTimeoutMs); + } else if (args.mineSentence) { + mineSentenceCard().catch((err) => { + console.error("mineSentenceCard failed:", err); + showMpvOsd(`Mine sentence failed: ${(err as Error).message}`); + }); + } else if (args.mineSentenceMultiple) { + startPendingMineSentenceMultiple(getConfiguredShortcuts().multiCopyTimeoutMs); + } else if (args.updateLastCardFromClipboard) { + updateLastCardFromClipboard().catch((err) => { + console.error("updateLastCardFromClipboard failed:", err); + showMpvOsd(`Update failed: ${(err as Error).message}`); + }); + } else if (args.toggleSecondarySub) { + cycleSecondarySubMode(); + } else if (args.triggerFieldGrouping) { + triggerFieldGrouping().catch((err) => { + console.error("triggerFieldGrouping failed:", err); + showMpvOsd(`Field grouping failed: ${(err as Error).message}`); + }); + } else if (args.triggerSubsync) { + triggerSubsyncFromConfig().catch((err) => { + console.error("triggerSubsyncFromConfig failed:", err); + showMpvOsd(`Subsync failed: ${(err as Error).message}`); + }); + } else if (args.markAudioCard) { + markLastCardAsAudioCard().catch((err) => { + console.error("markLastCardAsAudioCard failed:", err); + showMpvOsd(`Audio card failed: ${(err as Error).message}`); + }); + } else if (args.openRuntimeOptions) { + openRuntimeOptionsPalette(); + } else if (args.texthooker) { + if (!texthookerServer) { + startTexthookerServer(texthookerPort); + } + const config = getResolvedConfig(); + const openBrowser = config.texthooker?.openBrowser !== false; + if (openBrowser) { + shell.openExternal(`http://127.0.0.1:${texthookerPort}`); + } + console.log(`Texthooker available at http://127.0.0.1:${texthookerPort}`); + } else if (args.help) { + printHelp(); + if (!mainWindow) app.quit(); + } +} + +function handleInitialArgs(): void { + handleCliCommand(initialArgs, "initial"); +} + +function asFiniteNumber( + value: unknown, + fallback: number, + min?: number, + max?: number, +): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + return fallback; + } + let next = value; + if (typeof min === "number") next = Math.max(min, next); + if (typeof max === "number") next = Math.min(max, next); + return next; +} + +function asString(value: unknown, fallback: string): string { + if (typeof value !== "string") return fallback; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : fallback; +} + +function asBoolean(value: unknown, fallback: boolean): boolean { + if (typeof value === "boolean") return value; + if (typeof value === "string") { + const normalized = value.trim().toLowerCase(); + if (normalized === "yes" || normalized === "true" || normalized === "1") { + return true; + } + if (normalized === "no" || normalized === "false" || normalized === "0") { + return false; + } + } + return fallback; +} + +function updateMpvSubtitleRenderMetrics( + patch: Partial, +): void { + const patchOsd = patch.osdDimensions; + const nextOsdDimensions = + patchOsd && + typeof patchOsd.w === "number" && + typeof patchOsd.h === "number" && + typeof patchOsd.ml === "number" && + typeof patchOsd.mr === "number" && + typeof patchOsd.mt === "number" && + typeof patchOsd.mb === "number" + ? { + w: asFiniteNumber(patchOsd.w, 0, 1, 100000), + h: asFiniteNumber(patchOsd.h, 0, 1, 100000), + ml: asFiniteNumber(patchOsd.ml, 0, 0, 100000), + mr: asFiniteNumber(patchOsd.mr, 0, 0, 100000), + mt: asFiniteNumber(patchOsd.mt, 0, 0, 100000), + mb: asFiniteNumber(patchOsd.mb, 0, 0, 100000), + } + : patchOsd === null + ? null + : mpvSubtitleRenderMetrics.osdDimensions; + + const next: MpvSubtitleRenderMetrics = { + subPos: asFiniteNumber( + patch.subPos, + mpvSubtitleRenderMetrics.subPos, + 0, + 150, + ), + subFontSize: asFiniteNumber( + patch.subFontSize, + mpvSubtitleRenderMetrics.subFontSize, + 1, + 200, + ), + subScale: asFiniteNumber( + patch.subScale, + mpvSubtitleRenderMetrics.subScale, + 0.1, + 10, + ), + subMarginY: asFiniteNumber( + patch.subMarginY, + mpvSubtitleRenderMetrics.subMarginY, + 0, + 200, + ), + subMarginX: asFiniteNumber( + patch.subMarginX, + mpvSubtitleRenderMetrics.subMarginX, + 0, + 200, + ), + subFont: asString(patch.subFont, mpvSubtitleRenderMetrics.subFont), + subSpacing: asFiniteNumber( + patch.subSpacing, + mpvSubtitleRenderMetrics.subSpacing, + -100, + 100, + ), + subBold: asBoolean(patch.subBold, mpvSubtitleRenderMetrics.subBold), + subItalic: asBoolean(patch.subItalic, mpvSubtitleRenderMetrics.subItalic), + subBorderSize: asFiniteNumber( + patch.subBorderSize, + mpvSubtitleRenderMetrics.subBorderSize, + 0, + 100, + ), + subShadowOffset: asFiniteNumber( + patch.subShadowOffset, + mpvSubtitleRenderMetrics.subShadowOffset, + 0, + 100, + ), + subAssOverride: asString( + patch.subAssOverride, + mpvSubtitleRenderMetrics.subAssOverride, + ), + subScaleByWindow: asBoolean( + patch.subScaleByWindow, + mpvSubtitleRenderMetrics.subScaleByWindow, + ), + subUseMargins: asBoolean( + patch.subUseMargins, + mpvSubtitleRenderMetrics.subUseMargins, + ), + osdHeight: asFiniteNumber( + patch.osdHeight, + mpvSubtitleRenderMetrics.osdHeight, + 1, + 10000, + ), + osdDimensions: nextOsdDimensions, + }; + + const changed = + next.subPos !== mpvSubtitleRenderMetrics.subPos || + next.subFontSize !== mpvSubtitleRenderMetrics.subFontSize || + next.subScale !== mpvSubtitleRenderMetrics.subScale || + next.subMarginY !== mpvSubtitleRenderMetrics.subMarginY || + next.subMarginX !== mpvSubtitleRenderMetrics.subMarginX || + next.subFont !== mpvSubtitleRenderMetrics.subFont || + next.subSpacing !== mpvSubtitleRenderMetrics.subSpacing || + next.subBold !== mpvSubtitleRenderMetrics.subBold || + next.subItalic !== mpvSubtitleRenderMetrics.subItalic || + next.subBorderSize !== mpvSubtitleRenderMetrics.subBorderSize || + next.subShadowOffset !== mpvSubtitleRenderMetrics.subShadowOffset || + next.subAssOverride !== mpvSubtitleRenderMetrics.subAssOverride || + next.subScaleByWindow !== mpvSubtitleRenderMetrics.subScaleByWindow || + next.subUseMargins !== mpvSubtitleRenderMetrics.subUseMargins || + next.osdHeight !== mpvSubtitleRenderMetrics.osdHeight || + JSON.stringify(next.osdDimensions) !== + JSON.stringify(mpvSubtitleRenderMetrics.osdDimensions); + + if (!changed) return; + mpvSubtitleRenderMetrics = next; + broadcastToOverlayWindows( + "mpv-subtitle-render-metrics:set", + mpvSubtitleRenderMetrics, + ); +} + +interface MpvMessage { + event?: string; + name?: string; + data?: unknown; + request_id?: number; + error?: string; +} + +const MPV_REQUEST_ID_SUBTEXT = 101; +const MPV_REQUEST_ID_PATH = 102; +const MPV_REQUEST_ID_SECONDARY_SUBTEXT = 103; +const MPV_REQUEST_ID_SECONDARY_SUB_VISIBILITY = 104; +const MPV_REQUEST_ID_AID = 105; +const MPV_REQUEST_ID_SUB_POS = 106; +const MPV_REQUEST_ID_SUB_FONT_SIZE = 107; +const MPV_REQUEST_ID_SUB_SCALE = 108; +const MPV_REQUEST_ID_SUB_MARGIN_Y = 109; +const MPV_REQUEST_ID_SUB_MARGIN_X = 110; +const MPV_REQUEST_ID_SUB_FONT = 111; +const MPV_REQUEST_ID_SUB_SCALE_BY_WINDOW = 112; +const MPV_REQUEST_ID_OSD_HEIGHT = 113; +const MPV_REQUEST_ID_OSD_DIMENSIONS = 114; +const MPV_REQUEST_ID_SUBTEXT_ASS = 115; +const MPV_REQUEST_ID_SUB_SPACING = 116; +const MPV_REQUEST_ID_SUB_BOLD = 117; +const MPV_REQUEST_ID_SUB_ITALIC = 118; +const MPV_REQUEST_ID_SUB_BORDER_SIZE = 119; +const MPV_REQUEST_ID_SUB_SHADOW_OFFSET = 120; +const MPV_REQUEST_ID_SUB_ASS_OVERRIDE = 121; +const MPV_REQUEST_ID_SUB_USE_MARGINS = 122; +const MPV_REQUEST_ID_TRACK_LIST_SECONDARY = 200; +const MPV_REQUEST_ID_TRACK_LIST_AUDIO = 201; + +class MpvIpcClient implements MpvClient { + private socketPath: string; + public socket: net.Socket | null = null; + private buffer = ""; + public connected = false; + private connecting = false; + private reconnectAttempt = 0; + private firstConnection = true; + private hasConnectedOnce = false; + public currentVideoPath = ""; + public currentTimePos = 0; + public currentSubStart = 0; + public currentSubEnd = 0; + public currentSubText = ""; + public currentSecondarySubText = ""; + public currentAudioStreamIndex: number | null = null; + private currentAudioTrackId: number | null = null; + private pauseAtTime: number | null = null; + private pendingPauseAtSubEnd = false; + private nextDynamicRequestId = 1000; + private pendingRequests = new Map void>(); + + constructor(socketPath: string) { + this.socketPath = socketPath; + } + + setSocketPath(socketPath: string): void { + this.socketPath = socketPath; + } + + connect(): void { + if (this.connected || this.connecting) { + return; + } + + if (this.socket) { + this.socket.destroy(); + } + + this.connecting = true; + this.socket = new net.Socket(); + + this.socket.on("connect", () => { + console.log("Connected to MPV socket"); + this.connected = true; + this.connecting = false; + this.reconnectAttempt = 0; + this.hasConnectedOnce = true; + this.subscribeToProperties(); + this.getInitialState(); + + const shouldAutoStart = + autoStartOverlay || getResolvedConfig().auto_start_overlay === true; + if (this.firstConnection && shouldAutoStart) { + console.log("Auto-starting overlay, hiding mpv subtitles"); + setTimeout(() => { + setOverlayVisible(true); + }, 100); + } else if (shouldBindVisibleOverlayToMpvSubVisibility()) { + this.setSubVisibility(!visibleOverlayVisible); + } + + this.firstConnection = false; + }); + + this.socket.on("data", (data: Buffer) => { + this.buffer += data.toString(); + this.processBuffer(); + }); + + this.socket.on("error", (err: Error) => { + console.error("MPV socket error:", err.message); + this.connected = false; + this.connecting = false; + this.failPendingRequests(); + }); + + this.socket.on("close", () => { + console.log("MPV socket closed"); + this.connected = false; + this.connecting = false; + this.failPendingRequests(); + this.scheduleReconnect(); + }); + + this.socket.connect(this.socketPath); + } + + private scheduleReconnect(): void { + if (reconnectTimer) { + clearTimeout(reconnectTimer); + } + const attempt = this.reconnectAttempt++; + let delay: number; + if (this.hasConnectedOnce) { + if (attempt < 2) { + delay = 1000; + } else if (attempt < 4) { + delay = 2000; + } else if (attempt < 7) { + delay = 5000; + } else { + delay = 10000; + } + } else { + if (attempt < 2) { + delay = 200; + } else if (attempt < 4) { + delay = 500; + } else if (attempt < 6) { + delay = 1000; + } else { + delay = 2000; + } + } + reconnectTimer = setTimeout(() => { + console.log( + `Attempting to reconnect to MPV (attempt ${attempt + 1}, delay ${delay}ms)...`, + ); + this.connect(); + }, delay); + } + + private processBuffer(): void { + const lines = this.buffer.split("\n"); + this.buffer = lines.pop() || ""; + + for (const line of lines) { + if (!line.trim()) continue; + try { + const msg = JSON.parse(line) as MpvMessage; + this.handleMessage(msg); + } catch (e) { + console.error("Failed to parse MPV message:", line, e); + } + } + } + + private async handleMessage(msg: MpvMessage): Promise { + if (msg.event === "property-change") { + if (msg.name === "sub-text") { + currentSubText = (msg.data as string) || ""; + this.currentSubText = currentSubText; + if ( + subtitleTimingTracker && + this.currentSubStart !== undefined && + this.currentSubEnd !== undefined + ) { + subtitleTimingTracker.recordSubtitle( + currentSubText, + this.currentSubStart, + this.currentSubEnd, + ); + } + broadcastSubtitle(currentSubText); + if (getOverlayWindows().length > 0) { + const subtitleData = await tokenizeSubtitle(currentSubText); + broadcastToOverlayWindows("subtitle:set", subtitleData); + } + } else if (msg.name === "sub-text-ass") { + currentSubAssText = (msg.data as string) || ""; + broadcastToOverlayWindows("subtitle-ass:set", currentSubAssText); + } else if (msg.name === "sub-start") { + this.currentSubStart = (msg.data as number) || 0; + if (subtitleTimingTracker && currentSubText) { + subtitleTimingTracker.recordSubtitle( + currentSubText, + this.currentSubStart, + this.currentSubEnd, + ); + } + } else if (msg.name === "sub-end") { + this.currentSubEnd = (msg.data as number) || 0; + if (this.pendingPauseAtSubEnd && this.currentSubEnd > 0) { + this.pauseAtTime = this.currentSubEnd; + this.pendingPauseAtSubEnd = false; + this.send({ command: ["set_property", "pause", false] }); + } + if (subtitleTimingTracker && currentSubText) { + subtitleTimingTracker.recordSubtitle( + currentSubText, + this.currentSubStart, + this.currentSubEnd, + ); + } + } else if (msg.name === "secondary-sub-text") { + this.currentSecondarySubText = (msg.data as string) || ""; + broadcastToOverlayWindows( + "secondary-subtitle:set", + this.currentSecondarySubText, + ); + } else if (msg.name === "aid") { + this.currentAudioTrackId = + typeof msg.data === "number" ? (msg.data as number) : null; + this.syncCurrentAudioStreamIndex(); + } else if (msg.name === "time-pos") { + this.currentTimePos = (msg.data as number) || 0; + if ( + this.pauseAtTime !== null && + this.currentTimePos >= this.pauseAtTime + ) { + this.pauseAtTime = null; + this.send({ command: ["set_property", "pause", true] }); + } + } else if (msg.name === "path") { + this.currentVideoPath = (msg.data as string) || ""; + updateCurrentMediaPath(msg.data); + this.autoLoadSecondarySubTrack(); + this.syncCurrentAudioStreamIndex(); + } else if (msg.name === "sub-pos") { + updateMpvSubtitleRenderMetrics({ subPos: msg.data as number }); + } else if (msg.name === "sub-font-size") { + updateMpvSubtitleRenderMetrics({ subFontSize: msg.data as number }); + } else if (msg.name === "sub-scale") { + updateMpvSubtitleRenderMetrics({ subScale: msg.data as number }); + } else if (msg.name === "sub-margin-y") { + updateMpvSubtitleRenderMetrics({ subMarginY: msg.data as number }); + } else if (msg.name === "sub-margin-x") { + updateMpvSubtitleRenderMetrics({ subMarginX: msg.data as number }); + } else if (msg.name === "sub-font") { + updateMpvSubtitleRenderMetrics({ subFont: msg.data as string }); + } else if (msg.name === "sub-spacing") { + updateMpvSubtitleRenderMetrics({ subSpacing: msg.data as number }); + } else if (msg.name === "sub-bold") { + updateMpvSubtitleRenderMetrics({ + subBold: asBoolean(msg.data, mpvSubtitleRenderMetrics.subBold), + }); + } else if (msg.name === "sub-italic") { + updateMpvSubtitleRenderMetrics({ + subItalic: asBoolean(msg.data, mpvSubtitleRenderMetrics.subItalic), + }); + } else if (msg.name === "sub-border-size") { + updateMpvSubtitleRenderMetrics({ + subBorderSize: msg.data as number, + }); + } else if (msg.name === "sub-shadow-offset") { + updateMpvSubtitleRenderMetrics({ + subShadowOffset: msg.data as number, + }); + } else if (msg.name === "sub-ass-override") { + updateMpvSubtitleRenderMetrics({ + subAssOverride: msg.data as string, + }); + } else if (msg.name === "sub-scale-by-window") { + updateMpvSubtitleRenderMetrics({ + subScaleByWindow: asBoolean( + msg.data, + mpvSubtitleRenderMetrics.subScaleByWindow, + ), + }); + } else if (msg.name === "sub-use-margins") { + updateMpvSubtitleRenderMetrics({ + subUseMargins: asBoolean( + msg.data, + mpvSubtitleRenderMetrics.subUseMargins, + ), + }); + } else if (msg.name === "osd-height") { + updateMpvSubtitleRenderMetrics({ osdHeight: msg.data as number }); + } else if (msg.name === "osd-dimensions") { + const dims = msg.data as Record | null; + if (!dims) { + updateMpvSubtitleRenderMetrics({ osdDimensions: null }); + } else { + updateMpvSubtitleRenderMetrics({ + osdDimensions: { + w: asFiniteNumber(dims.w, 0), + h: asFiniteNumber(dims.h, 0), + ml: asFiniteNumber(dims.ml, 0), + mr: asFiniteNumber(dims.mr, 0), + mt: asFiniteNumber(dims.mt, 0), + mb: asFiniteNumber(dims.mb, 0), + }, + }); + } + } + } else if (msg.request_id) { + const pending = this.pendingRequests.get(msg.request_id); + if (pending) { + this.pendingRequests.delete(msg.request_id); + pending(msg); + return; + } + + if (msg.data === undefined) { + return; + } + + if (msg.request_id === MPV_REQUEST_ID_TRACK_LIST_SECONDARY) { + const tracks = msg.data as Array<{ + type: string; + lang?: string; + id: number; + }>; + if (Array.isArray(tracks)) { + const config = getResolvedConfig(); + const languages = config.secondarySub?.secondarySubLanguages || []; + const subTracks = tracks.filter((t) => t.type === "sub"); + for (const lang of languages) { + const match = subTracks.find((t) => t.lang === lang); + if (match) { + this.send({ + command: ["set_property", "secondary-sid", match.id], + }); + showMpvOsd(`Secondary subtitle: ${lang} (track ${match.id})`); + break; + } + } + } + } else if (msg.request_id === MPV_REQUEST_ID_TRACK_LIST_AUDIO) { + this.updateCurrentAudioStreamIndex( + msg.data as Array<{ + type?: string; + id?: number; + selected?: boolean; + "ff-index"?: number; + }>, + ); + } else if (msg.request_id === MPV_REQUEST_ID_SUBTEXT) { + currentSubText = (msg.data as string) || ""; + if (mpvClient) { + mpvClient.currentSubText = currentSubText; + } + broadcastSubtitle(currentSubText); + if (getOverlayWindows().length > 0) { + tokenizeSubtitle(currentSubText).then((subtitleData) => { + broadcastToOverlayWindows("subtitle:set", subtitleData); + }); + } + } else if (msg.request_id === MPV_REQUEST_ID_SUBTEXT_ASS) { + currentSubAssText = (msg.data as string) || ""; + broadcastToOverlayWindows("subtitle-ass:set", currentSubAssText); + } else if (msg.request_id === MPV_REQUEST_ID_PATH) { + updateCurrentMediaPath(msg.data); + } else if (msg.request_id === MPV_REQUEST_ID_AID) { + this.currentAudioTrackId = + typeof msg.data === "number" ? (msg.data as number) : null; + this.syncCurrentAudioStreamIndex(); + } else if (msg.request_id === MPV_REQUEST_ID_SECONDARY_SUBTEXT) { + this.currentSecondarySubText = (msg.data as string) || ""; + broadcastToOverlayWindows( + "secondary-subtitle:set", + this.currentSecondarySubText, + ); + } else if (msg.request_id === MPV_REQUEST_ID_SECONDARY_SUB_VISIBILITY) { + if (!shouldBindVisibleOverlayToMpvSubVisibility()) { + previousSecondarySubVisibility = null; + return; + } + previousSecondarySubVisibility = + msg.data === true || msg.data === "yes"; + this.send({ + command: ["set_property", "secondary-sub-visibility", "no"], + }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_POS) { + updateMpvSubtitleRenderMetrics({ subPos: msg.data as number }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_FONT_SIZE) { + updateMpvSubtitleRenderMetrics({ subFontSize: msg.data as number }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_SCALE) { + updateMpvSubtitleRenderMetrics({ subScale: msg.data as number }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_MARGIN_Y) { + updateMpvSubtitleRenderMetrics({ subMarginY: msg.data as number }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_MARGIN_X) { + updateMpvSubtitleRenderMetrics({ subMarginX: msg.data as number }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_FONT) { + updateMpvSubtitleRenderMetrics({ subFont: msg.data as string }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_SPACING) { + updateMpvSubtitleRenderMetrics({ subSpacing: msg.data as number }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_BOLD) { + updateMpvSubtitleRenderMetrics({ + subBold: asBoolean(msg.data, mpvSubtitleRenderMetrics.subBold), + }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_ITALIC) { + updateMpvSubtitleRenderMetrics({ + subItalic: asBoolean(msg.data, mpvSubtitleRenderMetrics.subItalic), + }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_BORDER_SIZE) { + updateMpvSubtitleRenderMetrics({ + subBorderSize: msg.data as number, + }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_SHADOW_OFFSET) { + updateMpvSubtitleRenderMetrics({ + subShadowOffset: msg.data as number, + }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_ASS_OVERRIDE) { + updateMpvSubtitleRenderMetrics({ + subAssOverride: msg.data as string, + }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_SCALE_BY_WINDOW) { + updateMpvSubtitleRenderMetrics({ + subScaleByWindow: asBoolean( + msg.data, + mpvSubtitleRenderMetrics.subScaleByWindow, + ), + }); + } else if (msg.request_id === MPV_REQUEST_ID_SUB_USE_MARGINS) { + updateMpvSubtitleRenderMetrics({ + subUseMargins: asBoolean( + msg.data, + mpvSubtitleRenderMetrics.subUseMargins, + ), + }); + } else if (msg.request_id === MPV_REQUEST_ID_OSD_HEIGHT) { + updateMpvSubtitleRenderMetrics({ osdHeight: msg.data as number }); + } else if (msg.request_id === MPV_REQUEST_ID_OSD_DIMENSIONS) { + const dims = msg.data as Record | null; + if (!dims) { + updateMpvSubtitleRenderMetrics({ osdDimensions: null }); + } else { + updateMpvSubtitleRenderMetrics({ + osdDimensions: { + w: asFiniteNumber(dims.w, 0), + h: asFiniteNumber(dims.h, 0), + ml: asFiniteNumber(dims.ml, 0), + mr: asFiniteNumber(dims.mr, 0), + mt: asFiniteNumber(dims.mt, 0), + mb: asFiniteNumber(dims.mb, 0), + }, + }); + } + } + } + } + + private autoLoadSecondarySubTrack(): void { + const config = getResolvedConfig(); + if (!config.secondarySub?.autoLoadSecondarySub) return; + const languages = config.secondarySub.secondarySubLanguages; + if (!languages || languages.length === 0) return; + + setTimeout(() => { + this.send({ + command: ["get_property", "track-list"], + request_id: MPV_REQUEST_ID_TRACK_LIST_SECONDARY, + }); + }, 500); + } + + private syncCurrentAudioStreamIndex(): void { + this.send({ + command: ["get_property", "track-list"], + request_id: MPV_REQUEST_ID_TRACK_LIST_AUDIO, + }); + } + + private updateCurrentAudioStreamIndex( + tracks: Array<{ + type?: string; + id?: number; + selected?: boolean; + "ff-index"?: number; + }>, + ): void { + if (!Array.isArray(tracks)) { + this.currentAudioStreamIndex = null; + return; + } + + const audioTracks = tracks.filter((track) => track.type === "audio"); + const activeTrack = + audioTracks.find((track) => track.id === this.currentAudioTrackId) || + audioTracks.find((track) => track.selected === true); + + const ffIndex = activeTrack?.["ff-index"]; + this.currentAudioStreamIndex = + typeof ffIndex === "number" && Number.isInteger(ffIndex) && ffIndex >= 0 + ? ffIndex + : null; + } + + send(command: { command: unknown[]; request_id?: number }): boolean { + if (!this.connected || !this.socket) { + return false; + } + const msg = JSON.stringify(command) + "\n"; + this.socket.write(msg); + return true; + } + + request(command: unknown[]): Promise { + return new Promise((resolve, reject) => { + if (!this.connected || !this.socket) { + reject(new Error("MPV not connected")); + return; + } + + const requestId = this.nextDynamicRequestId++; + this.pendingRequests.set(requestId, resolve); + const sent = this.send({ command, request_id: requestId }); + if (!sent) { + this.pendingRequests.delete(requestId); + reject(new Error("Failed to send MPV request")); + return; + } + + setTimeout(() => { + if (this.pendingRequests.delete(requestId)) { + reject(new Error("MPV request timed out")); + } + }, 4000); + }); + } + + async requestProperty(name: string): Promise { + const response = await this.request(["get_property", name]); + if (response.error && response.error !== "success") { + throw new Error( + `Failed to read MPV property '${name}': ${response.error}`, + ); + } + return response.data; + } + + private failPendingRequests(): void { + for (const [requestId, resolve] of this.pendingRequests.entries()) { + resolve({ request_id: requestId, error: "disconnected" }); + } + this.pendingRequests.clear(); + } + + private subscribeToProperties(): void { + this.send({ command: ["observe_property", 1, "sub-text"] }); + this.send({ command: ["observe_property", 2, "path"] }); + this.send({ command: ["observe_property", 3, "sub-start"] }); + this.send({ command: ["observe_property", 4, "sub-end"] }); + this.send({ command: ["observe_property", 5, "time-pos"] }); + this.send({ command: ["observe_property", 6, "secondary-sub-text"] }); + this.send({ command: ["observe_property", 7, "aid"] }); + this.send({ command: ["observe_property", 8, "sub-pos"] }); + this.send({ command: ["observe_property", 9, "sub-font-size"] }); + this.send({ command: ["observe_property", 10, "sub-scale"] }); + this.send({ command: ["observe_property", 11, "sub-margin-y"] }); + this.send({ command: ["observe_property", 12, "sub-margin-x"] }); + this.send({ command: ["observe_property", 13, "sub-font"] }); + this.send({ command: ["observe_property", 14, "sub-spacing"] }); + this.send({ command: ["observe_property", 15, "sub-bold"] }); + this.send({ command: ["observe_property", 16, "sub-italic"] }); + this.send({ command: ["observe_property", 17, "sub-scale-by-window"] }); + this.send({ command: ["observe_property", 18, "osd-height"] }); + this.send({ command: ["observe_property", 19, "osd-dimensions"] }); + this.send({ command: ["observe_property", 20, "sub-text-ass"] }); + this.send({ command: ["observe_property", 21, "sub-border-size"] }); + this.send({ command: ["observe_property", 22, "sub-shadow-offset"] }); + this.send({ command: ["observe_property", 23, "sub-ass-override"] }); + this.send({ command: ["observe_property", 24, "sub-use-margins"] }); + } + + private getInitialState(): void { + this.send({ + command: ["get_property", "sub-text"], + request_id: MPV_REQUEST_ID_SUBTEXT, + }); + this.send({ + command: ["get_property", "sub-text-ass"], + request_id: MPV_REQUEST_ID_SUBTEXT_ASS, + }); + this.send({ + command: ["get_property", "path"], + request_id: MPV_REQUEST_ID_PATH, + }); + this.send({ + command: ["get_property", "secondary-sub-text"], + request_id: MPV_REQUEST_ID_SECONDARY_SUBTEXT, + }); + this.send({ + command: ["get_property", "aid"], + request_id: MPV_REQUEST_ID_AID, + }); + this.send({ + command: ["get_property", "sub-pos"], + request_id: MPV_REQUEST_ID_SUB_POS, + }); + this.send({ + command: ["get_property", "sub-font-size"], + request_id: MPV_REQUEST_ID_SUB_FONT_SIZE, + }); + this.send({ + command: ["get_property", "sub-scale"], + request_id: MPV_REQUEST_ID_SUB_SCALE, + }); + this.send({ + command: ["get_property", "sub-margin-y"], + request_id: MPV_REQUEST_ID_SUB_MARGIN_Y, + }); + this.send({ + command: ["get_property", "sub-margin-x"], + request_id: MPV_REQUEST_ID_SUB_MARGIN_X, + }); + this.send({ + command: ["get_property", "sub-font"], + request_id: MPV_REQUEST_ID_SUB_FONT, + }); + this.send({ + command: ["get_property", "sub-spacing"], + request_id: MPV_REQUEST_ID_SUB_SPACING, + }); + this.send({ + command: ["get_property", "sub-bold"], + request_id: MPV_REQUEST_ID_SUB_BOLD, + }); + this.send({ + command: ["get_property", "sub-italic"], + request_id: MPV_REQUEST_ID_SUB_ITALIC, + }); + this.send({ + command: ["get_property", "sub-scale-by-window"], + request_id: MPV_REQUEST_ID_SUB_SCALE_BY_WINDOW, + }); + this.send({ + command: ["get_property", "osd-height"], + request_id: MPV_REQUEST_ID_OSD_HEIGHT, + }); + this.send({ + command: ["get_property", "osd-dimensions"], + request_id: MPV_REQUEST_ID_OSD_DIMENSIONS, + }); + this.send({ + command: ["get_property", "sub-border-size"], + request_id: MPV_REQUEST_ID_SUB_BORDER_SIZE, + }); + this.send({ + command: ["get_property", "sub-shadow-offset"], + request_id: MPV_REQUEST_ID_SUB_SHADOW_OFFSET, + }); + this.send({ + command: ["get_property", "sub-ass-override"], + request_id: MPV_REQUEST_ID_SUB_ASS_OVERRIDE, + }); + this.send({ + command: ["get_property", "sub-use-margins"], + request_id: MPV_REQUEST_ID_SUB_USE_MARGINS, + }); + } + + setSubVisibility(visible: boolean): void { + this.send({ + command: ["set_property", "sub-visibility", visible ? "yes" : "no"], + }); + } + + replayCurrentSubtitle(): void { + this.pendingPauseAtSubEnd = true; + this.send({ command: ["sub-seek", 0] }); + } + + playNextSubtitle(): void { + this.pendingPauseAtSubEnd = true; + this.send({ command: ["sub-seek", 1] }); + } +} + +async function tokenizeSubtitle(text: string): Promise { + if (!text || !mecabTokenizer) { + return { text, tokens: null }; + } + + const displayText = text + .replace(/\r\n/g, "\n") + .replace(/\\N/g, "\n") + .replace(/\\n/g, "\n") + .trim(); + + if (!displayText) { + return { text, tokens: null }; + } + + const tokenizeText = displayText + .replace(/\n/g, " ") + .replace(/\s+/g, " ") + .trim(); + + try { + const rawTokens = await mecabTokenizer.tokenize(tokenizeText); + + if (rawTokens && rawTokens.length > 0) { + const mergedTokens = mergeTokens(rawTokens); + return { text: displayText, tokens: mergedTokens }; + } + } catch (err) { + console.error("Tokenization error:", (err as Error).message); + } + + return { text: displayText, tokens: null }; +} + +function updateOverlayBounds(geometry: WindowGeometry): void { + if (!geometry) return; + for (const window of getOverlayWindows()) { + window.setBounds({ + x: geometry.x, + y: geometry.y, + width: geometry.width, + height: geometry.height, + }); + } +} + +function ensureOverlayWindowLevel(window: BrowserWindow): void { + if (process.platform === "darwin") { + window.setAlwaysOnTop(true, "screen-saver", 1); + window.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true }); + window.setFullScreenable(false); + return; + } + window.setAlwaysOnTop(true); +} + +function enforceOverlayLayerOrder(): void { + if (!visibleOverlayVisible || !invisibleOverlayVisible) return; + if (!mainWindow || mainWindow.isDestroyed()) return; + if (!invisibleWindow || invisibleWindow.isDestroyed()) return; + + ensureOverlayWindowLevel(mainWindow); + mainWindow.moveTop(); +} + +function ensureExtensionCopy(sourceDir: string): string { + // Copy extension to writable location on Linux and macOS + // MV3 service workers need write access for IndexedDB/storage + // App bundles on macOS are read-only, causing service worker failures + if (process.platform === "win32") { + return sourceDir; + } + + const extensionsRoot = path.join(USER_DATA_PATH, "extensions"); + const targetDir = path.join(extensionsRoot, "yomitan"); + + const sourceManifest = path.join(sourceDir, "manifest.json"); + const targetManifest = path.join(targetDir, "manifest.json"); + + let shouldCopy = !fs.existsSync(targetDir); + if ( + !shouldCopy && + fs.existsSync(sourceManifest) && + fs.existsSync(targetManifest) + ) { + try { + const sourceVersion = ( + JSON.parse(fs.readFileSync(sourceManifest, "utf-8")) as { + version: string; + } + ).version; + const targetVersion = ( + JSON.parse(fs.readFileSync(targetManifest, "utf-8")) as { + version: string; + } + ).version; + shouldCopy = sourceVersion !== targetVersion; + } catch (e) { + shouldCopy = true; + } + } + + if (shouldCopy) { + fs.mkdirSync(extensionsRoot, { recursive: true }); + fs.rmSync(targetDir, { recursive: true, force: true }); + fs.cpSync(sourceDir, targetDir, { recursive: true }); + console.log(`Copied yomitan extension to ${targetDir}`); + } + + return targetDir; +} + +async function loadYomitanExtension(): Promise { + const searchPaths = [ + path.join(__dirname, "..", "vendor", "yomitan"), + path.join(process.resourcesPath, "yomitan"), + "/usr/share/SubMiner/yomitan", + path.join(USER_DATA_PATH, "yomitan"), + ]; + + let extPath: string | null = null; + for (const p of searchPaths) { + if (fs.existsSync(p)) { + extPath = p; + break; + } + } + + console.log("Yomitan search paths:", searchPaths); + console.log("Found Yomitan at:", extPath); + + if (!extPath) { + console.error("Yomitan extension not found in any search path"); + console.error("Install Yomitan to one of:", searchPaths); + return null; + } + + extPath = ensureExtensionCopy(extPath); + console.log("Using extension path:", extPath); + + try { + const extensions = session.defaultSession.extensions; + if (extensions) { + yomitanExt = await extensions.loadExtension(extPath, { + allowFileAccess: true, + }); + } else { + yomitanExt = await session.defaultSession.loadExtension(extPath, { + allowFileAccess: true, + }); + } + console.log("Yomitan extension loaded successfully:", yomitanExt.id); + return yomitanExt; + } catch (err) { + console.error("Failed to load Yomitan extension:", (err as Error).message); + console.error("Full error:", err); + return null; + } +} + +function createOverlayWindow(kind: "visible" | "invisible"): BrowserWindow { + const window = new BrowserWindow({ + show: false, + width: 800, + height: 600, + x: 0, + y: 0, + transparent: true, + frame: false, + alwaysOnTop: true, + skipTaskbar: true, + resizable: false, + hasShadow: false, + focusable: true, + webPreferences: { + preload: path.join(__dirname, "preload.js"), + contextIsolation: true, + nodeIntegration: false, + webSecurity: true, + additionalArguments: [`--overlay-layer=${kind}`], + }, + }); + + ensureOverlayWindowLevel(window); + + const htmlPath = path.join(__dirname, "renderer", "index.html"); + console.log(`Loading ${kind} overlay HTML from:`, htmlPath); + console.log("HTML file exists:", fs.existsSync(htmlPath)); + + window + .loadFile(htmlPath, { + query: { layer: kind === "visible" ? "visible" : "invisible" }, + }) + .catch((err) => { + console.error("Failed to load HTML file:", err); + }); + + window.webContents.on( + "did-fail-load", + (_event, errorCode, errorDescription, validatedURL) => { + console.error( + "Page failed to load:", + errorCode, + errorDescription, + validatedURL, + ); + }, + ); + + window.webContents.on("did-finish-load", () => { + console.log(`${kind} overlay HTML loaded successfully`); + broadcastRuntimeOptionsChanged(); + window.webContents.send( + "overlay-debug-visualization:set", + overlayDebugVisualizationEnabled, + ); + }); + + if (kind === "visible") { + window.webContents.on("devtools-opened", () => { + setOverlayDebugVisualizationEnabled(true); + }); + window.webContents.on("devtools-closed", () => { + setOverlayDebugVisualizationEnabled(false); + }); + } + + window.webContents.on("before-input-event", (event, input) => { + const isOverlayVisible = + kind === "visible" ? visibleOverlayVisible : invisibleOverlayVisible; + if (!isOverlayVisible) return; + if (!tryHandleOverlayShortcutLocalFallback(input)) return; + event.preventDefault(); + }); + + window.hide(); + + window.on("closed", () => { + if (kind === "visible") { + mainWindow = null; + } else { + invisibleWindow = null; + } + }); + + window.on("blur", () => { + if (!window.isDestroyed()) { + ensureOverlayWindowLevel(window); + } + }); + + if (isDev && kind === "visible") { + window.webContents.openDevTools({ mode: "detach" }); + } + + return window; +} + +function createMainWindow(): BrowserWindow { + mainWindow = createOverlayWindow("visible"); + return mainWindow; +} + +function createInvisibleWindow(): BrowserWindow { + invisibleWindow = createOverlayWindow("invisible"); + return invisibleWindow; +} + +function initializeOverlayRuntime(): void { + if (overlayRuntimeInitialized) { + return; + } + + createMainWindow(); + createInvisibleWindow(); + invisibleOverlayVisible = getInitialInvisibleOverlayVisibility(); + registerGlobalShortcuts(); + + windowTracker = createWindowTracker(backendOverride); + if (windowTracker) { + windowTracker.onGeometryChange = (geometry: WindowGeometry) => { + updateOverlayBounds(geometry); + }; + windowTracker.onWindowFound = (geometry: WindowGeometry) => { + console.log("MPV window found:", geometry); + updateOverlayBounds(geometry); + if (visibleOverlayVisible) { + updateVisibleOverlayVisibility(); + } + if (invisibleOverlayVisible) { + updateInvisibleOverlayVisibility(); + } + }; + windowTracker.onWindowLost = () => { + console.log("MPV window lost"); + for (const window of getOverlayWindows()) { + window.hide(); + } + // Keep overlay shortcuts registered; tracking loss can be transient. + syncOverlayShortcuts(); + }; + windowTracker.start(); + } + + const config = getResolvedConfig(); + if ( + config.ankiConnect?.enabled && + subtitleTimingTracker && + mpvClient && + runtimeOptionsManager + ) { + const effectiveAnkiConfig = + runtimeOptionsManager.getEffectiveAnkiConnectConfig(config.ankiConnect); + ankiIntegration = new AnkiIntegration( + effectiveAnkiConfig, + subtitleTimingTracker, + mpvClient, + (text: string) => { + if (mpvClient) { + mpvClient.send({ + command: ["show-text", text, "3000"], + }); + } + }, + showDesktopNotification, + createFieldGroupingCallback(), + ); + ankiIntegration.start(); + } + + overlayRuntimeInitialized = true; + updateVisibleOverlayVisibility(); + updateInvisibleOverlayVisibility(); +} + +function openYomitanSettings(): void { + console.log("openYomitanSettings called"); + + if (!yomitanExt) { + console.error("Yomitan extension not loaded - yomitanExt is:", yomitanExt); + console.error( + "This may be due to Manifest V3 service worker issues with Electron", + ); + return; + } + + if (yomitanSettingsWindow && !yomitanSettingsWindow.isDestroyed()) { + console.log("Settings window already exists, focusing"); + yomitanSettingsWindow.focus(); + return; + } + + console.log("Creating new settings window for extension:", yomitanExt.id); + + yomitanSettingsWindow = new BrowserWindow({ + width: 1200, + height: 800, + show: false, + webPreferences: { + contextIsolation: true, + nodeIntegration: false, + session: session.defaultSession, + }, + }); + + const settingsUrl = `chrome-extension://${yomitanExt.id}/settings.html`; + console.log("Loading settings URL:", settingsUrl); + + let loadAttempts = 0; + const maxAttempts = 3; + + function attemptLoad(): void { + yomitanSettingsWindow! + .loadURL(settingsUrl) + .then(() => { + console.log("Settings URL loaded successfully"); + }) + .catch((err: Error) => { + console.error("Failed to load settings URL:", err); + loadAttempts++; + if ( + loadAttempts < maxAttempts && + yomitanSettingsWindow && + !yomitanSettingsWindow.isDestroyed() + ) { + console.log( + `Retrying in 500ms (attempt ${loadAttempts + 1}/${maxAttempts})`, + ); + setTimeout(attemptLoad, 500); + } + }); + } + + attemptLoad(); + + yomitanSettingsWindow.webContents.on( + "did-fail-load", + (_event, errorCode, errorDescription) => { + console.error( + "Settings page failed to load:", + errorCode, + errorDescription, + ); + }, + ); + + yomitanSettingsWindow.webContents.on("did-finish-load", () => { + console.log("Settings page loaded successfully"); + }); + + setTimeout(() => { + if (yomitanSettingsWindow && !yomitanSettingsWindow.isDestroyed()) { + yomitanSettingsWindow.setSize( + yomitanSettingsWindow.getSize()[0], + yomitanSettingsWindow.getSize()[1], + ); + yomitanSettingsWindow.webContents.invalidate(); + yomitanSettingsWindow.show(); + } + }, 500); + + yomitanSettingsWindow.on("closed", () => { + yomitanSettingsWindow = null; + }); +} + +function registerGlobalShortcuts(): void { + const shortcuts = getConfiguredShortcuts(); + const visibleShortcut = shortcuts.toggleVisibleOverlayGlobal; + const invisibleShortcut = shortcuts.toggleInvisibleOverlayGlobal; + const normalizedVisible = visibleShortcut?.replace(/\s+/g, "").toLowerCase(); + const normalizedInvisible = invisibleShortcut + ?.replace(/\s+/g, "") + .toLowerCase(); + + if (visibleShortcut) { + const toggleVisibleRegistered = globalShortcut.register( + visibleShortcut, + () => { + toggleVisibleOverlay(); + }, + ); + if (!toggleVisibleRegistered) { + console.warn( + `Failed to register global shortcut toggleVisibleOverlayGlobal: ${visibleShortcut}`, + ); + } + } + + if ( + invisibleShortcut && + normalizedInvisible && + normalizedInvisible !== normalizedVisible + ) { + const toggleInvisibleRegistered = globalShortcut.register( + invisibleShortcut, + () => { + toggleInvisibleOverlay(); + }, + ); + if (!toggleInvisibleRegistered) { + console.warn( + `Failed to register global shortcut toggleInvisibleOverlayGlobal: ${invisibleShortcut}`, + ); + } + } else if ( + invisibleShortcut && + normalizedInvisible && + normalizedInvisible === normalizedVisible + ) { + console.warn( + "Skipped registering toggleInvisibleOverlayGlobal because it collides with toggleVisibleOverlayGlobal", + ); + } + + const settingsRegistered = globalShortcut.register("Alt+Shift+Y", () => { + openYomitanSettings(); + }); + if (!settingsRegistered) { + console.warn("Failed to register global shortcut: Alt+Shift+Y"); + } + + if (isDev) { + const devtoolsRegistered = globalShortcut.register("F12", () => { + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.toggleDevTools(); + } + }); + if (!devtoolsRegistered) { + console.warn("Failed to register global shortcut: F12"); + } + } +} + +function getConfiguredShortcuts() { + const config = getResolvedConfig(); + const normalizeShortcut = ( + value: string | null | undefined, + ): string | null | undefined => { + if (typeof value !== "string") return value; + return value + .replace(/\bKey([A-Z])\b/g, "$1") + .replace(/\bDigit([0-9])\b/g, "$1"); + }; + + return { + toggleVisibleOverlayGlobal: normalizeShortcut( + config.shortcuts?.toggleVisibleOverlayGlobal ?? + DEFAULT_CONFIG.shortcuts.toggleVisibleOverlayGlobal, + ), + toggleInvisibleOverlayGlobal: normalizeShortcut( + config.shortcuts?.toggleInvisibleOverlayGlobal ?? + DEFAULT_CONFIG.shortcuts.toggleInvisibleOverlayGlobal, + ), + copySubtitle: normalizeShortcut( + config.shortcuts?.copySubtitle ?? DEFAULT_CONFIG.shortcuts.copySubtitle, + ), + copySubtitleMultiple: normalizeShortcut( + config.shortcuts?.copySubtitleMultiple ?? + DEFAULT_CONFIG.shortcuts.copySubtitleMultiple, + ), + updateLastCardFromClipboard: normalizeShortcut( + config.shortcuts?.updateLastCardFromClipboard ?? + DEFAULT_CONFIG.shortcuts.updateLastCardFromClipboard, + ), + triggerFieldGrouping: normalizeShortcut( + config.shortcuts?.triggerFieldGrouping ?? + DEFAULT_CONFIG.shortcuts.triggerFieldGrouping, + ), + triggerSubsync: normalizeShortcut( + config.shortcuts?.triggerSubsync ?? + DEFAULT_CONFIG.shortcuts.triggerSubsync, + ), + mineSentence: normalizeShortcut( + config.shortcuts?.mineSentence ?? DEFAULT_CONFIG.shortcuts.mineSentence, + ), + mineSentenceMultiple: normalizeShortcut( + config.shortcuts?.mineSentenceMultiple ?? + DEFAULT_CONFIG.shortcuts.mineSentenceMultiple, + ), + multiCopyTimeoutMs: + config.shortcuts?.multiCopyTimeoutMs ?? + DEFAULT_CONFIG.shortcuts.multiCopyTimeoutMs, + toggleSecondarySub: normalizeShortcut( + config.shortcuts?.toggleSecondarySub ?? + DEFAULT_CONFIG.shortcuts.toggleSecondarySub, + ), + markAudioCard: normalizeShortcut( + config.shortcuts?.markAudioCard ?? DEFAULT_CONFIG.shortcuts.markAudioCard, + ), + openRuntimeOptions: normalizeShortcut( + config.shortcuts?.openRuntimeOptions ?? + DEFAULT_CONFIG.shortcuts.openRuntimeOptions, + ), + }; +} + +function shouldUseMarkAudioCardLocalFallback(input: Electron.Input): boolean { + const shortcuts = getConfiguredShortcuts(); + if (!shortcuts.markAudioCard) return false; + if (globalShortcut.isRegistered(shortcuts.markAudioCard)) return false; + + const normalized = shortcuts.markAudioCard.replace(/\s+/g, "").toLowerCase(); + const supportsFallback = + normalized === "commandorcontrol+shift+a" || + normalized === "cmdorctrl+shift+a" || + normalized === "control+shift+a" || + normalized === "ctrl+shift+a"; + if (!supportsFallback) return false; + + if (input.type !== "keyDown" || input.isAutoRepeat) return false; + if ((input.key || "").toLowerCase() !== "a") return false; + if (!input.shift || input.alt) return false; + + if (process.platform === "darwin") { + return Boolean(input.meta || input.control); + } + return Boolean(input.control); +} + +function shouldUseRuntimeOptionsLocalFallback(input: Electron.Input): boolean { + const shortcuts = getConfiguredShortcuts(); + if (!shortcuts.openRuntimeOptions) return false; + if (globalShortcut.isRegistered(shortcuts.openRuntimeOptions)) return false; + + const normalized = shortcuts.openRuntimeOptions + .replace(/\s+/g, "") + .toLowerCase(); + const supportsFallback = + normalized === "commandorcontrol+shift+o" || + normalized === "cmdorctrl+shift+o" || + normalized === "control+shift+o" || + normalized === "ctrl+shift+o"; + if (!supportsFallback) return false; + + if (input.type !== "keyDown" || input.isAutoRepeat) return false; + if ((input.key || "").toLowerCase() !== "o") return false; + if (!input.shift || input.alt) return false; + + if (process.platform === "darwin") { + return Boolean(input.meta || input.control); + } + return Boolean(input.control); +} + +function isGlobalShortcutRegisteredSafe(accelerator: string): boolean { + try { + return globalShortcut.isRegistered(accelerator); + } catch { + return false; + } +} + +function shortcutMatchesInputForLocalFallback( + input: Electron.Input, + accelerator: string, + allowWhenRegistered = false, +): boolean { + if (input.type !== "keyDown" || input.isAutoRepeat) return false; + if (!accelerator) return false; + if (!allowWhenRegistered && isGlobalShortcutRegisteredSafe(accelerator)) { + return false; + } + + const normalized = accelerator + .replace(/\s+/g, "") + .replace(/cmdorctrl/gi, "CommandOrControl") + .toLowerCase(); + const parts = normalized.split("+").filter(Boolean); + if (parts.length === 0) return false; + + const keyToken = parts[parts.length - 1]; + const modifierTokens = new Set(parts.slice(0, -1)); + const allowedModifiers = new Set([ + "shift", + "alt", + "meta", + "control", + "commandorcontrol", + ]); + for (const token of modifierTokens) { + if (!allowedModifiers.has(token)) return false; + } + + const inputKey = (input.key || "").toLowerCase(); + if (keyToken.length === 1) { + if (inputKey !== keyToken) return false; + } else if (keyToken.startsWith("key") && keyToken.length === 4) { + if (inputKey !== keyToken.slice(3)) return false; + } else { + return false; + } + + const expectedShift = modifierTokens.has("shift"); + const expectedAlt = modifierTokens.has("alt"); + const expectedMeta = modifierTokens.has("meta"); + const expectedControl = modifierTokens.has("control"); + const expectedCommandOrControl = modifierTokens.has("commandorcontrol"); + + if (Boolean(input.shift) !== expectedShift) return false; + if (Boolean(input.alt) !== expectedAlt) return false; + + if (expectedCommandOrControl) { + const hasCmdOrCtrl = + process.platform === "darwin" + ? Boolean(input.meta || input.control) + : Boolean(input.control); + if (!hasCmdOrCtrl) return false; + } else { + if (process.platform === "darwin") { + if (input.meta || input.control) return false; + } else if (input.control) { + return false; + } + } + + if (expectedMeta && !input.meta) return false; + if (!expectedMeta && modifierTokens.has("meta") === false && input.meta) { + if (!expectedCommandOrControl) return false; + } + + if (expectedControl && !input.control) return false; + if ( + !expectedControl && + modifierTokens.has("control") === false && + input.control + ) { + if (!expectedCommandOrControl) return false; + } + + return true; +} + +function tryHandleOverlayShortcutLocalFallback(input: Electron.Input): boolean { + const shortcuts = getConfiguredShortcuts(); + const handlers: Array<{ + accelerator: string | null | undefined; + run: () => void; + allowWhenRegistered?: boolean; + }> = [ + { + accelerator: shortcuts.openRuntimeOptions, + run: () => { + openRuntimeOptionsPalette(); + }, + }, + { + accelerator: shortcuts.markAudioCard, + run: () => { + markLastCardAsAudioCard().catch((err) => { + console.error("markLastCardAsAudioCard failed:", err); + showMpvOsd(`Audio card failed: ${(err as Error).message}`); + }); + }, + }, + { + accelerator: shortcuts.copySubtitleMultiple, + run: () => { + startPendingMultiCopy(shortcuts.multiCopyTimeoutMs); + }, + }, + { + accelerator: shortcuts.copySubtitle, + run: () => { + copyCurrentSubtitle(); + }, + }, + { + accelerator: shortcuts.toggleSecondarySub, + run: () => cycleSecondarySubMode(), + allowWhenRegistered: true, + }, + { + accelerator: shortcuts.updateLastCardFromClipboard, + run: () => { + updateLastCardFromClipboard().catch((err) => { + console.error("updateLastCardFromClipboard failed:", err); + showMpvOsd(`Update failed: ${(err as Error).message}`); + }); + }, + }, + { + accelerator: shortcuts.triggerFieldGrouping, + run: () => { + triggerFieldGrouping().catch((err) => { + console.error("triggerFieldGrouping failed:", err); + showMpvOsd(`Field grouping failed: ${(err as Error).message}`); + }); + }, + }, + { + accelerator: shortcuts.triggerSubsync, + run: () => { + triggerSubsyncFromConfig().catch((err) => { + console.error("triggerSubsyncFromConfig failed:", err); + showMpvOsd(`Subsync failed: ${(err as Error).message}`); + }); + }, + }, + { + accelerator: shortcuts.mineSentence, + run: () => { + mineSentenceCard().catch((err) => { + console.error("mineSentenceCard failed:", err); + showMpvOsd(`Mine sentence failed: ${(err as Error).message}`); + }); + }, + }, + { + accelerator: shortcuts.mineSentenceMultiple, + run: () => { + startPendingMineSentenceMultiple(shortcuts.multiCopyTimeoutMs); + }, + }, + ]; + + for (const handler of handlers) { + if (!handler.accelerator) continue; + if ( + shortcutMatchesInputForLocalFallback( + input, + handler.accelerator, + handler.allowWhenRegistered === true, + ) + ) { + handler.run(); + return true; + } + } + + return false; +} + +function cycleSecondarySubMode(): void { + // Some platforms can trigger both global and in-window handlers for one key press. + const now = Date.now(); + if (now - lastSecondarySubToggleAtMs < 120) { + return; + } + lastSecondarySubToggleAtMs = now; + + const cycle: SecondarySubMode[] = ["hidden", "visible", "hover"]; + const idx = cycle.indexOf(secondarySubMode); + secondarySubMode = cycle[(idx + 1) % cycle.length]; + broadcastToOverlayWindows("secondary-subtitle:mode", secondarySubMode); + showMpvOsd(`Secondary subtitle: ${secondarySubMode}`); +} + +function showMpvOsd(text: string): void { + if (mpvClient && mpvClient.connected && mpvClient.send) { + mpvClient.send({ + command: ["show-text", text, "3000"], + }); + } else { + console.log("OSD (MPV not connected):", text); + } +} + +function getMpvClientForSubsync(): MpvIpcClient { + if (!mpvClient || !mpvClient.connected) { + throw new Error("MPV not connected"); + } + return mpvClient as MpvIpcClient; +} + +async function gatherSubsyncContext( + client: MpvIpcClient, +): Promise { + const [videoPathRaw, sidRaw, secondarySidRaw, trackListRaw] = + await Promise.all([ + client.requestProperty("path"), + client.requestProperty("sid"), + client.requestProperty("secondary-sid"), + client.requestProperty("track-list"), + ]); + + const videoPath = typeof videoPathRaw === "string" ? videoPathRaw : ""; + if (!videoPath) { + throw new Error("No video is currently loaded"); + } + + const tracks = Array.isArray(trackListRaw) + ? (trackListRaw as MpvTrack[]) + : []; + const subtitleTracks = tracks.filter((track) => track.type === "sub"); + const sid = typeof sidRaw === "number" ? sidRaw : null; + const secondarySid = + typeof secondarySidRaw === "number" ? secondarySidRaw : null; + + const primaryTrack = subtitleTracks.find((track) => track.id === sid); + if (!primaryTrack) { + throw new Error("No active subtitle track found"); + } + + const secondaryTrack = + subtitleTracks.find((track) => track.id === secondarySid) ?? null; + const sourceTracks = subtitleTracks + .filter((track) => track.id !== sid) + .filter((track) => { + if (!track.external) return true; + const filename = track["external-filename"]; + return typeof filename === "string" && filename.length > 0; + }); + + return { + videoPath, + primaryTrack, + secondaryTrack, + sourceTracks, + audioStreamIndex: client.currentAudioStreamIndex, + }; +} + +function ensureExecutablePath(pathOrName: string, name: string): string { + if (!pathOrName) { + throw new Error(`Missing ${name} path in config`); + } + + if (hasPathSeparators(pathOrName) && !fileExists(pathOrName)) { + throw new Error(`Configured ${name} executable not found: ${pathOrName}`); + } + return pathOrName; +} + +async function extractSubtitleTrackToFile( + ffmpegPath: string, + videoPath: string, + track: MpvTrack, +): Promise { + if (track.external) { + const externalPath = track["external-filename"]; + if (typeof externalPath !== "string" || externalPath.length === 0) { + throw new Error("External subtitle track has no file path"); + } + if (!fileExists(externalPath)) { + throw new Error(`Subtitle file not found: ${externalPath}`); + } + return { path: externalPath, temporary: false }; + } + + const ffIndex = track["ff-index"]; + const extension = codecToExtension(track.codec); + if ( + typeof ffIndex !== "number" || + !Number.isInteger(ffIndex) || + ffIndex < 0 + ) { + throw new Error("Internal subtitle track has no valid ff-index"); + } + if (!extension) { + throw new Error(`Unsupported subtitle codec: ${track.codec ?? "unknown"}`); + } + + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "subminer-subsync-")); + const outputPath = path.join(tempDir, `track_${ffIndex}.${extension}`); + const extraction = await runCommand(ffmpegPath, [ + "-hide_banner", + "-nostdin", + "-y", + "-loglevel", + "quiet", + "-an", + "-vn", + "-i", + videoPath, + "-map", + `0:${ffIndex}`, + "-f", + extension, + outputPath, + ]); + + if (!extraction.ok || !fileExists(outputPath)) { + throw new Error("Failed to extract internal subtitle track with ffmpeg"); + } + + return { path: outputPath, temporary: true }; +} + +function cleanupTemporaryFile(extraction: FileExtractionResult): void { + if (!extraction.temporary) return; + try { + if (fileExists(extraction.path)) { + fs.unlinkSync(extraction.path); + } + } catch { + // Ignore cleanup failures + } + try { + const dir = path.dirname(extraction.path); + if (fs.existsSync(dir)) { + fs.rmdirSync(dir); + } + } catch { + // Ignore cleanup failures + } +} + +function buildRetimedPath(subPath: string): string { + const parsed = path.parse(subPath); + const suffix = `_retimed_${Date.now()}`; + return path.join( + parsed.dir, + `${parsed.name}${suffix}${parsed.ext || ".srt"}`, + ); +} + +async function runAlassSync( + alassPath: string, + referenceFile: string, + inputSubtitlePath: string, + outputPath: string, +): Promise { + return runCommand(alassPath, [referenceFile, inputSubtitlePath, outputPath]); +} + +async function runFfsubsyncSync( + ffsubsyncPath: string, + videoPath: string, + inputSubtitlePath: string, + outputPath: string, + audioStreamIndex: number | null, +): Promise { + const args = [videoPath, "-i", inputSubtitlePath, "-o", outputPath]; + if (audioStreamIndex !== null) { + args.push("--reference-stream", `0:${audioStreamIndex}`); + } + return runCommand(ffsubsyncPath, args); +} + +function loadSyncedSubtitle(pathToLoad: string): void { + if (!mpvClient || !mpvClient.connected) { + throw new Error("MPV disconnected while loading subtitle"); + } + mpvClient.send({ command: ["sub_add", pathToLoad] }); + mpvClient.send({ command: ["set_property", "sub-delay", 0] }); +} + +async function subsyncToReference( + engine: "alass" | "ffsubsync", + referenceFilePath: string, + context: SubsyncContext, + resolved: SubsyncResolvedConfig, +): Promise { + const ffmpegPath = ensureExecutablePath(resolved.ffmpegPath, "ffmpeg"); + const primaryExtraction = await extractSubtitleTrackToFile( + ffmpegPath, + context.videoPath, + context.primaryTrack, + ); + const outputPath = buildRetimedPath(primaryExtraction.path); + + try { + let result: CommandResult; + if (engine === "alass") { + const alassPath = ensureExecutablePath(resolved.alassPath, "alass"); + result = await runAlassSync( + alassPath, + referenceFilePath, + primaryExtraction.path, + outputPath, + ); + } else { + const ffsubsyncPath = ensureExecutablePath( + resolved.ffsubsyncPath, + "ffsubsync", + ); + result = await runFfsubsyncSync( + ffsubsyncPath, + context.videoPath, + primaryExtraction.path, + outputPath, + context.audioStreamIndex, + ); + } + + if (!result.ok || !fileExists(outputPath)) { + return { + ok: false, + message: `${engine} synchronization failed`, + }; + } + + loadSyncedSubtitle(outputPath); + return { + ok: true, + message: `Subtitle synchronized with ${engine}`, + }; + } finally { + cleanupTemporaryFile(primaryExtraction); + } +} + +async function runSubsyncAuto(): Promise { + const client = getMpvClientForSubsync(); + const context = await gatherSubsyncContext(client); + const resolved = getSubsyncConfig(getResolvedConfig().subsync); + const ffmpegPath = ensureExecutablePath(resolved.ffmpegPath, "ffmpeg"); + + if (context.secondaryTrack) { + let secondaryExtraction: FileExtractionResult | null = null; + try { + secondaryExtraction = await extractSubtitleTrackToFile( + ffmpegPath, + context.videoPath, + context.secondaryTrack, + ); + const alassResult = await subsyncToReference( + "alass", + secondaryExtraction.path, + context, + resolved, + ); + if (alassResult.ok) { + return alassResult; + } + } catch (error) { + // Fall through to ffsubsync fallback + console.warn("Auto alass sync failed, trying ffsubsync fallback:", error); + } finally { + if (secondaryExtraction) { + cleanupTemporaryFile(secondaryExtraction); + } + } + } + + const ffsubsyncPath = ensureExecutablePath( + resolved.ffsubsyncPath, + "ffsubsync", + ); + if (!ffsubsyncPath) { + return { + ok: false, + message: "No secondary subtitle for alass and ffsubsync not configured", + }; + } + return subsyncToReference("ffsubsync", context.videoPath, context, resolved); +} + +async function openSubsyncManualPicker(): Promise { + const client = getMpvClientForSubsync(); + const context = await gatherSubsyncContext(client); + const payload: SubsyncManualPayload = { + sourceTracks: context.sourceTracks + .filter((track) => typeof track.id === "number") + .map((track) => ({ + id: track.id as number, + label: formatTrackLabel(track), + })), + }; + sendToVisibleOverlay("subsync:open-manual", payload, { + restoreOnModalClose: "subsync", + }); +} + +async function runSubsyncManual( + request: SubsyncManualRunRequest, +): Promise { + const client = getMpvClientForSubsync(); + const context = await gatherSubsyncContext(client); + const resolved = getSubsyncConfig(getResolvedConfig().subsync); + + if (request.engine === "ffsubsync") { + return subsyncToReference( + "ffsubsync", + context.videoPath, + context, + resolved, + ); + } + + const sourceTrack = getTrackById( + context.sourceTracks, + request.sourceTrackId ?? null, + ); + if (!sourceTrack) { + return { ok: false, message: "Select a subtitle source track for alass" }; + } + + const ffmpegPath = ensureExecutablePath(resolved.ffmpegPath, "ffmpeg"); + let sourceExtraction: FileExtractionResult | null = null; + try { + sourceExtraction = await extractSubtitleTrackToFile( + ffmpegPath, + context.videoPath, + sourceTrack, + ); + return subsyncToReference( + "alass", + sourceExtraction.path, + context, + resolved, + ); + } finally { + if (sourceExtraction) { + cleanupTemporaryFile(sourceExtraction); + } + } +} + +async function triggerSubsyncFromConfig(): Promise { + if (subsyncInProgress) { + showMpvOsd("Subsync already running"); + return; + } + const resolved = getSubsyncConfig(getResolvedConfig().subsync); + try { + if (resolved.defaultMode === "manual") { + await openSubsyncManualPicker(); + showMpvOsd("Subsync: choose engine and source"); + return; + } + + subsyncInProgress = true; + const result = await runWithSubsyncSpinner(() => runSubsyncAuto()); + showMpvOsd(result.message); + } catch (error) { + showMpvOsd(`Subsync failed: ${(error as Error).message}`); + } finally { + subsyncInProgress = false; + } +} + +function formatLangScore(name: string, pref: JimakuLanguagePreference): number { + if (pref === "none") return 0; + const upper = name.toUpperCase(); + const hasJa = + /(^|[\W_])JA([\W_]|$)/.test(upper) || + /(^|[\W_])JPN([\W_]|$)/.test(upper) || + upper.includes(".JA."); + const hasEn = + /(^|[\W_])EN([\W_]|$)/.test(upper) || + /(^|[\W_])ENG([\W_]|$)/.test(upper) || + upper.includes(".EN."); + if (pref === "ja") { + if (hasJa) return 2; + if (hasEn) return 1; + } else if (pref === "en") { + if (hasEn) return 2; + if (hasJa) return 1; + } + return 0; +} + +function sortJimakuFiles( + files: JimakuFileEntry[], + pref: JimakuLanguagePreference, +): JimakuFileEntry[] { + if (pref === "none") return files; + return [...files].sort((a, b) => { + const scoreDiff = + formatLangScore(b.name, pref) - formatLangScore(a.name, pref); + if (scoreDiff !== 0) return scoreDiff; + return a.name.localeCompare(b.name); + }); +} + +function isRemoteMediaPath(mediaPath: string): boolean { + return /^[a-z][a-z0-9+.-]*:\/\//i.test(mediaPath); +} + +async function downloadToFile( + url: string, + destPath: string, + headers: Record, + redirectCount = 0, +): Promise { + if (redirectCount > 3) { + return { + ok: false, + error: { error: "Too many redirects while downloading subtitle." }, + }; + } + + return new Promise((resolve) => { + const parsedUrl = new URL(url); + const transport = parsedUrl.protocol === "https:" ? https : http; + + const req = transport.get(parsedUrl, { headers }, (res) => { + const status = res.statusCode || 0; + if ([301, 302, 303, 307, 308].includes(status) && res.headers.location) { + const redirectUrl = new URL(res.headers.location, parsedUrl).toString(); + res.resume(); + downloadToFile(redirectUrl, destPath, headers, redirectCount + 1).then( + resolve, + ); + return; + } + + if (status < 200 || status >= 300) { + res.resume(); + resolve({ + ok: false, + error: { + error: `Failed to download subtitle (HTTP ${status}).`, + code: status, + }, + }); + return; + } + + const fileStream = fs.createWriteStream(destPath); + res.pipe(fileStream); + fileStream.on("finish", () => { + fileStream.close(() => { + resolve({ ok: true, path: destPath }); + }); + }); + fileStream.on("error", (err) => { + resolve({ + ok: false, + error: { + error: `Failed to save subtitle: ${(err as Error).message}`, + }, + }); + }); + }); + + req.on("error", (err) => { + resolve({ + ok: false, + error: { error: `Download request failed: ${(err as Error).message}` }, + }); + }); + }); +} + +function cancelPendingMultiCopy(): void { + if (!pendingMultiCopy) return; + + pendingMultiCopy = false; + if (pendingMultiCopyTimeout) { + clearTimeout(pendingMultiCopyTimeout); + pendingMultiCopyTimeout = null; + } + + // Unregister digit and escape shortcuts + for (const shortcut of multiCopyDigitShortcuts) { + globalShortcut.unregister(shortcut); + } + multiCopyDigitShortcuts = []; + + if (multiCopyEscapeShortcut) { + globalShortcut.unregister(multiCopyEscapeShortcut); + multiCopyEscapeShortcut = null; + } +} + +function startPendingMultiCopy(timeoutMs: number): void { + cancelPendingMultiCopy(); + pendingMultiCopy = true; + + // Register digit shortcuts 1-9 + for (let i = 1; i <= 9; i++) { + const shortcut = i.toString(); + if ( + globalShortcut.register(shortcut, () => { + handleMultiCopyDigit(i); + }) + ) { + multiCopyDigitShortcuts.push(shortcut); + } + } + + // Register Escape to cancel + if ( + globalShortcut.register("Escape", () => { + cancelPendingMultiCopy(); + showMpvOsd("Cancelled"); + }) + ) { + multiCopyEscapeShortcut = "Escape"; + } + + // Set timeout + pendingMultiCopyTimeout = setTimeout(() => { + cancelPendingMultiCopy(); + showMpvOsd("Copy timeout"); + }, timeoutMs); + + showMpvOsd("Copy how many lines? Press 1-9 (Esc to cancel)"); +} + +function handleMultiCopyDigit(count: number): void { + if (!pendingMultiCopy || !subtitleTimingTracker) return; + + cancelPendingMultiCopy(); + + // Check if we have enough history + const availableCount = Math.min(count, 200); // Max history size + const blocks = subtitleTimingTracker.getRecentBlocks(availableCount); + + if (blocks.length === 0) { + showMpvOsd("No subtitle history available"); + return; + } + + const actualCount = blocks.length; + const clipboardText = blocks.join("\n\n"); + clipboard.writeText(clipboardText); + + if (actualCount < count) { + showMpvOsd(`Only ${actualCount} lines available, copied ${actualCount}`); + } else { + showMpvOsd(`Copied ${actualCount} lines`); + } +} + +function copyCurrentSubtitle(): void { + if (!subtitleTimingTracker) { + showMpvOsd("Subtitle tracker not available"); + return; + } + + const currentSubtitle = subtitleTimingTracker.getCurrentSubtitle(); + if (!currentSubtitle) { + showMpvOsd("No current subtitle"); + return; + } + + clipboard.writeText(currentSubtitle); + showMpvOsd("Copied subtitle"); +} + +async function updateLastCardFromClipboard(): Promise { + if (!ankiIntegration) { + showMpvOsd("AnkiConnect integration not enabled"); + return; + } + + const clipboardText = clipboard.readText(); + await ankiIntegration.updateLastAddedFromClipboard(clipboardText); +} + +async function triggerFieldGrouping(): Promise { + if (!ankiIntegration) { + showMpvOsd("AnkiConnect integration not enabled"); + return; + } + await ankiIntegration.triggerFieldGroupingForLastAddedCard(); +} + +async function markLastCardAsAudioCard(): Promise { + if (!ankiIntegration) { + showMpvOsd("AnkiConnect integration not enabled"); + return; + } + await ankiIntegration.markLastCardAsAudioCard(); +} + +async function mineSentenceCard(): Promise { + if (!ankiIntegration) { + showMpvOsd("AnkiConnect integration not enabled"); + return; + } + + if (!mpvClient || !mpvClient.connected) { + showMpvOsd("MPV not connected"); + return; + } + + const text = mpvClient.currentSubText; + if (!text) { + showMpvOsd("No current subtitle"); + return; + } + + const startTime = mpvClient.currentSubStart; + const endTime = mpvClient.currentSubEnd; + const secondarySub = mpvClient.currentSecondarySubText || undefined; + + await ankiIntegration.createSentenceCard( + text, + startTime, + endTime, + secondarySub, + ); +} + +function cancelPendingMineSentenceMultiple(): void { + if (!pendingMineSentenceMultiple) return; + + pendingMineSentenceMultiple = false; + if (pendingMineSentenceMultipleTimeout) { + clearTimeout(pendingMineSentenceMultipleTimeout); + pendingMineSentenceMultipleTimeout = null; + } + + for (const shortcut of mineSentenceDigitShortcuts) { + globalShortcut.unregister(shortcut); + } + mineSentenceDigitShortcuts = []; + + if (mineSentenceEscapeShortcut) { + globalShortcut.unregister(mineSentenceEscapeShortcut); + mineSentenceEscapeShortcut = null; + } +} + +function startPendingMineSentenceMultiple(timeoutMs: number): void { + cancelPendingMineSentenceMultiple(); + pendingMineSentenceMultiple = true; + + for (let i = 1; i <= 9; i++) { + const shortcut = i.toString(); + if ( + globalShortcut.register(shortcut, () => { + handleMineSentenceDigit(i); + }) + ) { + mineSentenceDigitShortcuts.push(shortcut); + } + } + + if ( + globalShortcut.register("Escape", () => { + cancelPendingMineSentenceMultiple(); + showMpvOsd("Cancelled"); + }) + ) { + mineSentenceEscapeShortcut = "Escape"; + } + + pendingMineSentenceMultipleTimeout = setTimeout(() => { + cancelPendingMineSentenceMultiple(); + showMpvOsd("Mine sentence timeout"); + }, timeoutMs); + + showMpvOsd("Mine how many lines? Press 1-9 (Esc to cancel)"); +} + +function handleMineSentenceDigit(count: number): void { + if ( + !pendingMineSentenceMultiple || + !subtitleTimingTracker || + !ankiIntegration + ) + return; + + cancelPendingMineSentenceMultiple(); + + const blocks = subtitleTimingTracker.getRecentBlocks(count); + + if (blocks.length === 0) { + showMpvOsd("No subtitle history available"); + return; + } + + const timings: { startTime: number; endTime: number }[] = []; + for (const block of blocks) { + const timing = subtitleTimingTracker.findTiming(block); + if (timing) { + timings.push(timing); + } + } + + if (timings.length === 0) { + showMpvOsd("Subtitle timing not found"); + return; + } + + const rangeStart = Math.min(...timings.map((t) => t.startTime)); + const rangeEnd = Math.max(...timings.map((t) => t.endTime)); + const sentence = blocks.join(" "); + + const secondarySub = mpvClient?.currentSecondarySubText || undefined; + ankiIntegration + .createSentenceCard(sentence, rangeStart, rangeEnd, secondarySub) + .catch((err) => { + console.error("mineSentenceMultiple failed:", err); + showMpvOsd(`Mine sentence failed: ${(err as Error).message}`); + }); +} + +function registerOverlayShortcuts(): void { + const shortcuts = getConfiguredShortcuts(); + let registeredAny = false; + const registerOverlayShortcut = ( + accelerator: string, + handler: () => void, + label: string, + ): void => { + if (isGlobalShortcutRegisteredSafe(accelerator)) { + registeredAny = true; + return; + } + const ok = globalShortcut.register(accelerator, handler); + if (!ok) { + console.warn( + `Failed to register overlay shortcut ${label}: ${accelerator}`, + ); + return; + } + registeredAny = true; + }; + + if (shortcuts.copySubtitleMultiple) { + registerOverlayShortcut( + shortcuts.copySubtitleMultiple, + () => { + startPendingMultiCopy(shortcuts.multiCopyTimeoutMs); + }, + "copySubtitleMultiple", + ); + } + + if (shortcuts.copySubtitle) { + registerOverlayShortcut( + shortcuts.copySubtitle, + () => { + copyCurrentSubtitle(); + }, + "copySubtitle", + ); + } + + if (shortcuts.triggerFieldGrouping) { + registerOverlayShortcut( + shortcuts.triggerFieldGrouping, + () => { + triggerFieldGrouping().catch((err) => { + console.error("triggerFieldGrouping failed:", err); + showMpvOsd(`Field grouping failed: ${(err as Error).message}`); + }); + }, + "triggerFieldGrouping", + ); + } + + if (shortcuts.triggerSubsync) { + registerOverlayShortcut( + shortcuts.triggerSubsync, + () => { + triggerSubsyncFromConfig().catch((err) => { + console.error("triggerSubsyncFromConfig failed:", err); + showMpvOsd(`Subsync failed: ${(err as Error).message}`); + }); + }, + "triggerSubsync", + ); + } + + if (shortcuts.mineSentence) { + registerOverlayShortcut( + shortcuts.mineSentence, + () => { + mineSentenceCard().catch((err) => { + console.error("mineSentenceCard failed:", err); + showMpvOsd(`Mine sentence failed: ${(err as Error).message}`); + }); + }, + "mineSentence", + ); + } + + if (shortcuts.mineSentenceMultiple) { + registerOverlayShortcut( + shortcuts.mineSentenceMultiple, + () => { + startPendingMineSentenceMultiple(shortcuts.multiCopyTimeoutMs); + }, + "mineSentenceMultiple", + ); + } + + if (shortcuts.toggleSecondarySub) { + registerOverlayShortcut( + shortcuts.toggleSecondarySub, + () => cycleSecondarySubMode(), + "toggleSecondarySub", + ); + } + + if (shortcuts.updateLastCardFromClipboard) { + registerOverlayShortcut( + shortcuts.updateLastCardFromClipboard, + () => { + updateLastCardFromClipboard().catch((err) => { + console.error("updateLastCardFromClipboard failed:", err); + showMpvOsd(`Update failed: ${(err as Error).message}`); + }); + }, + "updateLastCardFromClipboard", + ); + } + + if (shortcuts.markAudioCard) { + registerOverlayShortcut( + shortcuts.markAudioCard, + () => { + markLastCardAsAudioCard().catch((err) => { + console.error("markLastCardAsAudioCard failed:", err); + showMpvOsd(`Audio card failed: ${(err as Error).message}`); + }); + }, + "markAudioCard", + ); + } + + if (shortcuts.openRuntimeOptions) { + registerOverlayShortcut( + shortcuts.openRuntimeOptions, + () => { + openRuntimeOptionsPalette(); + }, + "openRuntimeOptions", + ); + } + + shortcutsRegistered = registeredAny; +} + +function unregisterOverlayShortcuts(): void { + if (!shortcutsRegistered) return; + + cancelPendingMultiCopy(); + cancelPendingMineSentenceMultiple(); + + const shortcuts = getConfiguredShortcuts(); + + if (shortcuts.copySubtitle) { + globalShortcut.unregister(shortcuts.copySubtitle); + } + if (shortcuts.copySubtitleMultiple) { + globalShortcut.unregister(shortcuts.copySubtitleMultiple); + } + if (shortcuts.updateLastCardFromClipboard) { + globalShortcut.unregister(shortcuts.updateLastCardFromClipboard); + } + if (shortcuts.triggerFieldGrouping) { + globalShortcut.unregister(shortcuts.triggerFieldGrouping); + } + if (shortcuts.triggerSubsync) { + globalShortcut.unregister(shortcuts.triggerSubsync); + } + if (shortcuts.mineSentence) { + globalShortcut.unregister(shortcuts.mineSentence); + } + if (shortcuts.mineSentenceMultiple) { + globalShortcut.unregister(shortcuts.mineSentenceMultiple); + } + if (shortcuts.toggleSecondarySub) { + globalShortcut.unregister(shortcuts.toggleSecondarySub); + } + if (shortcuts.markAudioCard) { + globalShortcut.unregister(shortcuts.markAudioCard); + } + if (shortcuts.openRuntimeOptions) { + globalShortcut.unregister(shortcuts.openRuntimeOptions); + } + + shortcutsRegistered = false; +} + +function shouldOverlayShortcutsBeActive(): boolean { + return overlayRuntimeInitialized; +} + +function syncOverlayShortcuts(): void { + if (shouldOverlayShortcutsBeActive()) { + registerOverlayShortcuts(); + } else { + unregisterOverlayShortcuts(); + } +} + +function refreshOverlayShortcuts(): void { + unregisterOverlayShortcuts(); + syncOverlayShortcuts(); +} + +function updateVisibleOverlayVisibility(): void { + console.log( + "updateVisibleOverlayVisibility called, visibleOverlayVisible:", + visibleOverlayVisible, + ); + if (!mainWindow || mainWindow.isDestroyed()) { + console.log("mainWindow not available"); + return; + } + + if (!visibleOverlayVisible) { + console.log("Hiding visible overlay"); + mainWindow.hide(); + + if ( + shouldBindVisibleOverlayToMpvSubVisibility() && + previousSecondarySubVisibility !== null && + mpvClient && + mpvClient.connected + ) { + mpvClient.send({ + command: [ + "set_property", + "secondary-sub-visibility", + previousSecondarySubVisibility ? "yes" : "no", + ], + }); + previousSecondarySubVisibility = null; + } else if (!shouldBindVisibleOverlayToMpvSubVisibility()) { + previousSecondarySubVisibility = null; + } + syncOverlayShortcuts(); + } else { + console.log( + "Should show visible overlay, isTracking:", + windowTracker?.isTracking(), + ); + + if ( + shouldBindVisibleOverlayToMpvSubVisibility() && + mpvClient && + mpvClient.connected + ) { + mpvClient.send({ + command: ["get_property", "secondary-sub-visibility"], + request_id: MPV_REQUEST_ID_SECONDARY_SUB_VISIBILITY, + }); + } + + if (windowTracker && windowTracker.isTracking()) { + trackerNotReadyWarningShown = false; + const geometry = windowTracker.getGeometry(); + console.log("Geometry:", geometry); + if (geometry) { + updateOverlayBounds(geometry); + } + console.log("Showing visible overlay mainWindow"); + ensureOverlayWindowLevel(mainWindow); + mainWindow.show(); + mainWindow.focus(); + enforceOverlayLayerOrder(); + syncOverlayShortcuts(); + } else if (!windowTracker) { + trackerNotReadyWarningShown = false; + ensureOverlayWindowLevel(mainWindow); + mainWindow.show(); + mainWindow.focus(); + enforceOverlayLayerOrder(); + syncOverlayShortcuts(); + } else { + if (!trackerNotReadyWarningShown) { + console.warn( + "Window tracker exists but is not tracking yet; using fallback bounds until tracking starts", + ); + trackerNotReadyWarningShown = true; + } + const cursorPoint = screen.getCursorScreenPoint(); + const display = screen.getDisplayNearestPoint(cursorPoint); + const fallbackBounds = display.workArea; + updateOverlayBounds({ + x: fallbackBounds.x, + y: fallbackBounds.y, + width: fallbackBounds.width, + height: fallbackBounds.height, + }); + ensureOverlayWindowLevel(mainWindow); + mainWindow.show(); + mainWindow.focus(); + enforceOverlayLayerOrder(); + syncOverlayShortcuts(); + } + } +} + +function updateInvisibleOverlayVisibility(): void { + if (!invisibleWindow || invisibleWindow.isDestroyed()) { + return; + } + + // When the visible overlay is shown, keep the invisible layer hidden to + // avoid it intercepting or rerouting pointer interactions. + if (visibleOverlayVisible) { + invisibleWindow.hide(); + syncOverlayShortcuts(); + return; + } + + const showInvisibleWithoutFocus = (): void => { + ensureOverlayWindowLevel(invisibleWindow!); + if (typeof invisibleWindow!.showInactive === "function") { + invisibleWindow!.showInactive(); + } else { + invisibleWindow!.show(); + } + enforceOverlayLayerOrder(); + }; + + if (!invisibleOverlayVisible) { + invisibleWindow.hide(); + syncOverlayShortcuts(); + return; + } + + if (windowTracker && windowTracker.isTracking()) { + const geometry = windowTracker.getGeometry(); + if (geometry) { + updateOverlayBounds(geometry); + } + showInvisibleWithoutFocus(); + syncOverlayShortcuts(); + return; + } + + if (!windowTracker) { + showInvisibleWithoutFocus(); + syncOverlayShortcuts(); + return; + } + + const cursorPoint = screen.getCursorScreenPoint(); + const display = screen.getDisplayNearestPoint(cursorPoint); + const fallbackBounds = display.workArea; + updateOverlayBounds({ + x: fallbackBounds.x, + y: fallbackBounds.y, + width: fallbackBounds.width, + height: fallbackBounds.height, + }); + showInvisibleWithoutFocus(); + syncOverlayShortcuts(); +} + +function syncInvisibleOverlayMousePassthrough(): void { + if (!invisibleWindow || invisibleWindow.isDestroyed()) return; + if (visibleOverlayVisible) { + invisibleWindow.setIgnoreMouseEvents(true, { forward: true }); + } else if (invisibleOverlayVisible) { + invisibleWindow.setIgnoreMouseEvents(false); + } +} + +function setVisibleOverlayVisible(visible: boolean): void { + visibleOverlayVisible = visible; + updateVisibleOverlayVisibility(); + updateInvisibleOverlayVisibility(); + syncInvisibleOverlayMousePassthrough(); + if ( + shouldBindVisibleOverlayToMpvSubVisibility() && + mpvClient && + mpvClient.connected + ) { + mpvClient.setSubVisibility(!visible); + } +} + +function setInvisibleOverlayVisible(visible: boolean): void { + invisibleOverlayVisible = visible; + updateInvisibleOverlayVisibility(); + syncInvisibleOverlayMousePassthrough(); +} + +function toggleVisibleOverlay(): void { + setVisibleOverlayVisible(!visibleOverlayVisible); +} + +function toggleInvisibleOverlay(): void { + setInvisibleOverlayVisible(!invisibleOverlayVisible); +} + +function setOverlayVisible(visible: boolean): void { + setVisibleOverlayVisible(visible); +} + +function toggleOverlay(): void { + toggleVisibleOverlay(); +} + +ipcMain.on( + "set-ignore-mouse-events", + ( + event: IpcMainEvent, + ignore: boolean, + options: { forward?: boolean } = {}, + ) => { + const senderWindow = BrowserWindow.fromWebContents(event.sender); + if (senderWindow && !senderWindow.isDestroyed()) { + if ( + senderWindow === invisibleWindow && + visibleOverlayVisible && + !invisibleWindow.isDestroyed() + ) { + invisibleWindow.setIgnoreMouseEvents(true, { forward: true }); + } else { + senderWindow.setIgnoreMouseEvents(ignore, options); + } + } + }, +); + +ipcMain.on( + "overlay:modal-closed", + (_event: IpcMainEvent, modal: OverlayHostedModal) => { + if (!restoreVisibleOverlayOnModalClose.has(modal)) return; + restoreVisibleOverlayOnModalClose.delete(modal); + if (restoreVisibleOverlayOnModalClose.size === 0) { + setVisibleOverlayVisible(false); + } + }, +); + +ipcMain.on("open-yomitan-settings", () => { + openYomitanSettings(); +}); + +ipcMain.on("quit-app", () => { + app.quit(); +}); + +ipcMain.on("toggle-dev-tools", () => { + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.toggleDevTools(); + } +}); + +ipcMain.handle("get-overlay-visibility", () => { + return visibleOverlayVisible; +}); + +ipcMain.on("toggle-overlay", () => { + toggleVisibleOverlay(); +}); + +ipcMain.handle("get-visible-overlay-visibility", () => { + return visibleOverlayVisible; +}); + +ipcMain.handle("get-invisible-overlay-visibility", () => { + return invisibleOverlayVisible; +}); + +ipcMain.handle("get-current-subtitle", async () => { + return await tokenizeSubtitle(currentSubText); +}); + +ipcMain.handle("get-current-subtitle-ass", () => { + return currentSubAssText; +}); + +ipcMain.handle("get-mpv-subtitle-render-metrics", () => { + return mpvSubtitleRenderMetrics; +}); + +ipcMain.handle("get-subtitle-position", () => { + return loadSubtitlePosition(); +}); + +ipcMain.handle("get-subtitle-style", () => { + const config = getResolvedConfig(); + return config.subtitleStyle ?? null; +}); + +ipcMain.on( + "save-subtitle-position", + (_event: IpcMainEvent, position: SubtitlePosition) => { + saveSubtitlePosition(position); + }, +); + +ipcMain.handle("get-mecab-status", () => { + if (mecabTokenizer) { + return mecabTokenizer.getStatus(); + } + return { available: false, enabled: false, path: null }; +}); + +ipcMain.on("set-mecab-enabled", (_event: IpcMainEvent, enabled: boolean) => { + if (mecabTokenizer) { + mecabTokenizer.setEnabled(enabled); + } +}); + +ipcMain.on( + "mpv-command", + (_event: IpcMainEvent, command: (string | number)[]) => { + const first = typeof command[0] === "string" ? command[0] : ""; + if (first === SPECIAL_COMMANDS.SUBSYNC_TRIGGER) { + triggerSubsyncFromConfig(); + return; + } + + if (first === SPECIAL_COMMANDS.RUNTIME_OPTIONS_OPEN) { + openRuntimeOptionsPalette(); + return; + } + + if (first.startsWith(SPECIAL_COMMANDS.RUNTIME_OPTION_CYCLE_PREFIX)) { + if (!runtimeOptionsManager) return; + const [, idToken, directionToken] = first.split(":"); + const id = idToken as RuntimeOptionId; + const direction: 1 | -1 = directionToken === "prev" ? -1 : 1; + const result = applyRuntimeOptionResult( + runtimeOptionsManager.cycleOption(id, direction), + ); + if (!result.ok && result.error) { + showMpvOsd(result.error); + } + return; + } + + if (mpvClient && mpvClient.connected) { + if (first === SPECIAL_COMMANDS.REPLAY_SUBTITLE) { + mpvClient.replayCurrentSubtitle(); + } else if (first === SPECIAL_COMMANDS.PLAY_NEXT_SUBTITLE) { + mpvClient.playNextSubtitle(); + } else { + mpvClient.send({ command }); + } + } + }, +); + +ipcMain.handle("get-keybindings", () => { + return keybindings; +}); + +ipcMain.handle("get-secondary-sub-mode", () => { + return secondarySubMode; +}); + +ipcMain.handle("get-current-secondary-sub", () => { + return mpvClient?.currentSecondarySubText || ""; +}); + +ipcMain.handle( + "subsync:run-manual", + async (_event, request: SubsyncManualRunRequest): Promise => { + if (subsyncInProgress) { + const busy = "Subsync already running"; + showMpvOsd(busy); + return { ok: false, message: busy }; + } + try { + subsyncInProgress = true; + const result = await runWithSubsyncSpinner(() => + runSubsyncManual(request), + ); + showMpvOsd(result.message); + return result; + } catch (error) { + const message = `Subsync failed: ${(error as Error).message}`; + showMpvOsd(message); + return { ok: false, message }; + } finally { + subsyncInProgress = false; + } + }, +); + +ipcMain.handle("get-anki-connect-status", () => { + return ankiIntegration !== null; +}); + +ipcMain.handle("runtime-options:get", (): RuntimeOptionState[] => { + return getRuntimeOptionsState(); +}); + +ipcMain.handle( + "runtime-options:set", + ( + _event, + id: RuntimeOptionId, + value: RuntimeOptionValue, + ): RuntimeOptionApplyResult => { + if (!runtimeOptionsManager) { + return { ok: false, error: "Runtime options manager unavailable" }; + } + const result = applyRuntimeOptionResult( + runtimeOptionsManager.setOptionValue(id, value), + ); + if (!result.ok && result.error) { + showMpvOsd(result.error); + } + return result; + }, +); + +ipcMain.handle( + "runtime-options:cycle", + ( + _event, + id: RuntimeOptionId, + direction: 1 | -1, + ): RuntimeOptionApplyResult => { + if (!runtimeOptionsManager) { + return { ok: false, error: "Runtime options manager unavailable" }; + } + const result = applyRuntimeOptionResult( + runtimeOptionsManager.cycleOption(id, direction), + ); + if (!result.ok && result.error) { + showMpvOsd(result.error); + } + return result; + }, +); + +/** + * Create and show a desktop notification with robust icon handling. + * Supports both file paths (preferred on Linux/Wayland) and data URLs (fallback). + */ +function createFieldGroupingCallback() { + return async ( + data: KikuFieldGroupingRequestData, + ): Promise => { + return new Promise((resolve) => { + const previousVisibleOverlay = visibleOverlayVisible; + const previousInvisibleOverlay = invisibleOverlayVisible; + let settled = false; + + const finish = (choice: KikuFieldGroupingChoice): void => { + if (settled) return; + settled = true; + fieldGroupingResolver = null; + resolve(choice); + + // Treat the visible overlay as a temporary modal host and then restore + // the user's previous overlay visibility state. + if (!previousVisibleOverlay && visibleOverlayVisible) { + setVisibleOverlayVisible(false); + } + if (invisibleOverlayVisible !== previousInvisibleOverlay) { + setInvisibleOverlayVisible(previousInvisibleOverlay); + } + }; + + fieldGroupingResolver = finish; + // Manual Kiku flow is rendered only in the visible overlay window. + if (!sendToVisibleOverlay("kiku:field-grouping-request", data)) { + finish({ + keepNoteId: 0, + deleteNoteId: 0, + deleteDuplicate: true, + cancelled: true, + }); + return; + } + setTimeout(() => { + if (!settled) { + finish({ + keepNoteId: 0, + deleteNoteId: 0, + deleteDuplicate: true, + cancelled: true, + }); + } + }, 90000); + }); + }; +} + +function sendToVisibleOverlay( + channel: string, + payload?: unknown, + options?: { restoreOnModalClose?: OverlayHostedModal }, +): boolean { + if (!mainWindow || mainWindow.isDestroyed()) return false; + const wasVisible = visibleOverlayVisible; + if (!visibleOverlayVisible) { + setVisibleOverlayVisible(true); + } + if (!wasVisible && options?.restoreOnModalClose) { + restoreVisibleOverlayOnModalClose.add(options.restoreOnModalClose); + } + if (payload === undefined) { + mainWindow.webContents.send(channel); + } else { + mainWindow.webContents.send(channel, payload); + } + return true; +} + +function showDesktopNotification( + title: string, + options: { body?: string; icon?: string }, +): void { + const notificationOptions: { + title: string; + body?: string; + icon?: Electron.NativeImage | string; + } = { title }; + + if (options.body) { + notificationOptions.body = options.body; + } + + if (options.icon) { + // Check if it's a file path (starts with / on Linux/Mac, or drive letter on Windows) + const isFilePath = + typeof options.icon === "string" && + (options.icon.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(options.icon)); + + if (isFilePath) { + // File path - preferred for Linux/Wayland compatibility + // Verify file exists before using + if (fs.existsSync(options.icon)) { + notificationOptions.icon = options.icon; + } else { + console.warn("Notification icon file not found:", options.icon); + } + } else if ( + typeof options.icon === "string" && + options.icon.startsWith("data:image/") + ) { + // Data URL fallback - decode to nativeImage + const base64Data = options.icon.replace(/^data:image\/\w+;base64,/, ""); + try { + const image = nativeImage.createFromBuffer( + Buffer.from(base64Data, "base64"), + ); + if (image.isEmpty()) { + console.warn( + "Notification icon created from base64 is empty - image format may not be supported by Electron", + ); + } else { + notificationOptions.icon = image; + } + } catch (err) { + console.error("Failed to create notification icon from base64:", err); + } + } else { + // Unknown format, try to use as-is + notificationOptions.icon = options.icon; + } + } + + const notification = new Notification(notificationOptions); + notification.show(); +} + +ipcMain.on( + "set-anki-connect-enabled", + (_event: IpcMainEvent, enabled: boolean) => { + configService.patchRawConfig({ + ankiConnect: { + enabled, + }, + }); + const config = getResolvedConfig(); + + if (enabled && !ankiIntegration && subtitleTimingTracker && mpvClient) { + const effectiveAnkiConfig = runtimeOptionsManager + ? runtimeOptionsManager.getEffectiveAnkiConnectConfig( + config.ankiConnect, + ) + : config.ankiConnect; + ankiIntegration = new AnkiIntegration( + effectiveAnkiConfig, + subtitleTimingTracker, + mpvClient, + (text: string) => { + if (mpvClient) { + mpvClient.send({ + command: ["show-text", text, "3000"], + }); + } + }, + showDesktopNotification, + createFieldGroupingCallback(), + ); + ankiIntegration.start(); + console.log("AnkiConnect integration enabled"); + } else if (!enabled && ankiIntegration) { + ankiIntegration.destroy(); + ankiIntegration = null; + console.log("AnkiConnect integration disabled"); + } + + broadcastRuntimeOptionsChanged(); + }, +); + +ipcMain.on("clear-anki-connect-history", () => { + if (subtitleTimingTracker) { + subtitleTimingTracker.cleanup(); + console.log("AnkiConnect subtitle timing history cleared"); + } +}); + +ipcMain.on( + "kiku:field-grouping-respond", + (_event: IpcMainEvent, choice: KikuFieldGroupingChoice) => { + if (fieldGroupingResolver) { + fieldGroupingResolver(choice); + fieldGroupingResolver = null; + } + }, +); + +ipcMain.handle( + "kiku:build-merge-preview", + async ( + _event, + request: KikuMergePreviewRequest, + ): Promise => { + if (!ankiIntegration) { + return { ok: false, error: "AnkiConnect integration not enabled" }; + } + return ankiIntegration.buildFieldGroupingPreview( + request.keepNoteId, + request.deleteNoteId, + request.deleteDuplicate, + ); + }, +); + +ipcMain.handle("jimaku:get-media-info", (): JimakuMediaInfo => { + return parseMediaInfo(currentMediaPath); +}); + +ipcMain.handle( + "jimaku:search-entries", + async ( + _event, + query: JimakuSearchQuery, + ): Promise> => { + console.log(`[jimaku] search-entries query: "${query.query}"`); + const response = await jimakuFetchJson( + "/api/entries/search", + { + anime: true, + query: query.query, + }, + ); + if (!response.ok) return response; + const maxResults = getJimakuMaxEntryResults(); + console.log( + `[jimaku] search-entries returned ${response.data.length} results (capped to ${maxResults})`, + ); + return { ok: true, data: response.data.slice(0, maxResults) }; + }, +); + +ipcMain.handle( + "jimaku:list-files", + async ( + _event, + query: JimakuFilesQuery, + ): Promise> => { + console.log( + `[jimaku] list-files entryId=${query.entryId} episode=${query.episode ?? "all"}`, + ); + const response = await jimakuFetchJson( + `/api/entries/${query.entryId}/files`, + { + episode: query.episode ?? undefined, + }, + ); + if (!response.ok) return response; + const sorted = sortJimakuFiles( + response.data, + getJimakuLanguagePreference(), + ); + console.log(`[jimaku] list-files returned ${sorted.length} files`); + return { ok: true, data: sorted }; + }, +); + +ipcMain.handle( + "jimaku:download-file", + async (_event, query: JimakuDownloadQuery): Promise => { + const apiKey = await resolveJimakuApiKey(); + if (!apiKey) { + return { + ok: false, + error: { + error: + "Jimaku API key not set. Configure jimaku.apiKey or jimaku.apiKeyCommand.", + code: 401, + }, + }; + } + + if (!currentMediaPath) { + return { ok: false, error: { error: "No media file loaded in MPV." } }; + } + + if (isRemoteMediaPath(currentMediaPath)) { + return { + ok: false, + error: { error: "Cannot download subtitles for remote media paths." }, + }; + } + + const mediaDir = path.dirname(path.resolve(currentMediaPath)); + const safeName = path.basename(query.name); + if (!safeName) { + return { ok: false, error: { error: "Invalid subtitle filename." } }; + } + + const ext = path.extname(safeName); + const baseName = ext ? safeName.slice(0, -ext.length) : safeName; + let targetPath = path.join(mediaDir, safeName); + if (fs.existsSync(targetPath)) { + targetPath = path.join( + mediaDir, + `${baseName} (jimaku-${query.entryId})${ext}`, + ); + let counter = 2; + while (fs.existsSync(targetPath)) { + targetPath = path.join( + mediaDir, + `${baseName} (jimaku-${query.entryId}-${counter})${ext}`, + ); + counter += 1; + } + } + + console.log( + `[jimaku] download-file name="${query.name}" entryId=${query.entryId}`, + ); + const result = await downloadToFile(query.url, targetPath, { + Authorization: apiKey, + "User-Agent": "SubMiner", + }); + + if (result.ok) { + console.log(`[jimaku] download-file saved to ${result.path}`); + if (mpvClient && mpvClient.connected) { + mpvClient.send({ command: ["sub-add", result.path, "select"] }); + } + } else { + console.error( + `[jimaku] download-file failed: ${result.error?.error ?? "unknown error"}`, + ); + } + + return result; + }, +); diff --git a/src/mecab-tokenizer.ts b/src/mecab-tokenizer.ts new file mode 100644 index 0000000..f311710 --- /dev/null +++ b/src/mecab-tokenizer.ts @@ -0,0 +1,178 @@ +/* + * SubMiner - All-in-one sentence mining overlay + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +import { spawn, execSync } from "child_process"; +import { PartOfSpeech, Token, MecabStatus } from "./types"; +import { createLogger } from "./logger"; + +export { PartOfSpeech }; + +const log = createLogger("mecab"); + +function mapPartOfSpeech(pos1: string): PartOfSpeech { + switch (pos1) { + case "名詞": + return PartOfSpeech.noun; + case "動詞": + return PartOfSpeech.verb; + case "形容詞": + return PartOfSpeech.i_adjective; + case "形状詞": + case "形容動詞": + return PartOfSpeech.na_adjective; + case "助詞": + return PartOfSpeech.particle; + case "助動詞": + return PartOfSpeech.bound_auxiliary; + case "記号": + case "補助記号": + return PartOfSpeech.symbol; + default: + return PartOfSpeech.other; + } +} + +export function parseMecabLine(line: string): Token | null { + if (!line || line === "EOS" || line.trim() === "") { + return null; + } + + const tabIndex = line.indexOf("\t"); + if (tabIndex === -1) { + return null; + } + + const surface = line.substring(0, tabIndex); + const featureString = line.substring(tabIndex + 1); + const features = featureString.split(","); + + const pos1 = features[0] || ""; + const pos2 = features[1] || ""; + const pos3 = features[2] || ""; + const pos4 = features[3] || ""; + const inflectionType = features[4] || ""; + const inflectionForm = features[5] || ""; + const lemma = features[6] || surface; + const reading = features[7] || ""; + const pronunciation = features[8] || ""; + + return { + word: surface, + partOfSpeech: mapPartOfSpeech(pos1), + pos1, + pos2, + pos3, + pos4, + inflectionType, + inflectionForm, + headword: lemma !== "*" ? lemma : surface, + katakanaReading: reading !== "*" ? reading : "", + pronunciation: pronunciation !== "*" ? pronunciation : "", + }; +} + +export class MecabTokenizer { + private mecabPath: string | null = null; + private available: boolean = false; + private enabled: boolean = true; + + async checkAvailability(): Promise { + try { + const result = execSync("which mecab", { encoding: "utf-8" }).trim(); + if (result) { + this.mecabPath = result; + this.available = true; + log.info("MeCab found at:", this.mecabPath); + return true; + } + } catch (err) { + log.info("MeCab not found on system"); + } + + this.available = false; + return false; + } + + async tokenize(text: string): Promise { + if (!this.available || !this.enabled || !text) { + return null; + } + + return new Promise((resolve) => { + const mecab = spawn("mecab", [], { + stdio: ["pipe", "pipe", "pipe"], + }); + + let stdout = ""; + let stderr = ""; + + mecab.stdout.on("data", (data: Buffer) => { + stdout += data.toString(); + }); + + mecab.stderr.on("data", (data: Buffer) => { + stderr += data.toString(); + }); + + mecab.on("close", (code: number | null) => { + if (code !== 0) { + log.error("MeCab process exited with code:", code); + if (stderr) { + log.error("MeCab stderr:", stderr); + } + resolve(null); + return; + } + + const lines = stdout.split("\n"); + const tokens: Token[] = []; + + for (const line of lines) { + const token = parseMecabLine(line); + if (token) { + tokens.push(token); + } + } + + resolve(tokens); + }); + + mecab.on("error", (err: Error) => { + log.error("Failed to spawn MeCab:", err.message); + resolve(null); + }); + + mecab.stdin.write(text); + mecab.stdin.end(); + }); + } + + getStatus(): MecabStatus { + return { + available: this.available, + enabled: this.enabled, + path: this.mecabPath, + }; + } + + setEnabled(enabled: boolean): void { + this.enabled = enabled; + } +} + +export { mapPartOfSpeech }; diff --git a/src/media-generator.ts b/src/media-generator.ts new file mode 100644 index 0000000..7647f40 --- /dev/null +++ b/src/media-generator.ts @@ -0,0 +1,431 @@ +/* + * SubMiner - Subtitle mining overlay for mpv + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +import { ExecFileException, execFile } from "child_process"; +import * as fs from "fs"; +import * as path from "path"; +import * as os from "os"; +import { createLogger } from "./logger"; + +const log = createLogger("media"); + +export class MediaGenerator { + private tempDir: string; + private notifyIconDir: string; + private av1EncoderPromise: Promise | null = null; + + constructor(tempDir?: string) { + this.tempDir = tempDir || path.join(os.tmpdir(), "subminer-media"); + this.notifyIconDir = path.join(os.tmpdir(), "subminer-notify"); + if (!fs.existsSync(this.tempDir)) { + fs.mkdirSync(this.tempDir, { recursive: true }); + } + if (!fs.existsSync(this.notifyIconDir)) { + fs.mkdirSync(this.notifyIconDir, { recursive: true }); + } + // Clean up old notification icons on startup (older than 1 hour) + this.cleanupOldNotificationIcons(); + } + + /** + * Clean up notification icons older than 1 hour. + * Called on startup to prevent accumulation of temp files. + */ + private cleanupOldNotificationIcons(): void { + try { + if (!fs.existsSync(this.notifyIconDir)) return; + + const files = fs.readdirSync(this.notifyIconDir); + const oneHourAgo = Date.now() - 60 * 60 * 1000; + + for (const file of files) { + if (!file.endsWith(".png")) continue; + const filePath = path.join(this.notifyIconDir, file); + try { + const stat = fs.statSync(filePath); + if (stat.mtimeMs < oneHourAgo) { + fs.unlinkSync(filePath); + } + } catch (err) { + log.debug( + `Failed to clean up ${filePath}:`, + (err as Error).message, + ); + } + } + } catch (err) { + log.error("Failed to cleanup old notification icons:", err); + } + } + + /** + * Write a notification icon buffer to a temp file and return the file path. + * The file path can be passed directly to Electron Notification for better + * compatibility with Linux/Wayland notification daemons. + */ + writeNotificationIconToFile(iconBuffer: Buffer, noteId: number): string { + const filename = `icon_${noteId}_${Date.now()}.png`; + const filePath = path.join(this.notifyIconDir, filename); + fs.writeFileSync(filePath, iconBuffer); + return filePath; + } + + scheduleNotificationIconCleanup(filePath: string, delayMs = 10000): void { + setTimeout(() => { + try { + fs.unlinkSync(filePath); + } catch {} + }, delayMs); + } + + private ffmpegError(label: string, error: ExecFileException): Error { + if (error.code === "ENOENT") { + return new Error( + "FFmpeg not found. Install FFmpeg to enable media generation.", + ); + } + return new Error(`FFmpeg ${label} failed: ${error.message}`); + } + + private detectAv1Encoder(): Promise { + if (this.av1EncoderPromise) return this.av1EncoderPromise; + + this.av1EncoderPromise = new Promise((resolve) => { + execFile( + "ffmpeg", + ["-hide_banner", "-encoders"], + { timeout: 10000 }, + (error, stdout, stderr) => { + if (error) { + resolve(null); + return; + } + + const output = `${stdout || ""}\n${stderr || ""}`; + const candidates = ["libaom-av1", "libsvtav1", "librav1e"]; + for (const encoder of candidates) { + if (output.includes(encoder)) { + resolve(encoder); + return; + } + } + resolve(null); + }, + ); + }); + + return this.av1EncoderPromise; + } + + async generateAudio( + videoPath: string, + startTime: number, + endTime: number, + padding: number = 0.5, + audioStreamIndex: number | null = null, + ): Promise { + const start = Math.max(0, startTime - padding); + const duration = endTime - startTime + 2 * padding; + + return new Promise((resolve, reject) => { + const outputPath = path.join(this.tempDir, `audio_${Date.now()}.mp3`); + const args: string[] = [ + "-ss", + start.toString(), + "-t", + duration.toString(), + "-i", + videoPath, + ]; + + if ( + typeof audioStreamIndex === "number" && + Number.isInteger(audioStreamIndex) && + audioStreamIndex >= 0 + ) { + args.push("-map", `0:${audioStreamIndex}`); + } + + args.push( + "-vn", + "-acodec", + "libmp3lame", + "-q:a", + "2", + "-ar", + "44100", + "-y", + outputPath, + ); + + execFile("ffmpeg", args, { timeout: 30000 }, (error) => { + if (error) { + reject(this.ffmpegError("audio generation", error)); + return; + } + + try { + const data = fs.readFileSync(outputPath); + fs.unlinkSync(outputPath); + resolve(data); + } catch (err) { + reject(err); + } + }); + }); + } + + async generateScreenshot( + videoPath: string, + timestamp: number, + options: { + format: "jpg" | "png" | "webp"; + quality?: number; + maxWidth?: number; + maxHeight?: number; + }, + ): Promise { + const { format, quality = 92, maxWidth, maxHeight } = options; + const ext = format === "webp" ? "webp" : format === "png" ? "png" : "jpg"; + const codecMap: Record = { + jpg: "mjpeg", + png: "png", + webp: "webp", + }; + + const args: string[] = [ + "-ss", + timestamp.toString(), + "-i", + videoPath, + "-vframes", + "1", + ]; + + const vfParts: string[] = []; + if (maxWidth && maxWidth > 0 && maxHeight && maxHeight > 0) { + vfParts.push( + `scale=w=${maxWidth}:h=${maxHeight}:force_original_aspect_ratio=decrease`, + ); + } else if (maxWidth && maxWidth > 0) { + vfParts.push(`scale=w=${maxWidth}:h=-2`); + } else if (maxHeight && maxHeight > 0) { + vfParts.push(`scale=w=-2:h=${maxHeight}`); + } + if (vfParts.length > 0) { + args.push("-vf", vfParts.join(",")); + } + + args.push("-c:v", codecMap[format]); + + if (format !== "png") { + const clampedQuality = Math.max(1, Math.min(100, quality)); + if (format === "jpg") { + const qv = Math.round(2 + (100 - clampedQuality) * (29 / 99)); + args.push("-q:v", qv.toString()); + } else { + args.push("-q:v", clampedQuality.toString()); + } + } + + args.push("-y"); + + return new Promise((resolve, reject) => { + const outputPath = path.join( + this.tempDir, + `screenshot_${Date.now()}.${ext}`, + ); + args.push(outputPath); + + execFile("ffmpeg", args, { timeout: 30000 }, (error) => { + if (error) { + reject(this.ffmpegError("screenshot generation", error)); + return; + } + + try { + const data = fs.readFileSync(outputPath); + fs.unlinkSync(outputPath); + resolve(data); + } catch (err) { + reject(err); + } + }); + }); + } + + /** + * Generate a small PNG icon suitable for desktop notifications. + * Always outputs PNG format (known-good for Electron + Linux notification daemons). + * Scaled to 256px width for fast encoding and small file size. + */ + async generateNotificationIcon( + videoPath: string, + timestamp: number, + ): Promise { + return new Promise((resolve, reject) => { + const outputPath = path.join( + this.tempDir, + `notify_icon_${Date.now()}.png`, + ); + + execFile( + "ffmpeg", + [ + "-ss", + timestamp.toString(), + "-i", + videoPath, + "-vframes", + "1", + "-vf", + "scale=256:256:force_original_aspect_ratio=decrease,pad=256:256:(ow-iw)/2:(oh-ih)/2:black", + "-c:v", + "png", + "-y", + outputPath, + ], + { timeout: 30000 }, + (error) => { + if (error) { + reject(this.ffmpegError("notification icon generation", error)); + return; + } + + try { + const data = fs.readFileSync(outputPath); + fs.unlinkSync(outputPath); + resolve(data); + } catch (err) { + reject(err); + } + }, + ); + }); + } + + async generateAnimatedImage( + videoPath: string, + startTime: number, + endTime: number, + padding: number = 0.5, + options: { + fps?: number; + maxWidth?: number; + maxHeight?: number; + crf?: number; + } = {}, + ): Promise { + const start = Math.max(0, startTime - padding); + const duration = endTime - startTime + 2 * padding; + const { fps = 10, maxWidth = 640, maxHeight, crf = 35 } = options; + + const clampedFps = Math.max(1, Math.min(60, fps)); + const clampedCrf = Math.max(0, Math.min(63, crf)); + + const vfParts: string[] = []; + vfParts.push(`fps=${clampedFps}`); + if (maxWidth && maxWidth > 0 && maxHeight && maxHeight > 0) { + vfParts.push( + `scale=w=${maxWidth}:h=${maxHeight}:force_original_aspect_ratio=decrease`, + ); + } else if (maxWidth && maxWidth > 0) { + vfParts.push(`scale=w=${maxWidth}:h=-2`); + } else if (maxHeight && maxHeight > 0) { + vfParts.push(`scale=w=-2:h=${maxHeight}`); + } + + const av1Encoder = await this.detectAv1Encoder(); + if (!av1Encoder) { + throw new Error( + "No supported AV1 encoder found for animated AVIF (tried libaom-av1, libsvtav1, librav1e).", + ); + } + + return new Promise((resolve, reject) => { + const outputPath = path.join( + this.tempDir, + `animation_${Date.now()}.avif`, + ); + + const encoderArgs: string[] = ["-c:v", av1Encoder]; + if (av1Encoder === "libaom-av1") { + encoderArgs.push( + "-crf", + clampedCrf.toString(), + "-b:v", + "0", + "-cpu-used", + "8", + ); + } else if (av1Encoder === "libsvtav1") { + encoderArgs.push( + "-crf", + clampedCrf.toString(), + "-preset", + "8", + ); + } else { + // librav1e + encoderArgs.push("-qp", clampedCrf.toString(), "-speed", "8"); + } + + execFile( + "ffmpeg", + [ + "-ss", + start.toString(), + "-t", + duration.toString(), + "-i", + videoPath, + "-vf", + vfParts.join(","), + ...encoderArgs, + "-y", + outputPath, + ], + { timeout: 60000 }, + (error) => { + if (error) { + reject(this.ffmpegError("animation generation", error)); + return; + } + + try { + const data = fs.readFileSync(outputPath); + fs.unlinkSync(outputPath); + resolve(data); + } catch (err) { + reject(err); + } + }, + ); + }); + } + + cleanup(): void { + try { + if (fs.existsSync(this.tempDir)) { + fs.rmSync(this.tempDir, { recursive: true, force: true }); + } + } catch (err) { + log.error("Failed to cleanup media generator temp directory:", err); + } + } +} diff --git a/src/preload.ts b/src/preload.ts new file mode 100644 index 0000000..71dfa17 --- /dev/null +++ b/src/preload.ts @@ -0,0 +1,267 @@ +/* + * SubMiner - All-in-one sentence mining overlay + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +import { contextBridge, ipcRenderer, IpcRendererEvent } from "electron"; +import type { + SubtitleData, + SubtitlePosition, + MecabStatus, + Keybinding, + ElectronAPI, + SecondarySubMode, + SubtitleStyleConfig, + JimakuMediaInfo, + JimakuSearchQuery, + JimakuFilesQuery, + JimakuDownloadQuery, + JimakuEntry, + JimakuFileEntry, + JimakuApiResponse, + JimakuDownloadResult, + SubsyncManualPayload, + SubsyncManualRunRequest, + SubsyncResult, + KikuFieldGroupingRequestData, + KikuFieldGroupingChoice, + KikuMergePreviewRequest, + KikuMergePreviewResponse, + RuntimeOptionApplyResult, + RuntimeOptionId, + RuntimeOptionState, + RuntimeOptionValue, + MpvSubtitleRenderMetrics, +} from "./types"; + +const overlayLayerArg = process.argv.find((arg) => + arg.startsWith("--overlay-layer="), +); +const overlayLayerFromArg = overlayLayerArg?.slice("--overlay-layer=".length); +const overlayLayer = + overlayLayerFromArg === "visible" || overlayLayerFromArg === "invisible" + ? overlayLayerFromArg + : null; + +const electronAPI: ElectronAPI = { + getOverlayLayer: () => overlayLayer, + onSubtitle: (callback: (data: SubtitleData) => void) => { + ipcRenderer.on( + "subtitle:set", + (_event: IpcRendererEvent, data: SubtitleData) => callback(data), + ); + }, + + onVisibility: (callback: (visible: boolean) => void) => { + ipcRenderer.on( + "mpv:subVisibility", + (_event: IpcRendererEvent, visible: boolean) => callback(visible), + ); + }, + + onSubtitlePosition: ( + callback: (position: SubtitlePosition | null) => void, + ) => { + ipcRenderer.on( + "subtitle-position:set", + (_event: IpcRendererEvent, position: SubtitlePosition | null) => { + callback(position); + }, + ); + }, + + getOverlayVisibility: (): Promise => + ipcRenderer.invoke("get-overlay-visibility"), + getCurrentSubtitle: (): Promise => + ipcRenderer.invoke("get-current-subtitle"), + getCurrentSubtitleAss: (): Promise => + ipcRenderer.invoke("get-current-subtitle-ass"), + getMpvSubtitleRenderMetrics: () => + ipcRenderer.invoke("get-mpv-subtitle-render-metrics"), + onMpvSubtitleRenderMetrics: ( + callback: (metrics: MpvSubtitleRenderMetrics) => void, + ) => { + ipcRenderer.on( + "mpv-subtitle-render-metrics:set", + (_event: IpcRendererEvent, metrics: MpvSubtitleRenderMetrics) => { + callback(metrics); + }, + ); + }, + onSubtitleAss: (callback: (assText: string) => void) => { + ipcRenderer.on( + "subtitle-ass:set", + (_event: IpcRendererEvent, assText: string) => { + callback(assText); + }, + ); + }, + onOverlayDebugVisualization: (callback: (enabled: boolean) => void) => { + ipcRenderer.on( + "overlay-debug-visualization:set", + (_event: IpcRendererEvent, enabled: boolean) => { + callback(enabled); + }, + ); + }, + + setIgnoreMouseEvents: (ignore: boolean, options?: { forward?: boolean }) => { + ipcRenderer.send("set-ignore-mouse-events", ignore, options); + }, + + openYomitanSettings: () => { + ipcRenderer.send("open-yomitan-settings"); + }, + + getSubtitlePosition: (): Promise => + ipcRenderer.invoke("get-subtitle-position"), + saveSubtitlePosition: (position: SubtitlePosition) => { + ipcRenderer.send("save-subtitle-position", position); + }, + + getMecabStatus: (): Promise => + ipcRenderer.invoke("get-mecab-status"), + setMecabEnabled: (enabled: boolean) => { + ipcRenderer.send("set-mecab-enabled", enabled); + }, + + sendMpvCommand: (command: (string | number)[]) => { + ipcRenderer.send("mpv-command", command); + }, + + getKeybindings: (): Promise => + ipcRenderer.invoke("get-keybindings"), + + getJimakuMediaInfo: (): Promise => + ipcRenderer.invoke("jimaku:get-media-info"), + jimakuSearchEntries: ( + query: JimakuSearchQuery, + ): Promise> => + ipcRenderer.invoke("jimaku:search-entries", query), + jimakuListFiles: ( + query: JimakuFilesQuery, + ): Promise> => + ipcRenderer.invoke("jimaku:list-files", query), + jimakuDownloadFile: ( + query: JimakuDownloadQuery, + ): Promise => + ipcRenderer.invoke("jimaku:download-file", query), + + quitApp: () => { + ipcRenderer.send("quit-app"); + }, + + toggleDevTools: () => { + ipcRenderer.send("toggle-dev-tools"); + }, + + toggleOverlay: () => { + ipcRenderer.send("toggle-overlay"); + }, + + getAnkiConnectStatus: (): Promise => + ipcRenderer.invoke("get-anki-connect-status"), + setAnkiConnectEnabled: (enabled: boolean) => { + ipcRenderer.send("set-anki-connect-enabled", enabled); + }, + clearAnkiConnectHistory: () => { + ipcRenderer.send("clear-anki-connect-history"); + }, + + onSecondarySub: (callback: (text: string) => void) => { + ipcRenderer.on( + "secondary-subtitle:set", + (_event: IpcRendererEvent, text: string) => callback(text), + ); + }, + + onSecondarySubMode: (callback: (mode: SecondarySubMode) => void) => { + ipcRenderer.on( + "secondary-subtitle:mode", + (_event: IpcRendererEvent, mode: SecondarySubMode) => callback(mode), + ); + }, + + getSecondarySubMode: (): Promise => + ipcRenderer.invoke("get-secondary-sub-mode"), + getCurrentSecondarySub: (): Promise => + ipcRenderer.invoke("get-current-secondary-sub"), + getSubtitleStyle: (): Promise => + ipcRenderer.invoke("get-subtitle-style"), + onSubsyncManualOpen: (callback: (payload: SubsyncManualPayload) => void) => { + ipcRenderer.on( + "subsync:open-manual", + (_event: IpcRendererEvent, payload: SubsyncManualPayload) => { + callback(payload); + }, + ); + }, + runSubsyncManual: ( + request: SubsyncManualRunRequest, + ): Promise => + ipcRenderer.invoke("subsync:run-manual", request), + + onKikuFieldGroupingRequest: ( + callback: (data: KikuFieldGroupingRequestData) => void, + ) => { + ipcRenderer.on( + "kiku:field-grouping-request", + (_event: IpcRendererEvent, data: KikuFieldGroupingRequestData) => + callback(data), + ); + }, + kikuBuildMergePreview: ( + request: KikuMergePreviewRequest, + ): Promise => + ipcRenderer.invoke("kiku:build-merge-preview", request), + + kikuFieldGroupingRespond: (choice: KikuFieldGroupingChoice) => { + ipcRenderer.send("kiku:field-grouping-respond", choice); + }, + + getRuntimeOptions: (): Promise => + ipcRenderer.invoke("runtime-options:get"), + setRuntimeOptionValue: ( + id: RuntimeOptionId, + value: RuntimeOptionValue, + ): Promise => + ipcRenderer.invoke("runtime-options:set", id, value), + cycleRuntimeOption: ( + id: RuntimeOptionId, + direction: 1 | -1, + ): Promise => + ipcRenderer.invoke("runtime-options:cycle", id, direction), + onRuntimeOptionsChanged: ( + callback: (options: RuntimeOptionState[]) => void, + ) => { + ipcRenderer.on( + "runtime-options:changed", + (_event: IpcRendererEvent, options: RuntimeOptionState[]) => { + callback(options); + }, + ); + }, + onOpenRuntimeOptions: (callback: () => void) => { + ipcRenderer.on("runtime-options:open", () => { + callback(); + }); + }, + notifyOverlayModalClosed: (modal: "runtime-options" | "subsync") => { + ipcRenderer.send("overlay:modal-closed", modal); + }, +}; + +contextBridge.exposeInMainWorld("electronAPI", electronAPI); diff --git a/src/renderer/index.html b/src/renderer/index.html new file mode 100644 index 0000000..1ee7f27 --- /dev/null +++ b/src/renderer/index.html @@ -0,0 +1,265 @@ + + + + + + + + SubMiner + + + +
+
+
+
+
+
+
+ + + + +
+ + + diff --git a/src/renderer/renderer.ts b/src/renderer/renderer.ts new file mode 100644 index 0000000..aa02489 --- /dev/null +++ b/src/renderer/renderer.ts @@ -0,0 +1,2443 @@ +/* + * SubMiner - All-in-one sentence mining overlay + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +interface MergedToken { + surface: string; + reading: string; + headword: string; + startPos: number; + endPos: number; + partOfSpeech: string; + isMerged: boolean; +} + +interface SubtitleData { + text: string; + tokens: MergedToken[] | null; +} + +interface AssInlineOverrides { + fontFamily?: string; + fontSize?: number; + letterSpacing?: number; + scaleX?: number; + scaleY?: number; + bold?: boolean; + italic?: boolean; + borderSize?: number; + shadowOffset?: number; + alignment?: number; +} + +interface MpvSubtitleRenderMetrics { + subPos: number; + subFontSize: number; + subScale: number; + subMarginY: number; + subMarginX: number; + subFont: string; + subSpacing: number; + subBold: boolean; + subItalic: boolean; + subBorderSize: number; + subShadowOffset: number; + subAssOverride: string; + subScaleByWindow: boolean; + subUseMargins: boolean; + osdHeight: number; + osdDimensions: { + w: number; + h: number; + ml: number; + mr: number; + mt: number; + mb: number; + } | null; +} + +interface Keybinding { + key: string; + command: (string | number)[] | null; +} + +interface SubtitlePosition { + yPercent: number; +} + +type SecondarySubMode = "hidden" | "visible" | "hover"; + +interface SubtitleStyleConfig { + fontFamily?: string; + fontSize?: number; + fontColor?: string; + fontWeight?: string; + fontStyle?: string; + backgroundColor?: string; + secondary?: { + fontFamily?: string; + fontSize?: number; + fontColor?: string; + fontWeight?: string; + fontStyle?: string; + backgroundColor?: string; + }; +} + +type JimakuConfidence = "high" | "medium" | "low"; + +interface JimakuMediaInfo { + title: string; + season: number | null; + episode: number | null; + confidence: JimakuConfidence; + filename: string; + rawTitle: string; +} + +interface JimakuEntryFlags { + anime?: boolean; + movie?: boolean; + adult?: boolean; + external?: boolean; + unverified?: boolean; +} + +interface JimakuEntry { + id: number; + name: string; + english_name?: string | null; + japanese_name?: string | null; + flags?: JimakuEntryFlags; + last_modified?: string; +} + +interface JimakuFileEntry { + name: string; + url: string; + size: number; + last_modified: string; +} + +interface JimakuApiError { + error: string; + code?: number; + retryAfter?: number; +} + +type JimakuApiResponse = + | { ok: true; data: T } + | { ok: false; error: JimakuApiError }; + +type JimakuDownloadResult = + | { ok: true; path: string } + | { ok: false; error: JimakuApiError }; + +interface KikuDuplicateCardInfo { + noteId: number; + expression: string; + sentencePreview: string; + hasAudio: boolean; + hasImage: boolean; + isOriginal: boolean; +} + +interface KikuFieldGroupingChoice { + keepNoteId: number; + deleteNoteId: number; + deleteDuplicate: boolean; + cancelled: boolean; +} + +interface KikuMergePreviewResponse { + ok: boolean; + compact?: Record; + full?: Record; + error?: string; +} + +type RuntimeOptionId = "anki.autoUpdateNewCards" | "anki.kikuFieldGrouping"; +type RuntimeOptionValue = boolean | string; +type RuntimeOptionValueType = "boolean" | "enum"; + +interface RuntimeOptionState { + id: RuntimeOptionId; + label: string; + scope: "ankiConnect"; + valueType: RuntimeOptionValueType; + value: RuntimeOptionValue; + allowedValues: RuntimeOptionValue[]; + requiresRestart: boolean; +} + +interface RuntimeOptionApplyResult { + ok: boolean; + option?: RuntimeOptionState; + osdMessage?: string; + requiresRestart?: boolean; + error?: string; +} + +interface SubsyncSourceTrack { + id: number; + label: string; +} + +interface SubsyncManualPayload { + sourceTracks: SubsyncSourceTrack[]; +} + +type KikuModalStep = "select" | "preview"; +type KikuPreviewMode = "compact" | "full"; + +const subtitleRoot = document.getElementById("subtitleRoot")!; +const subtitleContainer = document.getElementById("subtitleContainer")!; +const overlay = document.getElementById("overlay")!; +const secondarySubContainer = document.getElementById("secondarySubContainer")!; +const secondarySubRoot = document.getElementById("secondarySubRoot")!; +const jimakuModal = document.getElementById("jimakuModal") as HTMLDivElement; +const jimakuTitleInput = document.getElementById( + "jimakuTitle", +) as HTMLInputElement; +const jimakuSeasonInput = document.getElementById( + "jimakuSeason", +) as HTMLInputElement; +const jimakuEpisodeInput = document.getElementById( + "jimakuEpisode", +) as HTMLInputElement; +const jimakuSearchButton = document.getElementById( + "jimakuSearch", +) as HTMLButtonElement; +const jimakuCloseButton = document.getElementById( + "jimakuClose", +) as HTMLButtonElement; +const jimakuStatus = document.getElementById("jimakuStatus") as HTMLDivElement; +const jimakuEntriesSection = document.getElementById( + "jimakuEntriesSection", +) as HTMLDivElement; +const jimakuEntriesList = document.getElementById( + "jimakuEntries", +) as HTMLUListElement; +const jimakuFilesSection = document.getElementById( + "jimakuFilesSection", +) as HTMLDivElement; +const jimakuFilesList = document.getElementById( + "jimakuFiles", +) as HTMLUListElement; +const jimakuBroadenButton = document.getElementById( + "jimakuBroaden", +) as HTMLButtonElement; + +const kikuModal = document.getElementById( + "kikuFieldGroupingModal", +) as HTMLDivElement; +const kikuCard1 = document.getElementById("kikuCard1") as HTMLDivElement; +const kikuCard2 = document.getElementById("kikuCard2") as HTMLDivElement; +const kikuCard1Expression = document.getElementById( + "kikuCard1Expression", +) as HTMLDivElement; +const kikuCard2Expression = document.getElementById( + "kikuCard2Expression", +) as HTMLDivElement; +const kikuCard1Sentence = document.getElementById( + "kikuCard1Sentence", +) as HTMLDivElement; +const kikuCard2Sentence = document.getElementById( + "kikuCard2Sentence", +) as HTMLDivElement; +const kikuCard1Meta = document.getElementById( + "kikuCard1Meta", +) as HTMLDivElement; +const kikuCard2Meta = document.getElementById( + "kikuCard2Meta", +) as HTMLDivElement; +const kikuConfirmButton = document.getElementById( + "kikuConfirmButton", +) as HTMLButtonElement; +const kikuCancelButton = document.getElementById( + "kikuCancelButton", +) as HTMLButtonElement; +const kikuDeleteDuplicateCheckbox = document.getElementById( + "kikuDeleteDuplicate", +) as HTMLInputElement; +const kikuSelectionStep = document.getElementById( + "kikuSelectionStep", +) as HTMLDivElement; +const kikuPreviewStep = document.getElementById( + "kikuPreviewStep", +) as HTMLDivElement; +const kikuPreviewJson = document.getElementById( + "kikuPreviewJson", +) as HTMLPreElement; +const kikuPreviewCompactButton = document.getElementById( + "kikuPreviewCompact", +) as HTMLButtonElement; +const kikuPreviewFullButton = document.getElementById( + "kikuPreviewFull", +) as HTMLButtonElement; +const kikuPreviewError = document.getElementById( + "kikuPreviewError", +) as HTMLDivElement; +const kikuBackButton = document.getElementById( + "kikuBackButton", +) as HTMLButtonElement; +const kikuFinalConfirmButton = document.getElementById( + "kikuFinalConfirmButton", +) as HTMLButtonElement; +const kikuFinalCancelButton = document.getElementById( + "kikuFinalCancelButton", +) as HTMLButtonElement; +const kikuHint = document.getElementById("kikuHint") as HTMLDivElement; +const runtimeOptionsModal = document.getElementById( + "runtimeOptionsModal", +) as HTMLDivElement; +const runtimeOptionsClose = document.getElementById( + "runtimeOptionsClose", +) as HTMLButtonElement; +const runtimeOptionsList = document.getElementById( + "runtimeOptionsList", +) as HTMLUListElement; +const runtimeOptionsStatus = document.getElementById( + "runtimeOptionsStatus", +) as HTMLDivElement; +const subsyncModal = document.getElementById("subsyncModal") as HTMLDivElement; +const subsyncCloseButton = document.getElementById( + "subsyncClose", +) as HTMLButtonElement; +const subsyncEngineAlass = document.getElementById( + "subsyncEngineAlass", +) as HTMLInputElement; +const subsyncEngineFfsubsync = document.getElementById( + "subsyncEngineFfsubsync", +) as HTMLInputElement; +const subsyncSourceLabel = document.getElementById( + "subsyncSourceLabel", +) as HTMLLabelElement; +const subsyncSourceSelect = document.getElementById( + "subsyncSourceSelect", +) as HTMLSelectElement; +const subsyncRunButton = document.getElementById( + "subsyncRun", +) as HTMLButtonElement; +const subsyncStatus = document.getElementById( + "subsyncStatus", +) as HTMLDivElement; + +const overlayLayerFromPreload = window.electronAPI.getOverlayLayer(); +const overlayLayerFromQuery = + new URLSearchParams(window.location.search).get("layer") === "invisible" + ? "invisible" + : "visible"; +const overlayLayer = + overlayLayerFromPreload === "visible" || + overlayLayerFromPreload === "invisible" + ? overlayLayerFromPreload + : overlayLayerFromQuery; +const isInvisibleLayer = overlayLayer === "invisible"; +const isLinuxPlatform = navigator.platform.toLowerCase().includes("linux"); +// Linux passthrough forwarding is not reliable for this overlay; keep pointer +// routing local so hover lookup, drag-reposition, and key handling remain usable. +const shouldToggleMouseIgnore = !isLinuxPlatform; + +let isOverSubtitle = false; +let isDragging = false; +let dragStartY = 0; +let startYPercent = 0; +let currentYPercent: number | null = null; +let jimakuModalOpen = false; +let jimakuEntries: JimakuEntry[] = []; +let jimakuFiles: JimakuFileEntry[] = []; +let selectedEntryIndex = 0; +let selectedFileIndex = 0; +let currentEpisodeFilter: number | null = null; +let currentEntryId: number | null = null; + +let kikuModalOpen = false; +let kikuSelectedCard: 1 | 2 = 1; +let kikuOriginalData: KikuDuplicateCardInfo | null = null; +let kikuDuplicateData: KikuDuplicateCardInfo | null = null; +let kikuModalStep: KikuModalStep = "select"; +let kikuPreviewMode: KikuPreviewMode = "compact"; +let kikuPendingChoice: KikuFieldGroupingChoice | null = null; +let kikuPreviewCompactData: Record | null = null; +let kikuPreviewFullData: Record | null = null; +let runtimeOptionsModalOpen = false; +let runtimeOptions: RuntimeOptionState[] = []; +let runtimeOptionSelectedIndex = 0; +let runtimeOptionDraftValues = new Map(); +let subsyncModalOpen = false; +let subsyncSourceTracks: SubsyncSourceTrack[] = []; +let subsyncSubmitting = false; +const DEFAULT_MPV_SUBTITLE_RENDER_METRICS: MpvSubtitleRenderMetrics = { + subPos: 100, + subFontSize: 38, + subScale: 1, + subMarginY: 34, + subMarginX: 19, + subFont: "sans-serif", + subSpacing: 0, + subBold: false, + subItalic: false, + subBorderSize: 2.5, + subShadowOffset: 0, + subAssOverride: "yes", + subScaleByWindow: true, + subUseMargins: true, + osdHeight: 720, + osdDimensions: null, +}; +let mpvSubtitleRenderMetrics: MpvSubtitleRenderMetrics = { + ...DEFAULT_MPV_SUBTITLE_RENDER_METRICS, +}; +let currentSubtitleAss = ""; + +function normalizeSubtitle(text: string, trim = true): string { + if (!text) return ""; + + let normalized = text.replace(/\\N/g, "\n").replace(/\\n/g, "\n"); + + normalized = normalized.replace(/\{[^}]*\}/g, ""); + + return trim ? normalized.trim() : normalized; +} + +function renderWithTokens(tokens: MergedToken[]): void { + const fragment = document.createDocumentFragment(); + + for (const token of tokens) { + const surface = token.surface; + + if (surface.includes("\n")) { + const parts = surface.split("\n"); + for (let i = 0; i < parts.length; i++) { + if (parts[i]) { + const span = document.createElement("span"); + span.className = "word"; + span.textContent = parts[i]; + if (token.reading) { + span.dataset.reading = token.reading; + } + if (token.headword) { + span.dataset.headword = token.headword; + } + fragment.appendChild(span); + } + if (i < parts.length - 1) { + fragment.appendChild(document.createElement("br")); + } + } + } else { + const span = document.createElement("span"); + span.className = "word"; + span.textContent = surface; + if (token.reading) { + span.dataset.reading = token.reading; + } + if (token.headword) { + span.dataset.headword = token.headword; + } + fragment.appendChild(span); + } + } + + subtitleRoot.appendChild(fragment); +} + +function renderCharacterLevel(text: string): void { + const fragment = document.createDocumentFragment(); + + for (const char of text) { + if (char === "\n") { + fragment.appendChild(document.createElement("br")); + } else { + const span = document.createElement("span"); + span.className = "c"; + span.textContent = char; + fragment.appendChild(span); + } + } + + subtitleRoot.appendChild(fragment); +} + +function renderPlainTextPreserveLineBreaks(text: string): void { + const lines = text.split("\n"); + const fragment = document.createDocumentFragment(); + + for (let i = 0; i < lines.length; i += 1) { + fragment.appendChild(document.createTextNode(lines[i])); + if (i < lines.length - 1) { + fragment.appendChild(document.createElement("br")); + } + } + + subtitleRoot.appendChild(fragment); +} + +function renderSubtitle(data: SubtitleData | string): void { + subtitleRoot.innerHTML = ""; + + let text: string; + let tokens: MergedToken[] | null; + + if (typeof data === "string") { + text = data; + tokens = null; + } else if (data && typeof data === "object") { + text = data.text; + tokens = data.tokens; + } else { + return; + } + + if (!text) { + return; + } + + if (isInvisibleLayer) { + // Keep natural kerning/shaping for accurate hitbox alignment with mpv/libass. + renderPlainTextPreserveLineBreaks(normalizeSubtitle(text, false)); + return; + } + + const normalized = normalizeSubtitle(text); + + if (tokens && tokens.length > 0) { + renderWithTokens(tokens); + } else { + renderCharacterLevel(normalized); + } +} + +function handleMouseEnter(): void { + isOverSubtitle = true; + overlay.classList.add("interactive"); + if (shouldToggleMouseIgnore) { + window.electronAPI.setIgnoreMouseEvents(false); + } +} + +function handleMouseLeave(): void { + isOverSubtitle = false; + const yomitanPopup = document.querySelector('iframe[id^="yomitan-popup"]'); + if ( + !yomitanPopup && + !jimakuModalOpen && + !kikuModalOpen && + !runtimeOptionsModalOpen && + !subsyncModalOpen + ) { + overlay.classList.remove("interactive"); + if (shouldToggleMouseIgnore) { + window.electronAPI.setIgnoreMouseEvents(true, { forward: true }); + } + } +} + +function clampYPercent(yPercent: number): number { + return Math.max(2, Math.min(80, yPercent)); +} + +function getCurrentYPercent(): number { + if (currentYPercent !== null) { + return currentYPercent; + } + const marginBottom = parseFloat(subtitleContainer.style.marginBottom) || 60; + const windowHeight = window.innerHeight; + currentYPercent = clampYPercent((marginBottom / windowHeight) * 100); + return currentYPercent; +} + +function applyYPercent(yPercent: number): void { + const clampedPercent = clampYPercent(yPercent); + currentYPercent = clampedPercent; + const marginBottom = (clampedPercent / 100) * window.innerHeight; + + subtitleContainer.style.position = ""; + subtitleContainer.style.left = ""; + subtitleContainer.style.top = ""; + subtitleContainer.style.right = ""; + subtitleContainer.style.transform = ""; + + subtitleContainer.style.marginBottom = `${marginBottom}px`; +} + +function applyStoredSubtitlePosition( + position: SubtitlePosition | null, + source: string, +): void { + if (position && position.yPercent !== undefined) { + applyYPercent(position.yPercent); + console.log( + "Applied subtitle position from", + source, + ":", + position.yPercent, + "%", + ); + } else { + const defaultMarginBottom = 60; + const defaultYPercent = (defaultMarginBottom / window.innerHeight) * 100; + applyYPercent(defaultYPercent); + console.log("Applied default subtitle position from", source); + } +} + +function applySubtitleFontSize(fontSize: number): void { + const clampedSize = Math.max(10, fontSize); + subtitleRoot.style.fontSize = `${clampedSize}px`; + document.documentElement.style.setProperty( + "--subtitle-font-size", + `${clampedSize}px`, + ); +} + +function coerceFiniteNumber( + value: unknown, + fallback: number, + min?: number, + max?: number, +): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + return fallback; + } + let next = value; + if (typeof min === "number") next = Math.max(min, next); + if (typeof max === "number") next = Math.min(max, next); + return next; +} + +function sanitizeMpvSubtitleRenderMetrics( + metrics: Partial | null | undefined, +): MpvSubtitleRenderMetrics { + const dims = metrics?.osdDimensions; + const nextOsdDimensions = + dims && + typeof dims.w === "number" && + typeof dims.h === "number" && + typeof dims.ml === "number" && + typeof dims.mr === "number" && + typeof dims.mt === "number" && + typeof dims.mb === "number" + ? { + w: coerceFiniteNumber(dims.w, 0, 1, 100000), + h: coerceFiniteNumber(dims.h, 0, 1, 100000), + ml: coerceFiniteNumber(dims.ml, 0, 0, 100000), + mr: coerceFiniteNumber(dims.mr, 0, 0, 100000), + mt: coerceFiniteNumber(dims.mt, 0, 0, 100000), + mb: coerceFiniteNumber(dims.mb, 0, 0, 100000), + } + : dims === null + ? null + : mpvSubtitleRenderMetrics.osdDimensions; + + return { + subPos: coerceFiniteNumber( + metrics?.subPos, + mpvSubtitleRenderMetrics.subPos, + 0, + 150, + ), + subFontSize: coerceFiniteNumber( + metrics?.subFontSize, + mpvSubtitleRenderMetrics.subFontSize, + 1, + 200, + ), + subScale: coerceFiniteNumber( + metrics?.subScale, + mpvSubtitleRenderMetrics.subScale, + 0.1, + 10, + ), + subMarginY: coerceFiniteNumber( + metrics?.subMarginY, + mpvSubtitleRenderMetrics.subMarginY, + 0, + 200, + ), + subMarginX: coerceFiniteNumber( + metrics?.subMarginX, + mpvSubtitleRenderMetrics.subMarginX, + 0, + 200, + ), + subFont: + typeof metrics?.subFont === "string" && metrics.subFont.trim().length > 0 + ? metrics.subFont.trim() + : mpvSubtitleRenderMetrics.subFont, + subSpacing: coerceFiniteNumber( + metrics?.subSpacing, + mpvSubtitleRenderMetrics.subSpacing, + -100, + 100, + ), + subBold: + typeof metrics?.subBold === "boolean" + ? metrics.subBold + : mpvSubtitleRenderMetrics.subBold, + subItalic: + typeof metrics?.subItalic === "boolean" + ? metrics.subItalic + : mpvSubtitleRenderMetrics.subItalic, + subBorderSize: coerceFiniteNumber( + metrics?.subBorderSize, + mpvSubtitleRenderMetrics.subBorderSize, + 0, + 100, + ), + subShadowOffset: coerceFiniteNumber( + metrics?.subShadowOffset, + mpvSubtitleRenderMetrics.subShadowOffset, + 0, + 100, + ), + subAssOverride: + typeof metrics?.subAssOverride === "string" && + metrics.subAssOverride.trim().length > 0 + ? metrics.subAssOverride.trim() + : mpvSubtitleRenderMetrics.subAssOverride, + subScaleByWindow: + typeof metrics?.subScaleByWindow === "boolean" + ? metrics.subScaleByWindow + : mpvSubtitleRenderMetrics.subScaleByWindow, + subUseMargins: + typeof metrics?.subUseMargins === "boolean" + ? metrics.subUseMargins + : mpvSubtitleRenderMetrics.subUseMargins, + osdHeight: coerceFiniteNumber( + metrics?.osdHeight, + mpvSubtitleRenderMetrics.osdHeight, + 1, + 10000, + ), + osdDimensions: nextOsdDimensions, + }; +} + +function getLastMatch(text: string, pattern: RegExp): string | undefined { + let last: string | undefined; + let match: RegExpExecArray | null; + // eslint-disable-next-line no-cond-assign + while ((match = pattern.exec(text)) !== null) { + last = match[1]; + } + return last; +} + +function parseAssInlineOverrides(assText: string): AssInlineOverrides { + if (!assText) return {}; + + const result: AssInlineOverrides = {}; + + const fontFamily = getLastMatch(assText, /\\fn([^\\}]+)/g); + if (fontFamily && fontFamily.trim()) { + result.fontFamily = fontFamily.trim(); + } + + const fontSize = getLastMatch(assText, /\\fs(-?\d+(?:\.\d+)?)/g); + if (fontSize) { + const parsed = Number.parseFloat(fontSize); + if (Number.isFinite(parsed) && parsed > 0) { + result.fontSize = parsed; + } + } + + const letterSpacing = getLastMatch(assText, /\\fsp(-?\d+(?:\.\d+)?)/g); + if (letterSpacing) { + const parsed = Number.parseFloat(letterSpacing); + if (Number.isFinite(parsed)) { + result.letterSpacing = parsed; + } + } + + const scaleX = getLastMatch(assText, /\\fscx(-?\d+(?:\.\d+)?)/g); + if (scaleX) { + const parsed = Number.parseFloat(scaleX); + if (Number.isFinite(parsed) && parsed > 0) { + result.scaleX = parsed / 100; + } + } + + const scaleY = getLastMatch(assText, /\\fscy(-?\d+(?:\.\d+)?)/g); + if (scaleY) { + const parsed = Number.parseFloat(scaleY); + if (Number.isFinite(parsed) && parsed > 0) { + result.scaleY = parsed / 100; + } + } + + const bold = getLastMatch(assText, /\\b(-?\d+)/g); + if (bold) { + const parsed = Number.parseInt(bold, 10); + if (!Number.isNaN(parsed)) { + result.bold = parsed !== 0; + } + } + + const italic = getLastMatch(assText, /\\i(-?\d+)/g); + if (italic) { + const parsed = Number.parseInt(italic, 10); + if (!Number.isNaN(parsed)) { + result.italic = parsed !== 0; + } + } + + const borderSize = getLastMatch(assText, /\\bord(-?\d+(?:\.\d+)?)/g); + if (borderSize) { + const parsed = Number.parseFloat(borderSize); + if (Number.isFinite(parsed) && parsed >= 0) { + result.borderSize = parsed; + } + } + + const shadowOffset = getLastMatch(assText, /\\shad(-?\d+(?:\.\d+)?)/g); + if (shadowOffset) { + const parsed = Number.parseFloat(shadowOffset); + if (Number.isFinite(parsed) && parsed >= 0) { + result.shadowOffset = parsed; + } + } + + const alignment = getLastMatch(assText, /\\an(\d)/g); + if (alignment) { + const parsed = Number.parseInt(alignment, 10); + if (parsed >= 1 && parsed <= 9) { + result.alignment = parsed; + } + } + + return result; +} + +function applyInvisibleSubtitleLayoutFromMpvMetrics( + metrics: Partial | null | undefined, + source: string, +): void { + mpvSubtitleRenderMetrics = sanitizeMpvSubtitleRenderMetrics(metrics); + + const dims = mpvSubtitleRenderMetrics.osdDimensions; + const renderAreaHeight = dims?.h ?? window.innerHeight; + const renderAreaWidth = dims?.w ?? window.innerWidth; + const videoLeftInset = dims?.ml ?? 0; + const videoRightInset = dims?.mr ?? 0; + const videoTopInset = dims?.mt ?? 0; + const videoBottomInset = dims?.mb ?? 0; + const anchorToVideoArea = !mpvSubtitleRenderMetrics.subUseMargins; + const leftInset = anchorToVideoArea ? videoLeftInset : 0; + const rightInset = anchorToVideoArea ? videoRightInset : 0; + const topInset = anchorToVideoArea ? videoTopInset : 0; + const bottomInset = anchorToVideoArea ? videoBottomInset : 0; + + // Match mpv subtitle sizing from scaled pixels in mpv's OSD space. + const osdReferenceHeight = mpvSubtitleRenderMetrics.subScaleByWindow + ? mpvSubtitleRenderMetrics.osdHeight + : 720; + const pxPerScaledPixel = Math.max(0.1, renderAreaHeight / osdReferenceHeight); + const computedFontSize = + mpvSubtitleRenderMetrics.subFontSize * + mpvSubtitleRenderMetrics.subScale * + pxPerScaledPixel; + const rawAssOverrides = parseAssInlineOverrides(currentSubtitleAss); + + // When sub-ass-override is "yes" (default), "force", or "strip", mpv ignores + // ASS inline style tags (\fn, \fs, \b, \i, \bord, \shad, \fsp, \fscx, \fscy) + // and uses its own sub-* settings instead. Only positioning tags like \an and + // \pos are always respected. Since sub-text-ass returns the raw ASS text + // regardless of this setting, we must skip style overrides when mpv is + // overriding them. + const assOverrideMode = mpvSubtitleRenderMetrics.subAssOverride; + const mpvOverridesAssStyles = + assOverrideMode === "yes" || + assOverrideMode === "force" || + assOverrideMode === "strip"; + const assOverrides: AssInlineOverrides = mpvOverridesAssStyles + ? {} + : rawAssOverrides; + + const effectiveFontSize = + assOverrides.fontSize && assOverrides.fontSize > 0 + ? assOverrides.fontSize * pxPerScaledPixel + : computedFontSize; + applySubtitleFontSize(effectiveFontSize); + + // \an is a positioning tag — always respected regardless of sub-ass-override + const alignment = rawAssOverrides.alignment ?? 2; + const hAlign = ((alignment - 1) % 3) as 0 | 1 | 2; // 0=left, 1=center, 2=right + const vAlign = Math.floor((alignment - 1) / 3) as 0 | 1 | 2; // 0=bottom, 1=middle, 2=top + + const marginY = mpvSubtitleRenderMetrics.subMarginY * pxPerScaledPixel; + const marginX = Math.max( + 0, + mpvSubtitleRenderMetrics.subMarginX * pxPerScaledPixel, + ); + const horizontalAvailable = Math.max( + 0, + renderAreaWidth - leftInset - rightInset - Math.round(marginX * 2), + ); + + subtitleContainer.style.position = "absolute"; + subtitleContainer.style.maxWidth = `${horizontalAvailable}px`; + subtitleContainer.style.width = `${horizontalAvailable}px`; + subtitleContainer.style.padding = "0"; + subtitleContainer.style.background = "transparent"; + subtitleContainer.style.marginBottom = "0"; + + // Horizontal positioning based on \an alignment. + // All alignments position the container at the left margin with full available + // width and use text-align for alignment. This avoids translateX(-50%) which + // can cause subpixel rounding artifacts from GPU rasterization. + subtitleContainer.style.left = `${leftInset + marginX}px`; + subtitleContainer.style.right = ""; + subtitleContainer.style.transform = ""; + if (hAlign === 0) { + subtitleRoot.style.textAlign = "left"; + } else if (hAlign === 2) { + subtitleRoot.style.textAlign = "right"; + } else { + subtitleRoot.style.textAlign = "center"; + } + + // Vertical positioning based on \an alignment + if (vAlign === 2) { + subtitleContainer.style.top = `${topInset + marginY}px`; + subtitleContainer.style.bottom = ""; + } else if (vAlign === 1) { + subtitleContainer.style.top = "50%"; + subtitleContainer.style.bottom = ""; + subtitleContainer.style.transform = "translateY(-50%)"; + } else { + const subPosOffset = + ((100 - mpvSubtitleRenderMetrics.subPos) / 100) * renderAreaHeight; + const bottomPx = Math.max(0, bottomInset + marginY + subPosOffset); + subtitleContainer.style.top = ""; + subtitleContainer.style.bottom = `${bottomPx}px`; + } + + subtitleRoot.style.fontFamily = + assOverrides.fontFamily || mpvSubtitleRenderMetrics.subFont; + const effectiveSpacing = + typeof assOverrides.letterSpacing === "number" + ? assOverrides.letterSpacing + : mpvSubtitleRenderMetrics.subSpacing; + subtitleRoot.style.letterSpacing = + Math.abs(effectiveSpacing) > 0.0001 + ? `${effectiveSpacing * pxPerScaledPixel}px` + : "normal"; + const effectiveBold = assOverrides.bold ?? mpvSubtitleRenderMetrics.subBold; + const effectiveItalic = + assOverrides.italic ?? mpvSubtitleRenderMetrics.subItalic; + subtitleRoot.style.fontWeight = effectiveBold ? "700" : "400"; + subtitleRoot.style.fontStyle = effectiveItalic ? "italic" : "normal"; + const scaleX = assOverrides.scaleX ?? 1; + const scaleY = assOverrides.scaleY ?? 1; + if (Math.abs(scaleX - 1) > 0.0001 || Math.abs(scaleY - 1) > 0.0001) { + subtitleRoot.style.transform = `scale(${scaleX}, ${scaleY})`; + subtitleRoot.style.transformOrigin = "50% 100%"; + } else { + subtitleRoot.style.transform = ""; + subtitleRoot.style.transformOrigin = ""; + } + + // CSS line-height: normal adds "half-leading" — extra space equally distributed + // above and below text within each line box. This means the text's visual bottom + // is above the element's bottom edge by halfLeading pixels. We must compensate + // by shifting the element down by that amount so glyph positions match mpv/libass. + const computedLineHeight = parseFloat( + getComputedStyle(subtitleRoot).lineHeight, + ); + if ( + Number.isFinite(computedLineHeight) && + computedLineHeight > effectiveFontSize + ) { + const halfLeading = (computedLineHeight - effectiveFontSize) / 2; + if (vAlign === 0 && halfLeading > 0.5) { + const currentBottom = parseFloat(subtitleContainer.style.bottom); + if (Number.isFinite(currentBottom)) { + subtitleContainer.style.bottom = `${Math.max(0, currentBottom - halfLeading)}px`; + } + } else if (vAlign === 2 && halfLeading > 0.5) { + const currentTop = parseFloat(subtitleContainer.style.top); + if (Number.isFinite(currentTop)) { + subtitleContainer.style.top = `${Math.max(0, currentTop - halfLeading)}px`; + } + } + } + console.log( + "[invisible-overlay] Applied mpv subtitle render metrics from", + source, + mpvSubtitleRenderMetrics, + assOverrides, + ); +} + +function setJimakuStatus(message: string, isError = false): void { + jimakuStatus.textContent = message; + jimakuStatus.style.color = isError + ? "rgba(255, 120, 120, 0.95)" + : "rgba(255, 255, 255, 0.8)"; +} + +function resetJimakuLists(): void { + jimakuEntries = []; + jimakuFiles = []; + selectedEntryIndex = 0; + selectedFileIndex = 0; + currentEntryId = null; + jimakuEntriesList.innerHTML = ""; + jimakuFilesList.innerHTML = ""; + jimakuEntriesSection.classList.add("hidden"); + jimakuFilesSection.classList.add("hidden"); + jimakuBroadenButton.classList.add("hidden"); +} + +function openJimakuModal(): void { + if (isInvisibleLayer) return; + if (jimakuModalOpen) return; + jimakuModalOpen = true; + overlay.classList.add("interactive"); + jimakuModal.classList.remove("hidden"); + jimakuModal.setAttribute("aria-hidden", "false"); + setJimakuStatus("Loading media info..."); + resetJimakuLists(); + + window.electronAPI + .getJimakuMediaInfo() + .then((info: JimakuMediaInfo) => { + jimakuTitleInput.value = info.title || ""; + jimakuSeasonInput.value = info.season ? String(info.season) : ""; + jimakuEpisodeInput.value = info.episode ? String(info.episode) : ""; + currentEpisodeFilter = info.episode ?? null; + + if (info.confidence === "high" && info.title && info.episode) { + performJimakuSearch(); + } else if (info.title) { + setJimakuStatus("Check title/season/episode and press Search."); + } else { + setJimakuStatus("Enter title/season/episode and press Search."); + } + }) + .catch(() => { + setJimakuStatus("Failed to load media info.", true); + }); +} + +function closeJimakuModal(): void { + if (!jimakuModalOpen) return; + jimakuModalOpen = false; + jimakuModal.classList.add("hidden"); + jimakuModal.setAttribute("aria-hidden", "true"); + if ( + !isOverSubtitle && + !kikuModalOpen && + !runtimeOptionsModalOpen && + !subsyncModalOpen + ) { + overlay.classList.remove("interactive"); + } + resetJimakuLists(); +} + +function formatRuntimeOptionValue(value: RuntimeOptionValue): string { + if (typeof value === "boolean") { + return value ? "On" : "Off"; + } + return value; +} + +function setRuntimeOptionsStatus(message: string, isError = false): void { + runtimeOptionsStatus.textContent = message; + runtimeOptionsStatus.classList.toggle("error", isError); +} + +function getRuntimeOptionDisplayValue( + option: RuntimeOptionState, +): RuntimeOptionValue { + return runtimeOptionDraftValues.get(option.id) ?? option.value; +} + +function renderRuntimeOptionsList(): void { + runtimeOptionsList.innerHTML = ""; + runtimeOptions.forEach((option, index) => { + const li = document.createElement("li"); + li.className = "runtime-options-item"; + li.classList.toggle("active", index === runtimeOptionSelectedIndex); + + const label = document.createElement("div"); + label.className = "runtime-options-label"; + label.textContent = option.label; + + const value = document.createElement("div"); + value.className = "runtime-options-value"; + value.textContent = `Value: ${formatRuntimeOptionValue(getRuntimeOptionDisplayValue(option))}`; + value.title = "Click to cycle value, right-click to cycle backward"; + + const allowed = document.createElement("div"); + allowed.className = "runtime-options-allowed"; + allowed.textContent = `Allowed: ${option.allowedValues + .map((entry) => formatRuntimeOptionValue(entry)) + .join(" | ")}`; + + li.appendChild(label); + li.appendChild(value); + li.appendChild(allowed); + li.addEventListener("click", () => { + runtimeOptionSelectedIndex = index; + renderRuntimeOptionsList(); + }); + li.addEventListener("dblclick", () => { + runtimeOptionSelectedIndex = index; + void applySelectedRuntimeOption(); + }); + + value.addEventListener("click", (event) => { + event.stopPropagation(); + runtimeOptionSelectedIndex = index; + cycleRuntimeDraftValue(1); + }); + value.addEventListener("contextmenu", (event) => { + event.preventDefault(); + event.stopPropagation(); + runtimeOptionSelectedIndex = index; + cycleRuntimeDraftValue(-1); + }); + + runtimeOptionsList.appendChild(li); + }); +} + +function updateRuntimeOptions(options: RuntimeOptionState[]): void { + const previousId = + runtimeOptions[runtimeOptionSelectedIndex]?.id ?? runtimeOptions[0]?.id; + runtimeOptions = options; + + runtimeOptionDraftValues.clear(); + for (const option of runtimeOptions) { + runtimeOptionDraftValues.set(option.id, option.value); + } + + const nextIndex = runtimeOptions.findIndex( + (option) => option.id === previousId, + ); + runtimeOptionSelectedIndex = nextIndex >= 0 ? nextIndex : 0; + renderRuntimeOptionsList(); +} + +function closeRuntimeOptionsModal(): void { + if (!runtimeOptionsModalOpen) return; + runtimeOptionsModalOpen = false; + runtimeOptionsModal.classList.add("hidden"); + runtimeOptionsModal.setAttribute("aria-hidden", "true"); + window.electronAPI.notifyOverlayModalClosed("runtime-options"); + setRuntimeOptionsStatus(""); + if ( + !isOverSubtitle && + !jimakuModalOpen && + !kikuModalOpen && + !subsyncModalOpen + ) { + overlay.classList.remove("interactive"); + } +} + +async function openRuntimeOptionsModal(): Promise { + if (isInvisibleLayer) return; + const options = await window.electronAPI.getRuntimeOptions(); + updateRuntimeOptions(options); + runtimeOptionsModalOpen = true; + overlay.classList.add("interactive"); + runtimeOptionsModal.classList.remove("hidden"); + runtimeOptionsModal.setAttribute("aria-hidden", "false"); + setRuntimeOptionsStatus( + "Use arrow keys. Click value to cycle. Enter or double-click to apply.", + ); +} + +function getSelectedRuntimeOption(): RuntimeOptionState | null { + if (runtimeOptions.length === 0) return null; + if (runtimeOptionSelectedIndex < 0) return null; + if (runtimeOptionSelectedIndex >= runtimeOptions.length) return null; + return runtimeOptions[runtimeOptionSelectedIndex]; +} + +function cycleRuntimeDraftValue(direction: 1 | -1): void { + const option = getSelectedRuntimeOption(); + if (!option || option.allowedValues.length === 0) return; + const currentValue = getRuntimeOptionDisplayValue(option); + const currentIndex = option.allowedValues.findIndex( + (value) => value === currentValue, + ); + const safeIndex = currentIndex >= 0 ? currentIndex : 0; + const nextIndex = + direction === 1 + ? (safeIndex + 1) % option.allowedValues.length + : (safeIndex - 1 + option.allowedValues.length) % + option.allowedValues.length; + runtimeOptionDraftValues.set(option.id, option.allowedValues[nextIndex]); + renderRuntimeOptionsList(); + setRuntimeOptionsStatus( + `Selected ${option.label}: ${formatRuntimeOptionValue(option.allowedValues[nextIndex])}`, + ); +} + +async function applySelectedRuntimeOption(): Promise { + const option = getSelectedRuntimeOption(); + if (!option) return; + const nextValue = getRuntimeOptionDisplayValue(option); + const result: RuntimeOptionApplyResult = + await window.electronAPI.setRuntimeOptionValue(option.id, nextValue); + if (!result.ok) { + setRuntimeOptionsStatus(result.error || "Failed to apply option", true); + return; + } + + if (result.option) { + runtimeOptionDraftValues.set(result.option.id, result.option.value); + } + const latest = await window.electronAPI.getRuntimeOptions(); + updateRuntimeOptions(latest); + setRuntimeOptionsStatus(result.osdMessage || "Option applied."); +} + +function handleRuntimeOptionsKeydown(e: KeyboardEvent): boolean { + if (e.key === "Escape") { + e.preventDefault(); + closeRuntimeOptionsModal(); + return true; + } + + if ( + e.key === "ArrowDown" || + e.key === "j" || + e.key === "J" || + (e.ctrlKey && (e.key === "n" || e.key === "N")) + ) { + e.preventDefault(); + if (runtimeOptions.length > 0) { + runtimeOptionSelectedIndex = Math.min( + runtimeOptions.length - 1, + runtimeOptionSelectedIndex + 1, + ); + renderRuntimeOptionsList(); + } + return true; + } + + if ( + e.key === "ArrowUp" || + e.key === "k" || + e.key === "K" || + (e.ctrlKey && (e.key === "p" || e.key === "P")) + ) { + e.preventDefault(); + if (runtimeOptions.length > 0) { + runtimeOptionSelectedIndex = Math.max(0, runtimeOptionSelectedIndex - 1); + renderRuntimeOptionsList(); + } + return true; + } + + if (e.key === "ArrowRight" || e.key === "l" || e.key === "L") { + e.preventDefault(); + cycleRuntimeDraftValue(1); + return true; + } + + if (e.key === "ArrowLeft" || e.key === "h" || e.key === "H") { + e.preventDefault(); + cycleRuntimeDraftValue(-1); + return true; + } + + if (e.key === "Enter") { + e.preventDefault(); + void applySelectedRuntimeOption(); + return true; + } + + return true; +} + +function setSubsyncStatus(message: string, isError = false): void { + subsyncStatus.textContent = message; + subsyncStatus.classList.toggle("error", isError); +} + +function updateSubsyncSourceVisibility(): void { + const useAlass = subsyncEngineAlass.checked; + subsyncSourceLabel.classList.toggle("hidden", !useAlass); +} + +function renderSubsyncSourceTracks(): void { + subsyncSourceSelect.innerHTML = ""; + for (const track of subsyncSourceTracks) { + const option = document.createElement("option"); + option.value = String(track.id); + option.textContent = track.label; + subsyncSourceSelect.appendChild(option); + } + subsyncSourceSelect.disabled = subsyncSourceTracks.length === 0; +} + +function closeSubsyncModal(): void { + if (!subsyncModalOpen) return; + subsyncModalOpen = false; + subsyncModal.classList.add("hidden"); + subsyncModal.setAttribute("aria-hidden", "true"); + window.electronAPI.notifyOverlayModalClosed("subsync"); + if ( + !isOverSubtitle && + !jimakuModalOpen && + !kikuModalOpen && + !runtimeOptionsModalOpen + ) { + overlay.classList.remove("interactive"); + } +} + +function openSubsyncModal(payload: SubsyncManualPayload): void { + if (isInvisibleLayer) return; + subsyncSubmitting = false; + subsyncRunButton.disabled = false; + subsyncSourceTracks = payload.sourceTracks; + const hasSources = subsyncSourceTracks.length > 0; + subsyncEngineAlass.checked = hasSources; + subsyncEngineFfsubsync.checked = !hasSources; + renderSubsyncSourceTracks(); + updateSubsyncSourceVisibility(); + setSubsyncStatus( + hasSources + ? "Choose engine and source, then run." + : "No source subtitles available for alass. Use ffsubsync.", + false, + ); + subsyncModalOpen = true; + overlay.classList.add("interactive"); + subsyncModal.classList.remove("hidden"); + subsyncModal.setAttribute("aria-hidden", "false"); +} + +async function runSubsyncManualFromModal(): Promise { + if (subsyncSubmitting) return; + const engine = subsyncEngineAlass.checked ? "alass" : "ffsubsync"; + const sourceTrackId = + engine === "alass" && subsyncSourceSelect.value + ? Number.parseInt(subsyncSourceSelect.value, 10) + : null; + + if (engine === "alass" && !Number.isFinite(sourceTrackId)) { + setSubsyncStatus("Select a source subtitle track for alass.", true); + return; + } + + subsyncSubmitting = true; + subsyncRunButton.disabled = true; + closeSubsyncModal(); + try { + await window.electronAPI.runSubsyncManual({ + engine, + sourceTrackId, + }); + } finally { + subsyncSubmitting = false; + subsyncRunButton.disabled = false; + } +} + +function handleSubsyncKeydown(e: KeyboardEvent): boolean { + if (e.key === "Escape") { + e.preventDefault(); + closeSubsyncModal(); + return true; + } + if (e.key === "Enter") { + e.preventDefault(); + void runSubsyncManualFromModal(); + return true; + } + return true; +} + +function formatMediaMeta(card: KikuDuplicateCardInfo): string { + const parts: string[] = []; + parts.push(card.hasAudio ? "Audio: Yes" : "Audio: No"); + parts.push(card.hasImage ? "Image: Yes" : "Image: No"); + return parts.join(" | "); +} + +function updateKikuCardSelection(): void { + kikuCard1.classList.toggle("active", kikuSelectedCard === 1); + kikuCard2.classList.toggle("active", kikuSelectedCard === 2); +} + +function setKikuModalStep(step: KikuModalStep): void { + kikuModalStep = step; + const isSelect = step === "select"; + kikuSelectionStep.classList.toggle("hidden", !isSelect); + kikuPreviewStep.classList.toggle("hidden", isSelect); + kikuHint.textContent = isSelect + ? "Press 1 or 2 to select · Enter to continue · Esc to cancel" + : "Enter to confirm merge · Backspace to go back · Esc to cancel"; +} + +function updateKikuPreviewToggle(): void { + kikuPreviewCompactButton.classList.toggle( + "active", + kikuPreviewMode === "compact", + ); + kikuPreviewFullButton.classList.toggle("active", kikuPreviewMode === "full"); +} + +function renderKikuPreview(): void { + const payload = + kikuPreviewMode === "compact" + ? kikuPreviewCompactData + : kikuPreviewFullData; + kikuPreviewJson.textContent = payload + ? JSON.stringify(payload, null, 2) + : "{}"; + updateKikuPreviewToggle(); +} + +function setKikuPreviewError(message: string | null): void { + if (!message) { + kikuPreviewError.textContent = ""; + kikuPreviewError.classList.add("hidden"); + return; + } + kikuPreviewError.textContent = message; + kikuPreviewError.classList.remove("hidden"); +} + +function openKikuFieldGroupingModal(data: { + original: KikuDuplicateCardInfo; + duplicate: KikuDuplicateCardInfo; +}): void { + if (isInvisibleLayer) return; + if (kikuModalOpen) return; + kikuModalOpen = true; + kikuOriginalData = data.original; + kikuDuplicateData = data.duplicate; + kikuSelectedCard = 1; + + kikuCard1Expression.textContent = data.original.expression; + kikuCard1Sentence.textContent = + data.original.sentencePreview || "(no sentence)"; + kikuCard1Meta.textContent = formatMediaMeta(data.original); + + kikuCard2Expression.textContent = data.duplicate.expression; + kikuCard2Sentence.textContent = + data.duplicate.sentencePreview || "(current subtitle)"; + kikuCard2Meta.textContent = formatMediaMeta(data.duplicate); + kikuDeleteDuplicateCheckbox.checked = true; + kikuPendingChoice = null; + kikuPreviewCompactData = null; + kikuPreviewFullData = null; + kikuPreviewMode = "compact"; + renderKikuPreview(); + setKikuPreviewError(null); + setKikuModalStep("select"); + + updateKikuCardSelection(); + + overlay.classList.add("interactive"); + kikuModal.classList.remove("hidden"); + kikuModal.setAttribute("aria-hidden", "false"); +} + +function closeKikuFieldGroupingModal(): void { + if (!kikuModalOpen) return; + kikuModalOpen = false; + kikuModal.classList.add("hidden"); + kikuModal.setAttribute("aria-hidden", "true"); + setKikuPreviewError(null); + kikuPreviewJson.textContent = ""; + kikuPendingChoice = null; + kikuPreviewCompactData = null; + kikuPreviewFullData = null; + kikuPreviewMode = "compact"; + setKikuModalStep("select"); + kikuOriginalData = null; + kikuDuplicateData = null; + if ( + !isOverSubtitle && + !jimakuModalOpen && + !runtimeOptionsModalOpen && + !subsyncModalOpen + ) { + overlay.classList.remove("interactive"); + } +} + +async function confirmKikuSelection(): Promise { + if (!kikuOriginalData || !kikuDuplicateData) return; + + const keepData = + kikuSelectedCard === 1 ? kikuOriginalData : kikuDuplicateData; + const deleteData = + kikuSelectedCard === 1 ? kikuDuplicateData : kikuOriginalData; + + const choice: KikuFieldGroupingChoice = { + keepNoteId: keepData.noteId, + deleteNoteId: deleteData.noteId, + deleteDuplicate: kikuDeleteDuplicateCheckbox.checked, + cancelled: false, + }; + kikuPendingChoice = choice; + setKikuPreviewError(null); + kikuConfirmButton.disabled = true; + + try { + const preview: KikuMergePreviewResponse = + await window.electronAPI.kikuBuildMergePreview({ + keepNoteId: choice.keepNoteId, + deleteNoteId: choice.deleteNoteId, + deleteDuplicate: choice.deleteDuplicate, + }); + + if (!preview.ok) { + setKikuPreviewError(preview.error || "Failed to build merge preview"); + return; + } + + kikuPreviewCompactData = preview.compact || {}; + kikuPreviewFullData = preview.full || {}; + kikuPreviewMode = "compact"; + renderKikuPreview(); + setKikuModalStep("preview"); + } finally { + kikuConfirmButton.disabled = false; + } +} + +function confirmKikuMerge(): void { + if (!kikuPendingChoice) return; + window.electronAPI.kikuFieldGroupingRespond(kikuPendingChoice); + closeKikuFieldGroupingModal(); +} + +function goBackFromKikuPreview(): void { + setKikuPreviewError(null); + setKikuModalStep("select"); +} + +function cancelKikuFieldGrouping(): void { + const choice: KikuFieldGroupingChoice = { + keepNoteId: 0, + deleteNoteId: 0, + deleteDuplicate: true, + cancelled: true, + }; + + window.electronAPI.kikuFieldGroupingRespond(choice); + closeKikuFieldGroupingModal(); +} + +function handleKikuKeydown(e: KeyboardEvent): boolean { + if (kikuModalStep === "preview") { + if (e.key === "Escape") { + e.preventDefault(); + cancelKikuFieldGrouping(); + return true; + } + + if (e.key === "Backspace") { + e.preventDefault(); + goBackFromKikuPreview(); + return true; + } + + if (e.key === "Enter") { + e.preventDefault(); + confirmKikuMerge(); + return true; + } + + return true; + } + + if (e.key === "Escape") { + e.preventDefault(); + cancelKikuFieldGrouping(); + return true; + } + + if (e.key === "1") { + e.preventDefault(); + kikuSelectedCard = 1; + updateKikuCardSelection(); + return true; + } + + if (e.key === "2") { + e.preventDefault(); + kikuSelectedCard = 2; + updateKikuCardSelection(); + return true; + } + + if (e.key === "ArrowLeft" || e.key === "ArrowRight") { + e.preventDefault(); + kikuSelectedCard = kikuSelectedCard === 1 ? 2 : 1; + updateKikuCardSelection(); + return true; + } + + if (e.key === "Enter") { + e.preventDefault(); + void confirmKikuSelection(); + return true; + } + + return true; +} + +function formatEntryLabel(entry: JimakuEntry): string { + if (entry.english_name && entry.english_name !== entry.name) { + return `${entry.name} / ${entry.english_name}`; + } + return entry.name; +} + +function renderEntries(): void { + jimakuEntriesList.innerHTML = ""; + if (jimakuEntries.length === 0) { + jimakuEntriesSection.classList.add("hidden"); + return; + } + jimakuEntriesSection.classList.remove("hidden"); + jimakuEntries.forEach((entry, index) => { + const li = document.createElement("li"); + li.textContent = formatEntryLabel(entry); + if (entry.japanese_name) { + const sub = document.createElement("div"); + sub.className = "jimaku-subtext"; + sub.textContent = entry.japanese_name; + li.appendChild(sub); + } + if (index === selectedEntryIndex) { + li.classList.add("active"); + } + li.addEventListener("click", () => { + selectEntry(index); + }); + jimakuEntriesList.appendChild(li); + }); +} + +function formatBytes(size: number): string { + if (!Number.isFinite(size)) return ""; + const units = ["B", "KB", "MB", "GB"]; + let value = size; + let idx = 0; + while (value >= 1024 && idx < units.length - 1) { + value /= 1024; + idx += 1; + } + return `${value.toFixed(value >= 10 || idx === 0 ? 0 : 1)} ${units[idx]}`; +} + +function renderFiles(): void { + jimakuFilesList.innerHTML = ""; + if (jimakuFiles.length === 0) { + jimakuFilesSection.classList.add("hidden"); + return; + } + jimakuFilesSection.classList.remove("hidden"); + jimakuFiles.forEach((file, index) => { + const li = document.createElement("li"); + li.textContent = file.name; + const sub = document.createElement("div"); + sub.className = "jimaku-subtext"; + sub.textContent = `${formatBytes(file.size)} • ${file.last_modified}`; + li.appendChild(sub); + if (index === selectedFileIndex) { + li.classList.add("active"); + } + li.addEventListener("click", () => { + selectFile(index); + }); + jimakuFilesList.appendChild(li); + }); +} + +function getSearchQuery(): { query: string; episode: number | null } { + const title = jimakuTitleInput.value.trim(); + const episode = jimakuEpisodeInput.value + ? Number.parseInt(jimakuEpisodeInput.value, 10) + : null; + const query = title; + return { query, episode: Number.isFinite(episode) ? episode : null }; +} + +async function performJimakuSearch(): Promise { + const { query, episode } = getSearchQuery(); + if (!query) { + setJimakuStatus("Enter a title before searching.", true); + return; + } + resetJimakuLists(); + setJimakuStatus("Searching Jimaku..."); + currentEpisodeFilter = episode; + + const response: JimakuApiResponse = + await window.electronAPI.jimakuSearchEntries({ query }); + if (!response.ok) { + const retry = response.error.retryAfter + ? ` Retry after ${response.error.retryAfter.toFixed(1)}s.` + : ""; + setJimakuStatus(`${response.error.error}${retry}`, true); + return; + } + + jimakuEntries = response.data; + selectedEntryIndex = 0; + if (jimakuEntries.length === 0) { + setJimakuStatus("No entries found."); + return; + } + setJimakuStatus("Select an entry."); + renderEntries(); + if (jimakuEntries.length === 1) { + selectEntry(0); + } +} + +async function loadFiles( + entryId: number, + episode: number | null, +): Promise { + setJimakuStatus("Loading files..."); + jimakuFiles = []; + selectedFileIndex = 0; + jimakuFilesList.innerHTML = ""; + jimakuFilesSection.classList.add("hidden"); + + const response: JimakuApiResponse = + await window.electronAPI.jimakuListFiles({ + entryId, + episode, + }); + if (!response.ok) { + const retry = response.error.retryAfter + ? ` Retry after ${response.error.retryAfter.toFixed(1)}s.` + : ""; + setJimakuStatus(`${response.error.error}${retry}`, true); + return; + } + + jimakuFiles = response.data; + if (jimakuFiles.length === 0) { + if (episode !== null) { + setJimakuStatus("No files found for this episode."); + jimakuBroadenButton.classList.remove("hidden"); + } else { + setJimakuStatus("No files found."); + } + return; + } + + jimakuBroadenButton.classList.add("hidden"); + setJimakuStatus("Select a subtitle file."); + renderFiles(); + if (jimakuFiles.length === 1) { + selectFile(0); + } +} + +function selectEntry(index: number): void { + if (index < 0 || index >= jimakuEntries.length) return; + selectedEntryIndex = index; + currentEntryId = jimakuEntries[index].id; + renderEntries(); + if (currentEntryId !== null) { + loadFiles(currentEntryId, currentEpisodeFilter); + } +} + +async function selectFile(index: number): Promise { + if (index < 0 || index >= jimakuFiles.length) return; + selectedFileIndex = index; + renderFiles(); + if (currentEntryId === null) { + setJimakuStatus("Select an entry first.", true); + return; + } + + const file = jimakuFiles[index]; + setJimakuStatus("Downloading subtitle..."); + const result: JimakuDownloadResult = + await window.electronAPI.jimakuDownloadFile({ + entryId: currentEntryId, + url: file.url, + name: file.name, + }); + + if (result.ok) { + setJimakuStatus(`Downloaded and loaded: ${result.path}`); + } else { + const retry = result.error.retryAfter + ? ` Retry after ${result.error.retryAfter.toFixed(1)}s.` + : ""; + setJimakuStatus(`${result.error.error}${retry}`, true); + } +} + +function isTextInputFocused(): boolean { + const active = document.activeElement; + if (!active) return false; + const tag = active.tagName.toLowerCase(); + return tag === "input" || tag === "textarea"; +} + +function handleJimakuKeydown(e: KeyboardEvent): boolean { + if (e.key === "Escape") { + e.preventDefault(); + closeJimakuModal(); + return true; + } + + if (isTextInputFocused()) { + if (e.key === "Enter") { + e.preventDefault(); + performJimakuSearch(); + return true; + } + return true; + } + + if (e.key === "ArrowDown") { + e.preventDefault(); + if (jimakuFiles.length > 0) { + selectedFileIndex = Math.min( + jimakuFiles.length - 1, + selectedFileIndex + 1, + ); + renderFiles(); + } else if (jimakuEntries.length > 0) { + selectedEntryIndex = Math.min( + jimakuEntries.length - 1, + selectedEntryIndex + 1, + ); + renderEntries(); + } + return true; + } + + if (e.key === "ArrowUp") { + e.preventDefault(); + if (jimakuFiles.length > 0) { + selectedFileIndex = Math.max(0, selectedFileIndex - 1); + renderFiles(); + } else if (jimakuEntries.length > 0) { + selectedEntryIndex = Math.max(0, selectedEntryIndex - 1); + renderEntries(); + } + return true; + } + + if (e.key === "Enter") { + e.preventDefault(); + if (jimakuFiles.length > 0) { + selectFile(selectedFileIndex); + } else if (jimakuEntries.length > 0) { + selectEntry(selectedEntryIndex); + } else { + performJimakuSearch(); + } + return true; + } + + return true; +} + +function setupDragging(): void { + subtitleContainer.addEventListener("mousedown", (e: MouseEvent) => { + if (e.button === 2) { + e.preventDefault(); + isDragging = true; + dragStartY = e.clientY; + startYPercent = getCurrentYPercent(); + subtitleContainer.style.cursor = "grabbing"; + } + }); + + document.addEventListener("mousemove", (e: MouseEvent) => { + if (!isDragging) return; + + const deltaY = dragStartY - e.clientY; + const deltaPercent = (deltaY / window.innerHeight) * 100; + const newYPercent = startYPercent + deltaPercent; + + applyYPercent(newYPercent); + }); + + document.addEventListener("mouseup", (e: MouseEvent) => { + if (isDragging && e.button === 2) { + isDragging = false; + subtitleContainer.style.cursor = ""; + + const yPercent = getCurrentYPercent(); + window.electronAPI.saveSubtitlePosition({ yPercent }); + } + }); + + subtitleContainer.addEventListener("contextmenu", (e: Event) => { + e.preventDefault(); + }); +} + +function isInteractiveTarget(target: EventTarget | null): boolean { + if (!(target instanceof Element)) return false; + if (target.closest(".modal")) return true; + if (subtitleContainer.contains(target)) return true; + if ( + target.tagName === "IFRAME" && + target.id && + target.id.startsWith("yomitan-popup") + ) + return true; + if (target.closest && target.closest('iframe[id^="yomitan-popup"]')) + return true; + return false; +} + +function keyEventToString(e: KeyboardEvent): string { + const parts: string[] = []; + if (e.ctrlKey) parts.push("Ctrl"); + if (e.altKey) parts.push("Alt"); + if (e.shiftKey) parts.push("Shift"); + if (e.metaKey) parts.push("Meta"); + parts.push(e.code); + return parts.join("+"); +} + +let keybindingsMap = new Map(); + +type ChordAction = + | { type: "mpv"; command: string[] } + | { type: "electron"; action: () => void } + | { type: "noop" }; + +const CHORD_MAP = new Map([ + ["KeyS", { type: "mpv", command: ["script-message", "subminer-start"] }], + ["Shift+KeyS", { type: "mpv", command: ["script-message", "subminer-stop"] }], + ["KeyT", { type: "mpv", command: ["script-message", "subminer-toggle"] }], + [ + "KeyI", + { type: "mpv", command: ["script-message", "subminer-toggle-invisible"] }, + ], + [ + "Shift+KeyI", + { type: "mpv", command: ["script-message", "subminer-show-invisible"] }, + ], + [ + "KeyU", + { type: "mpv", command: ["script-message", "subminer-hide-invisible"] }, + ], + ["KeyO", { type: "mpv", command: ["script-message", "subminer-options"] }], + ["KeyR", { type: "mpv", command: ["script-message", "subminer-restart"] }], + ["KeyC", { type: "mpv", command: ["script-message", "subminer-status"] }], + ["KeyY", { type: "mpv", command: ["script-message", "subminer-menu"] }], + ["KeyJ", { type: "electron", action: () => openJimakuModal() }], + [ + "KeyD", + { type: "electron", action: () => window.electronAPI.toggleDevTools() }, + ], +]); + +let chordPending = false; +let chordTimeout: ReturnType | null = null; + +function resetChord(): void { + chordPending = false; + if (chordTimeout !== null) { + clearTimeout(chordTimeout); + chordTimeout = null; + } +} + +async function setupMpvInputForwarding(): Promise { + const keybindings: Keybinding[] = await window.electronAPI.getKeybindings(); + keybindingsMap = new Map(); + for (const binding of keybindings) { + if (binding.command) { + keybindingsMap.set(binding.key, binding.command); + } + } + + document.addEventListener("keydown", (e: KeyboardEvent) => { + const yomitanPopup = document.querySelector('iframe[id^="yomitan-popup"]'); + if (yomitanPopup) return; + + if (runtimeOptionsModalOpen) { + handleRuntimeOptionsKeydown(e); + return; + } + + if (subsyncModalOpen) { + handleSubsyncKeydown(e); + return; + } + + if (kikuModalOpen) { + handleKikuKeydown(e); + return; + } + + if (jimakuModalOpen) { + handleJimakuKeydown(e); + return; + } + + if (chordPending) { + const modifierKeys = [ + "ShiftLeft", + "ShiftRight", + "ControlLeft", + "ControlRight", + "AltLeft", + "AltRight", + "MetaLeft", + "MetaRight", + ]; + if (modifierKeys.includes(e.code)) { + return; + } + + e.preventDefault(); + const secondKey = keyEventToString(e); + const action = CHORD_MAP.get(secondKey); + resetChord(); + if (action) { + if (action.type === "mpv") { + window.electronAPI.sendMpvCommand(action.command); + } else if (action.type === "electron") { + action.action(); + } + } + return; + } + + if ( + e.code === "KeyY" && + !e.ctrlKey && + !e.altKey && + !e.shiftKey && + !e.metaKey && + !e.repeat + ) { + e.preventDefault(); + chordPending = true; + chordTimeout = setTimeout(() => { + resetChord(); + }, 1000); + return; + } + + const keyString = keyEventToString(e); + const command = keybindingsMap.get(keyString); + + if (command) { + e.preventDefault(); + window.electronAPI.sendMpvCommand(command); + } + }); + + document.addEventListener("mousedown", (e: MouseEvent) => { + if (e.button === 2 && !isInteractiveTarget(e.target)) { + e.preventDefault(); + window.electronAPI.sendMpvCommand(["cycle", "pause"]); + } + }); + + document.addEventListener("contextmenu", (e: Event) => { + if (!isInteractiveTarget(e.target)) { + e.preventDefault(); + } + }); +} + +function setupResizeHandler(): void { + window.addEventListener("resize", () => { + if (isInvisibleLayer) { + applyInvisibleSubtitleLayoutFromMpvMetrics( + mpvSubtitleRenderMetrics, + "resize", + ); + return; + } + applyYPercent(getCurrentYPercent()); + }); +} + +async function restoreSubtitlePosition(): Promise { + const position = await window.electronAPI.getSubtitlePosition(); + applyStoredSubtitlePosition(position, "startup"); +} + +async function restoreSubtitleFontSize(): Promise { + const style = await window.electronAPI.getSubtitleStyle(); + if (style && style.fontSize !== undefined) { + applySubtitleFontSize(style.fontSize); + console.log("Applied subtitle font size:", style.fontSize); + } +} + +function setupSelectionObserver(): void { + document.addEventListener("selectionchange", () => { + const selection = window.getSelection(); + const hasSelection = + selection && selection.rangeCount > 0 && !selection.isCollapsed; + + if (hasSelection) { + subtitleRoot.classList.add("has-selection"); + } else { + subtitleRoot.classList.remove("has-selection"); + } + }); +} + +function setupYomitanObserver(): void { + const observer = new MutationObserver((mutations: MutationRecord[]) => { + for (const mutation of mutations) { + mutation.addedNodes.forEach((node) => { + if (node.nodeType === Node.ELEMENT_NODE) { + const element = node as Element; + if ( + element.tagName === "IFRAME" && + element.id && + element.id.startsWith("yomitan-popup") + ) { + overlay.classList.add("interactive"); + if (shouldToggleMouseIgnore) { + window.electronAPI.setIgnoreMouseEvents(false); + } + } + } + }); + mutation.removedNodes.forEach((node) => { + if (node.nodeType === Node.ELEMENT_NODE) { + const element = node as Element; + if ( + element.tagName === "IFRAME" && + element.id && + element.id.startsWith("yomitan-popup") + ) { + if ( + !isOverSubtitle && + !jimakuModalOpen && + !kikuModalOpen && + !runtimeOptionsModalOpen && + !subsyncModalOpen + ) { + overlay.classList.remove("interactive"); + if (shouldToggleMouseIgnore) { + window.electronAPI.setIgnoreMouseEvents(true, { + forward: true, + }); + } + } + } + } + }); + } + }); + + observer.observe(document.body, { + childList: true, + subtree: true, + }); +} + +function renderSecondarySub(text: string): void { + secondarySubRoot.innerHTML = ""; + if (!text) return; + + let normalized = text + .replace(/\\N/g, "\n") + .replace(/\\n/g, "\n") + .replace(/\{[^}]*\}/g, "") + .trim(); + + if (!normalized) return; + + const lines = normalized.split("\n"); + for (let i = 0; i < lines.length; i++) { + if (lines[i]) { + const textNode = document.createTextNode(lines[i]); + secondarySubRoot.appendChild(textNode); + } + if (i < lines.length - 1) { + secondarySubRoot.appendChild(document.createElement("br")); + } + } +} + +function updateSecondarySubMode(mode: SecondarySubMode): void { + secondarySubContainer.classList.remove( + "secondary-sub-hidden", + "secondary-sub-visible", + "secondary-sub-hover", + ); + secondarySubContainer.classList.add(`secondary-sub-${mode}`); +} + +async function applySubtitleStyle(): Promise { + const style = await window.electronAPI.getSubtitleStyle(); + if (!style) return; + + if (style.fontFamily) { + subtitleRoot.style.fontFamily = style.fontFamily; + } + if (style.fontSize) { + subtitleRoot.style.fontSize = `${style.fontSize}px`; + } + if (style.fontColor) { + subtitleRoot.style.color = style.fontColor; + } + if (style.fontWeight) { + subtitleRoot.style.fontWeight = style.fontWeight; + } + if (style.fontStyle) { + subtitleRoot.style.fontStyle = style.fontStyle; + } + if (style.backgroundColor) { + subtitleContainer.style.background = style.backgroundColor; + } + + const sec = style.secondary; + if (sec) { + if (sec.fontFamily) { + secondarySubRoot.style.fontFamily = sec.fontFamily; + } + if (sec.fontSize) { + secondarySubRoot.style.fontSize = `${sec.fontSize}px`; + } + if (sec.fontColor) { + secondarySubRoot.style.color = sec.fontColor; + } + if (sec.fontWeight) { + secondarySubRoot.style.fontWeight = sec.fontWeight; + } + if (sec.fontStyle) { + secondarySubRoot.style.fontStyle = sec.fontStyle; + } + if (sec.backgroundColor) { + secondarySubContainer.style.background = sec.backgroundColor; + } + } +} + +async function init(): Promise { + document.body.classList.add(`layer-${overlayLayer}`); + + window.electronAPI.onSubtitle((data: SubtitleData) => { + renderSubtitle(data); + }); + + if (isInvisibleLayer) { + window.electronAPI.onSubtitleAss((assText: string) => { + currentSubtitleAss = assText || ""; + applyInvisibleSubtitleLayoutFromMpvMetrics( + mpvSubtitleRenderMetrics, + "subtitle-ass", + ); + }); + } + + if (!isInvisibleLayer) { + window.electronAPI.onSubtitlePosition( + (position: SubtitlePosition | null) => { + applyStoredSubtitlePosition(position, "media-change"); + }, + ); + } + + if (isInvisibleLayer) { + window.electronAPI.onMpvSubtitleRenderMetrics( + (metrics: MpvSubtitleRenderMetrics) => { + applyInvisibleSubtitleLayoutFromMpvMetrics(metrics, "event"); + }, + ); + window.electronAPI.onOverlayDebugVisualization((enabled: boolean) => { + document.body.classList.toggle("debug-invisible-visualization", enabled); + }); + } + + if (isInvisibleLayer) { + currentSubtitleAss = await window.electronAPI.getCurrentSubtitleAss(); + } + const initialSubtitle = await window.electronAPI.getCurrentSubtitle(); + renderSubtitle(initialSubtitle); + + window.electronAPI.onSecondarySub((text: string) => { + renderSecondarySub(text); + }); + + window.electronAPI.onSecondarySubMode((mode: SecondarySubMode) => { + updateSecondarySubMode(mode); + }); + + const initialMode = await window.electronAPI.getSecondarySubMode(); + updateSecondarySubMode(initialMode); + + const initialSecondary = await window.electronAPI.getCurrentSecondarySub(); + renderSecondarySub(initialSecondary); + + subtitleContainer.addEventListener("mouseenter", handleMouseEnter); + subtitleContainer.addEventListener("mouseleave", handleMouseLeave); + + secondarySubContainer.addEventListener("mouseenter", handleMouseEnter); + secondarySubContainer.addEventListener("mouseleave", handleMouseLeave); + + jimakuSearchButton.addEventListener("click", () => { + performJimakuSearch(); + }); + + jimakuCloseButton.addEventListener("click", () => { + closeJimakuModal(); + }); + + jimakuBroadenButton.addEventListener("click", () => { + if (currentEntryId !== null) { + jimakuBroadenButton.classList.add("hidden"); + loadFiles(currentEntryId, null); + } + }); + + kikuCard1.addEventListener("click", () => { + kikuSelectedCard = 1; + updateKikuCardSelection(); + }); + + kikuCard1.addEventListener("dblclick", () => { + kikuSelectedCard = 1; + void confirmKikuSelection(); + }); + + kikuCard2.addEventListener("click", () => { + kikuSelectedCard = 2; + updateKikuCardSelection(); + }); + + kikuCard2.addEventListener("dblclick", () => { + kikuSelectedCard = 2; + void confirmKikuSelection(); + }); + + kikuConfirmButton.addEventListener("click", () => { + void confirmKikuSelection(); + }); + + kikuCancelButton.addEventListener("click", () => { + cancelKikuFieldGrouping(); + }); + + kikuBackButton.addEventListener("click", () => { + goBackFromKikuPreview(); + }); + + kikuFinalConfirmButton.addEventListener("click", () => { + confirmKikuMerge(); + }); + + kikuFinalCancelButton.addEventListener("click", () => { + cancelKikuFieldGrouping(); + }); + + kikuPreviewCompactButton.addEventListener("click", () => { + kikuPreviewMode = "compact"; + renderKikuPreview(); + }); + + kikuPreviewFullButton.addEventListener("click", () => { + kikuPreviewMode = "full"; + renderKikuPreview(); + }); + + runtimeOptionsClose.addEventListener("click", () => { + closeRuntimeOptionsModal(); + }); + subsyncCloseButton.addEventListener("click", () => { + closeSubsyncModal(); + }); + subsyncEngineAlass.addEventListener("change", () => { + updateSubsyncSourceVisibility(); + }); + subsyncEngineFfsubsync.addEventListener("change", () => { + updateSubsyncSourceVisibility(); + }); + subsyncRunButton.addEventListener("click", () => { + void runSubsyncManualFromModal(); + }); + + window.electronAPI.onRuntimeOptionsChanged( + (options: RuntimeOptionState[]) => { + updateRuntimeOptions(options); + }, + ); + + window.electronAPI.onOpenRuntimeOptions(() => { + openRuntimeOptionsModal().catch(() => { + setRuntimeOptionsStatus("Failed to load runtime options", true); + window.electronAPI.notifyOverlayModalClosed("runtime-options"); + }); + }); + window.electronAPI.onSubsyncManualOpen((payload: SubsyncManualPayload) => { + openSubsyncModal(payload); + }); + + window.electronAPI.onKikuFieldGroupingRequest( + (data: { + original: KikuDuplicateCardInfo; + duplicate: KikuDuplicateCardInfo; + }) => { + openKikuFieldGroupingModal(data); + }, + ); + + if (!isInvisibleLayer) { + setupDragging(); + } + + await setupMpvInputForwarding(); + + setupResizeHandler(); + + if (isInvisibleLayer) { + const metrics = await window.electronAPI.getMpvSubtitleRenderMetrics(); + applyInvisibleSubtitleLayoutFromMpvMetrics(metrics, "startup"); + } else { + await restoreSubtitlePosition(); + await restoreSubtitleFontSize(); + await applySubtitleStyle(); + } + + setupYomitanObserver(); + + setupSelectionObserver(); + if (shouldToggleMouseIgnore) { + window.electronAPI.setIgnoreMouseEvents(true, { forward: true }); + } +} + +if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", init); +} else { + init(); +} diff --git a/src/renderer/style.css b/src/renderer/style.css new file mode 100644 index 0000000..b9885e8 --- /dev/null +++ b/src/renderer/style.css @@ -0,0 +1,703 @@ +/* + * SubMiner - All-in-one sentence mining overlay + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +html, +body { + width: 100%; + height: 100%; + overflow: hidden; + background: transparent; + font-family: + "Noto Sans CJK JP Regular", "Noto Sans CJK JP", "Arial Unicode MS", Arial, + sans-serif; +} + +#overlay { + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + justify-content: flex-end; + align-items: center; + pointer-events: none; +} + +#overlay.interactive { + pointer-events: auto; +} + +.modal { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + background: rgba(0, 0, 0, 0.55); + pointer-events: auto; + z-index: 1000; +} + +.modal.hidden { + display: none; +} + +.hidden { + display: none !important; +} + +.modal-content { + width: min(720px, 92%); + max-height: 80%; + background: rgba(20, 20, 20, 0.95); + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 12px; + padding: 16px; + color: #fff; + display: flex; + flex-direction: column; + gap: 12px; +} + +.modal-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.modal-title { + font-size: 18px; + font-weight: 600; +} + +.modal-close { + background: rgba(255, 255, 255, 0.1); + color: #fff; + border: 1px solid rgba(255, 255, 255, 0.2); + border-radius: 6px; + padding: 6px 10px; + cursor: pointer; +} + +.modal-close:hover { + background: rgba(255, 255, 255, 0.2); +} + +.modal-body { + display: flex; + flex-direction: column; + gap: 12px; + overflow: hidden; +} + +.jimaku-form { + display: grid; + grid-template-columns: 1fr 120px 120px auto; + gap: 10px; + align-items: end; +} + +.jimaku-field { + display: flex; + flex-direction: column; + gap: 6px; + font-size: 12px; + color: rgba(255, 255, 255, 0.7); +} + +.jimaku-field input { + background: rgba(0, 0, 0, 0.5); + border: 1px solid rgba(255, 255, 255, 0.15); + border-radius: 6px; + color: #fff; + padding: 6px 8px; +} + +.jimaku-button { + height: 36px; + padding: 0 14px; + border-radius: 6px; + border: 1px solid rgba(255, 255, 255, 0.25); + background: rgba(255, 255, 255, 0.15); + color: #fff; + cursor: pointer; +} + +.jimaku-button:hover { + background: rgba(255, 255, 255, 0.25); +} + +.jimaku-status { + min-height: 20px; + font-size: 13px; + color: rgba(255, 255, 255, 0.8); +} + +.jimaku-section { + display: flex; + flex-direction: column; + gap: 6px; + max-height: 220px; + overflow: hidden; +} + +.jimaku-section.hidden { + display: none; +} + +.jimaku-section-title { + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.08em; + color: rgba(255, 255, 255, 0.6); +} + +.jimaku-list { + list-style: none; + padding: 0; + margin: 0; + overflow-y: auto; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 8px; + max-height: 180px; +} + +.jimaku-list li { + padding: 8px 10px; + border-bottom: 1px solid rgba(255, 255, 255, 0.05); + cursor: pointer; + display: flex; + flex-direction: column; + gap: 2px; +} + +.jimaku-list li:last-child { + border-bottom: none; +} + +.jimaku-list li.active { + background: rgba(255, 255, 255, 0.15); +} + +.jimaku-list .jimaku-subtext { + font-size: 12px; + color: rgba(255, 255, 255, 0.6); +} + +.jimaku-link { + align-self: flex-start; + background: transparent; + color: rgba(255, 255, 255, 0.8); + border: none; + padding: 0; + cursor: pointer; + text-decoration: underline; +} + +.jimaku-link.hidden { + display: none; +} + +@media (max-width: 640px) { + .jimaku-form { + grid-template-columns: 1fr 1fr; + } + + .jimaku-button { + grid-column: span 2; + } +} + +#subtitleContainer { + max-width: 80%; + margin-bottom: 60px; + padding: 12px 20px; + background: rgba(54, 58, 79, 0.5); + border-radius: 8px; + pointer-events: auto; +} + +#subtitleRoot { + text-align: center; + font-size: 35px; + line-height: 1.5; + color: #cad3f5; + text-shadow: + 2px 2px 4px rgba(0, 0, 0, 0.8), + -1px -1px 2px rgba(0, 0, 0, 0.5); + /* Enable text selection for Yomitan */ + user-select: text; + cursor: text; +} + +#subtitleRoot:empty { + display: none; +} + +#subtitleContainer:has(#subtitleRoot:empty) { + display: none; +} + +#subtitleRoot .c { + display: inline; + position: relative; +} + +#subtitleRoot .c:hover { + background: rgba(255, 255, 255, 0.15); + border-radius: 2px; +} + +#subtitleRoot .word { + display: inline; + position: relative; +} + +#subtitleRoot .word:hover { + background: rgba(255, 255, 255, 0.2); + border-radius: 3px; +} + +#subtitleRoot br { + display: block; + content: ""; + margin-bottom: 0.3em; +} + +#subtitleRoot.has-selection .word:hover, +#subtitleRoot.has-selection .c:hover { + background: transparent; +} + +body.layer-invisible #subtitleContainer { + background: transparent !important; + border: 0 !important; + padding: 0 !important; + border-radius: 0 !important; +} + +body.layer-invisible #subtitleRoot, +body.layer-invisible #subtitleRoot .word, +body.layer-invisible #subtitleRoot .c { + color: transparent !important; + text-shadow: none !important; + -webkit-text-stroke: 0 !important; + -webkit-text-fill-color: transparent !important; + background: transparent !important; + caret-color: transparent !important; + line-height: normal !important; + font-kerning: auto; + letter-spacing: normal; + font-variant-ligatures: normal; + font-feature-settings: normal; + text-rendering: auto; +} + +body.layer-invisible #subtitleRoot br { + margin-bottom: 0 !important; +} + +body.layer-invisible #subtitleRoot .word:hover, +body.layer-invisible #subtitleRoot .c:hover, +body.layer-invisible #subtitleRoot.has-selection .word:hover, +body.layer-invisible #subtitleRoot.has-selection .c:hover { + background: transparent !important; +} + +body.layer-invisible #subtitleRoot::selection, +body.layer-invisible #subtitleRoot .word::selection, +body.layer-invisible #subtitleRoot .c::selection { + background: transparent !important; + color: transparent !important; +} + +body.layer-invisible.debug-invisible-visualization #subtitleRoot, +body.layer-invisible.debug-invisible-visualization #subtitleRoot .word, +body.layer-invisible.debug-invisible-visualization #subtitleRoot .c { + color: #ed8796 !important; + -webkit-text-fill-color: #ed8796 !important; + -webkit-text-stroke: 0.55px rgba(0, 0, 0, 0.95) !important; + text-shadow: + 0 0 8px rgba(237, 135, 150, 0.9), + 0 2px 6px rgba(0, 0, 0, 0.95) !important; +} + +#secondarySubContainer { + position: absolute; + top: 40px; + left: 50%; + transform: translateX(-50%); + max-width: 80%; + padding: 10px 18px; + background: transparent; + border-radius: 8px; + pointer-events: auto; +} + +#secondarySubRoot { + text-align: center; + font-size: 24px; + line-height: 1.5; + color: #ffffff; + -webkit-text-stroke: 0.45px rgba(0, 0, 0, 0.7); + paint-order: stroke fill; + text-shadow: + 0 2px 4px rgba(0, 0, 0, 0.95), + 0 0 8px rgba(0, 0, 0, 0.8), + 0 0 16px rgba(0, 0, 0, 0.55); + user-select: text; + cursor: text; +} + +#secondarySubRoot:empty { + display: none; +} + +#secondarySubContainer:has(#secondarySubRoot:empty) { + display: none; +} + +.secondary-sub-hidden { + display: none !important; +} + +#secondarySubContainer.secondary-sub-hover { + opacity: 0; + transition: opacity 0.2s ease; + pointer-events: auto; + top: 0; + left: 0; + right: 0; + transform: none; + max-width: 100%; + background: transparent; + padding: 40px 0 0 0; + border-radius: 0; + display: flex; + justify-content: center; +} + +#secondarySubContainer.secondary-sub-hover #secondarySubRoot { + background: transparent; + border-radius: 8px; + padding: 10px 18px; +} + +#secondarySubContainer.secondary-sub-hover:hover { + opacity: 1; +} + +iframe[id^="yomitan-popup"] { + pointer-events: auto !important; + z-index: 2147483647 !important; +} + +.kiku-info-text { + font-size: 14px; + color: rgba(255, 255, 255, 0.8); + line-height: 1.5; +} + +.kiku-cards-container { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} + +.kiku-card { + background: rgba(40, 40, 40, 0.8); + border: 2px solid rgba(255, 255, 255, 0.1); + border-radius: 10px; + padding: 14px; + display: flex; + flex-direction: column; + gap: 8px; + cursor: pointer; + transition: border-color 0.15s; + outline: none; +} + +.kiku-card:hover { + border-color: rgba(255, 255, 255, 0.3); +} + +.kiku-card.active { + border-color: rgba(100, 180, 255, 0.8); + background: rgba(40, 60, 90, 0.5); +} + +.kiku-card-label { + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.08em; + color: rgba(255, 255, 255, 0.5); + font-weight: 600; +} + +.kiku-card.active .kiku-card-label { + color: rgba(100, 180, 255, 0.9); +} + +.kiku-card-expression { + font-size: 22px; + font-weight: 600; + color: #fff; +} + +.kiku-card-sentence { + font-size: 14px; + color: rgba(255, 255, 255, 0.75); + max-height: 52px; + overflow: hidden; + text-overflow: ellipsis; + line-height: 1.4; +} + +.kiku-card-meta { + font-size: 12px; + color: rgba(255, 255, 255, 0.45); + display: flex; + gap: 10px; +} + +.kiku-footer { + display: flex; + flex-wrap: wrap; + justify-content: center; + align-items: center; + gap: 10px; + padding-top: 8px; + border-top: 1px solid rgba(255, 255, 255, 0.08); +} + +.kiku-preview-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 10px; +} + +.kiku-preview-title { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.88); +} + +.kiku-preview-toggle { + display: inline-flex; + gap: 6px; +} + +.kiku-preview-toggle button { + padding: 5px 10px; + border-radius: 5px; + border: 1px solid rgba(255, 255, 255, 0.15); + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.7); + cursor: pointer; + font-size: 12px; +} + +.kiku-preview-toggle button.active { + border-color: rgba(100, 180, 255, 0.45); + background: rgba(100, 180, 255, 0.16); + color: rgba(100, 180, 255, 0.95); +} + +.kiku-preview-json { + margin: 0; + min-height: 220px; + max-height: 320px; + overflow: auto; + white-space: pre-wrap; + word-break: break-word; + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 8px; + background: rgba(0, 0, 0, 0.34); + padding: 10px; + font-size: 11px; + line-height: 1.45; + color: rgba(255, 255, 255, 0.88); +} + +.kiku-preview-error { + margin: 0 0 10px; + font-size: 12px; + color: #ff8f8f; +} + +.kiku-delete-toggle { + display: inline-flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: rgba(255, 255, 255, 0.8); + user-select: none; +} + +.kiku-delete-toggle input { + accent-color: rgba(100, 180, 255, 0.9); +} + +.kiku-confirm-button { + padding: 8px 20px; + border-radius: 6px; + border: 1px solid rgba(100, 180, 255, 0.4); + background: rgba(100, 180, 255, 0.15); + color: rgba(100, 180, 255, 0.95); + font-weight: 600; + cursor: pointer; +} + +.kiku-confirm-button:hover { + background: rgba(100, 180, 255, 0.25); +} + +.subsync-modal-content { + width: min(560px, 92%); +} + +.subsync-form { + display: flex; + flex-direction: column; + gap: 10px; +} + +.subsync-field { + display: flex; + flex-direction: column; + gap: 6px; + font-size: 13px; + color: rgba(255, 255, 255, 0.85); +} + +.subsync-radio { + display: inline-flex; + align-items: center; + gap: 8px; + margin-right: 14px; + font-size: 13px; + color: rgba(255, 255, 255, 0.8); +} + +.subsync-field select { + background: rgba(0, 0, 0, 0.5); + border: 1px solid rgba(255, 255, 255, 0.15); + border-radius: 6px; + color: #fff; + padding: 8px 10px; +} + +.subsync-footer { + display: flex; + justify-content: flex-end; +} + +.kiku-cancel-button { + padding: 8px 16px; + border-radius: 6px; + border: 1px solid rgba(255, 255, 255, 0.15); + background: transparent; + color: rgba(255, 255, 255, 0.6); + cursor: pointer; +} + +.kiku-cancel-button:hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; +} + +.kiku-hint { + text-align: center; + font-size: 11px; + color: rgba(255, 255, 255, 0.35); +} + +.runtime-modal-content { + width: min(560px, 92%); +} + +.runtime-options-hint { + font-size: 12px; + color: rgba(255, 255, 255, 0.65); +} + +.runtime-options-list { + list-style: none; + margin: 0; + padding: 0; + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 8px; + max-height: 320px; + overflow-y: auto; +} + +.runtime-options-item { + display: flex; + flex-direction: column; + gap: 4px; + padding: 10px 12px; + border-bottom: 1px solid rgba(255, 255, 255, 0.08); + cursor: pointer; +} + +.runtime-options-item:last-child { + border-bottom: none; +} + +.runtime-options-item.active { + background: rgba(100, 180, 255, 0.15); +} + +.runtime-options-label { + font-size: 14px; + color: #fff; +} + +.runtime-options-value { + font-size: 13px; + color: rgba(100, 180, 255, 0.9); +} + +.runtime-options-allowed { + font-size: 11px; + color: rgba(255, 255, 255, 0.55); +} + +.runtime-options-status { + min-height: 18px; + font-size: 12px; + color: rgba(255, 255, 255, 0.75); +} + +.runtime-options-status.error { + color: #ff8f8f; +} + +@media (max-width: 640px) { + .kiku-cards-container { + grid-template-columns: 1fr; + } +} diff --git a/src/runtime-options.ts b/src/runtime-options.ts new file mode 100644 index 0000000..88a3e1b --- /dev/null +++ b/src/runtime-options.ts @@ -0,0 +1,208 @@ +/* + * SubMiner - All-in-one sentence mining overlay + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +import { + AnkiConnectConfig, + RuntimeOptionApplyResult, + RuntimeOptionId, + RuntimeOptionState, + RuntimeOptionValue, +} from "./types"; +import { RUNTIME_OPTION_REGISTRY, RuntimeOptionRegistryEntry } from "./config"; + +type RuntimeOverrides = Record; + +function deepClone(value: T): T { + return JSON.parse(JSON.stringify(value)) as T; +} + +function getPathValue(source: Record, path: string): unknown { + const parts = path.split("."); + let current: unknown = source; + for (const part of parts) { + if (!current || typeof current !== "object" || Array.isArray(current)) { + return undefined; + } + current = (current as Record)[part]; + } + return current; +} + +function setPathValue(target: Record, path: string, value: unknown): void { + const parts = path.split("."); + let current = target; + for (let i = 0; i < parts.length; i += 1) { + const part = parts[i]; + const isLeaf = i === parts.length - 1; + if (isLeaf) { + current[part] = value; + return; + } + + const next = current[part]; + if (!next || typeof next !== "object" || Array.isArray(next)) { + current[part] = {}; + } + current = current[part] as Record; + } +} + +function allowedValues(definition: RuntimeOptionRegistryEntry): RuntimeOptionValue[] { + return [...definition.allowedValues]; +} + +function isAllowedValue( + definition: RuntimeOptionRegistryEntry, + value: RuntimeOptionValue, +): boolean { + if (definition.valueType === "boolean") { + return typeof value === "boolean"; + } + return typeof value === "string" && definition.allowedValues.includes(value); +} + +export class RuntimeOptionsManager { + private readonly getAnkiConfig: () => AnkiConnectConfig; + private readonly applyAnkiPatch: (patch: Partial) => void; + private readonly onOptionsChanged: (options: RuntimeOptionState[]) => void; + private runtimeOverrides: RuntimeOverrides = {}; + private readonly definitions = new Map(); + + constructor( + getAnkiConfig: () => AnkiConnectConfig, + callbacks: { + applyAnkiPatch: (patch: Partial) => void; + onOptionsChanged: (options: RuntimeOptionState[]) => void; + }, + ) { + this.getAnkiConfig = getAnkiConfig; + this.applyAnkiPatch = callbacks.applyAnkiPatch; + this.onOptionsChanged = callbacks.onOptionsChanged; + for (const definition of RUNTIME_OPTION_REGISTRY) { + this.definitions.set(definition.id, definition); + } + } + + private getEffectiveValue(definition: RuntimeOptionRegistryEntry): RuntimeOptionValue { + const override = getPathValue(this.runtimeOverrides, definition.path); + if (override !== undefined) return override as RuntimeOptionValue; + + const source = { + ankiConnect: this.getAnkiConfig(), + } as Record; + + const raw = getPathValue(source, definition.path); + if (raw === undefined || raw === null) { + return definition.defaultValue; + } + return raw as RuntimeOptionValue; + } + + listOptions(): RuntimeOptionState[] { + const options: RuntimeOptionState[] = []; + for (const definition of RUNTIME_OPTION_REGISTRY) { + options.push({ + id: definition.id, + label: definition.label, + scope: definition.scope, + valueType: definition.valueType, + value: this.getEffectiveValue(definition), + allowedValues: allowedValues(definition), + requiresRestart: definition.requiresRestart, + }); + } + return options; + } + + getOptionValue(id: RuntimeOptionId): RuntimeOptionValue | undefined { + const definition = this.definitions.get(id); + if (!definition) return undefined; + return this.getEffectiveValue(definition); + } + + setOptionValue(id: RuntimeOptionId, value: RuntimeOptionValue): RuntimeOptionApplyResult { + const definition = this.definitions.get(id); + if (!definition) { + return { ok: false, error: `Unknown runtime option: ${id}` }; + } + + if (!isAllowedValue(definition, value)) { + return { + ok: false, + error: `Invalid value for ${id}: ${String(value)}`, + }; + } + + const next = deepClone(this.runtimeOverrides); + setPathValue(next, definition.path, value); + this.runtimeOverrides = next; + + const ankiPatch = definition.toAnkiPatch(value); + this.applyAnkiPatch(ankiPatch); + + const option = this.listOptions().find((item) => item.id === id); + if (!option) { + return { ok: false, error: `Failed to apply option: ${id}` }; + } + + const osdMessage = `Runtime option: ${definition.label} -> ${definition.formatValueForOsd(option.value)}`; + this.onOptionsChanged(this.listOptions()); + return { + ok: true, + option, + osdMessage, + requiresRestart: definition.requiresRestart, + }; + } + + cycleOption(id: RuntimeOptionId, direction: 1 | -1): RuntimeOptionApplyResult { + const definition = this.definitions.get(id); + if (!definition) { + return { ok: false, error: `Unknown runtime option: ${id}` }; + } + + const values = allowedValues(definition); + if (values.length === 0) { + return { ok: false, error: `Option ${id} has no allowed values` }; + } + + const currentValue = this.getEffectiveValue(definition); + const currentIndex = values.findIndex((value) => value === currentValue); + const safeIndex = currentIndex >= 0 ? currentIndex : 0; + const nextIndex = + direction === 1 + ? (safeIndex + 1) % values.length + : (safeIndex - 1 + values.length) % values.length; + return this.setOptionValue(id, values[nextIndex]); + } + + getEffectiveAnkiConnectConfig(baseConfig?: AnkiConnectConfig): AnkiConnectConfig { + const source = baseConfig ?? this.getAnkiConfig(); + const effective: AnkiConnectConfig = deepClone(source); + + for (const definition of RUNTIME_OPTION_REGISTRY) { + const override = getPathValue(this.runtimeOverrides, definition.path); + if (override === undefined) continue; + + const subPath = definition.path.replace(/^ankiConnect\./, ""); + setPathValue(effective as unknown as Record, subPath, override); + } + + return effective; + } +} diff --git a/src/subtitle-timing-tracker.ts b/src/subtitle-timing-tracker.ts new file mode 100644 index 0000000..da15d06 --- /dev/null +++ b/src/subtitle-timing-tracker.ts @@ -0,0 +1,215 @@ +/* + * SubMiner - Subtitle mining overlay for mpv + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +interface TimingEntry { + startTime: number; + endTime: number; + timestamp: number; +} + +interface HistoryEntry { + displayText: string; + timingKey: string; + startTime: number; + endTime: number; + timestamp: number; +} + +export class SubtitleTimingTracker { + private timings = new Map(); + private history: HistoryEntry[] = []; + private readonly maxHistory = 200; + private readonly ttlMs = 5 * 60 * 1000; + private cleanupInterval: ReturnType | null = null; + + constructor() { + this.startCleanup(); + } + + recordSubtitle(text: string, startTime: number, endTime: number): void { + const normalizedText = this.normalizeText(text); + if (!normalizedText) return; + + const displayText = this.prepareDisplayText(text); + const timingKey = normalizedText; + + this.timings.set(timingKey, { + startTime, + endTime, + timestamp: Date.now(), + }); + + // Check for duplicate of most recent entry (deduplicate adjacent repeats) + const lastEntry = this.history[this.history.length - 1]; + if (lastEntry && lastEntry.timingKey === timingKey) { + // Update timing to most recent occurrence + lastEntry.startTime = startTime; + lastEntry.endTime = endTime; + lastEntry.timestamp = Date.now(); + return; + } + + this.history.push({ + displayText, + timingKey, + startTime, + endTime, + timestamp: Date.now(), + }); + + // Prune history if too large + if (this.history.length > this.maxHistory) { + this.history = this.history.slice(-this.maxHistory); + } + } + + findTiming(text: string): { startTime: number; endTime: number } | null { + const normalizedText = this.normalizeText(text); + if (!normalizedText) return null; + + const entry = this.timings.get(normalizedText); + if (!entry) { + return this.findFuzzyMatch(normalizedText); + } + + return { + startTime: entry.startTime, + endTime: entry.endTime, + }; + } + + /** + * Get recent subtitle blocks in chronological order. + * Returns the last `count` subtitle events (oldest → newest). + * Blocks preserve internal line breaks and are joined with blank lines. + */ + getRecentBlocks(count: number): string[] { + if (count <= 0) return []; + if (count > this.history.length) { + count = this.history.length; + } + return this.history.slice(-count).map((entry) => entry.displayText); + } + + /** + * Get display text for the most recent subtitle. + */ + getCurrentSubtitle(): string | null { + const lastEntry = this.history[this.history.length - 1]; + return lastEntry ? lastEntry.displayText : null; + } + + private findFuzzyMatch( + text: string, + ): { startTime: number; endTime: number } | null { + let bestMatch: TimingEntry | null = null; + let bestScore = 0; + + for (const [key, entry] of this.timings.entries()) { + const score = this.calculateSimilarity(text, key); + if (score > bestScore && score > 0.7) { + bestScore = score; + bestMatch = entry; + } + } + + if (bestMatch) { + return { + startTime: bestMatch.startTime, + endTime: bestMatch.endTime, + }; + } + + return null; + } + + private calculateSimilarity(a: string, b: string): number { + const longer = a.length > b.length ? a : b; + const shorter = a.length > b.length ? b : a; + + if (longer.length === 0) return 1; + + const editDistance = this.getEditDistance(longer, shorter); + return (longer.length - editDistance) / longer.length; + } + + private getEditDistance(longer: string, shorter: string): number { + const costs: number[] = []; + for (let i = 0; i <= shorter.length; i++) { + let lastValue = i; + for (let j = 1; j <= longer.length; j++) { + let newValue = costs[j - 1] || 0; + if (longer.charAt(j - 1) !== shorter.charAt(i - 1)) { + newValue = Math.min(Math.min(newValue, lastValue), costs[j] || 0) + 1; + } + costs[j - 1] = lastValue; + lastValue = newValue; + } + costs[shorter.length] = lastValue; + } + return costs[shorter.length] || 0; + } + + private normalizeText(text: string): string { + return text + .replace(/\\N/g, " ") + .replace(/\\n/g, " ") + .replace(/\n/g, " ") + .replace(/{[^}]*}/g, "") + .replace(/\s+/g, " ") + .trim(); + } + + private prepareDisplayText(text: string): string { + // Convert ASS/SSA newlines to real newlines, strip tags + return text + .replace(/\\N/g, "\n") + .replace(/\\n/g, "\n") + .replace(/{[^}]*}/g, "") + .trim(); + } + + private startCleanup(): void { + this.cleanupInterval = setInterval(() => { + this.cleanup(); + }, 60000); + } + + cleanup(): void { + const now = Date.now(); + // Clean up old timing entries + for (const [key, entry] of this.timings.entries()) { + if (now - entry.timestamp > this.ttlMs) { + this.timings.delete(key); + } + } + // Clean up old history entries + this.history = this.history.filter( + (entry) => now - entry.timestamp <= this.ttlMs, + ); + } + + destroy(): void { + if (this.cleanupInterval) { + clearInterval(this.cleanupInterval); + this.cleanupInterval = null; + } + this.timings.clear(); + this.history = []; + } +} diff --git a/src/token-merger.ts b/src/token-merger.ts new file mode 100644 index 0000000..9c38be9 --- /dev/null +++ b/src/token-merger.ts @@ -0,0 +1,233 @@ +/* + * SubMiner - All-in-one sentence mining overlay + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +import { PartOfSpeech, Token, MergedToken } from "./types"; + +export function isNoun(tok: Token): boolean { + return tok.partOfSpeech === PartOfSpeech.noun; +} + +export function isProperNoun(tok: Token): boolean { + return tok.partOfSpeech === PartOfSpeech.noun && tok.pos2 === "固有名詞"; +} + +export function ignoreReading(tok: Token): boolean { + return tok.partOfSpeech === PartOfSpeech.symbol && tok.pos2 === "文字"; +} + +export function isCopula(tok: Token): boolean { + const raw = tok.inflectionType; + if (!raw) { + return false; + } + return ["特殊・ダ", "特殊・デス", "特殊|だ", "特殊|デス"].includes(raw); +} + +export function isAuxVerb(tok: Token): boolean { + return tok.partOfSpeech === PartOfSpeech.bound_auxiliary && !isCopula(tok); +} + +export function isContinuativeForm(tok: Token): boolean { + if (!tok.inflectionForm) { + return false; + } + const inflectionForm = tok.inflectionForm; + const isContinuative = + inflectionForm === "連用デ接続" || + inflectionForm === "連用タ接続" || + inflectionForm.startsWith("連用形"); + + if (!isContinuative) { + return false; + } + return tok.headword !== "ない"; +} + +export function isVerbSuffix(tok: Token): boolean { + return ( + tok.partOfSpeech === PartOfSpeech.verb && + (tok.pos2 === "非自立" || tok.pos2 === "接尾") + ); +} + +export function isTatteParticle(tok: Token): boolean { + return ( + tok.partOfSpeech === PartOfSpeech.particle && + tok.pos2 === "接続助詞" && + tok.headword === "たって" + ); +} + +export function isBaParticle(tok: Token): boolean { + return ( + tok.partOfSpeech === PartOfSpeech.particle && + tok.pos2 === "接続助詞" && + tok.word === "ば" + ); +} + +export function isTeDeParticle(tok: Token): boolean { + return ( + tok.partOfSpeech === PartOfSpeech.particle && + tok.pos2 === "接続助詞" && + ["て", "で", "ちゃ"].includes(tok.word) + ); +} + +export function isTaDaParticle(tok: Token): boolean { + return isAuxVerb(tok) && ["た", "だ"].includes(tok.word); +} + +export function isVerb(tok: Token): boolean { + return [PartOfSpeech.verb, PartOfSpeech.bound_auxiliary].includes( + tok.partOfSpeech, + ); +} + +export function isVerbNonIndependent(): boolean { + return true; +} + +export function canReceiveAuxiliary(tok: Token): boolean { + return [ + PartOfSpeech.verb, + PartOfSpeech.bound_auxiliary, + PartOfSpeech.i_adjective, + ].includes(tok.partOfSpeech); +} + +export function isNounSuffix(tok: Token): boolean { + return tok.partOfSpeech === PartOfSpeech.verb && tok.pos2 === "接尾"; +} + +export function isCounter(tok: Token): boolean { + return ( + tok.partOfSpeech === PartOfSpeech.noun && + tok.pos3 !== undefined && + tok.pos3.startsWith("助数詞") + ); +} + +export function isNumeral(tok: Token): boolean { + return ( + tok.partOfSpeech === PartOfSpeech.noun && + tok.pos2 !== undefined && + tok.pos2.startsWith("数") + ); +} + +export function shouldMerge(lastStandaloneToken: Token, token: Token): boolean { + if (isVerb(lastStandaloneToken)) { + if (isAuxVerb(token)) { + return true; + } + if (isContinuativeForm(lastStandaloneToken) && isVerbSuffix(token)) { + return true; + } + if (isVerbSuffix(token) && isVerbNonIndependent()) { + return true; + } + } + + if ( + isNoun(lastStandaloneToken) && + !isProperNoun(lastStandaloneToken) && + isNounSuffix(token) + ) { + return true; + } + + if (isCounter(token) && isNumeral(lastStandaloneToken)) { + return true; + } + + if (isBaParticle(token) && canReceiveAuxiliary(lastStandaloneToken)) { + return true; + } + + if (isTatteParticle(token) && canReceiveAuxiliary(lastStandaloneToken)) { + return true; + } + + if (isTeDeParticle(token) && isContinuativeForm(lastStandaloneToken)) { + return true; + } + + if (isTaDaParticle(token) && canReceiveAuxiliary(lastStandaloneToken)) { + return true; + } + + if (isTeDeParticle(lastStandaloneToken) && isVerbSuffix(token)) { + return true; + } + + return false; +} + +export function mergeTokens(tokens: Token[]): MergedToken[] { + if (!tokens || tokens.length === 0) { + return []; + } + + const result: MergedToken[] = []; + let charOffset = 0; + let lastStandaloneToken: Token | null = null; + + for (const token of tokens) { + const start = charOffset; + const end = charOffset + token.word.length; + charOffset = end; + + let shouldMergeToken = false; + + if (result.length > 0 && lastStandaloneToken !== null) { + shouldMergeToken = shouldMerge(lastStandaloneToken, token); + } + + const tokenReading = ignoreReading(token) + ? "" + : token.katakanaReading || token.word; + + if (shouldMergeToken && result.length > 0) { + const prev = result.pop()!; + result.push({ + surface: prev.surface + token.word, + reading: prev.reading + tokenReading, + headword: prev.headword, + startPos: prev.startPos, + endPos: end, + partOfSpeech: prev.partOfSpeech, + isMerged: true, + }); + } else { + result.push({ + surface: token.word, + reading: tokenReading, + headword: token.headword, + startPos: start, + endPos: end, + partOfSpeech: token.partOfSpeech, + isMerged: false, + }); + } + + lastStandaloneToken = token; + } + + return result; +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..77f58f0 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,616 @@ +/* + * SubMiner - All-in-one sentence mining overlay + * Copyright (C) 2024 sudacode + * + * 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 . + */ + +export enum PartOfSpeech { + noun = "noun", + verb = "verb", + i_adjective = "i_adjective", + na_adjective = "na_adjective", + particle = "particle", + bound_auxiliary = "bound_auxiliary", + symbol = "symbol", + other = "other", +} + +export interface Token { + word: string; + partOfSpeech: PartOfSpeech; + pos1: string; + pos2: string; + pos3: string; + pos4: string; + inflectionType: string; + inflectionForm: string; + headword: string; + katakanaReading: string; + pronunciation: string; +} + +export interface MergedToken { + surface: string; + reading: string; + headword: string; + startPos: number; + endPos: number; + partOfSpeech: PartOfSpeech; + isMerged: boolean; +} + +export interface WindowGeometry { + x: number; + y: number; + width: number; + height: number; +} + +export interface SubtitlePosition { + yPercent: number; +} + +export interface SubtitleStyle { + fontSize: number; +} + +export interface Keybinding { + key: string; + command: (string | number)[] | null; +} + +export type SecondarySubMode = "hidden" | "visible" | "hover"; + +export interface SecondarySubConfig { + secondarySubLanguages?: string[]; + autoLoadSecondarySub?: boolean; + defaultMode?: SecondarySubMode; +} + +export type SubsyncMode = "auto" | "manual"; + +export interface SubsyncConfig { + defaultMode?: SubsyncMode; + alass_path?: string; + ffsubsync_path?: string; + ffmpeg_path?: string; +} + +export interface WebSocketConfig { + enabled?: boolean | "auto"; + port?: number; +} + +export interface TexthookerConfig { + openBrowser?: boolean; +} + +export interface NotificationOptions { + body?: string; + icon?: string; +} + +export interface MpvClient { + currentSubText: string; + currentVideoPath: string; + currentTimePos: number; + currentSubStart: number; + currentSubEnd: number; + currentAudioStreamIndex: number | null; + send(command: { command: unknown[]; request_id?: number }): boolean; +} + +export interface KikuDuplicateCardInfo { + noteId: number; + expression: string; + sentencePreview: string; + hasAudio: boolean; + hasImage: boolean; + isOriginal: boolean; +} + +export interface KikuFieldGroupingRequestData { + original: KikuDuplicateCardInfo; + duplicate: KikuDuplicateCardInfo; +} + +export interface KikuFieldGroupingChoice { + keepNoteId: number; + deleteNoteId: number; + deleteDuplicate: boolean; + cancelled: boolean; +} + +export interface KikuMergePreviewRequest { + keepNoteId: number; + deleteNoteId: number; + deleteDuplicate: boolean; +} + +export interface KikuMergePreviewResponse { + ok: boolean; + compact?: Record; + full?: Record; + error?: string; +} + +export type RuntimeOptionId = + | "anki.autoUpdateNewCards" + | "anki.kikuFieldGrouping"; + +export type RuntimeOptionScope = "ankiConnect"; + +export type RuntimeOptionValueType = "boolean" | "enum"; + +export type RuntimeOptionValue = boolean | string; + +export interface RuntimeOptionState { + id: RuntimeOptionId; + label: string; + scope: RuntimeOptionScope; + valueType: RuntimeOptionValueType; + value: RuntimeOptionValue; + allowedValues: RuntimeOptionValue[]; + requiresRestart: boolean; +} + +export interface RuntimeOptionApplyResult { + ok: boolean; + option?: RuntimeOptionState; + osdMessage?: string; + requiresRestart?: boolean; + error?: string; +} + +export interface AnkiConnectConfig { + enabled?: boolean; + url?: string; + pollingRate?: number; + fields?: { + audio?: string; + image?: string; + sentence?: string; + miscInfo?: string; + translation?: string; + }; + ai?: { + enabled?: boolean; + alwaysUseAiTranslation?: boolean; + apiKey?: string; + model?: string; + baseUrl?: string; + targetLanguage?: string; + systemPrompt?: string; + }; + openRouter?: { + enabled?: boolean; + alwaysUseAiTranslation?: boolean; + apiKey?: string; + model?: string; + baseUrl?: string; + targetLanguage?: string; + systemPrompt?: string; + }; + media?: { + generateAudio?: boolean; + generateImage?: boolean; + imageType?: "static" | "avif"; + imageFormat?: "jpg" | "png" | "webp"; + imageQuality?: number; + imageMaxWidth?: number; + imageMaxHeight?: number; + animatedFps?: number; + animatedMaxWidth?: number; + animatedMaxHeight?: number; + animatedCrf?: number; + audioPadding?: number; + fallbackDuration?: number; + maxMediaDuration?: number; + }; + behavior?: { + overwriteAudio?: boolean; + overwriteImage?: boolean; + mediaInsertMode?: "append" | "prepend"; + highlightWord?: boolean; + notificationType?: "osd" | "system" | "both" | "none"; + autoUpdateNewCards?: boolean; + }; + metadata?: { + pattern?: string; + }; + deck?: string; + isLapis?: { + enabled?: boolean; + sentenceCardModel?: string; + sentenceCardSentenceField?: string; + sentenceCardAudioField?: string; + }; + isKiku?: { + enabled?: boolean; + fieldGrouping?: "auto" | "manual" | "disabled"; + deleteDuplicateInAuto?: boolean; + }; +} + +export interface SubtitleStyleConfig { + fontFamily?: string; + fontSize?: number; + fontColor?: string; + fontWeight?: string; + fontStyle?: string; + backgroundColor?: string; + secondary?: { + fontFamily?: string; + fontSize?: number; + fontColor?: string; + fontWeight?: string; + fontStyle?: string; + backgroundColor?: string; + }; +} + +export interface ShortcutsConfig { + toggleVisibleOverlayGlobal?: string | null; + toggleInvisibleOverlayGlobal?: string | null; + copySubtitle?: string | null; + copySubtitleMultiple?: string | null; + updateLastCardFromClipboard?: string | null; + triggerFieldGrouping?: string | null; + triggerSubsync?: string | null; + mineSentence?: string | null; + mineSentenceMultiple?: string | null; + multiCopyTimeoutMs?: number; + toggleSecondarySub?: string | null; + markAudioCard?: string | null; + openRuntimeOptions?: string | null; +} + +export type JimakuLanguagePreference = "ja" | "en" | "none"; + +export interface JimakuConfig { + apiKey?: string; + apiKeyCommand?: string; + apiBaseUrl?: string; + languagePreference?: JimakuLanguagePreference; + maxEntryResults?: number; +} + +export interface InvisibleOverlayConfig { + startupVisibility?: "platform-default" | "visible" | "hidden"; +} + +export type YoutubeSubgenMode = "automatic" | "preprocess" | "off"; + +export interface YoutubeSubgenConfig { + mode?: YoutubeSubgenMode; + whisperBin?: string; + whisperModel?: string; + primarySubLanguages?: string[]; +} + +export interface Config { + subtitlePosition?: SubtitlePosition; + keybindings?: Keybinding[]; + websocket?: WebSocketConfig; + texthooker?: TexthookerConfig; + ankiConnect?: AnkiConnectConfig; + shortcuts?: ShortcutsConfig; + secondarySub?: SecondarySubConfig; + subsync?: SubsyncConfig; + subtitleStyle?: SubtitleStyleConfig; + auto_start_overlay?: boolean; + bind_visible_overlay_to_mpv_sub_visibility?: boolean; + jimaku?: JimakuConfig; + invisibleOverlay?: InvisibleOverlayConfig; + youtubeSubgen?: YoutubeSubgenConfig; +} + +export type RawConfig = Config; + +export interface ResolvedConfig { + subtitlePosition: SubtitlePosition; + keybindings: Keybinding[]; + websocket: Required; + texthooker: Required; + ankiConnect: AnkiConnectConfig & { + enabled: boolean; + url: string; + pollingRate: number; + fields: { + audio: string; + image: string; + sentence: string; + miscInfo: string; + translation: string; + }; + ai: { + enabled: boolean; + alwaysUseAiTranslation: boolean; + apiKey: string; + model: string; + baseUrl: string; + targetLanguage: string; + systemPrompt: string; + }; + media: { + generateAudio: boolean; + generateImage: boolean; + imageType: "static" | "avif"; + imageFormat: "jpg" | "png" | "webp"; + imageQuality: number; + imageMaxWidth?: number; + imageMaxHeight?: number; + animatedFps: number; + animatedMaxWidth: number; + animatedMaxHeight?: number; + animatedCrf: number; + audioPadding: number; + fallbackDuration: number; + maxMediaDuration: number; + }; + behavior: { + overwriteAudio: boolean; + overwriteImage: boolean; + mediaInsertMode: "append" | "prepend"; + highlightWord: boolean; + notificationType: "osd" | "system" | "both" | "none"; + autoUpdateNewCards: boolean; + }; + metadata: { + pattern: string; + }; + isLapis: { + enabled: boolean; + sentenceCardModel: string; + sentenceCardSentenceField: string; + sentenceCardAudioField: string; + }; + isKiku: { + enabled: boolean; + fieldGrouping: "auto" | "manual" | "disabled"; + deleteDuplicateInAuto: boolean; + }; + }; + shortcuts: Required; + secondarySub: Required; + subsync: Required; + subtitleStyle: Required> & { + secondary: Required>; + }; + auto_start_overlay: boolean; + bind_visible_overlay_to_mpv_sub_visibility: boolean; + jimaku: JimakuConfig & { + apiBaseUrl: string; + languagePreference: JimakuLanguagePreference; + maxEntryResults: number; + }; + invisibleOverlay: Required; + youtubeSubgen: YoutubeSubgenConfig & { + mode: YoutubeSubgenMode; + whisperBin: string; + whisperModel: string; + primarySubLanguages: string[]; + }; +} + +export interface ConfigValidationWarning { + path: string; + value: unknown; + fallback: unknown; + message: string; +} + +export interface SubsyncSourceTrack { + id: number; + label: string; +} + +export interface SubsyncManualPayload { + sourceTracks: SubsyncSourceTrack[]; +} + +export interface SubsyncManualRunRequest { + engine: "alass" | "ffsubsync"; + sourceTrackId?: number | null; +} + +export interface SubsyncResult { + ok: boolean; + message: string; +} + +export interface SubtitleData { + text: string; + tokens: MergedToken[] | null; +} + +export interface MpvSubtitleRenderMetrics { + subPos: number; + subFontSize: number; + subScale: number; + subMarginY: number; + subMarginX: number; + subFont: string; + subSpacing: number; + subBold: boolean; + subItalic: boolean; + subBorderSize: number; + subShadowOffset: number; + subAssOverride: string; + subScaleByWindow: boolean; + subUseMargins: boolean; + osdHeight: number; + osdDimensions: { + w: number; + h: number; + ml: number; + mr: number; + mt: number; + mb: number; + } | null; +} + +export interface MecabStatus { + available: boolean; + enabled: boolean; + path: string | null; +} + +export type JimakuConfidence = "high" | "medium" | "low"; + +export interface JimakuMediaInfo { + title: string; + season: number | null; + episode: number | null; + confidence: JimakuConfidence; + filename: string; + rawTitle: string; +} + +export interface JimakuSearchQuery { + query: string; +} + +export interface JimakuEntryFlags { + anime?: boolean; + movie?: boolean; + adult?: boolean; + external?: boolean; + unverified?: boolean; +} + +export interface JimakuEntry { + id: number; + name: string; + english_name?: string | null; + japanese_name?: string | null; + flags?: JimakuEntryFlags; + last_modified?: string; +} + +export interface JimakuFilesQuery { + entryId: number; + episode?: number | null; +} + +export interface JimakuFileEntry { + name: string; + url: string; + size: number; + last_modified: string; +} + +export interface JimakuDownloadQuery { + entryId: number; + url: string; + name: string; +} + +export interface JimakuApiError { + error: string; + code?: number; + retryAfter?: number; +} + +export type JimakuApiResponse = + | { ok: true; data: T } + | { ok: false; error: JimakuApiError }; + +export type JimakuDownloadResult = + | { ok: true; path: string } + | { ok: false; error: JimakuApiError }; + +export interface ElectronAPI { + getOverlayLayer: () => "visible" | "invisible" | null; + onSubtitle: (callback: (data: SubtitleData) => void) => void; + onVisibility: (callback: (visible: boolean) => void) => void; + onSubtitlePosition: ( + callback: (position: SubtitlePosition | null) => void, + ) => void; + getOverlayVisibility: () => Promise; + getCurrentSubtitle: () => Promise; + getCurrentSubtitleAss: () => Promise; + getMpvSubtitleRenderMetrics: () => Promise; + onMpvSubtitleRenderMetrics: ( + callback: (metrics: MpvSubtitleRenderMetrics) => void, + ) => void; + onSubtitleAss: (callback: (assText: string) => void) => void; + onOverlayDebugVisualization: (callback: (enabled: boolean) => void) => void; + setIgnoreMouseEvents: ( + ignore: boolean, + options?: { forward?: boolean }, + ) => void; + openYomitanSettings: () => void; + getSubtitlePosition: () => Promise; + saveSubtitlePosition: (position: SubtitlePosition) => void; + getMecabStatus: () => Promise; + setMecabEnabled: (enabled: boolean) => void; + sendMpvCommand: (command: (string | number)[]) => void; + getKeybindings: () => Promise; + getJimakuMediaInfo: () => Promise; + jimakuSearchEntries: ( + query: JimakuSearchQuery, + ) => Promise>; + jimakuListFiles: ( + query: JimakuFilesQuery, + ) => Promise>; + jimakuDownloadFile: ( + query: JimakuDownloadQuery, + ) => Promise; + quitApp: () => void; + toggleDevTools: () => void; + toggleOverlay: () => void; + getAnkiConnectStatus: () => Promise; + setAnkiConnectEnabled: (enabled: boolean) => void; + clearAnkiConnectHistory: () => void; + onSecondarySub: (callback: (text: string) => void) => void; + onSecondarySubMode: (callback: (mode: SecondarySubMode) => void) => void; + getSecondarySubMode: () => Promise; + getCurrentSecondarySub: () => Promise; + getSubtitleStyle: () => Promise; + onSubsyncManualOpen: ( + callback: (payload: SubsyncManualPayload) => void, + ) => void; + runSubsyncManual: ( + request: SubsyncManualRunRequest, + ) => Promise; + onKikuFieldGroupingRequest: ( + callback: (data: KikuFieldGroupingRequestData) => void, + ) => void; + kikuBuildMergePreview: ( + request: KikuMergePreviewRequest, + ) => Promise; + kikuFieldGroupingRespond: (choice: KikuFieldGroupingChoice) => void; + getRuntimeOptions: () => Promise; + setRuntimeOptionValue: ( + id: RuntimeOptionId, + value: RuntimeOptionValue, + ) => Promise; + cycleRuntimeOption: ( + id: RuntimeOptionId, + direction: 1 | -1, + ) => Promise; + onRuntimeOptionsChanged: ( + callback: (options: RuntimeOptionState[]) => void, + ) => void; + onOpenRuntimeOptions: (callback: () => void) => void; + notifyOverlayModalClosed: (modal: "runtime-options" | "subsync") => void; +} + +declare global { + interface Window { + electronAPI: ElectronAPI; + } +} diff --git a/src/window-trackers/base-tracker.ts b/src/window-trackers/base-tracker.ts new file mode 100644 index 0000000..14364ee --- /dev/null +++ b/src/window-trackers/base-tracker.ts @@ -0,0 +1,68 @@ +/* + SubMiner - All-in-one sentence mining overlay + Copyright (C) 2024 sudacode + + 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 . +*/ + +import { WindowGeometry } from "../types"; + +export type GeometryChangeCallback = (geometry: WindowGeometry) => void; +export type WindowFoundCallback = (geometry: WindowGeometry) => void; +export type WindowLostCallback = () => void; + +export abstract class BaseWindowTracker { + protected currentGeometry: WindowGeometry | null = null; + protected windowFound: boolean = false; + public onGeometryChange: GeometryChangeCallback | null = null; + public onWindowFound: WindowFoundCallback | null = null; + public onWindowLost: WindowLostCallback | null = null; + + abstract start(): void; + abstract stop(): void; + + getGeometry(): WindowGeometry | null { + return this.currentGeometry; + } + + isTracking(): boolean { + return this.windowFound; + } + + protected updateGeometry(newGeometry: WindowGeometry | null): void { + if (newGeometry) { + if (!this.windowFound) { + this.windowFound = true; + if (this.onWindowFound) this.onWindowFound(newGeometry); + } + + if ( + !this.currentGeometry || + this.currentGeometry.x !== newGeometry.x || + this.currentGeometry.y !== newGeometry.y || + this.currentGeometry.width !== newGeometry.width || + this.currentGeometry.height !== newGeometry.height + ) { + this.currentGeometry = newGeometry; + if (this.onGeometryChange) this.onGeometryChange(newGeometry); + } + } else { + if (this.windowFound) { + this.windowFound = false; + this.currentGeometry = null; + if (this.onWindowLost) this.onWindowLost(); + } + } + } +} diff --git a/src/window-trackers/hyprland-tracker.ts b/src/window-trackers/hyprland-tracker.ts new file mode 100644 index 0000000..591201c --- /dev/null +++ b/src/window-trackers/hyprland-tracker.ts @@ -0,0 +1,114 @@ +/* + SubMiner - All-in-one sentence mining overlay + Copyright (C) 2024 sudacode + + 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 . +*/ + +import * as net from "net"; +import { execSync } from "child_process"; +import { BaseWindowTracker } from "./base-tracker"; +import { createLogger } from "../logger"; + +const log = createLogger("tracker").child("hyprland"); + +interface HyprlandClient { + class: string; + at: [number, number]; + size: [number, number]; +} + +export class HyprlandWindowTracker extends BaseWindowTracker { + private pollInterval: ReturnType | null = null; + private eventSocket: net.Socket | null = null; + + start(): void { + this.pollInterval = setInterval(() => this.pollGeometry(), 250); + this.pollGeometry(); + this.connectEventSocket(); + } + + stop(): void { + if (this.pollInterval) { + clearInterval(this.pollInterval); + this.pollInterval = null; + } + if (this.eventSocket) { + this.eventSocket.destroy(); + this.eventSocket = null; + } + } + + private connectEventSocket(): void { + const hyprlandSig = process.env.HYPRLAND_INSTANCE_SIGNATURE; + if (!hyprlandSig) { + log.info("HYPRLAND_INSTANCE_SIGNATURE not set, skipping event socket"); + return; + } + + const xdgRuntime = process.env.XDG_RUNTIME_DIR || "/tmp"; + const socketPath = `${xdgRuntime}/hypr/${hyprlandSig}/.socket2.sock`; + this.eventSocket = new net.Socket(); + + this.eventSocket.on("connect", () => { + log.info("Connected to Hyprland event socket"); + }); + + this.eventSocket.on("data", (data: Buffer) => { + const events = data.toString().split("\n"); + for (const event of events) { + if ( + event.includes("movewindow") || + event.includes("windowtitle") || + event.includes("openwindow") || + event.includes("closewindow") || + event.includes("fullscreen") + ) { + this.pollGeometry(); + } + } + }); + + this.eventSocket.on("error", (err: Error) => { + log.error("Hyprland event socket error:", err.message); + }); + + this.eventSocket.on("close", () => { + log.info("Hyprland event socket closed"); + }); + + this.eventSocket.connect(socketPath); + } + + private pollGeometry(): void { + try { + const output = execSync("hyprctl clients -j", { encoding: "utf-8" }); + const clients: HyprlandClient[] = JSON.parse(output); + const mpvWindow = clients.find((c) => c.class === "mpv"); + + if (mpvWindow) { + this.updateGeometry({ + x: mpvWindow.at[0], + y: mpvWindow.at[1], + width: mpvWindow.size[0], + height: mpvWindow.size[1], + }); + } else { + this.updateGeometry(null); + } + } catch (err) { + // hyprctl not available or failed - silent fail + } + } +} diff --git a/src/window-trackers/index.ts b/src/window-trackers/index.ts new file mode 100644 index 0000000..0d22198 --- /dev/null +++ b/src/window-trackers/index.ts @@ -0,0 +1,86 @@ +/* + SubMiner - All-in-one sentence mining overlay + Copyright (C) 2024 sudacode + + 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 . +*/ + +import { BaseWindowTracker } from "./base-tracker"; +import { HyprlandWindowTracker } from "./hyprland-tracker"; +import { SwayWindowTracker } from "./sway-tracker"; +import { X11WindowTracker } from "./x11-tracker"; +import { MacOSWindowTracker } from "./macos-tracker"; +import { createLogger } from "../logger"; + +const log = createLogger("tracker"); + +export type Compositor = "hyprland" | "sway" | "x11" | "macos" | null; +export type Backend = "auto" | Exclude; + +export function detectCompositor(): Compositor { + if (process.platform === "darwin") return "macos"; + if (process.env.HYPRLAND_INSTANCE_SIGNATURE) return "hyprland"; + if (process.env.SWAYSOCK) return "sway"; + if (process.env.XDG_SESSION_TYPE === "x11") return "x11"; + return null; +} + +function normalizeCompositor(value: string): Compositor | null { + const normalized = value.trim().toLowerCase(); + if (normalized === "hyprland") return "hyprland"; + if (normalized === "sway") return "sway"; + if (normalized === "x11") return "x11"; + if (normalized === "macos") return "macos"; + return null; +} + +export function createWindowTracker( + override?: string | null, +): BaseWindowTracker | null { + let compositor = detectCompositor(); + + if (override && override !== "auto") { + const normalized = normalizeCompositor(override); + if (normalized) { + compositor = normalized; + } else { + log.warn( + `Unsupported backend override "${override}", falling back to auto.`, + ); + } + } + log.info(`Detected compositor: ${compositor || "none"}`); + + switch (compositor) { + case "hyprland": + return new HyprlandWindowTracker(); + case "sway": + return new SwayWindowTracker(); + case "x11": + return new X11WindowTracker(); + case "macos": + return new MacOSWindowTracker(); + default: + log.warn("No supported compositor detected. Window tracking disabled."); + return null; + } +} + +export { + BaseWindowTracker, + HyprlandWindowTracker, + SwayWindowTracker, + X11WindowTracker, + MacOSWindowTracker, +}; diff --git a/src/window-trackers/macos-tracker.ts b/src/window-trackers/macos-tracker.ts new file mode 100644 index 0000000..dfbf6aa --- /dev/null +++ b/src/window-trackers/macos-tracker.ts @@ -0,0 +1,114 @@ +/* + subminer - Yomitan integration for mpv + Copyright (C) 2024 sudacode + + 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 . +*/ + +import { execFile } from "child_process"; +import { BaseWindowTracker } from "./base-tracker"; + +export class MacOSWindowTracker extends BaseWindowTracker { + private pollInterval: ReturnType | null = null; + private pollInFlight = false; + + start(): void { + this.pollInterval = setInterval(() => this.pollGeometry(), 250); + this.pollGeometry(); + } + + stop(): void { + if (this.pollInterval) { + clearInterval(this.pollInterval); + this.pollInterval = null; + } + } + + private pollGeometry(): void { + if (this.pollInFlight) { + return; + } + + this.pollInFlight = true; + + const script = ` + set processNames to {"mpv", "MPV", "org.mpv.mpv"} + tell application "System Events" + repeat with procName in processNames + set procList to (every process whose name is procName) + repeat with p in procList + try + if (count of windows of p) > 0 then + set targetWindow to window 1 of p + set windowPos to position of targetWindow + set windowSize to size of targetWindow + return (item 1 of windowPos) & "," & (item 2 of windowPos) & "," & (item 1 of windowSize) & "," & (item 2 of windowSize) + end if + end try + end repeat + end repeat + end tell + return "not-found" + `; + + execFile( + "osascript", + ["-e", script], + { + encoding: "utf-8", + timeout: 1000, + maxBuffer: 1024 * 1024, + }, + (err, stdout) => { + if (err) { + this.updateGeometry(null); + this.pollInFlight = false; + return; + } + + const result = (stdout || "").trim(); + if (result && result !== "not-found") { + const parts = result.split(","); + if (parts.length === 4) { + const x = parseInt(parts[0], 10); + const y = parseInt(parts[1], 10); + const width = parseInt(parts[2], 10); + const height = parseInt(parts[3], 10); + + if ( + Number.isFinite(x) && + Number.isFinite(y) && + Number.isFinite(width) && + Number.isFinite(height) && + width > 0 && + height > 0 + ) { + this.updateGeometry({ + x, + y, + width, + height, + }); + this.pollInFlight = false; + return; + } + } + } + + this.updateGeometry(null); + this.pollInFlight = false; + }, + ); + } +} diff --git a/src/window-trackers/sway-tracker.ts b/src/window-trackers/sway-tracker.ts new file mode 100644 index 0000000..519b9e9 --- /dev/null +++ b/src/window-trackers/sway-tracker.ts @@ -0,0 +1,94 @@ +/* + SubMiner - All-in-one sentence mining overlay + Copyright (C) 2024 sudacode + + 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 . +*/ + +import { execSync } from "child_process"; +import { BaseWindowTracker } from "./base-tracker"; + +interface SwayRect { + x: number; + y: number; + width: number; + height: number; +} + +interface SwayNode { + app_id?: string; + window_properties?: { class?: string }; + rect?: SwayRect; + nodes?: SwayNode[]; + floating_nodes?: SwayNode[]; +} + +export class SwayWindowTracker extends BaseWindowTracker { + private pollInterval: ReturnType | null = null; + + start(): void { + this.pollInterval = setInterval(() => this.pollGeometry(), 250); + this.pollGeometry(); + } + + stop(): void { + if (this.pollInterval) { + clearInterval(this.pollInterval); + this.pollInterval = null; + } + } + + private findMpvWindow(node: SwayNode): SwayNode | null { + if (node.app_id === "mpv" || node.window_properties?.class === "mpv") { + return node; + } + + if (node.nodes) { + for (const child of node.nodes) { + const found = this.findMpvWindow(child); + if (found) return found; + } + } + + if (node.floating_nodes) { + for (const child of node.floating_nodes) { + const found = this.findMpvWindow(child); + if (found) return found; + } + } + + return null; + } + + private pollGeometry(): void { + try { + const output = execSync("swaymsg -t get_tree", { encoding: "utf-8" }); + const tree: SwayNode = JSON.parse(output); + const mpvWindow = this.findMpvWindow(tree); + + if (mpvWindow && mpvWindow.rect) { + this.updateGeometry({ + x: mpvWindow.rect.x, + y: mpvWindow.rect.y, + width: mpvWindow.rect.width, + height: mpvWindow.rect.height, + }); + } else { + this.updateGeometry(null); + } + } catch (err) { + // swaymsg not available or failed - silent fail + } + } +} diff --git a/src/window-trackers/x11-tracker.ts b/src/window-trackers/x11-tracker.ts new file mode 100644 index 0000000..5375cea --- /dev/null +++ b/src/window-trackers/x11-tracker.ts @@ -0,0 +1,73 @@ +/* + SubMiner - All-in-one sentence mining overlay + Copyright (C) 2024 sudacode + + 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 . +*/ + +import { execSync } from "child_process"; +import { BaseWindowTracker } from "./base-tracker"; + +export class X11WindowTracker extends BaseWindowTracker { + private pollInterval: ReturnType | null = null; + + start(): void { + this.pollInterval = setInterval(() => this.pollGeometry(), 250); + this.pollGeometry(); + } + + stop(): void { + if (this.pollInterval) { + clearInterval(this.pollInterval); + this.pollInterval = null; + } + } + + private pollGeometry(): void { + try { + const windowIds = execSync("xdotool search --class mpv", { + encoding: "utf-8", + }).trim(); + + if (!windowIds) { + this.updateGeometry(null); + return; + } + + const windowId = windowIds.split("\n")[0]; + + const winInfo = execSync(`xwininfo -id ${windowId}`, { + encoding: "utf-8", + }); + + const xMatch = winInfo.match(/Absolute upper-left X:\s*(\d+)/); + const yMatch = winInfo.match(/Absolute upper-left Y:\s*(\d+)/); + const widthMatch = winInfo.match(/Width:\s*(\d+)/); + const heightMatch = winInfo.match(/Height:\s*(\d+)/); + + if (xMatch && yMatch && widthMatch && heightMatch) { + this.updateGeometry({ + x: parseInt(xMatch[1], 10), + y: parseInt(yMatch[1], 10), + width: parseInt(widthMatch[1], 10), + height: parseInt(heightMatch[1], 10), + }); + } else { + this.updateGeometry(null); + } + } catch (err) { + this.updateGeometry(null); + } + } +} diff --git a/subminer b/subminer new file mode 100755 index 0000000..41c1f99 --- /dev/null +++ b/subminer @@ -0,0 +1,1951 @@ +#!/usr/bin/env bun + +/** + * SubMiner launcher (Bun runtime) + * Local-only wrapper for mpv + SubMiner overlay orchestration. + */ + +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import net from "node:net"; +import { spawn, spawnSync } from "node:child_process"; +import { parse as parseJsonc } from "jsonc-parser"; + +const VIDEO_EXTENSIONS = new Set([ + "mkv", + "mp4", + "avi", + "webm", + "mov", + "flv", + "wmv", + "m4v", + "ts", + "m2ts", +]); + +const ROFI_THEME_FILE = "subminer.rasi"; +const DEFAULT_SOCKET_PATH = "/tmp/subminer-socket"; +const DEFAULT_YOUTUBE_PRIMARY_SUB_LANGS = ["ja", "jpn"]; +const DEFAULT_YOUTUBE_SECONDARY_SUB_LANGS = ["en", "eng"]; +const YOUTUBE_SUB_EXTENSIONS = new Set([".srt", ".vtt", ".ass"]); +const YOUTUBE_AUDIO_EXTENSIONS = new Set([ + ".m4a", + ".mp3", + ".webm", + ".opus", + ".wav", + ".aac", + ".flac", +]); +const DEFAULT_YOUTUBE_SUBGEN_OUT_DIR = path.join( + os.homedir(), + ".cache", + "subminer", + "youtube-subs", +); +const DEFAULT_YOUTUBE_YTDL_FORMAT = "bestvideo*+bestaudio/best"; + +type LogLevel = "debug" | "info" | "warn" | "error"; +type YoutubeSubgenMode = "automatic" | "preprocess" | "off"; + +type Backend = "auto" | "hyprland" | "x11" | "macos"; + +interface Args { + backend: Backend; + directory: string; + recursive: boolean; + profile: string; + youtubeSubgenMode: YoutubeSubgenMode; + whisperBin: string; + whisperModel: string; + youtubeSubgenOutDir: string; + youtubeSubgenAudioFormat: string; + youtubeSubgenKeepTemp: boolean; + youtubePrimarySubLangs: string[]; + youtubeSecondarySubLangs: string[]; + youtubeAudioLangs: string[]; + youtubeWhisperSourceLanguage: string; + useTexthooker: boolean; + texthookerOnly: boolean; + useRofi: boolean; + logLevel: LogLevel; + target: string; + targetKind: "" | "file" | "url"; +} + +interface LauncherYoutubeSubgenConfig { + mode?: YoutubeSubgenMode; + whisperBin?: string; + whisperModel?: string; + primarySubLanguages?: string[]; + secondarySubLanguages?: string[]; +} + +const COLORS = { + red: "\x1b[0;31m", + green: "\x1b[0;32m", + yellow: "\x1b[0;33m", + cyan: "\x1b[0;36m", + reset: "\x1b[0m", +}; + +const LOG_PRI: Record = { + debug: 10, + info: 20, + warn: 30, + error: 40, +}; + +const state = { + overlayProc: null as ReturnType | null, + mpvProc: null as ReturnType | null, + youtubeSubgenChildren: new Set>(), + appPath: "" as string, + stopRequested: false, +}; + +function usage(scriptName: string): string { + return `subminer - Launch MPV with SubMiner sentence mining overlay + +Usage: ${scriptName} [OPTIONS] [FILE|DIRECTORY|URL] + +Options: + -b, --backend BACKEND Display backend to use: auto, hyprland, x11, macos (default: auto) + -d, --directory DIR Directory to browse for videos (default: current directory) + -r, --recursive Search for videos recursively + -p, --profile PROFILE MPV profile to use (default: subminer) + --yt-subgen-mode MODE + YouTube subtitle generation mode: automatic, preprocess, off (default: automatic) + --whisper-bin PATH whisper.cpp CLI binary (used for fallback transcription) + --whisper-model PATH + whisper model file path (used for fallback transcription) + --yt-subgen-out-dir DIR + Output directory for generated YouTube subtitles (default: ${DEFAULT_YOUTUBE_SUBGEN_OUT_DIR}) + --yt-subgen-audio-format FORMAT + Audio format for extraction (default: m4a) + --yt-subgen-keep-temp + Keep YouTube subtitle temp directory + -v, --verbose Enable verbose/debug logging + --log-level LEVEL Set log level: debug, info, warn, error + -R, --rofi Use rofi file browser instead of fzf for video selection + -T, --no-texthooker Disable texthooker-ui server + --texthooker Launch only texthooker page (no MPV/overlay workflow) + -h, --help Show this help message + +Environment: + SUBMINER_APPIMAGE_PATH Path to SubMiner AppImage/binary (optional override) + SUBMINER_ROFI_THEME Path to rofi theme file (optional override) + SUBMINER_YT_SUBGEN_MODE automatic, preprocess, off (optional default) + SUBMINER_WHISPER_BIN whisper.cpp binary path (optional fallback) + SUBMINER_WHISPER_MODEL whisper model path (optional fallback) + SUBMINER_YT_SUBGEN_OUT_DIR Generated subtitle output directory + +Examples: + ${scriptName} # Browse current directory with fzf + ${scriptName} -R # Browse current directory with rofi + ${scriptName} -d ~/Videos # Browse ~/Videos + ${scriptName} -r -d ~/Anime # Recursively browse ~/Anime + ${scriptName} video.mkv # Play specific file + ${scriptName} https://youtu.be/... # Play a YouTube URL + ${scriptName} ytsearch:query # Play first YouTube search result + ${scriptName} --yt-subgen-mode preprocess --whisper-bin /path/whisper-cli --whisper-model /path/model.bin https://youtu.be/... + ${scriptName} video.mkv # Play with subminer profile + ${scriptName} -p gpu-hq video.mkv # Play with gpu-hq profile + ${scriptName} -b x11 video.mkv # Force x11 backend + ${scriptName} --texthooker # Launch only texthooker page +`; +} + +function shouldLog(level: LogLevel, configured: LogLevel): boolean { + return LOG_PRI[level] >= LOG_PRI[configured]; +} + +function log(level: LogLevel, configured: LogLevel, message: string): void { + if (!shouldLog(level, configured)) return; + const color = + level === "info" + ? COLORS.green + : level === "warn" + ? COLORS.yellow + : level === "error" + ? COLORS.red + : COLORS.cyan; + process.stdout.write( + `${color}[${level.toUpperCase()}]${COLORS.reset} ${message}\n`, + ); +} + +function fail(message: string): never { + process.stderr.write(`${COLORS.red}[ERROR]${COLORS.reset} ${message}\n`); + process.exit(1); +} + +function isExecutable(filePath: string): boolean { + try { + fs.accessSync(filePath, fs.constants.X_OK); + return true; + } catch { + return false; + } +} + +function commandExists(command: string): boolean { + const pathEnv = process.env.PATH ?? ""; + for (const dir of pathEnv.split(path.delimiter)) { + if (!dir) continue; + const full = path.join(dir, command); + if (isExecutable(full)) return true; + } + return false; +} + +function resolvePathMaybe(input: string): string { + if (input.startsWith("~")) { + return path.join(os.homedir(), input.slice(1)); + } + return input; +} + +function loadLauncherYoutubeSubgenConfig(): LauncherYoutubeSubgenConfig { + const configDir = path.join(os.homedir(), ".config", "SubMiner"); + const jsoncPath = path.join(configDir, "config.jsonc"); + const jsonPath = path.join(configDir, "config.json"); + const configPath = fs.existsSync(jsoncPath) + ? jsoncPath + : fs.existsSync(jsonPath) + ? jsonPath + : ""; + if (!configPath) return {}; + + try { + const data = fs.readFileSync(configPath, "utf8"); + const parsed = configPath.endsWith(".jsonc") + ? parseJsonc(data) + : JSON.parse(data); + if (!parsed || typeof parsed !== "object") return {}; + const root = parsed as { + youtubeSubgen?: unknown; + secondarySub?: { secondarySubLanguages?: unknown }; + }; + const youtubeSubgen = root.youtubeSubgen; + const mode = + youtubeSubgen && typeof youtubeSubgen === "object" + ? (youtubeSubgen as { mode?: unknown }).mode + : undefined; + const whisperBin = + youtubeSubgen && typeof youtubeSubgen === "object" + ? (youtubeSubgen as { whisperBin?: unknown }).whisperBin + : undefined; + const whisperModel = + youtubeSubgen && typeof youtubeSubgen === "object" + ? (youtubeSubgen as { whisperModel?: unknown }).whisperModel + : undefined; + const primarySubLanguagesRaw = + youtubeSubgen && typeof youtubeSubgen === "object" + ? (youtubeSubgen as { primarySubLanguages?: unknown }).primarySubLanguages + : undefined; + const secondarySubLanguagesRaw = root.secondarySub?.secondarySubLanguages; + const primarySubLanguages = Array.isArray(primarySubLanguagesRaw) + ? primarySubLanguagesRaw.filter( + (value): value is string => typeof value === "string", + ) + : undefined; + const secondarySubLanguages = Array.isArray(secondarySubLanguagesRaw) + ? secondarySubLanguagesRaw.filter( + (value): value is string => typeof value === "string", + ) + : undefined; + + return { + mode: + mode === "automatic" || mode === "preprocess" || mode === "off" + ? mode + : undefined, + whisperBin: typeof whisperBin === "string" ? whisperBin : undefined, + whisperModel: typeof whisperModel === "string" ? whisperModel : undefined, + primarySubLanguages, + secondarySubLanguages, + }; + } catch { + return {}; + } +} + +function realpathMaybe(filePath: string): string { + try { + return fs.realpathSync(filePath); + } catch { + return path.resolve(filePath); + } +} + +function isUrlTarget(target: string): boolean { + return /^https?:\/\//.test(target) || /^ytsearch:/.test(target); +} + +function isYoutubeTarget(target: string): boolean { + return ( + /^ytsearch:/.test(target) || + /^https?:\/\/(www\.)?(youtube\.com|youtu\.be)\//.test(target) + ); +} + +interface CommandExecOptions { + allowFailure?: boolean; + captureStdout?: boolean; + logLevel?: LogLevel; + commandLabel?: string; + streamOutput?: boolean; +} + +interface CommandExecResult { + code: number; + stdout: string; + stderr: string; +} + +interface SubtitleCandidate { + path: string; + lang: "primary" | "secondary"; + ext: string; + size: number; + source: "manual" | "auto" | "whisper" | "whisper-translate"; +} + +interface YoutubeSubgenOutputs { + basename: string; + primaryPath?: string; + secondaryPath?: string; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function sanitizeToken(value: string): string { + return String(value) + .toLowerCase() + .replace(/[^a-z0-9._-]+/g, "-") + .replace(/-+/g, "-") + .replace(/^-|-$/g, ""); +} + +function normalizeBasename(value: string, fallback: string): string { + const safe = sanitizeToken(value.replace(/[\\/]+/g, "-")); + if (safe) return safe; + const fallbackSafe = sanitizeToken(fallback); + if (fallbackSafe) return fallbackSafe; + return `${Date.now()}`; +} + +function normalizeLangCode(value: string): string { + return value.trim().toLowerCase().replace(/[^a-z0-9-]+/g, ""); +} + +function uniqueNormalizedLangCodes(values: string[]): string[] { + const seen = new Set(); + const out: string[] = []; + for (const value of values) { + const normalized = normalizeLangCode(value); + if (!normalized || seen.has(normalized)) continue; + seen.add(normalized); + out.push(normalized); + } + return out; +} + +function toYtdlpLangPattern(langCodes: string[]): string { + return langCodes.map((lang) => `${lang}.*`).join(","); +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function filenameHasLanguageTag(filenameLower: string, langCode: string): boolean { + const escaped = escapeRegExp(langCode); + const pattern = new RegExp(`(^|[._-])${escaped}([._-]|$)`); + return pattern.test(filenameLower); +} + +function classifyLanguage( + filename: string, + primaryLangCodes: string[], + secondaryLangCodes: string[], +): "primary" | "secondary" | null { + const lower = filename.toLowerCase(); + const primary = primaryLangCodes.some((code) => + filenameHasLanguageTag(lower, code), + ); + const secondary = secondaryLangCodes.some((code) => + filenameHasLanguageTag(lower, code), + ); + if (primary && !secondary) return "primary"; + if (secondary && !primary) return "secondary"; + return null; +} + +function preferredLangLabel(langCodes: string[], fallback: string): string { + return uniqueNormalizedLangCodes(langCodes)[0] || fallback; +} + +function inferWhisperLanguage(langCodes: string[], fallback: string): string { + for (const lang of uniqueNormalizedLangCodes(langCodes)) { + if (lang === "jpn") return "ja"; + if (lang.length >= 2) return lang.slice(0, 2); + } + return fallback; +} + +function sourceTag(source: SubtitleCandidate["source"]): string { + if (source === "manual" || source === "auto") return `ytdlp-${source}`; + if (source === "whisper-translate") return "whisper-translate"; + return "whisper"; +} + +function runExternalCommand( + executable: string, + args: string[], + opts: CommandExecOptions = {}, +): Promise { + const allowFailure = opts.allowFailure === true; + const captureStdout = opts.captureStdout === true; + const configuredLogLevel = opts.logLevel ?? "info"; + const commandLabel = opts.commandLabel || executable; + const streamOutput = opts.streamOutput === true; + + return new Promise((resolve, reject) => { + log("debug", configuredLogLevel, `[${commandLabel}] spawn: ${executable} ${args.join(" ")}`); + const child = spawn(executable, args, { + stdio: ["ignore", "pipe", "pipe"], + }); + state.youtubeSubgenChildren.add(child); + + let stdout = ""; + let stderr = ""; + let stdoutBuffer = ""; + let stderrBuffer = ""; + const flushLines = ( + buffer: string, + level: LogLevel, + sink: (remaining: string) => void, + ): void => { + const lines = buffer.split(/\r?\n/); + const remaining = lines.pop() ?? ""; + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed.length > 0) { + log(level, configuredLogLevel, `[${commandLabel}] ${trimmed}`); + } + } + sink(remaining); + }; + + child.stdout.on("data", (chunk: Buffer) => { + const text = chunk.toString(); + if (captureStdout) stdout += text; + if (streamOutput) { + stdoutBuffer += text; + flushLines(stdoutBuffer, "debug", (remaining) => { + stdoutBuffer = remaining; + }); + } + }); + + child.stderr.on("data", (chunk: Buffer) => { + const text = chunk.toString(); + stderr += text; + if (streamOutput) { + stderrBuffer += text; + flushLines(stderrBuffer, "debug", (remaining) => { + stderrBuffer = remaining; + }); + } + }); + + child.on("error", (error) => { + state.youtubeSubgenChildren.delete(child); + reject(new Error(`Failed to start "${executable}": ${error.message}`)); + }); + + child.on("close", (code) => { + state.youtubeSubgenChildren.delete(child); + if (streamOutput) { + const trailingOut = stdoutBuffer.trim(); + if (trailingOut.length > 0) { + log("debug", configuredLogLevel, `[${commandLabel}] ${trailingOut}`); + } + const trailingErr = stderrBuffer.trim(); + if (trailingErr.length > 0) { + log("debug", configuredLogLevel, `[${commandLabel}] ${trailingErr}`); + } + } + log( + code === 0 ? "debug" : "warn", + configuredLogLevel, + `[${commandLabel}] exit code ${code ?? 1}`, + ); + if (code !== 0 && !allowFailure) { + const commandString = `${executable} ${args.join(" ")}`; + reject( + new Error( + `Command failed (${commandString}): ${stderr.trim() || `exit code ${code}`}`, + ), + ); + return; + } + resolve({ code: code ?? 1, stdout, stderr }); + }); + }); +} + +function pickBestCandidate(candidates: SubtitleCandidate[]): SubtitleCandidate | null { + if (candidates.length === 0) return null; + const scored = [...candidates].sort((a, b) => { + const sourceA = a.source === "manual" ? 1 : 0; + const sourceB = b.source === "manual" ? 1 : 0; + if (sourceA !== sourceB) return sourceB - sourceA; + const srtA = a.ext === ".srt" ? 1 : 0; + const srtB = b.ext === ".srt" ? 1 : 0; + if (srtA !== srtB) return srtB - srtA; + return b.size - a.size; + }); + return scored[0]; +} + +function scanSubtitleCandidates( + tempDir: string, + knownSet: Set, + source: "manual" | "auto", + primaryLangCodes: string[], + secondaryLangCodes: string[], +): SubtitleCandidate[] { + const entries = fs.readdirSync(tempDir); + const out: SubtitleCandidate[] = []; + for (const name of entries) { + const fullPath = path.join(tempDir, name); + if (knownSet.has(fullPath)) continue; + let stat: fs.Stats; + try { + stat = fs.statSync(fullPath); + } catch { + continue; + } + if (!stat.isFile()) continue; + const ext = path.extname(fullPath).toLowerCase(); + if (!YOUTUBE_SUB_EXTENSIONS.has(ext)) continue; + const lang = classifyLanguage(name, primaryLangCodes, secondaryLangCodes); + if (!lang) continue; + out.push({ path: fullPath, lang, ext, size: stat.size, source }); + } + return out; +} + +async function convertToSrt( + inputPath: string, + tempDir: string, + langLabel: string, +): Promise { + if (path.extname(inputPath).toLowerCase() === ".srt") return inputPath; + const outputPath = path.join(tempDir, `converted.${langLabel}.srt`); + await runExternalCommand("ffmpeg", ["-y", "-loglevel", "error", "-i", inputPath, outputPath]); + return outputPath; +} + +function findAudioFile(tempDir: string, preferredExt: string): string | null { + const entries = fs.readdirSync(tempDir); + const audioFiles: Array<{ path: string; ext: string; mtimeMs: number }> = []; + for (const name of entries) { + const fullPath = path.join(tempDir, name); + let stat: fs.Stats; + try { + stat = fs.statSync(fullPath); + } catch { + continue; + } + if (!stat.isFile()) continue; + const ext = path.extname(name).toLowerCase(); + if (!YOUTUBE_AUDIO_EXTENSIONS.has(ext)) continue; + audioFiles.push({ path: fullPath, ext, mtimeMs: stat.mtimeMs }); + } + if (audioFiles.length === 0) return null; + const preferred = audioFiles.find((entry) => entry.ext === `.${preferredExt.toLowerCase()}`); + if (preferred) return preferred.path; + audioFiles.sort((a, b) => b.mtimeMs - a.mtimeMs); + return audioFiles[0].path; +} + +async function runWhisper( + whisperBin: string, + modelPath: string, + audioPath: string, + language: string, + translate: boolean, + outputPrefix: string, +): Promise { + const args = [ + "-m", + modelPath, + "-f", + audioPath, + "--output-srt", + "--output-file", + outputPrefix, + "--language", + language, + ]; + if (translate) args.push("--translate"); + await runExternalCommand(whisperBin, args, { + commandLabel: "whisper", + streamOutput: true, + }); + const outputPath = `${outputPrefix}.srt`; + if (!fs.existsSync(outputPath)) { + throw new Error(`whisper output not found: ${outputPath}`); + } + return outputPath; +} + +async function convertAudioForWhisper(inputPath: string, tempDir: string): Promise { + const wavPath = path.join(tempDir, "whisper-input.wav"); + await runExternalCommand("ffmpeg", [ + "-y", + "-loglevel", + "error", + "-i", + inputPath, + "-ar", + "16000", + "-ac", + "1", + "-c:a", + "pcm_s16le", + wavPath, + ]); + if (!fs.existsSync(wavPath)) { + throw new Error(`Failed to prepare whisper audio input: ${wavPath}`); + } + return wavPath; +} + +function sendMpvCommand(socketPath: string, command: unknown[]): Promise { + return new Promise((resolve, reject) => { + const socket = net.createConnection(socketPath); + socket.once("connect", () => { + socket.write(`${JSON.stringify({ command })}\n`); + socket.end(); + resolve(); + }); + socket.once("error", (error) => { + reject(error); + }); + }); +} + +async function loadSubtitleIntoMpv( + socketPath: string, + subtitlePath: string, + select: boolean, + logLevel: LogLevel, +): Promise { + for (let attempt = 1; ; attempt += 1) { + const mpvExited = + state.mpvProc !== null && + state.mpvProc.exitCode !== null && + state.mpvProc.exitCode !== undefined; + if (mpvExited) { + throw new Error(`mpv exited before subtitle could be loaded: ${subtitlePath}`); + } + + if (!fs.existsSync(socketPath)) { + if (attempt % 20 === 0) { + log( + "debug", + logLevel, + `Waiting for mpv socket before loading subtitle (${attempt} attempts): ${path.basename(subtitlePath)}`, + ); + } + await sleep(250); + continue; + } + try { + await sendMpvCommand( + socketPath, + select ? ["sub-add", subtitlePath, "select"] : ["sub-add", subtitlePath], + ); + log( + "info", + logLevel, + `Loaded generated subtitle into mpv: ${path.basename(subtitlePath)}`, + ); + return; + } catch { + if (attempt % 20 === 0) { + log( + "debug", + logLevel, + `Retrying subtitle load into mpv (${attempt} attempts): ${path.basename(subtitlePath)}`, + ); + } + await sleep(250); + } + } +} + +function detectBackend(backend: Backend): Exclude { + if (backend !== "auto") return backend; + if (process.platform === "darwin") return "macos"; + const xdgCurrentDesktop = (process.env.XDG_CURRENT_DESKTOP || "").toLowerCase(); + const xdgSessionDesktop = (process.env.XDG_SESSION_DESKTOP || "").toLowerCase(); + const xdgSessionType = (process.env.XDG_SESSION_TYPE || "").toLowerCase(); + const hasWayland = Boolean(process.env.WAYLAND_DISPLAY) || xdgSessionType === "wayland"; + + if ( + process.env.HYPRLAND_INSTANCE_SIGNATURE || + xdgCurrentDesktop.includes("hyprland") || + xdgSessionDesktop.includes("hyprland") + ) { + return "hyprland"; + } + if (hasWayland && commandExists("hyprctl")) return "hyprland"; + if (process.env.DISPLAY) return "x11"; + fail("Could not detect display backend"); +} + +function findRofiTheme(scriptPath: string): string | null { + const envTheme = process.env.SUBMINER_ROFI_THEME; + if (envTheme && fs.existsSync(envTheme)) return envTheme; + + const scriptDir = path.dirname(realpathMaybe(scriptPath)); + const candidates: string[] = []; + + if (process.platform === "darwin") { + candidates.push( + path.join( + os.homedir(), + "Library/Application Support/SubMiner/themes", + ROFI_THEME_FILE, + ), + ); + } else { + const xdgDataHome = + process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local/share"); + candidates.push(path.join(xdgDataHome, "SubMiner/themes", ROFI_THEME_FILE)); + candidates.push( + path.join("/usr/local/share/SubMiner/themes", ROFI_THEME_FILE), + ); + candidates.push(path.join("/usr/share/SubMiner/themes", ROFI_THEME_FILE)); + } + + candidates.push(path.join(scriptDir, ROFI_THEME_FILE)); + + for (const candidate of candidates) { + if (fs.existsSync(candidate)) return candidate; + } + + return null; +} + +function collectVideos(dir: string, recursive: boolean): string[] { + const root = path.resolve(dir); + const out: string[] = []; + + const walk = (current: string): void => { + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(current, { withFileTypes: true }); + } catch { + return; + } + + for (const entry of entries) { + const full = path.join(current, entry.name); + if (entry.isDirectory()) { + if (recursive) walk(full); + continue; + } + if (!entry.isFile()) continue; + const ext = path.extname(entry.name).slice(1).toLowerCase(); + if (VIDEO_EXTENSIONS.has(ext)) out.push(full); + } + }; + + walk(root); + return out.sort((a, b) => + a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }), + ); +} + +function buildRofiMenu( + videos: string[], + dir: string, + recursive: boolean, +): Buffer { + const chunks: Buffer[] = []; + for (const video of videos) { + const display = recursive + ? path.relative(dir, video) + : path.basename(video); + const line = `${display}\0icon\x1fthumbnail://${video}\n`; + chunks.push(Buffer.from(line, "utf8")); + } + return Buffer.concat(chunks); +} + +function showRofiMenu( + videos: string[], + dir: string, + recursive: boolean, + scriptPath: string, + logLevel: LogLevel, +): string { + const args = [ + "-dmenu", + "-i", + "-p", + "Select Video ", + "-show-icons", + "-theme-str", + 'configuration { font: "Noto Sans CJK JP Regular 8";}', + ]; + + const theme = findRofiTheme(scriptPath); + if (theme) { + args.push("-theme", theme); + } else { + log( + "warn", + logLevel, + "Rofi theme not found; using rofi defaults (set SUBMINER_ROFI_THEME to override)", + ); + } + + const result = spawnSync("rofi", args, { + input: buildRofiMenu(videos, dir, recursive), + encoding: "utf8", + stdio: ["pipe", "pipe", "ignore"], + }); + if (result.error) { + fail( + formatPickerLaunchError("rofi", result.error as NodeJS.ErrnoException), + ); + } + + const selection = (result.stdout || "").trim(); + if (!selection) return ""; + return path.join(dir, selection); +} + +function buildFzfMenu(videos: string[]): string { + return videos.map((video) => `${path.basename(video)}\t${video}`).join("\n"); +} + +function showFzfMenu(videos: string[]): string { + const chafaFormat = process.env.TMUX + ? "--format=symbols --symbols=vhalf+wide --color-space=din99d" + : "--format=kitty"; + + const previewCmd = commandExists("chafa") + ? ` +video={2} +thumb_dir="$HOME/.cache/thumbnails/large" +video_uri="file://$(realpath "$video")" +if command -v md5sum >/dev/null 2>&1; then + thumb_hash=$(echo -n "$video_uri" | md5sum | cut -d' ' -f1) +else + thumb_hash=$(echo -n "$video_uri" | md5 -q) +fi +thumb_path="$thumb_dir/$thumb_hash.png" + +get_thumb() { + if [[ -f "$thumb_path" ]]; then + echo "$thumb_path" + elif command -v ffmpegthumbnailer >/dev/null 2>&1; then + tmp="/tmp/subminer-preview.jpg" + ffmpegthumbnailer -i "$video" -o "$tmp" -s 512 -q 5 2>/dev/null && echo "$tmp" + elif command -v ffmpeg >/dev/null 2>&1; then + tmp="/tmp/subminer-preview.jpg" + ffmpeg -y -i "$video" -ss 00:00:05 -vframes 1 -vf "scale=512:-1" "$tmp" 2>/dev/null && echo "$tmp" + fi +} + +thumb=$(get_thumb) +[[ -n "$thumb" ]] && chafa ${chafaFormat} --size=${"${FZF_PREVIEW_COLUMNS}"}x${"${FZF_PREVIEW_LINES}"} "$thumb" 2>/dev/null +`.trim() + : 'echo "Install chafa for thumbnail preview"'; + + const result = spawnSync( + "fzf", + [ + "--ansi", + "--reverse", + "--prompt=Select Video: ", + "--delimiter=\t", + "--with-nth=1", + "--preview-window=right:50%:wrap", + "--preview", + previewCmd, + ], + { + input: buildFzfMenu(videos), + encoding: "utf8", + stdio: ["pipe", "pipe", "inherit"], + }, + ); + if (result.error) { + fail(formatPickerLaunchError("fzf", result.error as NodeJS.ErrnoException)); + } + + const selection = (result.stdout || "").trim(); + if (!selection) return ""; + const tabIndex = selection.indexOf("\t"); + if (tabIndex === -1) return ""; + return selection.slice(tabIndex + 1); +} + +function formatPickerLaunchError( + picker: "rofi" | "fzf", + error: NodeJS.ErrnoException, +): string { + if (error.code === "ENOENT") { + return picker === "rofi" + ? "rofi not found. Install rofi or use --no-rofi to use fzf." + : "fzf not found. Install fzf or use --rofi to use rofi."; + } + return `Failed to launch ${picker}: ${error.message}`; +} + +function findAppBinary(selfPath: string): string | null { + const envPath = process.env.SUBMINER_APPIMAGE_PATH; + if (envPath && isExecutable(envPath)) return envPath; + + const candidates: string[] = []; + if (process.platform === "darwin") { + candidates.push("/Applications/SubMiner.app/Contents/MacOS/SubMiner"); + candidates.push("/Applications/SubMiner.app/Contents/MacOS/subminer"); + candidates.push( + path.join( + os.homedir(), + "Applications/SubMiner.app/Contents/MacOS/SubMiner", + ), + ); + candidates.push( + path.join( + os.homedir(), + "Applications/SubMiner.app/Contents/MacOS/subminer", + ), + ); + } + + candidates.push(path.join(os.homedir(), ".local/bin/SubMiner.AppImage")); + candidates.push("/opt/SubMiner/SubMiner.AppImage"); + + for (const candidate of candidates) { + if (isExecutable(candidate)) return candidate; + } + + const fromPath = process.env.PATH?.split(path.delimiter) + .map((dir) => path.join(dir, "subminer")) + .find((candidate) => isExecutable(candidate)); + + if (fromPath) { + const resolvedSelf = realpathMaybe(selfPath); + const resolvedCandidate = realpathMaybe(fromPath); + if (resolvedSelf !== resolvedCandidate) return fromPath; + } + + return null; +} + +function checkDependencies(args: Args): void { + const missing: string[] = []; + + if (!commandExists("mpv")) missing.push("mpv"); + + if ( + args.targetKind === "url" && + isYoutubeTarget(args.target) && + !commandExists("yt-dlp") + ) { + missing.push("yt-dlp"); + } + + if ( + args.targetKind === "url" && + isYoutubeTarget(args.target) && + args.youtubeSubgenMode !== "off" && + !commandExists("ffmpeg") + ) { + missing.push("ffmpeg"); + } + + if (missing.length > 0) fail(`Missing dependencies: ${missing.join(" ")}`); +} + +function resolveWhisperBinary(args: Args): string | null { + const explicit = args.whisperBin.trim(); + if (explicit) return resolvePathMaybe(explicit); + if (commandExists("whisper-cli")) return "whisper-cli"; + return null; +} + +async function generateYoutubeSubtitles( + target: string, + args: Args, + onReady?: (lang: "primary" | "secondary", pathToLoad: string) => Promise, +): Promise { + const outDir = path.resolve(resolvePathMaybe(args.youtubeSubgenOutDir)); + fs.mkdirSync(outDir, { recursive: true }); + + const primaryLangCodes = uniqueNormalizedLangCodes(args.youtubePrimarySubLangs); + const secondaryLangCodes = uniqueNormalizedLangCodes(args.youtubeSecondarySubLangs); + const primaryLabel = preferredLangLabel(primaryLangCodes, "primary"); + const secondaryLabel = preferredLangLabel(secondaryLangCodes, "secondary"); + const secondaryCanUseWhisperTranslate = + secondaryLangCodes.includes("en") || secondaryLangCodes.includes("eng"); + const ytdlpManualLangs = toYtdlpLangPattern([ + ...primaryLangCodes, + ...secondaryLangCodes, + ]); + + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "subminer-yt-subgen-")); + const knownFiles = new Set(); + let keepTemp = args.youtubeSubgenKeepTemp; + + const publishTrack = async ( + lang: "primary" | "secondary", + source: SubtitleCandidate["source"], + selectedPath: string, + basename: string, + ): Promise => { + const langLabel = lang === "primary" ? primaryLabel : secondaryLabel; + const taggedPath = path.join( + outDir, + `${basename}.${langLabel}.${sourceTag(source)}.srt`, + ); + const aliasPath = path.join(outDir, `${basename}.${langLabel}.srt`); + fs.copyFileSync(selectedPath, taggedPath); + fs.copyFileSync(taggedPath, aliasPath); + log( + "info", + args.logLevel, + `Generated subtitle (${langLabel}, ${source}) -> ${aliasPath}`, + ); + if (onReady) await onReady(lang, aliasPath); + return aliasPath; + }; + + try { + log("debug", args.logLevel, `YouTube subtitle temp dir: ${tempDir}`); + const meta = await runExternalCommand( + "yt-dlp", + ["--dump-single-json", "--no-warnings", target], + { + captureStdout: true, + logLevel: args.logLevel, + commandLabel: "yt-dlp:meta", + }, + ); + const metadata = JSON.parse(meta.stdout) as { id?: string }; + const videoId = metadata.id || `${Date.now()}`; + const basename = normalizeBasename(videoId, videoId); + + await runExternalCommand( + "yt-dlp", + [ + "--skip-download", + "--no-warnings", + "--write-subs", + "--sub-format", + "srt/vtt/best", + "--sub-langs", + ytdlpManualLangs, + "-o", + path.join(tempDir, "%(id)s.%(ext)s"), + target, + ], + { + allowFailure: true, + logLevel: args.logLevel, + commandLabel: "yt-dlp:manual-subs", + streamOutput: true, + }, + ); + + const manualSubs = scanSubtitleCandidates( + tempDir, + knownFiles, + "manual", + primaryLangCodes, + secondaryLangCodes, + ); + for (const sub of manualSubs) knownFiles.add(sub.path); + let primaryCandidates = manualSubs.filter((entry) => entry.lang === "primary"); + let secondaryCandidates = manualSubs.filter( + (entry) => entry.lang === "secondary", + ); + + const missingAuto: string[] = []; + if (primaryCandidates.length === 0) + missingAuto.push(toYtdlpLangPattern(primaryLangCodes)); + if (secondaryCandidates.length === 0) + missingAuto.push(toYtdlpLangPattern(secondaryLangCodes)); + + if (missingAuto.length > 0) { + await runExternalCommand( + "yt-dlp", + [ + "--skip-download", + "--no-warnings", + "--write-auto-subs", + "--sub-format", + "srt/vtt/best", + "--sub-langs", + missingAuto.join(","), + "-o", + path.join(tempDir, "%(id)s.%(ext)s"), + target, + ], + { + allowFailure: true, + logLevel: args.logLevel, + commandLabel: "yt-dlp:auto-subs", + streamOutput: true, + }, + ); + + const autoSubs = scanSubtitleCandidates( + tempDir, + knownFiles, + "auto", + primaryLangCodes, + secondaryLangCodes, + ); + for (const sub of autoSubs) knownFiles.add(sub.path); + primaryCandidates = primaryCandidates.concat( + autoSubs.filter((entry) => entry.lang === "primary"), + ); + secondaryCandidates = secondaryCandidates.concat( + autoSubs.filter((entry) => entry.lang === "secondary"), + ); + } + + let primaryAlias = ""; + let secondaryAlias = ""; + const selectedPrimary = pickBestCandidate(primaryCandidates); + const selectedSecondary = pickBestCandidate(secondaryCandidates); + + if (selectedPrimary) { + const srt = await convertToSrt(selectedPrimary.path, tempDir, primaryLabel); + primaryAlias = await publishTrack( + "primary", + selectedPrimary.source, + srt, + basename, + ); + } + if (selectedSecondary) { + const srt = await convertToSrt( + selectedSecondary.path, + tempDir, + secondaryLabel, + ); + secondaryAlias = await publishTrack( + "secondary", + selectedSecondary.source, + srt, + basename, + ); + } + + const needsPrimaryWhisper = !selectedPrimary; + const needsSecondaryWhisper = !selectedSecondary && secondaryCanUseWhisperTranslate; + if (needsPrimaryWhisper || needsSecondaryWhisper) { + const whisperBin = resolveWhisperBinary(args); + const modelPath = args.whisperModel.trim() + ? path.resolve(resolvePathMaybe(args.whisperModel.trim())) + : ""; + const hasWhisperFallback = !!whisperBin && !!modelPath && fs.existsSync(modelPath); + + if (!hasWhisperFallback) { + log( + "warn", + args.logLevel, + "Whisper fallback is not configured; continuing with available subtitle tracks.", + ); + } else { + try { + await runExternalCommand( + "yt-dlp", + [ + "-f", + "bestaudio/best", + "--extract-audio", + "--audio-format", + args.youtubeSubgenAudioFormat, + "--no-warnings", + "-o", + path.join(tempDir, "%(id)s.%(ext)s"), + target, + ], + { + logLevel: args.logLevel, + commandLabel: "yt-dlp:audio", + streamOutput: true, + }, + ); + const audioPath = findAudioFile(tempDir, args.youtubeSubgenAudioFormat); + if (!audioPath) { + throw new Error("Audio extraction succeeded, but no audio file was found."); + } + const whisperAudioPath = await convertAudioForWhisper(audioPath, tempDir); + + if (needsPrimaryWhisper) { + try { + const primaryPrefix = path.join(tempDir, `${basename}.${primaryLabel}`); + const primarySrt = await runWhisper( + whisperBin!, + modelPath, + whisperAudioPath, + args.youtubeWhisperSourceLanguage, + false, + primaryPrefix, + ); + primaryAlias = await publishTrack( + "primary", + "whisper", + primarySrt, + basename, + ); + } catch (error) { + log( + "warn", + args.logLevel, + `Failed to generate primary subtitle via whisper fallback: ${(error as Error).message}`, + ); + } + } + + if (needsSecondaryWhisper) { + try { + const secondaryPrefix = path.join( + tempDir, + `${basename}.${secondaryLabel}`, + ); + const secondarySrt = await runWhisper( + whisperBin!, + modelPath, + whisperAudioPath, + args.youtubeWhisperSourceLanguage, + true, + secondaryPrefix, + ); + secondaryAlias = await publishTrack( + "secondary", + "whisper-translate", + secondarySrt, + basename, + ); + } catch (error) { + log( + "warn", + args.logLevel, + `Failed to generate secondary subtitle via whisper fallback: ${(error as Error).message}`, + ); + } + } + } catch (error) { + log( + "warn", + args.logLevel, + `Whisper fallback pipeline failed: ${(error as Error).message}`, + ); + } + } + } + + if (!secondaryCanUseWhisperTranslate && !selectedSecondary) { + log( + "warn", + args.logLevel, + `Secondary subtitle language (${secondaryLabel}) has no whisper translate fallback; relying on yt-dlp subtitles only.`, + ); + } + + if (!primaryAlias && !secondaryAlias) { + throw new Error("Failed to generate any subtitle tracks."); + } + if (!primaryAlias || !secondaryAlias) { + log( + "warn", + args.logLevel, + `Generated partial subtitle result: primary=${primaryAlias ? "ok" : "missing"}, secondary=${secondaryAlias ? "ok" : "missing"}`, + ); + } + + return { + basename, + primaryPath: primaryAlias || undefined, + secondaryPath: secondaryAlias || undefined, + }; + } catch (error) { + keepTemp = true; + throw error; + } finally { + if (keepTemp) { + log("warn", args.logLevel, `Keeping subtitle temp dir: ${tempDir}`); + } else { + try { + fs.rmSync(tempDir, { recursive: true, force: true }); + } catch { + // ignore cleanup failures + } + } + } +} + +function checkPickerDependencies(args: Args): void { + if (args.useRofi) { + if (!commandExists("rofi")) fail("Missing dependency: rofi"); + return; + } + + if (!commandExists("fzf")) fail("Missing dependency: fzf"); +} + +function parseArgs( + argv: string[], + scriptName: string, + launcherConfig: LauncherYoutubeSubgenConfig, +): Args { + const envMode = (process.env.SUBMINER_YT_SUBGEN_MODE || "").toLowerCase(); + const defaultMode: YoutubeSubgenMode = + envMode === "preprocess" || envMode === "off" || envMode === "automatic" + ? (envMode as YoutubeSubgenMode) + : launcherConfig.mode + ? launcherConfig.mode + : "automatic"; + const configuredSecondaryLangs = uniqueNormalizedLangCodes( + launcherConfig.secondarySubLanguages ?? [], + ); + const configuredPrimaryLangs = uniqueNormalizedLangCodes( + launcherConfig.primarySubLanguages ?? [], + ); + const primarySubLangs = + configuredPrimaryLangs.length > 0 + ? configuredPrimaryLangs + : [...DEFAULT_YOUTUBE_PRIMARY_SUB_LANGS]; + const secondarySubLangs = + configuredSecondaryLangs.length > 0 + ? configuredSecondaryLangs + : [...DEFAULT_YOUTUBE_SECONDARY_SUB_LANGS]; + const youtubeAudioLangs = uniqueNormalizedLangCodes([ + ...primarySubLangs, + ...secondarySubLangs, + ]); + const parsed: Args = { + backend: "auto", + directory: ".", + recursive: false, + profile: "subminer", + youtubeSubgenMode: defaultMode, + whisperBin: process.env.SUBMINER_WHISPER_BIN || launcherConfig.whisperBin || "", + whisperModel: + process.env.SUBMINER_WHISPER_MODEL || launcherConfig.whisperModel || "", + youtubeSubgenOutDir: + process.env.SUBMINER_YT_SUBGEN_OUT_DIR || DEFAULT_YOUTUBE_SUBGEN_OUT_DIR, + youtubeSubgenAudioFormat: process.env.SUBMINER_YT_SUBGEN_AUDIO_FORMAT || "m4a", + youtubeSubgenKeepTemp: process.env.SUBMINER_YT_SUBGEN_KEEP_TEMP === "1", + youtubePrimarySubLangs: primarySubLangs, + youtubeSecondarySubLangs: secondarySubLangs, + youtubeAudioLangs, + youtubeWhisperSourceLanguage: inferWhisperLanguage(primarySubLangs, "ja"), + useTexthooker: true, + texthookerOnly: false, + useRofi: false, + logLevel: "info", + target: "", + targetKind: "", + }; + + const isValidLogLevel = (value: string): value is LogLevel => + value === "debug" || + value === "info" || + value === "warn" || + value === "error"; + const isValidYoutubeSubgenMode = (value: string): value is YoutubeSubgenMode => + value === "automatic" || value === "preprocess" || value === "off"; + + let i = 0; + while (i < argv.length) { + const arg = argv[i]; + + if (arg === "-b" || arg === "--backend") { + const value = argv[i + 1]; + if (!value) fail("--backend requires a value"); + if (!["auto", "hyprland", "x11", "macos"].includes(value)) { + fail( + `Invalid backend: ${value} (must be auto, hyprland, x11, or macos)`, + ); + } + parsed.backend = value as Backend; + i += 2; + continue; + } + + if (arg === "-d" || arg === "--directory") { + const value = argv[i + 1]; + if (!value) fail("--directory requires a value"); + parsed.directory = value; + i += 2; + continue; + } + + if (arg === "-r" || arg === "--recursive") { + parsed.recursive = true; + i += 1; + continue; + } + + if (arg === "-p" || arg === "--profile") { + const value = argv[i + 1]; + if (!value) fail("--profile requires a value"); + parsed.profile = value; + i += 2; + continue; + } + + if (arg === "--yt-subgen-mode" || arg === "--youtube-subgen-mode") { + const value = (argv[i + 1] || "").toLowerCase(); + if (!isValidYoutubeSubgenMode(value)) { + fail( + `Invalid yt-subgen mode: ${value || ""} (must be automatic, preprocess, or off)`, + ); + } + parsed.youtubeSubgenMode = value; + i += 2; + continue; + } + + if ( + arg.startsWith("--yt-subgen-mode=") || + arg.startsWith("--youtube-subgen-mode=") + ) { + const value = arg.split("=", 2)[1]?.toLowerCase() || ""; + if (!isValidYoutubeSubgenMode(value)) { + fail( + `Invalid yt-subgen mode: ${value || ""} (must be automatic, preprocess, or off)`, + ); + } + parsed.youtubeSubgenMode = value; + i += 1; + continue; + } + + if (arg === "--whisper-bin") { + const value = argv[i + 1]; + if (!value) fail("--whisper-bin requires a value"); + parsed.whisperBin = value; + i += 2; + continue; + } + + if (arg.startsWith("--whisper-bin=")) { + const value = arg.slice("--whisper-bin=".length); + if (!value) fail("--whisper-bin requires a value"); + parsed.whisperBin = value; + i += 1; + continue; + } + + if (arg === "--whisper-model") { + const value = argv[i + 1]; + if (!value) fail("--whisper-model requires a value"); + parsed.whisperModel = value; + i += 2; + continue; + } + + if (arg.startsWith("--whisper-model=")) { + const value = arg.slice("--whisper-model=".length); + if (!value) fail("--whisper-model requires a value"); + parsed.whisperModel = value; + i += 1; + continue; + } + + if (arg === "--yt-subgen-out-dir") { + const value = argv[i + 1]; + if (!value) fail("--yt-subgen-out-dir requires a value"); + parsed.youtubeSubgenOutDir = value; + i += 2; + continue; + } + + if (arg.startsWith("--yt-subgen-out-dir=")) { + const value = arg.slice("--yt-subgen-out-dir=".length); + if (!value) fail("--yt-subgen-out-dir requires a value"); + parsed.youtubeSubgenOutDir = value; + i += 1; + continue; + } + + if (arg === "--yt-subgen-audio-format") { + const value = argv[i + 1]; + if (!value) fail("--yt-subgen-audio-format requires a value"); + parsed.youtubeSubgenAudioFormat = value; + i += 2; + continue; + } + + if (arg.startsWith("--yt-subgen-audio-format=")) { + const value = arg.slice("--yt-subgen-audio-format=".length); + if (!value) fail("--yt-subgen-audio-format requires a value"); + parsed.youtubeSubgenAudioFormat = value; + i += 1; + continue; + } + + if (arg === "--yt-subgen-keep-temp") { + parsed.youtubeSubgenKeepTemp = true; + i += 1; + continue; + } + + if (arg === "-v" || arg === "--verbose") { + parsed.logLevel = "debug"; + i += 1; + continue; + } + + if (arg === "--log-level") { + const value = argv[i + 1]; + if (!value || !isValidLogLevel(value)) { + fail( + `Invalid log level: ${value ?? ""} (must be debug, info, warn, or error)`, + ); + } + parsed.logLevel = value; + i += 2; + continue; + } + + if (arg.startsWith("--log-level=")) { + const value = arg.slice("--log-level=".length); + if (!isValidLogLevel(value)) { + fail( + `Invalid log level: ${value} (must be debug, info, warn, or error)`, + ); + } + parsed.logLevel = value; + i += 1; + continue; + } + + if (arg === "-R" || arg === "--rofi") { + parsed.useRofi = true; + i += 1; + continue; + } + + if (arg === "-T" || arg === "--no-texthooker") { + parsed.useTexthooker = false; + i += 1; + continue; + } + + if (arg === "--texthooker") { + parsed.texthookerOnly = true; + i += 1; + continue; + } + + if (arg === "-h" || arg === "--help") { + process.stdout.write(usage(scriptName)); + process.exit(0); + } + + if (arg === "--") { + i += 1; + break; + } + + if (arg.startsWith("-")) { + fail(`Unknown option: ${arg}`); + } + + break; + } + + const positional = argv.slice(i); + if (positional.length > 0) { + const target = positional[0]; + if (isUrlTarget(target)) { + parsed.target = target; + parsed.targetKind = "url"; + } else { + const resolved = resolvePathMaybe(target); + if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) { + parsed.target = resolved; + parsed.targetKind = "file"; + } else if ( + fs.existsSync(resolved) && + fs.statSync(resolved).isDirectory() + ) { + parsed.directory = resolved; + } else { + fail(`Not a file, directory, or supported URL: ${target}`); + } + } + } + + return parsed; +} + +function startOverlay( + appPath: string, + args: Args, + socketPath: string, +): Promise { + const backend = detectBackend(args.backend); + log( + "info", + args.logLevel, + `Starting SubMiner overlay (backend: ${backend})...`, + ); + + const overlayArgs = ["--start", "--backend", backend, "--socket", socketPath]; + if (args.logLevel === "debug") overlayArgs.push("--verbose"); + else if (args.logLevel !== "info") + overlayArgs.push("--log-level", args.logLevel); + if (args.useTexthooker) overlayArgs.push("--texthooker"); + + state.overlayProc = spawn(appPath, overlayArgs, { stdio: "inherit" }); + + return new Promise((resolve) => { + setTimeout(resolve, 2000); + }); +} + +function launchTexthookerOnly(appPath: string, args: Args): never { + const overlayArgs = ["--texthooker"]; + if (args.logLevel === "debug") overlayArgs.push("--verbose"); + else if (args.logLevel !== "info") + overlayArgs.push("--log-level", args.logLevel); + + log("info", args.logLevel, "Launching texthooker mode..."); + const result = spawnSync(appPath, overlayArgs, { stdio: "inherit" }); + process.exit(result.status ?? 0); +} + +function stopOverlay(args: Args): void { + if (!state.appPath || state.stopRequested) return; + state.stopRequested = true; + + log("info", args.logLevel, "Stopping SubMiner overlay..."); + + const stopArgs = ["--stop"]; + if (args.logLevel === "debug") stopArgs.push("--verbose"); + else if (args.logLevel !== "info") + stopArgs.push("--log-level", args.logLevel); + + spawnSync(state.appPath, stopArgs, { stdio: "ignore" }); + + if (state.overlayProc && !state.overlayProc.killed) { + try { + state.overlayProc.kill("SIGTERM"); + } catch { + // ignore + } + } + + if (state.mpvProc && !state.mpvProc.killed) { + try { + state.mpvProc.kill("SIGTERM"); + } catch { + // ignore + } + } + + for (const child of state.youtubeSubgenChildren) { + if (!child.killed) { + try { + child.kill("SIGTERM"); + } catch { + // ignore + } + } + } + state.youtubeSubgenChildren.clear(); +} + +function waitForSocket( + socketPath: string, + timeoutMs = 10000, +): Promise { + const start = Date.now(); + return new Promise((resolve) => { + const timer = setInterval(() => { + if (fs.existsSync(socketPath)) { + clearInterval(timer); + resolve(true); + return; + } + if (Date.now() - start >= timeoutMs) { + clearInterval(timer); + resolve(false); + } + }, 100); + }); +} + +function startMpv( + target: string, + targetKind: "file" | "url", + args: Args, + socketPath: string, + preloadedSubtitles?: { primaryPath?: string; secondaryPath?: string }, +): void { + if ( + targetKind === "file" && + (!fs.existsSync(target) || !fs.statSync(target).isFile()) + ) { + fail(`Video file not found: ${target}`); + } + + if (targetKind === "url") { + log("info", args.logLevel, `Playing URL: ${target}`); + } else { + log("info", args.logLevel, `Playing: ${path.basename(target)}`); + } + + const mpvArgs: string[] = []; + if (args.profile) mpvArgs.push(`--profile=${args.profile}`); + + if (targetKind === "url" && isYoutubeTarget(target)) { + const subtitleLangs = uniqueNormalizedLangCodes([ + ...args.youtubePrimarySubLangs, + ...args.youtubeSecondarySubLangs, + ]).join(","); + const audioLangs = uniqueNormalizedLangCodes(args.youtubeAudioLangs).join(","); + log("info", args.logLevel, "Applying YouTube playback options"); + log("debug", args.logLevel, `YouTube subtitle langs: ${subtitleLangs}`); + log("debug", args.logLevel, `YouTube audio langs: ${audioLangs}`); + mpvArgs.push( + "--ytdl=yes", + `--ytdl-format=${DEFAULT_YOUTUBE_YTDL_FORMAT}`, + "--ytdl-raw-options=", + `--alang=${audioLangs}`, + ); + + if (args.youtubeSubgenMode === "off") { + mpvArgs.push( + "--sub-auto=fuzzy", + `--slang=${subtitleLangs}`, + "--ytdl-raw-options-append=write-auto-subs=", + "--ytdl-raw-options-append=write-subs=", + "--ytdl-raw-options-append=sub-format=vtt/best", + `--ytdl-raw-options-append=sub-langs=${subtitleLangs}`, + ); + } + } + + if (preloadedSubtitles?.primaryPath) { + mpvArgs.push(`--sub-file=${preloadedSubtitles.primaryPath}`); + } + if (preloadedSubtitles?.secondaryPath) { + mpvArgs.push(`--sub-file=${preloadedSubtitles.secondaryPath}`); + } + + try { + fs.rmSync(socketPath, { force: true }); + } catch { + // ignore + } + + mpvArgs.push(`--input-ipc-server=${socketPath}`); + mpvArgs.push(target); + + state.mpvProc = spawn("mpv", mpvArgs, { stdio: "inherit" }); +} + +async function chooseTarget( + args: Args, + scriptPath: string, +): Promise<{ target: string; kind: "file" | "url" } | null> { + if (args.target) { + return { target: args.target, kind: args.targetKind as "file" | "url" }; + } + + const searchDir = realpathMaybe(resolvePathMaybe(args.directory)); + if (!fs.existsSync(searchDir) || !fs.statSync(searchDir).isDirectory()) { + fail(`Directory not found: ${searchDir}`); + } + + const videos = collectVideos(searchDir, args.recursive); + if (videos.length === 0) { + fail(`No video files found in: ${searchDir}`); + } + + log( + "info", + args.logLevel, + `Browsing: ${searchDir} (${videos.length} videos found)`, + ); + + const selected = args.useRofi + ? showRofiMenu(videos, searchDir, args.recursive, scriptPath, args.logLevel) + : showFzfMenu(videos); + + if (!selected) return null; + return { target: selected, kind: "file" }; +} + +function registerCleanup(args: Args): void { + process.on("SIGINT", () => { + stopOverlay(args); + process.exit(130); + }); + process.on("SIGTERM", () => { + stopOverlay(args); + process.exit(143); + }); +} + +async function main(): Promise { + const scriptName = path.basename(process.argv[1] || "subminer"); + const launcherConfig = loadLauncherYoutubeSubgenConfig(); + const args = parseArgs(process.argv.slice(2), scriptName, launcherConfig); + + log("debug", args.logLevel, `Wrapper log level set to: ${args.logLevel}`); + + const appPath = findAppBinary(process.argv[1] || "subminer"); + if (!appPath) { + if (process.platform === "darwin") { + fail( + "SubMiner app binary not found. Install SubMiner.app to /Applications or ~/Applications, or set SUBMINER_APPIMAGE_PATH.", + ); + } + fail( + "SubMiner AppImage not found. Install to ~/.local/bin/ or set SUBMINER_APPIMAGE_PATH.", + ); + } + state.appPath = appPath; + + if (args.texthookerOnly) { + launchTexthookerOnly(appPath, args); + } + + if (!args.target) { + checkPickerDependencies(args); + } + + const targetChoice = await chooseTarget(args, process.argv[1] || "subminer"); + if (!targetChoice) { + log("info", args.logLevel, "No video selected, exiting"); + process.exit(0); + } + + checkDependencies({ + ...args, + target: targetChoice.target, + targetKind: targetChoice.kind, + }); + + registerCleanup(args); + + const isYoutubeUrl = + targetChoice.kind === "url" && isYoutubeTarget(targetChoice.target); + let preloadedSubtitles: + | { primaryPath?: string; secondaryPath?: string } + | undefined; + + if (isYoutubeUrl && args.youtubeSubgenMode === "preprocess") { + log("info", args.logLevel, "YouTube subtitle mode: preprocess"); + const generated = await generateYoutubeSubtitles(targetChoice.target, args); + preloadedSubtitles = { + primaryPath: generated.primaryPath, + secondaryPath: generated.secondaryPath, + }; + log( + "info", + args.logLevel, + `YouTube preprocess result: primary=${generated.primaryPath ? "ready" : "missing"}, secondary=${generated.secondaryPath ? "ready" : "missing"}`, + ); + } else if (isYoutubeUrl && args.youtubeSubgenMode === "automatic") { + log("info", args.logLevel, "YouTube subtitle mode: automatic (background)"); + } else if (isYoutubeUrl) { + log("info", args.logLevel, "YouTube subtitle mode: off"); + } + + startMpv( + targetChoice.target, + targetChoice.kind, + args, + DEFAULT_SOCKET_PATH, + preloadedSubtitles, + ); + + if (isYoutubeUrl && args.youtubeSubgenMode === "automatic") { + void generateYoutubeSubtitles(targetChoice.target, args, async (lang, subtitlePath) => { + try { + await loadSubtitleIntoMpv( + DEFAULT_SOCKET_PATH, + subtitlePath, + lang === "primary", + args.logLevel, + ); + } catch (error) { + log( + "warn", + args.logLevel, + `Generated subtitle ready but failed to load in mpv: ${(error as Error).message}`, + ); + } + }).catch((error) => { + log( + "warn", + args.logLevel, + `Background subtitle generation failed: ${(error as Error).message}`, + ); + }); + } + + const ready = await waitForSocket(DEFAULT_SOCKET_PATH); + if (ready) { + log( + "info", + args.logLevel, + "MPV IPC socket ready, starting SubMiner overlay", + ); + } else { + log( + "info", + args.logLevel, + "MPV IPC socket not ready after timeout, starting SubMiner overlay anyway", + ); + } + await startOverlay(appPath, args, DEFAULT_SOCKET_PATH); + + await new Promise((resolve) => { + if (!state.mpvProc) { + stopOverlay(args); + resolve(); + return; + } + state.mpvProc.on("exit", (code) => { + stopOverlay(args); + process.exitCode = code ?? 0; + resolve(); + }); + }); +} + +main().catch((error: unknown) => { + const message = error instanceof Error ? error.message : String(error); + fail(message); +}); + +// vim: ft=typescript diff --git a/subminer.rasi b/subminer.rasi new file mode 100644 index 0000000..bae317b --- /dev/null +++ b/subminer.rasi @@ -0,0 +1,125 @@ +* { + rosewater: #f4dbd6; + flamingo: #f0c6c6; + pink: #f5bde6; + mauve: #c6a0f6; + red: #ed8796; + maroon: #ee99a0; + peach: #f5a97f; + yellow: #eed49f; + green: #a6da95; + teal: #8bd5ca; + sky: #91d7e3; + sapphire: #7dc4e4; + blue: #8aadf4; + lavender: #b7bdf8; + text: #cad3f5; + subtext1: #b8c0e0; + subtext0: #a5adcb; + overlay2: #939ab7; + overlay1: #8087a2; + overlay0: #6e738d; + surface2: #5b6078; + surface1: #494d64; + surface0: #363a4f; + base: #24273a; + mantle: #1e2030; + crust: #181926; + + background-color: @base; + text-color: @text; + accent: @mauve; +} + +configuration { + show-icons: true; + icon-theme: "Papirus"; +} + +window { + width: 88%; + height: 88%; + background-color: @base; + border: 2px; + border-color: @mauve; + border-radius: 8px; +} + +mainbox { + children: [inputbar, listview-split]; + background-color: transparent; +} + +inputbar { + children: [prompt, entry]; + background-color: @surface0; + padding: 12px; + border-radius: 4px; + margin: 8px; +} + +prompt { + text-color: @mauve; + background-color: transparent; +} + +entry { + text-color: @text; + background-color: transparent; + placeholder: "Search videos..."; + placeholder-color: @overlay0; +} + +listview-split { + orientation: horizontal; + children: [listview]; + spacing: 8px; + background-color: transparent; +} + +listview { + columns: 1; + lines: 12; + scrollbar: true; + background-color: transparent; + padding: 4px; + fixed-columns: true; +} + +element { + padding: 4px 8px; + background-color: transparent; + border-radius: 4px; +} + +element normal.normal { + background-color: transparent; + text-color: @text; +} + +element selected.normal { + background-color: @surface1; + text-color: @mauve; + border: 2px; + border-color: @mauve; + border-radius: 4px; +} + +element-icon { + size: 128px; + background-color: transparent; + margin: 0px 4px; +} + +element-text { + text-color: inherit; + background-color: transparent; + margin: 50px 0 0 0; +} + +scrollbar { + width: 4px; + handle-color: @surface2; + handle-width: 4px; + background-color: @surface0; +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..352ec68 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "commonjs", + "lib": ["ES2022", "DOM"], + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "vendor"] +} diff --git a/vendor/texthooker-ui/.editorconfig b/vendor/texthooker-ui/.editorconfig new file mode 100644 index 0000000..1e78484 --- /dev/null +++ b/vendor/texthooker-ui/.editorconfig @@ -0,0 +1,10 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = tab +indent_size = 4 +insert_final_newline = true +max_line_length = 120 +trim_trailing_whitespace = true diff --git a/vendor/texthooker-ui/.eslintrc.cjs b/vendor/texthooker-ui/.eslintrc.cjs new file mode 100644 index 0000000..16b09a5 --- /dev/null +++ b/vendor/texthooker-ui/.eslintrc.cjs @@ -0,0 +1,19 @@ +module.exports = { + root: true, + extends: ['plugin:@typescript-eslint/recommended', 'eslint:recommended', 'prettier', 'prettier/@typescript-eslint'], + plugins: ['svelte3', '@typescript-eslint'], + overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }], + parserOptions: { + sourceType: 'module', + ecmaVersion: 2020, + }, + env: { + browser: true, + es2017: true, + node: true, + }, + parser: '@typescript-eslint/parser', + settings: { + 'svelte3/typescript': () => require('typescript'), + }, +}; diff --git a/vendor/texthooker-ui/.gitignore b/vendor/texthooker-ui/.gitignore new file mode 100644 index 0000000..7b36b8c --- /dev/null +++ b/vendor/texthooker-ui/.gitignore @@ -0,0 +1,27 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +# nix flake build output +result diff --git a/vendor/texthooker-ui/.npmrc b/vendor/texthooker-ui/.npmrc new file mode 100644 index 0000000..b6f27f1 --- /dev/null +++ b/vendor/texthooker-ui/.npmrc @@ -0,0 +1 @@ +engine-strict=true diff --git a/vendor/texthooker-ui/.prettierrc b/vendor/texthooker-ui/.prettierrc new file mode 100644 index 0000000..51f6f5e --- /dev/null +++ b/vendor/texthooker-ui/.prettierrc @@ -0,0 +1,6 @@ +{ + "editorconfig": true, + "printWidth": 120, + "singleQuote": true, + "tabWidth": 4 +} diff --git a/vendor/texthooker-ui/.vscode/extensions.json b/vendor/texthooker-ui/.vscode/extensions.json new file mode 100644 index 0000000..28d1e67 --- /dev/null +++ b/vendor/texthooker-ui/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["svelte.svelte-vscode"] +} diff --git a/vendor/texthooker-ui/LICENSE b/vendor/texthooker-ui/LICENSE new file mode 100644 index 0000000..5e300d9 --- /dev/null +++ b/vendor/texthooker-ui/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Renji-xD + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/texthooker-ui/README.md b/vendor/texthooker-ui/README.md new file mode 100644 index 0000000..b8387c9 --- /dev/null +++ b/vendor/texthooker-ui/README.md @@ -0,0 +1,206 @@ +# Texthooker UI + +A web interface for using websocket-based interfaces, such as: +- [Textractor](https://github.com/Artikash/Textractor) with [textractor-websocket](https://github.com/kuroahna/textractor_websocket) or [TextractorSender](https://github.com/KamWithK/TextractorSender) +- [mpv](https://mpv.io) with [mpv_websocket](https://github.com/kuroahna/mpv_websocket) + +An online version of the page can be accessed [here](https://renji-xd.github.io/texthooker-ui/). + +An offline version of the page can be downloaded from the [docs](https://github.com/Renji-XD/texthooker-ui/tree/main/docs) folder (make sure to also download the assets folder and content in case you want to use some of the custom online fonts) or build locally by your own. + +When facing connection issues check the [FAQ](https://github.com/Renji-XD/texthooker-ui#faq) for common issues like ad blocker extensions (uBlock) or wrong websocket urls. + +**Note:** If you are interested in persistent statistics, history and additional mining capabitilies / workflows you may want to checkout [GameSentenceMiner](https://github.com/bpwhelan/GameSentenceMiner) which runs a forked version of this web interface. + +## Building + +``` +# Install pnpm +npm install --global pnpm + +# Install dependencies +pnpm install + +# Build the Page +pnpm run build + +# Optional - serve the Page via local Server +pnpm run preview +``` + +The page can be opened via the index.html inside the "docs" folder and is usable without the need of hosting it via a server. + +## FAQ + +### I can't connect to the websocket with textractor-websocket. + +- [Sadolit's textractor-websocket](https://github.com/sadolit/textractor-websocket) requires that textractor captures at least one line before starting the server - connect manually afterwards. Alternatively try [kuroahna's textractor_websocket](https://github.com/kuroahna/textractor_websocket) which does not have this issue. + +### I can't connect to the websocket with TextractorSender. + +- Make sure you are using the right port which is 9001 + +### I can't connect to the websocket with a different plugin/still can't connect to the websocket with one of the mentioned plugins. + +- Make sure your firewall is not blocking the required ports. You can also check if another extension is interfering by trying out the page with a clean temporary profile and disabled extensions +- Adblocker extensions like uBlock may block connections to localhost / websocket addresses. Try to disable them for this page / running a clean temporary profile to verify the functionality +- **For Brave Users**: If you are using a hosted / online version of the page disable the brave shield for the domain to allow the usage of unsafe websocket connections. Alternatively try out the local / offline version which you can find in the [docs](https://raw.githubusercontent.com/Renji-XD/texthooker-ui/main/docs/index.html) folder + +### Can I use this page with extensions like [Clipboard Inserter](https://github.com/kmltml/clipboard-inserter) or [lap-clipboard-inserter](https://github.com/laplus-sadness/lap-clipboard-inserter)? + +- When "Enable external Clipboard Monitor" is checked text appended as paragraph to the page body will be taken over by the app. Make sure to enable this setting before the actual extension to avoid wrongly pasted elements + +### How do I customize the page with CSS? + +- You can use normal CSS syntax and rules via the "Custom CSS" Field. The content will be appended as style node to the page header + +### How can I delete lines? + +There are multiple ways of deleting a line: + +- Click on the "Delete last Line" Icon in the header +- Click on the "Reset Lines" / "Reset Data" / "Reset All" Icon in the settings menu +- Highlight a line and press the "Delete" key on the keyboard +- Have no text highlighted and press the "Alt" + "Delete" key on the keyboard +- Select a Line for deletion by holding the "CTRL" key (or "command" key on macOS) on the keyboard and double click on it (you can press "Escape" to unselect lines again). Afterwards click on the "Remove selected Lines" icon in the header + +### How can I edit a line? + +- You can modify the content of a line by double clicking on it. Clicking somewhere outside will exit the edit mode. Changes to the text will automatically be reflected in the character counter + +### What is covered by "Undo last Action"? + +_Note_: By default, the undo history is stored in memory only. If you want to keep it across tab reloads, make sure to enable the respective setting. + +- Deleting lines by clicking on the "Remove last line" icon +- Deleting lines by highlighting them and pressing the "Delete" key on the keyboard +- Deleting last line pressing the "Alt" + "Delete" key on the keyboard +- Deleting lines by clicking on the "Remove selected lines" icon +- Editing content of a line + +### What is NOT covered by "Undo last Action"? + +- Deleting data by clicking on the "Reset Lines" / "Reset Data" / "Reset All" icon +- Overwritten data by an import +- Skipping duplicates resulting out of setting changes / changed Data +- Skipping duplicates resulting out of replacement pattern changes / changed Data +- Removed lines by the "Max Lines" setting +- Filtered lines by the "Filter lines without jp content" setting + +### Can I move the data to another device / browser? + +- You can export/import data by clicking on the respective Icon in the settings menu +- Clicking on the icon will export the current time value, notes, displayed lines and action history (settings will not be exported) +- Clicking on the icon while holding the "ALT" key on the keyboard lets you select a previously exported file for import. Note that all existing data will be overwritten +- The same steps can be executed for exporting/importing all Settings/Presets or single Presets via respective Icons + + +### What is the order of settings / transformations on new text lines? +1. Replacements +2. Remove all Whitespace +3. Filter lines without jp content +4. Global or last line Duplicate +5. Max Lines +6. Merge equal Line Starts + +### Can I use the floating window in other browsers except chrome / edge? +- No - (Desktop) Chromium Browser are currently the only browser having the required api implemented + +### What options / actions are applied to the floating Window? +- Applied: Font Size, Online Font, Max Lines (floating window),Reverse Line Order, Preserve Whitespace, Enable Line Animation, AFK Blur, Custom CSS +- Implicit: All Line related text adjustments like replacement patterns, duplicate management, line start merges, jp content filter etc. +- Not available: Vertical Display, Main window actions, timer / stats, keybinds, pasting and line actions like selecting or editing + +### Can i let my dictionary extension exceed the floating Window? + +- No - technically the floating window behaves exactly as any other browser window and therefore it is not possible that content exceeds it + +### Will the floating Window remember the last Position? + +- In Terms of height and width the page will attempt to restore the last used dimensions but the browser may clamp or ignore the values as appropriate to provide a reasonable user experience. The window position itself typically resets when closing the tab or floating window + +### Can i further customize the floating Window? + +- You can apply custom styles as per standard settings. In order to target the floating window content you can use the id selector "#pip-container" (e.g. `#pip-container p {color: red;}` will only apply to paragraphs in the floating window and not the main window). Further customizations like exeeding height, transparency etc. is not possible + + +## Available Keybinds +Note: The actions are only executed when settings/notes are closed, no (confirmation) dialog is displayed and no line is in edit mode. + +| Keybind | Description | +|-|-| +| Delete | Deletes current highlighted lines on the page. | +| Esc | Deselects Lines. | +| Alt + Delete | Deletes last line if no lines are highlighted | +| Alt + a | Deletes all Lines and resets the Timer to 00:00:00. | +| Alt + q | Deletes all Lines. | +| Alt + g | Toggles Websocket Icon. | +| Control + Space | Toggles the Timer. | + + +## Available Settings + +The following section contains explanations and details on the settings you can configure. The settings can be accessed by clicking on the gear at the top right corner. + +
+ Settings List + +| Setting | Description | +|-|-| +| Presets | Allows you to save the current Settings as a Preset and to quickly switch between them.
**Note:** Changes to Settings needs to be manually saved to a Preset by clicking on the Save button. The Dialog to apply Settings to current Lines or Storage like "Store X persistently", "Prevent Last Line Duplicate", "Remove all Whitespace" etc. will not be triggered by switching between Presets. You can still execute them by toggling respective Setting.| +| Replacements | Allows you to configure (regex) patterns and replacements which are getting applied to new lines. See [this documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#description) for more Information. You can change the order of patterns by holding down your mouse on the box and moving it to the item you want to swap the position with +| Window Title | Lets you set the current document title. This can be used with Yomichan to tag your created cards (with the `{document-title}` [marker](https://github.com/FooSoft/yomichan#markers-for-term-cards)). | +| Primary WebSocket | URL of the primary WebSocket to which you want to connect. | +| Secondary WebSocket | URL of the secondary WebSocket to which you want to connect. | +| Font Size | The font size, in number of pixels. | +| Character Milestone | Interval of Characters after which a milestone section will be inserted (< 2 = disabled) | +| Online Font | Lets you select a font from a predefined selection. An internet connection is required in order for this work. | +| Prevent Last Line Duplicate | This will prevent the insertion/pasting of a line if the text is equal to one of the last n configured lines. | +| Max lines | Sets the maximum number of lines allowed. Once the limit is reached, the oldest line is automatically removed when a new one is added. The feature is active only when the limit is greater than 0. Undo Action will enforce this setting on execution. | +| AFK Timer (s) | Number of seconds after which the timer will automatically pause without page interaction (no new line, text selection, or pointer move). | +| Adjust Timer after AFK | If enabled, the timer will be subtracted by the configured `AFK Timer (s)` value whenever the timer was paused due to no page interaction. | +| Enable external Clipboard Monitor | If enabled, this will allow the texthooker page to handle lines pasted by extensions like [Clipboard Inserter](https://github.com/kmltml/clipboard-inserter) or [lap-clipboard-inserter](https://github.com/laplus-sadness/lap-clipboard-inserter). | +| Show Preset Quick Switch | If enabled and you have more than 2 preset stored, this will display a preset selector in the page header for quick access to your presets. | +| Skip Reset Confirmations | If enabled, reset / delete actions like "Reset Lines" will be immediately executed without asking for confirmation. | +| Store Stats persistently | If enabled, the stats (time, speed, etc.) will be stored in your local browser storage. This means the stats will be available after tab reloads, etc. | +| Store Notes persistently | If enabled, the text within the notes section will be stored in your local browser storage. | +| Store Lines persistently | If enabled, the inserted/pasted lines will be stored in your local browser storage. | +| Store Action History persistently | If enabled, the [revertible actions](#what-is-covered-by-undo-last-action) will be stored in your local browser storage. | +| Enable Paste | If enabled, this will allow the user to manually paste new lines to the texthooker page (i.e. with ctrl+v). | +| Block Copy from Page | If enabled, this will block the next line insertion by an external clipboard monitor after copying text from the page | +| Allow Paste during Pause | If enabled, this will allow the page to paste new lines even with a paused timer. | +| Allow new Line during Pause | If enabled, this will allow the page to insert new lines from other sources than pasting even with a paused timer. | +| Autostart Timer by Paste during Pause | If enabled, the time will automatically re-start if it was paused and new lines were pasted. | +| Autostart Timer by Line during Pause | If enabled, the time will automatically re-start if it was paused and new lines were inserted by sources than pasting. | +| Prevent Global Duplicate | This is the same as "Prevent Last Line Duplicate", except the line is checked against the entire document. The line will not be inserted/pasted if it is found anywhere within the document. | +| Merge equal Line Start | If enabled, a new text line will be merged with the previous one in case it starts with the exact same content | +| Filter lines without jp content | If enabled, lines without any Japanese character or punctuation will be ignored and not added to the list of lines. | +| Flash on missed Line | If enabled, the page will flash every time a line is inserted/pasted *if your timer is paused*. These lines will be ignored from stats collection. | +| Display Text vertically | If enabled, the lines will be displayed vertically instead horizontally. | +| Reverse Line Order | If enabled, the new lines will be appended on top (horizontal mode) / left (vertical mode) instead of bottom / right respectively. | +| Preserve Whitespace | If enabled, all existing whitespace (such as spaces, new line characters, etc.) within the line will be fully displayed. If left disabled, newlines and multiple spaces in a row will be collapsed to a singular space. This has no effect if the whitespace is already removed (i.e. with the `Remove all Whitespace` option enabled). | +| Remove all Whitespace | If enabled, all whitespace will be removed from the lines before they are inserted into the page. | +| Show Timer | If enabled, the page will display the current passed (active) time in the header. | +| Show Speed | If enabled, the page will display the current characters per hour in the header. | +| Show Character Count | If enabled, the page will display the current number of displayed characters within the page. | +| Show Line Count | If enabled, the page will display the current number of inserted lines within the page. | +| Blur Stats | If enabled, the displayed stats will be blurred. These stats are unblurred on hover. | +| Enable Line Animation | If enabled, adds Lines with a short animated Transition. | +| Enable AFK Blur | If enabled the screen will be blurred when the afk timer gets activated. You can exit by double clicking/tapping on the page. | +| Restart Timer after AFK Blur | If enabled the timer will automatically restart when you exit the afk blur mode. | +| Continuous Reconnect | If enabled, supresses Connection Error Messages and retries to connect to the Websocket Url continuously. | +| Custom CSS | Lets you insert custom CSS rules to customize the page further. | + +
+ +## Known Issues + +- High number of displayed characters may slow down the page performance due to the current greedy way of counting characters etc. +- The horizontal reading mode performs overall better than the vertical one +- Line breaks added manually during editing a line are sometimes removed +- The page was build with desktop / maximized window usage in mind - following guides (e. g. like [this](https://rentry.co/android-texthook) one) to access the page via tablet or mobile devices / using smaller window / screen sizes may have a limited user experience or functionality + +## Acknowledgements + +- [Anacreon Texthooker](https://anacreondjt.gitlab.io/texthooker.html) +- [MarvNC texthooker-websocket User Script](https://github.com/MarvNC/texthooker-websocket) diff --git a/vendor/texthooker-ui/docs/assets/fonts/ackaisyo.ttf b/vendor/texthooker-ui/docs/assets/fonts/ackaisyo.ttf new file mode 100644 index 0000000..c4ddb30 Binary files /dev/null and b/vendor/texthooker-ui/docs/assets/fonts/ackaisyo.ttf differ diff --git a/vendor/texthooker-ui/docs/assets/fonts/cinecaption226.ttf b/vendor/texthooker-ui/docs/assets/fonts/cinecaption226.ttf new file mode 100644 index 0000000..0ad3f98 Binary files /dev/null and b/vendor/texthooker-ui/docs/assets/fonts/cinecaption226.ttf differ diff --git a/vendor/texthooker-ui/docs/index.html b/vendor/texthooker-ui/docs/index.html new file mode 100644 index 0000000..e1ffc41 --- /dev/null +++ b/vendor/texthooker-ui/docs/index.html @@ -0,0 +1,49 @@ + + + + + + + + + + Texthooker UI + + + + + + + + diff --git a/vendor/texthooker-ui/flake.lock b/vendor/texthooker-ui/flake.lock new file mode 100644 index 0000000..89fa686 --- /dev/null +++ b/vendor/texthooker-ui/flake.lock @@ -0,0 +1,60 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1738680400, + "narHash": "sha256-ooLh+XW8jfa+91F1nhf9OF7qhuA/y1ChLx6lXDNeY5U=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "799ba5bffed04ced7067a91798353d360788b30d", + "type": "github" + }, + "original": { + "id": "nixpkgs", + "ref": "nixos-unstable", + "type": "indirect" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/vendor/texthooker-ui/flake.nix b/vendor/texthooker-ui/flake.nix new file mode 100644 index 0000000..01a2067 --- /dev/null +++ b/vendor/texthooker-ui/flake.nix @@ -0,0 +1,44 @@ +{ + description = "texthooker-ui"; + + inputs = { + nixpkgs.url = "nixpkgs/nixos-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = { + self, + nixpkgs, + flake-utils, + }: + flake-utils.lib.eachDefaultSystem ( + system: let + name = "texthooker-ui"; + src = ./.; + pkgs = import nixpkgs {inherit system;}; + nativeBuildInputs = with pkgs; [nodejs pnpm.configHook]; + in { + # index.html will be located in the nix store + # build with "nix build . --print-out-paths" to get the path + packages.default = pkgs.stdenv.mkDerivation (finalAttrs: { + inherit name nativeBuildInputs src; + pname = name; + + pnpmDeps = pkgs.pnpm.fetchDeps { + pname = name; + inherit src; + hash = "sha256-Wqs3aO4uq/5eqVmp9FFZNVEWo/TpwDib9PJFABmFrbk="; + }; + + installPhase = '' + pnpm run build + cp -r ./docs $out + ''; + }); + + devShell = pkgs.mkShell { + inherit nativeBuildInputs; + }; + } + ); +} diff --git a/vendor/texthooker-ui/index.html b/vendor/texthooker-ui/index.html new file mode 100644 index 0000000..fd1ec31 --- /dev/null +++ b/vendor/texthooker-ui/index.html @@ -0,0 +1,23 @@ + + + + + + + + + + Texthooker UI + + + + + + diff --git a/vendor/texthooker-ui/package.json b/vendor/texthooker-ui/package.json new file mode 100644 index 0000000..7f21a3f --- /dev/null +++ b/vendor/texthooker-ui/package.json @@ -0,0 +1,44 @@ +{ + "author": "Renji-xD", + "devDependencies": { + "@mdi/js": "^7.1.96", + "@sveltejs/vite-plugin-svelte": "^2.0.2", + "@tsconfig/svelte": "^3.0.0", + "@types/dom-screen-wake-lock": "^1.0.0", + "@types/sortablejs": "^1.15.8", + "autoprefixer": "^10.4.13", + "daisyui": "^2.45.0", + "eslint": "^8.30.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-svelte3": "^4.0.0", + "postcss": "^8.4.20", + "postcss-load-config": "^4.0.1", + "prettier": "^2.8.1", + "rollup": "^3.14.0", + "rxjs": "^7.8.0", + "svelte": "^3.55.0", + "svelte-check": "^2.10.2", + "svelte-preprocess": "^5.0.0", + "tailwindcss": "^3.2.4", + "tslib": "^2.4.1", + "typescript": "^4.9.4", + "vite": "^4.0.1", + "vite-plugin-singlefile": "^0.13.2" + }, + "license": "MIT", + "name": "texthooker-ui", + "private": true, + "scripts": { + "build": "vite -c vite.main.config.ts build", + "build:lib": "vite -c vite.lib.config.ts build", + "check": "svelte-check --tsconfig ./tsconfig.json", + "check:types": "tsc --noEmit", + "dev": "vite -c vite.main.config.ts", + "preview": "vite -c vite.main.config.ts preview --host" + }, + "type": "module", + "version": "1.0.0", + "dependencies": { + "sortablejs": "^1.15.2" + } +} diff --git a/vendor/texthooker-ui/pnpm-lock.yaml b/vendor/texthooker-ui/pnpm-lock.yaml new file mode 100644 index 0000000..e86c6e3 --- /dev/null +++ b/vendor/texthooker-ui/pnpm-lock.yaml @@ -0,0 +1,2096 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + sortablejs: + specifier: ^1.15.2 + version: 1.15.2 + devDependencies: + '@mdi/js': + specifier: ^7.1.96 + version: 7.1.96 + '@sveltejs/vite-plugin-svelte': + specifier: ^2.0.2 + version: 2.0.2(svelte@3.55.0)(vite@4.0.1(@types/node@18.11.9)) + '@tsconfig/svelte': + specifier: ^3.0.0 + version: 3.0.0 + '@types/dom-screen-wake-lock': + specifier: ^1.0.0 + version: 1.0.0 + '@types/sortablejs': + specifier: ^1.15.8 + version: 1.15.8 + autoprefixer: + specifier: ^10.4.13 + version: 10.4.13(postcss@8.4.20) + daisyui: + specifier: ^2.45.0 + version: 2.45.0(autoprefixer@10.4.13(postcss@8.4.20))(postcss@8.4.20) + eslint: + specifier: ^8.30.0 + version: 8.30.0 + eslint-config-prettier: + specifier: ^8.5.0 + version: 8.5.0(eslint@8.30.0) + eslint-plugin-svelte3: + specifier: ^4.0.0 + version: 4.0.0(eslint@8.30.0)(svelte@3.55.0) + postcss: + specifier: ^8.4.20 + version: 8.4.20 + postcss-load-config: + specifier: ^4.0.1 + version: 4.0.1(postcss@8.4.20) + prettier: + specifier: ^2.8.1 + version: 2.8.1 + rollup: + specifier: ^3.14.0 + version: 3.14.0 + rxjs: + specifier: ^7.8.0 + version: 7.8.0 + svelte: + specifier: ^3.55.0 + version: 3.55.0 + svelte-check: + specifier: ^2.10.2 + version: 2.10.2(postcss-load-config@4.0.1(postcss@8.4.20))(postcss@8.4.20)(svelte@3.55.0) + svelte-preprocess: + specifier: ^5.0.0 + version: 5.0.0(postcss-load-config@4.0.1(postcss@8.4.20))(postcss@8.4.20)(svelte@3.55.0)(typescript@4.9.4) + tailwindcss: + specifier: ^3.2.4 + version: 3.2.4(postcss@8.4.20) + tslib: + specifier: ^2.4.1 + version: 2.4.1 + typescript: + specifier: ^4.9.4 + version: 4.9.4 + vite: + specifier: ^4.0.1 + version: 4.0.1(@types/node@18.11.9) + vite-plugin-singlefile: + specifier: ^0.13.2 + version: 0.13.2(rollup@3.14.0)(vite@4.0.1(@types/node@18.11.9)) + +packages: + + '@esbuild/android-arm64@0.16.8': + resolution: {integrity: sha512-TGQM/tdy5EV1KoFHu0+cMrKvPR8UBLGEfwS84PTCJ07KVp21Fr488aFEL2TCamz9CxoF1np36kY6XOSdLncg2Q==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.16.8': + resolution: {integrity: sha512-r/qxYWkC3gY+Uq24wZacAUevGGb6d7d8VpyO8R0HGg31LXVi+eUr8XxHLCcmVzAjRjlZsZfzPelGpAKP/DafKg==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.16.8': + resolution: {integrity: sha512-HtA4BNfrf5Nyoz3G2IS3qW4A0yckPJ1NjCMA3SiOw3zS1IfpMkbepDGp/Gdokc/tASFd38IP2uIL3W6bHJzAQw==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.16.8': + resolution: {integrity: sha512-Ks8K1HGFf6LEjLnnVqB/zyaJcv7zMjbJ9txRZAwQwj+bzg8/AP0TmLBMJf9Ahwn6ATnHrhORtpydP8A/mNthXg==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.16.8': + resolution: {integrity: sha512-XXh2070hatspZdG/uPqyHLFlHlGbytvT4JlqZuTU3AizcyOvmatPBSnuARvwCtJMw30wjjehcYY8DWPZ5UF2og==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.16.8': + resolution: {integrity: sha512-6DJuU3+tG9LcHCG/4K3e0AnqmmKWhUc9WDNIhLHOOdleafXwZeFvsqwfyaowNg9yUw5KipRLvV3JJMQ8kT1aPg==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.16.8': + resolution: {integrity: sha512-UcsCaR25C0tZWnoImprPzr7vMEMjLImlTQAIfWXU2wvjF4gBWKO9GEH2JlsKYqBjfWfGgH+HHoGSF/evZbKyxA==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.16.8': + resolution: {integrity: sha512-WTL1v/OhSxgE7rEELRFNWskym0e+hKDMl4JZs7jpQp7218yJPOjdOEWsbzVEYv4G1cbbtWFvp9DtaAONtdCW5w==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.16.8': + resolution: {integrity: sha512-Hn36NbKd6Prh0Ehv1A2ObjfXtN2g81jTpmq1+uRLHrW7CJW+W8GdVgOCVwyeupADUIOOa8bars6IZGcjkwq21w==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.16.8': + resolution: {integrity: sha512-Jt+8YBFR2Pk68oS7E9z9PtmgJrDonGdEW3Camb2plZcztKpu/OxfnxFu8f41+TYpKhzUDm5uNMwqxRH3yDYrsQ==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.16.8': + resolution: {integrity: sha512-P+5J/U/WwPEwcKOFTlTQBK6Gqw4OytpfBvR2V+kBRb5jujwMOQ1aG8iKX14DAwCLks1YHXrXPwXXDPNWEWC59A==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.16.8': + resolution: {integrity: sha512-RDSnljcka9UkVxcLtWv2lG5zcqkZUxIPY47ZSKytv4aoo8b05dH1gnKVWrxBZ+owp3dX48s2lXm6zp3hZHl8qw==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.16.8': + resolution: {integrity: sha512-fNGvIKXyigXYhSflraBsqR/EBhXhuH0/0r7IpU+3reh+8yX3VjowjC/dwmqHDOSQXbcj+HJb1o9kWYi+fJQ/3g==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.16.8': + resolution: {integrity: sha512-CsE1IKyVq/Y55PDnBUvm/e7XfvBgfb5kZxHbIEdmB9xt6cTcBkaVvv8EwLDZuYPkYI60WGl0UwyYYx9B2LLgkg==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.16.8': + resolution: {integrity: sha512-k8RIN4M+GWQAfJ/oGqwxZlpzOyGF8mxp5mH1A1WUJrpSUo4pe0zkq2EoP1KMQbYkjeJi45YsjwK3IOnSoueXbA==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.16.8': + resolution: {integrity: sha512-u0hOo4E9PKyVDmPgJNeip1Tg63wxq+3KBJZKQFblqCl+d5N7n1h7pFwdN5ZzeLaaE645ep8aXzf76ndGnyOypg==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-x64@0.16.8': + resolution: {integrity: sha512-wtENU7TOrnEbUes9aQuNe5PeBM4cTK5dn1W7v6XCr1LatJxAOn6Jn8yDGRsa2uKeEbAS5HeYx7uBAbTBd98OXQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-x64@0.16.8': + resolution: {integrity: sha512-Y0DRVd/PIiutCpAYvRZHkpDNN3tdSQ1oyKy6xoh5TFTElAmzdlO7CO8ABs8689gq47lJ466cQEq9adJrKXrgXg==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/sunos-x64@0.16.8': + resolution: {integrity: sha512-eKg0I3C5z4NTF396Yo9QByXA8DdRS7QiYPFf6JHcED0BanyLW/jX8csUy96wyGivTNrmU0mCOShbeLgzb0eX7w==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.16.8': + resolution: {integrity: sha512-M2BZhsa7z8kMGre96HTMXpm266cfJkbdtcZgVfAL8hY4ptkh5MwNDasl85CDo++ffW2issVT+W/xIGJOr0v2pg==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.16.8': + resolution: {integrity: sha512-mzzHVpnuHQT+IrptiW+uUswEMpVIueYuAkjwt1m4tQuVq9dGWqCA1y9EE+W3S19nMg6JvHMbaRjv3mlCcmi0rA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.16.8': + resolution: {integrity: sha512-Zgzyn7njXpSSe1YGQk03eW4uei4QoZKloe/TBQZXgQHo6ul/ux0BtYdLz3MZ8WDlvqTG3QnLV4+gtV5ordM0+g==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@eslint/eslintrc@1.4.0': + resolution: {integrity: sha512-7yfvXy6MWLgWSFsLhz5yH3iQ52St8cdUY6FoGieKkRDVxuxmrNuUetIuu6cmjNWwniUHiWXjxCr5tTXDrbYS5A==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + '@humanwhocodes/config-array@0.11.8': + resolution: {integrity: sha512-UybHIJzJnR5Qc/MsD9Kr+RpO2h+/P1GhOwdiLPXK5TWk5sgTdu88bTD9UP+CKbPPh5Rni1u0GjAdYQLemG8g+g==} + engines: {node: '>=10.10.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/object-schema@1.2.1': + resolution: {integrity: sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==} + + '@jridgewell/resolve-uri@3.1.0': + resolution: {integrity: sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.4.14': + resolution: {integrity: sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==} + + '@jridgewell/trace-mapping@0.3.17': + resolution: {integrity: sha512-MCNzAp77qzKca9+W/+I0+sEpaUnZoeasnghNeVc41VZCEKaCH73Vq3BZZ/SzWIgrqE4H4ceI+p+b6C0mHf9T4g==} + + '@mdi/js@7.1.96': + resolution: {integrity: sha512-wlrJs6Ryhaa5CqhK3FjTfMRnb/s7HeLkKMFqwQySkK86cdN1TGdzpSM3O4tsmzCA1dYBeTbXvOwSE/Y42cUrvA==} + + '@nodelib/fs.scandir@2.1.5': + resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} + engines: {node: '>= 8'} + + '@nodelib/fs.stat@2.0.5': + resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} + engines: {node: '>= 8'} + + '@nodelib/fs.walk@1.2.8': + resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} + engines: {node: '>= 8'} + + '@sveltejs/vite-plugin-svelte@2.0.2': + resolution: {integrity: sha512-xCEan0/NNpQuL0l5aS42FjwQ6wwskdxC3pW1OeFtEKNZwRg7Evro9lac9HesGP6TdFsTv2xMes5ASQVKbCacxg==} + engines: {node: ^14.18.0 || >= 16} + peerDependencies: + svelte: ^3.54.0 + vite: ^4.0.0 + + '@tsconfig/svelte@3.0.0': + resolution: {integrity: sha512-pYrtLtOwku/7r1i9AMONsJMVYAtk3hzOfiGNekhtq5tYBGA7unMve8RvUclKLMT3PrihvJqUmzsRGh0RP84hKg==} + + '@types/dom-screen-wake-lock@1.0.0': + resolution: {integrity: sha512-3o5jkfJsuhFcKj2EZ3PiEoiQQbB3J/nffsXJBKtyubkBHsX2siS6b4uij3ukr5xgDHsF4BaT9fHo8DneAw/YxA==} + + '@types/node@18.11.9': + resolution: {integrity: sha512-CRpX21/kGdzjOpFsZSkcrXMGIBWMGNIHXXBVFSH+ggkftxg+XYP20TESbh+zFvFj3EQOl5byk0HTRn1IL6hbqg==} + + '@types/pug@2.0.6': + resolution: {integrity: sha512-SnHmG9wN1UVmagJOnyo/qkk0Z7gejYxOYYmaAwr5u2yFYfsupN3sg10kyzN8Hep/2zbHxCnsumxOoRIRMBwKCg==} + + '@types/sass@1.43.1': + resolution: {integrity: sha512-BPdoIt1lfJ6B7rw35ncdwBZrAssjcwzI5LByIrYs+tpXlj/CAkuVdRsgZDdP4lq5EjyWzwxZCqAoFyHKFwp32g==} + + '@types/sortablejs@1.15.8': + resolution: {integrity: sha512-b79830lW+RZfwaztgs1aVPgbasJ8e7AXtZYHTELNXZPsERt4ymJdjV4OccDbHQAvHrCcFpbF78jkm0R6h/pZVg==} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn-node@1.8.2: + resolution: {integrity: sha512-8mt+fslDufLYntIoPAaIMUe/lrbrehIiwmR3t2k9LljIzoigEPF27eLk2hy8zSGzmR/ogr7zbRKINMo1u0yh5A==} + + acorn-walk@7.2.0: + resolution: {integrity: sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==} + engines: {node: '>=0.4.0'} + + acorn@7.4.1: + resolution: {integrity: sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==} + engines: {node: '>=0.4.0'} + hasBin: true + + acorn@8.8.1: + resolution: {integrity: sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==} + engines: {node: '>=0.4.0'} + hasBin: true + + ajv@6.12.6: + resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + anymatch@3.1.3: + resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} + engines: {node: '>= 8'} + + arg@5.0.2: + resolution: {integrity: sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==} + + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + + autoprefixer@10.4.13: + resolution: {integrity: sha512-49vKpMqcZYsJjwotvt4+h/BCjJVnhGwcLpDt5xkcaOG3eLrG/HUYLagrihYsQ+qrIBgIzX1Rw7a6L8I/ZA1Atg==} + engines: {node: ^10 || ^12 || >=14} + hasBin: true + peerDependencies: + postcss: ^8.1.0 + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + binary-extensions@2.2.0: + resolution: {integrity: sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==} + engines: {node: '>=8'} + + brace-expansion@1.1.11: + resolution: {integrity: sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==} + + braces@3.0.2: + resolution: {integrity: sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==} + engines: {node: '>=8'} + + browserslist@4.21.4: + resolution: {integrity: sha512-CBHJJdDmgjl3daYjN5Cp5kbTf1mUhZoS+beLklHIvkOWscs83YAhLlF3Wsh/lciQYAcbBJgTOD44VtG31ZM4Hw==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + buffer-crc32@0.2.13: + resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==} + + callsites@3.1.0: + resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} + engines: {node: '>=6'} + + camelcase-css@2.0.1: + resolution: {integrity: sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==} + engines: {node: '>= 6'} + + caniuse-lite@1.0.30001434: + resolution: {integrity: sha512-aOBHrLmTQw//WFa2rcF1If9fa3ypkC1wzqqiKHgfdrXTWcU8C4gKVZT77eQAPWN1APys3+uQ0Df07rKauXGEYA==} + + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + + chokidar@3.5.3: + resolution: {integrity: sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==} + engines: {node: '>= 8.10.0'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + color-string@1.9.1: + resolution: {integrity: sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==} + + color@4.2.3: + resolution: {integrity: sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==} + engines: {node: '>=12.5.0'} + + concat-map@0.0.1: + resolution: {integrity: sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=} + + cross-spawn@7.0.3: + resolution: {integrity: sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==} + engines: {node: '>= 8'} + + css-selector-tokenizer@0.8.0: + resolution: {integrity: sha512-Jd6Ig3/pe62/qe5SBPTN8h8LeUg/pT4lLgtavPf7updwwHpvFzxvOQBHYj2LZDMjUnBzgvIUSjRcf6oT5HzHFg==} + + cssesc@3.0.0: + resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} + engines: {node: '>=4'} + hasBin: true + + daisyui@2.45.0: + resolution: {integrity: sha512-hAWs7vQLxsWXCd3KMLAMBrZPO6OdU0gIDfOKGmZlyM0ro/pW3J2eGEaBs90Dy8w8L6wD/w1s8Ujd7zG8TYtD3g==} + peerDependencies: + autoprefixer: ^10.0.2 + postcss: ^8.1.6 + + debug@4.3.4: + resolution: {integrity: sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + deepmerge@4.2.2: + resolution: {integrity: sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==} + engines: {node: '>=0.10.0'} + + defined@1.0.1: + resolution: {integrity: sha512-hsBd2qSVCRE+5PmNdHt1uzyrFu5d3RwmFDKzyNZMFq/EwDNJF7Ee5+D5oEKF0hU6LhtoUF1macFvOe4AskQC1Q==} + + detect-indent@6.1.0: + resolution: {integrity: sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==} + engines: {node: '>=8'} + + detective@5.2.1: + resolution: {integrity: sha512-v9XE1zRnz1wRtgurGu0Bs8uHKFSTdteYZNbIPFVhUZ39L/S79ppMpdmVOZAnoz1jfEFodc48n6MX483Xo3t1yw==} + engines: {node: '>=0.8.0'} + hasBin: true + + didyoumean@1.2.2: + resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==} + + dlv@1.1.3: + resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==} + + doctrine@3.0.0: + resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==} + engines: {node: '>=6.0.0'} + + electron-to-chromium@1.4.284: + resolution: {integrity: sha512-M8WEXFuKXMYMVr45fo8mq0wUrrJHheiKZf6BArTKk9ZBYCKJEOU5H8cdWgDT+qCVZf7Na4lVUaZsA+h6uA9+PA==} + + es6-promise@3.3.1: + resolution: {integrity: sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==} + + esbuild@0.16.8: + resolution: {integrity: sha512-RKxRaLYAI5b/IVJ5k8jK3bO2G7cch2ZIZFbfKHbBzpwsWt9+VChcBEndNISBBZ5c3WwekFfkfl11/2QfIGHgDw==} + engines: {node: '>=12'} + hasBin: true + + escalade@3.1.1: + resolution: {integrity: sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==} + engines: {node: '>=6'} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-config-prettier@8.5.0: + resolution: {integrity: sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q==} + hasBin: true + peerDependencies: + eslint: '>=7.0.0' + + eslint-plugin-svelte3@4.0.0: + resolution: {integrity: sha512-OIx9lgaNzD02+MDFNLw0GEUbuovNcglg+wnd/UY0fbZmlQSz7GlQiQ1f+yX0XvC07XPcDOnFcichqI3xCwp71g==} + peerDependencies: + eslint: '>=8.0.0' + svelte: ^3.2.0 + + eslint-scope@7.1.1: + resolution: {integrity: sha512-QKQM/UXpIiHcLqJ5AOyIW7XZmzjkzQXYE54n1++wb0u9V/abW3l9uQnxX8Z5Xd18xyKIMTUAyQ0k1e8pz6LUrw==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-utils@3.0.0: + resolution: {integrity: sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==} + engines: {node: ^10.0.0 || ^12.0.0 || >= 14.0.0} + peerDependencies: + eslint: '>=5' + + eslint-visitor-keys@2.1.0: + resolution: {integrity: sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==} + engines: {node: '>=10'} + + eslint-visitor-keys@3.3.0: + resolution: {integrity: sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint@8.30.0: + resolution: {integrity: sha512-MGADB39QqYuzEGov+F/qb18r4i7DohCDOfatHaxI2iGlPuC65bwG2gxgO+7DkyL38dRFaRH7RaRAgU6JKL9rMQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + hasBin: true + + espree@9.4.1: + resolution: {integrity: sha512-XwctdmTO6SIvCzd9810yyNzIrOrqNYV9Koizx4C/mRhf9uq0o4yHoCEU/670pOxOL/MSraektvSAji79kX90Vg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + esquery@1.4.0: + resolution: {integrity: sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-glob@3.2.12: + resolution: {integrity: sha512-DVj4CQIYYow0BlaelwK1pHl5n5cRSJfM60UA0zK891sVInoPri2Ekj7+e1CT3/3qxXenpI+nBBmQAcJPJgaj4w==} + engines: {node: '>=8.6.0'} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fastparse@1.1.2: + resolution: {integrity: sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ==} + + fastq@1.13.0: + resolution: {integrity: sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==} + + file-entry-cache@6.0.1: + resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==} + engines: {node: ^10.12.0 || >=12.0.0} + + fill-range@7.0.1: + resolution: {integrity: sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==} + engines: {node: '>=8'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@3.0.4: + resolution: {integrity: sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==} + engines: {node: ^10.12.0 || >=12.0.0} + + flatted@3.2.7: + resolution: {integrity: sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==} + + fraction.js@4.2.0: + resolution: {integrity: sha512-MhLuK+2gUcnZe8ZHlaaINnQLl0xRIGRfcGk2yl8xoQAfHrSsL3rYu6FCmBdkdbhc9EPlwyGHewaRsvwRMJtAlA==} + + fs.realpath@1.0.0: + resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} + + fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + function-bind@1.1.1: + resolution: {integrity: sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==} + + glob-parent@5.1.2: + resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} + engines: {node: '>= 6'} + + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + glob@7.2.3: + resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} + + globals@13.19.0: + resolution: {integrity: sha512-dkQ957uSRWHw7CFXLUtUHQI3g3aWApYhfNR2O6jn/907riyTYKVBmxYVROkBcY614FSSeSJh7Xm7SrUWCxvJMQ==} + engines: {node: '>=8'} + + graceful-fs@4.2.10: + resolution: {integrity: sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==} + + grapheme-splitter@1.0.4: + resolution: {integrity: sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==} + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + has@1.0.3: + resolution: {integrity: sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==} + engines: {node: '>= 0.4.0'} + + ignore@5.2.1: + resolution: {integrity: sha512-d2qQLzTJ9WxQftPAuEQpSPmKqzxePjzVbpAVv62AQ64NTL+wR4JkrVqR/LqFsFEUsHDAiId52mJteHDFuDkElA==} + engines: {node: '>= 4'} + + import-fresh@3.3.0: + resolution: {integrity: sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==} + engines: {node: '>=6'} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + inflight@1.0.6: + resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + is-arrayish@0.3.2: + resolution: {integrity: sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==} + + is-binary-path@2.1.0: + resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} + engines: {node: '>=8'} + + is-core-module@2.11.0: + resolution: {integrity: sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + is-path-inside@3.0.3: + resolution: {integrity: sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==} + engines: {node: '>=8'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + js-sdsl@4.2.0: + resolution: {integrity: sha512-dyBIzQBDkCqCu+0upx25Y2jGdbTGxE9fshMsCdK0ViOongpV+n5tXRcZY9v7CaVQ79AGS9KA1KHtojxiM7aXSQ==} + + js-yaml@4.1.0: + resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} + hasBin: true + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + kleur@4.1.5: + resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} + engines: {node: '>=6'} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + + lilconfig@2.0.6: + resolution: {integrity: sha512-9JROoBW7pobfsx+Sq2JsASvCo6Pfo6WWoUW79HuB1BCoBXD4PLWJPqDF6fNj67pqBYTbAHkE57M1kS/+L1neOg==} + engines: {node: '>=10'} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + lodash.merge@4.6.2: + resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} + + magic-string@0.25.9: + resolution: {integrity: sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==} + + magic-string@0.27.0: + resolution: {integrity: sha512-8UnnX2PeRAPZuN12svgR9j7M1uWMovg/CEnIwIG0LFkXSJJe4PdfUGiTGl8V9bsBHFUtfVINcSyYxd7q+kx9fA==} + engines: {node: '>=12'} + + merge2@1.4.1: + resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} + engines: {node: '>= 8'} + + micromatch@4.0.5: + resolution: {integrity: sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==} + engines: {node: '>=8.6'} + + min-indent@1.0.1: + resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==} + engines: {node: '>=4'} + + minimatch@3.1.2: + resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==} + + minimist@1.2.7: + resolution: {integrity: sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==} + + mkdirp@0.5.6: + resolution: {integrity: sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==} + hasBin: true + + mri@1.2.0: + resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==} + engines: {node: '>=4'} + + ms@2.1.2: + resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==} + + nanoid@3.3.4: + resolution: {integrity: sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + + node-releases@2.0.6: + resolution: {integrity: sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg==} + + normalize-path@3.0.0: + resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} + engines: {node: '>=0.10.0'} + + normalize-range@0.1.2: + resolution: {integrity: sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==} + engines: {node: '>=0.10.0'} + + object-hash@3.0.0: + resolution: {integrity: sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==} + engines: {node: '>= 6'} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + optionator@0.9.1: + resolution: {integrity: sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==} + engines: {node: '>= 0.8.0'} + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + parent-module@1.0.1: + resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} + engines: {node: '>=6'} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-is-absolute@1.0.1: + resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} + engines: {node: '>=0.10.0'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + + picocolors@1.0.0: + resolution: {integrity: sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==} + + picomatch@2.3.1: + resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} + engines: {node: '>=8.6'} + + pify@2.3.0: + resolution: {integrity: sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==} + engines: {node: '>=0.10.0'} + + postcss-import@14.1.0: + resolution: {integrity: sha512-flwI+Vgm4SElObFVPpTIT7SU7R3qk2L7PyduMcokiaVKuWv9d/U+Gm/QAd8NDLuykTWTkcrjOeD2Pp1rMeBTGw==} + engines: {node: '>=10.0.0'} + peerDependencies: + postcss: ^8.0.0 + + postcss-js@4.0.0: + resolution: {integrity: sha512-77QESFBwgX4irogGVPgQ5s07vLvFqWr228qZY+w6lW599cRlK/HmnlivnnVUxkjHnCu4J16PDMHcH+e+2HbvTQ==} + engines: {node: ^12 || ^14 || >= 16} + peerDependencies: + postcss: ^8.3.3 + + postcss-load-config@3.1.4: + resolution: {integrity: sha512-6DiM4E7v4coTE4uzA8U//WhtPwyhiim3eyjEMFCnUpzbrkK9wJHgKDT2mR+HbtSrd/NubVaYTOpSpjUl8NQeRg==} + engines: {node: '>= 10'} + peerDependencies: + postcss: '>=8.0.9' + ts-node: '>=9.0.0' + peerDependenciesMeta: + postcss: + optional: true + ts-node: + optional: true + + postcss-load-config@4.0.1: + resolution: {integrity: sha512-vEJIc8RdiBRu3oRAI0ymerOn+7rPuMvRXslTvZUKZonDHFIczxztIyJ1urxM1x9JXEikvpWWTUUqal5j/8QgvA==} + engines: {node: '>= 14'} + peerDependencies: + postcss: '>=8.0.9' + ts-node: '>=9.0.0' + peerDependenciesMeta: + postcss: + optional: true + ts-node: + optional: true + + postcss-nested@6.0.0: + resolution: {integrity: sha512-0DkamqrPcmkBDsLn+vQDIrtkSbNkv5AD/M322ySo9kqFkCIYklym2xEmWkwo+Y3/qZo34tzEPNUw4y7yMCdv5w==} + engines: {node: '>=12.0'} + peerDependencies: + postcss: ^8.2.14 + + postcss-selector-parser@6.0.11: + resolution: {integrity: sha512-zbARubNdogI9j7WY4nQJBiNqQf3sLS3wCP4WfOidu+p28LofJqDH1tcXypGrcmMHhDk2t9wGhCsYe/+szLTy1g==} + engines: {node: '>=4'} + + postcss-value-parser@4.2.0: + resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==} + + postcss@8.4.20: + resolution: {integrity: sha512-6Q04AXR1212bXr5fh03u8aAwbLxAQNGQ/Q1LNa0VfOI06ZAlhPHtQvE4OIdpj4kLThXilalPnmDSOD65DcHt+g==} + engines: {node: ^10 || ^12 || >=14} + + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + prettier@2.8.1: + resolution: {integrity: sha512-lqGoSJBQNJidqCHE80vqZJHWHRFoNYsSpP9AjFhlhi9ODCJA541svILes/+/1GM3VaL/abZi7cpFzOpdR9UPKg==} + engines: {node: '>=10.13.0'} + hasBin: true + + punycode@2.1.1: + resolution: {integrity: sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==} + engines: {node: '>=6'} + + queue-microtask@1.2.3: + resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + + quick-lru@5.1.1: + resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==} + engines: {node: '>=10'} + + read-cache@1.0.0: + resolution: {integrity: sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==} + + readdirp@3.6.0: + resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} + engines: {node: '>=8.10.0'} + + regexpp@3.2.0: + resolution: {integrity: sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==} + engines: {node: '>=8'} + + resolve-from@4.0.0: + resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} + engines: {node: '>=4'} + + resolve@1.22.1: + resolution: {integrity: sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==} + hasBin: true + + reusify@1.0.4: + resolution: {integrity: sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + + rimraf@2.7.1: + resolution: {integrity: sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==} + hasBin: true + + rimraf@3.0.2: + resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==} + hasBin: true + + rollup@3.14.0: + resolution: {integrity: sha512-o23sdgCLcLSe3zIplT9nQ1+r97okuaiR+vmAPZPTDYB7/f3tgWIYNyiQveMsZwshBT0is4eGax/HH83Q7CG+/Q==} + engines: {node: '>=14.18.0', npm: '>=8.0.0'} + hasBin: true + + run-parallel@1.2.0: + resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + + rxjs@7.8.0: + resolution: {integrity: sha512-F2+gxDshqmIub1KdvZkaEfGDwLNpPvk9Fs6LD/MyQxNgMds/WH9OdDDXOmxUZpME+iSK3rQCctkL0DYyytUqMg==} + + sade@1.8.1: + resolution: {integrity: sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==} + engines: {node: '>=6'} + + sander@0.5.1: + resolution: {integrity: sha512-3lVqBir7WuKDHGrKRDn/1Ye3kwpXaDOMsiRP1wd6wpZW56gJhsbp5RqQpA6JG/P+pkXizygnr1dKR8vzWaVsfA==} + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + simple-swizzle@0.2.2: + resolution: {integrity: sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==} + + sorcery@0.10.0: + resolution: {integrity: sha512-R5ocFmKZQFfSTstfOtHjJuAwbpGyf9qjQa1egyhvXSbM7emjrtLXtGdZsDJDABC85YBfVvrOiGWKSYXPKdvP1g==} + hasBin: true + + sortablejs@1.15.2: + resolution: {integrity: sha512-FJF5jgdfvoKn1MAKSdGs33bIqLi3LmsgVTliuX6iITj834F+JRQZN90Z93yql8h0K2t0RwDPBmxwlbZfDcxNZA==} + + source-map-js@1.0.2: + resolution: {integrity: sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==} + engines: {node: '>=0.10.0'} + + sourcemap-codec@1.4.8: + resolution: {integrity: sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==} + deprecated: Please use @jridgewell/sourcemap-codec instead + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-indent@3.0.0: + resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==} + engines: {node: '>=8'} + + strip-json-comments@3.1.1: + resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} + engines: {node: '>=8'} + + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + + svelte-check@2.10.2: + resolution: {integrity: sha512-h1Tuiir0m8J5yqN+Vx6qgKKk1L871e6a9o7rMwVWfu8Qs6Wg7x2R+wcxS3SO3VpW5JCxCat90rxPsZMYgz+HaQ==} + hasBin: true + peerDependencies: + svelte: ^3.24.0 + + svelte-hmr@0.15.1: + resolution: {integrity: sha512-BiKB4RZ8YSwRKCNVdNxK/GfY+r4Kjgp9jCLEy0DuqAKfmQtpL38cQK3afdpjw4sqSs4PLi3jIPJIFp259NkZtA==} + engines: {node: ^12.20 || ^14.13.1 || >= 16} + peerDependencies: + svelte: '>=3.19.0' + + svelte-preprocess@4.10.7: + resolution: {integrity: sha512-sNPBnqYD6FnmdBrUmBCaqS00RyCsCpj2BG58A1JBswNF7b0OKviwxqVrOL/CKyJrLSClrSeqQv5BXNg2RUbPOw==} + engines: {node: '>= 9.11.2'} + peerDependencies: + '@babel/core': ^7.10.2 + coffeescript: ^2.5.1 + less: ^3.11.3 || ^4.0.0 + node-sass: '*' + postcss: ^7 || ^8 + postcss-load-config: ^2.1.0 || ^3.0.0 || ^4.0.0 + pug: ^3.0.0 + sass: ^1.26.8 + stylus: ^0.55.0 + sugarss: ^2.0.0 + svelte: ^3.23.0 + typescript: ^3.9.5 || ^4.0.0 + peerDependenciesMeta: + '@babel/core': + optional: true + coffeescript: + optional: true + less: + optional: true + node-sass: + optional: true + postcss: + optional: true + postcss-load-config: + optional: true + pug: + optional: true + sass: + optional: true + stylus: + optional: true + sugarss: + optional: true + typescript: + optional: true + + svelte-preprocess@5.0.0: + resolution: {integrity: sha512-q7lpa7i2FBu8Pa+G0MmuQQWETBwCKgsGmuq1Sf6n8q4uaG9ZLcLP0Y+etC6bF4sE6EbLxfiI38zV6RfPe3RSfg==} + engines: {node: '>= 14.10.0'} + peerDependencies: + '@babel/core': ^7.10.2 + coffeescript: ^2.5.1 + less: ^3.11.3 || ^4.0.0 + postcss: ^7 || ^8 + postcss-load-config: ^2.1.0 || ^3.0.0 || ^4.0.0 + pug: ^3.0.0 + sass: ^1.26.8 + stylus: ^0.55.0 + sugarss: ^2.0.0 || ^3.0.0 || ^4.0.0 + svelte: ^3.23.0 + typescript: ^3.9.5 || ^4.0.0 + peerDependenciesMeta: + '@babel/core': + optional: true + coffeescript: + optional: true + less: + optional: true + postcss: + optional: true + postcss-load-config: + optional: true + pug: + optional: true + sass: + optional: true + stylus: + optional: true + sugarss: + optional: true + typescript: + optional: true + + svelte@3.55.0: + resolution: {integrity: sha512-uGu2FVMlOuey4JoKHKrpZFkoYyj0VLjJdz47zX5+gVK5odxHM40RVhar9/iK2YFRVxvfg9FkhfVlR0sjeIrOiA==} + engines: {node: '>= 8'} + + tailwindcss@3.2.4: + resolution: {integrity: sha512-AhwtHCKMtR71JgeYDaswmZXhPcW9iuI9Sp2LvZPo9upDZ7231ZJ7eA9RaURbhpXGVlrjX4cFNlB4ieTetEb7hQ==} + engines: {node: '>=12.13.0'} + hasBin: true + peerDependencies: + postcss: ^8.0.9 + + text-table@0.2.0: + resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==} + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + tslib@2.4.1: + resolution: {integrity: sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==} + + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + type-fest@0.20.2: + resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==} + engines: {node: '>=10'} + + typescript@4.9.4: + resolution: {integrity: sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg==} + engines: {node: '>=4.2.0'} + hasBin: true + + update-browserslist-db@1.0.10: + resolution: {integrity: sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + vite-plugin-singlefile@0.13.2: + resolution: {integrity: sha512-HAvrU9mxasNMn/YF0Hb9NjsWDstCWe4iLQ6IR5ppOiNMvXjcyqU3C9SDQ32xnonx3Y04JUGjD2bGiT6q0S9T8w==} + engines: {node: ^14.18.0 || >=16.0.0} + peerDependencies: + rollup: '>=2.79.0' + vite: '>=3.2.0' + + vite@4.0.1: + resolution: {integrity: sha512-kZQPzbDau35iWOhy3CpkrRC7It+HIHtulAzBhMqzGHKRf/4+vmh8rPDDdv98SWQrFWo6//3ozwsRmwQIPZsK9g==} + engines: {node: ^14.18.0 || >=16.0.0} + hasBin: true + peerDependencies: + '@types/node': '>= 14' + less: '*' + sass: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + sass: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + + vitefu@0.2.3: + resolution: {integrity: sha512-75l7TTuU8isAhz1QFtNKjDkqjxvndfMC1AfIMjJ0ZQ59ZD0Ow9QOIsJJX16Wv9PS8f+zMzp6fHy5cCbKG/yVUQ==} + peerDependencies: + vite: ^3.0.0 || ^4.0.0 + peerDependenciesMeta: + vite: + optional: true + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + word-wrap@1.2.3: + resolution: {integrity: sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==} + engines: {node: '>=0.10.0'} + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + + yaml@1.10.2: + resolution: {integrity: sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==} + engines: {node: '>= 6'} + + yaml@2.1.3: + resolution: {integrity: sha512-AacA8nRULjKMX2DvWvOAdBZMOfQlypSFkjcOcu9FalllIDJ1kvlREzcdIZmidQUqqeMv7jorHjq2HlLv/+c2lg==} + engines: {node: '>= 14'} + + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + +snapshots: + + '@esbuild/android-arm64@0.16.8': + optional: true + + '@esbuild/android-arm@0.16.8': + optional: true + + '@esbuild/android-x64@0.16.8': + optional: true + + '@esbuild/darwin-arm64@0.16.8': + optional: true + + '@esbuild/darwin-x64@0.16.8': + optional: true + + '@esbuild/freebsd-arm64@0.16.8': + optional: true + + '@esbuild/freebsd-x64@0.16.8': + optional: true + + '@esbuild/linux-arm64@0.16.8': + optional: true + + '@esbuild/linux-arm@0.16.8': + optional: true + + '@esbuild/linux-ia32@0.16.8': + optional: true + + '@esbuild/linux-loong64@0.16.8': + optional: true + + '@esbuild/linux-mips64el@0.16.8': + optional: true + + '@esbuild/linux-ppc64@0.16.8': + optional: true + + '@esbuild/linux-riscv64@0.16.8': + optional: true + + '@esbuild/linux-s390x@0.16.8': + optional: true + + '@esbuild/linux-x64@0.16.8': + optional: true + + '@esbuild/netbsd-x64@0.16.8': + optional: true + + '@esbuild/openbsd-x64@0.16.8': + optional: true + + '@esbuild/sunos-x64@0.16.8': + optional: true + + '@esbuild/win32-arm64@0.16.8': + optional: true + + '@esbuild/win32-ia32@0.16.8': + optional: true + + '@esbuild/win32-x64@0.16.8': + optional: true + + '@eslint/eslintrc@1.4.0': + dependencies: + ajv: 6.12.6 + debug: 4.3.4 + espree: 9.4.1 + globals: 13.19.0 + ignore: 5.2.1 + import-fresh: 3.3.0 + js-yaml: 4.1.0 + minimatch: 3.1.2 + strip-json-comments: 3.1.1 + transitivePeerDependencies: + - supports-color + + '@humanwhocodes/config-array@0.11.8': + dependencies: + '@humanwhocodes/object-schema': 1.2.1 + debug: 4.3.4 + minimatch: 3.1.2 + transitivePeerDependencies: + - supports-color + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/object-schema@1.2.1': {} + + '@jridgewell/resolve-uri@3.1.0': {} + + '@jridgewell/sourcemap-codec@1.4.14': {} + + '@jridgewell/trace-mapping@0.3.17': + dependencies: + '@jridgewell/resolve-uri': 3.1.0 + '@jridgewell/sourcemap-codec': 1.4.14 + + '@mdi/js@7.1.96': {} + + '@nodelib/fs.scandir@2.1.5': + dependencies: + '@nodelib/fs.stat': 2.0.5 + run-parallel: 1.2.0 + + '@nodelib/fs.stat@2.0.5': {} + + '@nodelib/fs.walk@1.2.8': + dependencies: + '@nodelib/fs.scandir': 2.1.5 + fastq: 1.13.0 + + '@sveltejs/vite-plugin-svelte@2.0.2(svelte@3.55.0)(vite@4.0.1(@types/node@18.11.9))': + dependencies: + debug: 4.3.4 + deepmerge: 4.2.2 + kleur: 4.1.5 + magic-string: 0.27.0 + svelte: 3.55.0 + svelte-hmr: 0.15.1(svelte@3.55.0) + vite: 4.0.1(@types/node@18.11.9) + vitefu: 0.2.3(vite@4.0.1(@types/node@18.11.9)) + transitivePeerDependencies: + - supports-color + + '@tsconfig/svelte@3.0.0': {} + + '@types/dom-screen-wake-lock@1.0.0': {} + + '@types/node@18.11.9': {} + + '@types/pug@2.0.6': {} + + '@types/sass@1.43.1': + dependencies: + '@types/node': 18.11.9 + + '@types/sortablejs@1.15.8': {} + + acorn-jsx@5.3.2(acorn@8.8.1): + dependencies: + acorn: 8.8.1 + + acorn-node@1.8.2: + dependencies: + acorn: 7.4.1 + acorn-walk: 7.2.0 + xtend: 4.0.2 + + acorn-walk@7.2.0: {} + + acorn@7.4.1: {} + + acorn@8.8.1: {} + + ajv@6.12.6: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + ansi-regex@5.0.1: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + anymatch@3.1.3: + dependencies: + normalize-path: 3.0.0 + picomatch: 2.3.1 + + arg@5.0.2: {} + + argparse@2.0.1: {} + + autoprefixer@10.4.13(postcss@8.4.20): + dependencies: + browserslist: 4.21.4 + caniuse-lite: 1.0.30001434 + fraction.js: 4.2.0 + normalize-range: 0.1.2 + picocolors: 1.0.0 + postcss: 8.4.20 + postcss-value-parser: 4.2.0 + + balanced-match@1.0.2: {} + + binary-extensions@2.2.0: {} + + brace-expansion@1.1.11: + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + + braces@3.0.2: + dependencies: + fill-range: 7.0.1 + + browserslist@4.21.4: + dependencies: + caniuse-lite: 1.0.30001434 + electron-to-chromium: 1.4.284 + node-releases: 2.0.6 + update-browserslist-db: 1.0.10(browserslist@4.21.4) + + buffer-crc32@0.2.13: {} + + callsites@3.1.0: {} + + camelcase-css@2.0.1: {} + + caniuse-lite@1.0.30001434: {} + + chalk@4.1.2: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + + chokidar@3.5.3: + dependencies: + anymatch: 3.1.3 + braces: 3.0.2 + glob-parent: 5.1.2 + is-binary-path: 2.1.0 + is-glob: 4.0.3 + normalize-path: 3.0.0 + readdirp: 3.6.0 + optionalDependencies: + fsevents: 2.3.2 + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + color-string@1.9.1: + dependencies: + color-name: 1.1.4 + simple-swizzle: 0.2.2 + + color@4.2.3: + dependencies: + color-convert: 2.0.1 + color-string: 1.9.1 + + concat-map@0.0.1: {} + + cross-spawn@7.0.3: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + css-selector-tokenizer@0.8.0: + dependencies: + cssesc: 3.0.0 + fastparse: 1.1.2 + + cssesc@3.0.0: {} + + daisyui@2.45.0(autoprefixer@10.4.13(postcss@8.4.20))(postcss@8.4.20): + dependencies: + autoprefixer: 10.4.13(postcss@8.4.20) + color: 4.2.3 + css-selector-tokenizer: 0.8.0 + postcss: 8.4.20 + postcss-js: 4.0.0(postcss@8.4.20) + tailwindcss: 3.2.4(postcss@8.4.20) + transitivePeerDependencies: + - ts-node + + debug@4.3.4: + dependencies: + ms: 2.1.2 + + deep-is@0.1.4: {} + + deepmerge@4.2.2: {} + + defined@1.0.1: {} + + detect-indent@6.1.0: {} + + detective@5.2.1: + dependencies: + acorn-node: 1.8.2 + defined: 1.0.1 + minimist: 1.2.7 + + didyoumean@1.2.2: {} + + dlv@1.1.3: {} + + doctrine@3.0.0: + dependencies: + esutils: 2.0.3 + + electron-to-chromium@1.4.284: {} + + es6-promise@3.3.1: {} + + esbuild@0.16.8: + optionalDependencies: + '@esbuild/android-arm': 0.16.8 + '@esbuild/android-arm64': 0.16.8 + '@esbuild/android-x64': 0.16.8 + '@esbuild/darwin-arm64': 0.16.8 + '@esbuild/darwin-x64': 0.16.8 + '@esbuild/freebsd-arm64': 0.16.8 + '@esbuild/freebsd-x64': 0.16.8 + '@esbuild/linux-arm': 0.16.8 + '@esbuild/linux-arm64': 0.16.8 + '@esbuild/linux-ia32': 0.16.8 + '@esbuild/linux-loong64': 0.16.8 + '@esbuild/linux-mips64el': 0.16.8 + '@esbuild/linux-ppc64': 0.16.8 + '@esbuild/linux-riscv64': 0.16.8 + '@esbuild/linux-s390x': 0.16.8 + '@esbuild/linux-x64': 0.16.8 + '@esbuild/netbsd-x64': 0.16.8 + '@esbuild/openbsd-x64': 0.16.8 + '@esbuild/sunos-x64': 0.16.8 + '@esbuild/win32-arm64': 0.16.8 + '@esbuild/win32-ia32': 0.16.8 + '@esbuild/win32-x64': 0.16.8 + + escalade@3.1.1: {} + + escape-string-regexp@4.0.0: {} + + eslint-config-prettier@8.5.0(eslint@8.30.0): + dependencies: + eslint: 8.30.0 + + eslint-plugin-svelte3@4.0.0(eslint@8.30.0)(svelte@3.55.0): + dependencies: + eslint: 8.30.0 + svelte: 3.55.0 + + eslint-scope@7.1.1: + dependencies: + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-utils@3.0.0(eslint@8.30.0): + dependencies: + eslint: 8.30.0 + eslint-visitor-keys: 2.1.0 + + eslint-visitor-keys@2.1.0: {} + + eslint-visitor-keys@3.3.0: {} + + eslint@8.30.0: + dependencies: + '@eslint/eslintrc': 1.4.0 + '@humanwhocodes/config-array': 0.11.8 + '@humanwhocodes/module-importer': 1.0.1 + '@nodelib/fs.walk': 1.2.8 + ajv: 6.12.6 + chalk: 4.1.2 + cross-spawn: 7.0.3 + debug: 4.3.4 + doctrine: 3.0.0 + escape-string-regexp: 4.0.0 + eslint-scope: 7.1.1 + eslint-utils: 3.0.0(eslint@8.30.0) + eslint-visitor-keys: 3.3.0 + espree: 9.4.1 + esquery: 1.4.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 6.0.1 + find-up: 5.0.0 + glob-parent: 6.0.2 + globals: 13.19.0 + grapheme-splitter: 1.0.4 + ignore: 5.2.1 + import-fresh: 3.3.0 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + is-path-inside: 3.0.3 + js-sdsl: 4.2.0 + js-yaml: 4.1.0 + json-stable-stringify-without-jsonify: 1.0.1 + levn: 0.4.1 + lodash.merge: 4.6.2 + minimatch: 3.1.2 + natural-compare: 1.4.0 + optionator: 0.9.1 + regexpp: 3.2.0 + strip-ansi: 6.0.1 + strip-json-comments: 3.1.1 + text-table: 0.2.0 + transitivePeerDependencies: + - supports-color + + espree@9.4.1: + dependencies: + acorn: 8.8.1 + acorn-jsx: 5.3.2(acorn@8.8.1) + eslint-visitor-keys: 3.3.0 + + esquery@1.4.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + + esutils@2.0.3: {} + + fast-deep-equal@3.1.3: {} + + fast-glob@3.2.12: + dependencies: + '@nodelib/fs.stat': 2.0.5 + '@nodelib/fs.walk': 1.2.8 + glob-parent: 5.1.2 + merge2: 1.4.1 + micromatch: 4.0.5 + + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + + fastparse@1.1.2: {} + + fastq@1.13.0: + dependencies: + reusify: 1.0.4 + + file-entry-cache@6.0.1: + dependencies: + flat-cache: 3.0.4 + + fill-range@7.0.1: + dependencies: + to-regex-range: 5.0.1 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@3.0.4: + dependencies: + flatted: 3.2.7 + rimraf: 3.0.2 + + flatted@3.2.7: {} + + fraction.js@4.2.0: {} + + fs.realpath@1.0.0: {} + + fsevents@2.3.2: + optional: true + + function-bind@1.1.1: {} + + glob-parent@5.1.2: + dependencies: + is-glob: 4.0.3 + + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + glob@7.2.3: + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 3.1.2 + once: 1.4.0 + path-is-absolute: 1.0.1 + + globals@13.19.0: + dependencies: + type-fest: 0.20.2 + + graceful-fs@4.2.10: {} + + grapheme-splitter@1.0.4: {} + + has-flag@4.0.0: {} + + has@1.0.3: + dependencies: + function-bind: 1.1.1 + + ignore@5.2.1: {} + + import-fresh@3.3.0: + dependencies: + parent-module: 1.0.1 + resolve-from: 4.0.0 + + imurmurhash@0.1.4: {} + + inflight@1.0.6: + dependencies: + once: 1.4.0 + wrappy: 1.0.2 + + inherits@2.0.4: {} + + is-arrayish@0.3.2: {} + + is-binary-path@2.1.0: + dependencies: + binary-extensions: 2.2.0 + + is-core-module@2.11.0: + dependencies: + has: 1.0.3 + + is-extglob@2.1.1: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-number@7.0.0: {} + + is-path-inside@3.0.3: {} + + isexe@2.0.0: {} + + js-sdsl@4.2.0: {} + + js-yaml@4.1.0: + dependencies: + argparse: 2.0.1 + + json-schema-traverse@0.4.1: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + + kleur@4.1.5: {} + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + + lilconfig@2.0.6: {} + + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + + lodash.merge@4.6.2: {} + + magic-string@0.25.9: + dependencies: + sourcemap-codec: 1.4.8 + + magic-string@0.27.0: + dependencies: + '@jridgewell/sourcemap-codec': 1.4.14 + + merge2@1.4.1: {} + + micromatch@4.0.5: + dependencies: + braces: 3.0.2 + picomatch: 2.3.1 + + min-indent@1.0.1: {} + + minimatch@3.1.2: + dependencies: + brace-expansion: 1.1.11 + + minimist@1.2.7: {} + + mkdirp@0.5.6: + dependencies: + minimist: 1.2.7 + + mri@1.2.0: {} + + ms@2.1.2: {} + + nanoid@3.3.4: {} + + natural-compare@1.4.0: {} + + node-releases@2.0.6: {} + + normalize-path@3.0.0: {} + + normalize-range@0.1.2: {} + + object-hash@3.0.0: {} + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + optionator@0.9.1: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.3 + + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + + parent-module@1.0.1: + dependencies: + callsites: 3.1.0 + + path-exists@4.0.0: {} + + path-is-absolute@1.0.1: {} + + path-key@3.1.1: {} + + path-parse@1.0.7: {} + + picocolors@1.0.0: {} + + picomatch@2.3.1: {} + + pify@2.3.0: {} + + postcss-import@14.1.0(postcss@8.4.20): + dependencies: + postcss: 8.4.20 + postcss-value-parser: 4.2.0 + read-cache: 1.0.0 + resolve: 1.22.1 + + postcss-js@4.0.0(postcss@8.4.20): + dependencies: + camelcase-css: 2.0.1 + postcss: 8.4.20 + + postcss-load-config@3.1.4(postcss@8.4.20): + dependencies: + lilconfig: 2.0.6 + yaml: 1.10.2 + optionalDependencies: + postcss: 8.4.20 + + postcss-load-config@4.0.1(postcss@8.4.20): + dependencies: + lilconfig: 2.0.6 + yaml: 2.1.3 + optionalDependencies: + postcss: 8.4.20 + + postcss-nested@6.0.0(postcss@8.4.20): + dependencies: + postcss: 8.4.20 + postcss-selector-parser: 6.0.11 + + postcss-selector-parser@6.0.11: + dependencies: + cssesc: 3.0.0 + util-deprecate: 1.0.2 + + postcss-value-parser@4.2.0: {} + + postcss@8.4.20: + dependencies: + nanoid: 3.3.4 + picocolors: 1.0.0 + source-map-js: 1.0.2 + + prelude-ls@1.2.1: {} + + prettier@2.8.1: {} + + punycode@2.1.1: {} + + queue-microtask@1.2.3: {} + + quick-lru@5.1.1: {} + + read-cache@1.0.0: + dependencies: + pify: 2.3.0 + + readdirp@3.6.0: + dependencies: + picomatch: 2.3.1 + + regexpp@3.2.0: {} + + resolve-from@4.0.0: {} + + resolve@1.22.1: + dependencies: + is-core-module: 2.11.0 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + + reusify@1.0.4: {} + + rimraf@2.7.1: + dependencies: + glob: 7.2.3 + + rimraf@3.0.2: + dependencies: + glob: 7.2.3 + + rollup@3.14.0: + optionalDependencies: + fsevents: 2.3.2 + + run-parallel@1.2.0: + dependencies: + queue-microtask: 1.2.3 + + rxjs@7.8.0: + dependencies: + tslib: 2.4.1 + + sade@1.8.1: + dependencies: + mri: 1.2.0 + + sander@0.5.1: + dependencies: + es6-promise: 3.3.1 + graceful-fs: 4.2.10 + mkdirp: 0.5.6 + rimraf: 2.7.1 + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + simple-swizzle@0.2.2: + dependencies: + is-arrayish: 0.3.2 + + sorcery@0.10.0: + dependencies: + buffer-crc32: 0.2.13 + minimist: 1.2.7 + sander: 0.5.1 + sourcemap-codec: 1.4.8 + + sortablejs@1.15.2: {} + + source-map-js@1.0.2: {} + + sourcemap-codec@1.4.8: {} + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-indent@3.0.0: + dependencies: + min-indent: 1.0.1 + + strip-json-comments@3.1.1: {} + + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + + supports-preserve-symlinks-flag@1.0.0: {} + + svelte-check@2.10.2(postcss-load-config@4.0.1(postcss@8.4.20))(postcss@8.4.20)(svelte@3.55.0): + dependencies: + '@jridgewell/trace-mapping': 0.3.17 + chokidar: 3.5.3 + fast-glob: 3.2.12 + import-fresh: 3.3.0 + picocolors: 1.0.0 + sade: 1.8.1 + svelte: 3.55.0 + svelte-preprocess: 4.10.7(postcss-load-config@4.0.1(postcss@8.4.20))(postcss@8.4.20)(svelte@3.55.0)(typescript@4.9.4) + typescript: 4.9.4 + transitivePeerDependencies: + - '@babel/core' + - coffeescript + - less + - node-sass + - postcss + - postcss-load-config + - pug + - sass + - stylus + - sugarss + + svelte-hmr@0.15.1(svelte@3.55.0): + dependencies: + svelte: 3.55.0 + + svelte-preprocess@4.10.7(postcss-load-config@4.0.1(postcss@8.4.20))(postcss@8.4.20)(svelte@3.55.0)(typescript@4.9.4): + dependencies: + '@types/pug': 2.0.6 + '@types/sass': 1.43.1 + detect-indent: 6.1.0 + magic-string: 0.25.9 + sorcery: 0.10.0 + strip-indent: 3.0.0 + svelte: 3.55.0 + optionalDependencies: + postcss: 8.4.20 + postcss-load-config: 4.0.1(postcss@8.4.20) + typescript: 4.9.4 + + svelte-preprocess@5.0.0(postcss-load-config@4.0.1(postcss@8.4.20))(postcss@8.4.20)(svelte@3.55.0)(typescript@4.9.4): + dependencies: + '@types/pug': 2.0.6 + '@types/sass': 1.43.1 + detect-indent: 6.1.0 + magic-string: 0.27.0 + sorcery: 0.10.0 + strip-indent: 3.0.0 + svelte: 3.55.0 + optionalDependencies: + postcss: 8.4.20 + postcss-load-config: 4.0.1(postcss@8.4.20) + typescript: 4.9.4 + + svelte@3.55.0: {} + + tailwindcss@3.2.4(postcss@8.4.20): + dependencies: + arg: 5.0.2 + chokidar: 3.5.3 + color-name: 1.1.4 + detective: 5.2.1 + didyoumean: 1.2.2 + dlv: 1.1.3 + fast-glob: 3.2.12 + glob-parent: 6.0.2 + is-glob: 4.0.3 + lilconfig: 2.0.6 + micromatch: 4.0.5 + normalize-path: 3.0.0 + object-hash: 3.0.0 + picocolors: 1.0.0 + postcss: 8.4.20 + postcss-import: 14.1.0(postcss@8.4.20) + postcss-js: 4.0.0(postcss@8.4.20) + postcss-load-config: 3.1.4(postcss@8.4.20) + postcss-nested: 6.0.0(postcss@8.4.20) + postcss-selector-parser: 6.0.11 + postcss-value-parser: 4.2.0 + quick-lru: 5.1.1 + resolve: 1.22.1 + transitivePeerDependencies: + - ts-node + + text-table@0.2.0: {} + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + + tslib@2.4.1: {} + + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + + type-fest@0.20.2: {} + + typescript@4.9.4: {} + + update-browserslist-db@1.0.10(browserslist@4.21.4): + dependencies: + browserslist: 4.21.4 + escalade: 3.1.1 + picocolors: 1.0.0 + + uri-js@4.4.1: + dependencies: + punycode: 2.1.1 + + util-deprecate@1.0.2: {} + + vite-plugin-singlefile@0.13.2(rollup@3.14.0)(vite@4.0.1(@types/node@18.11.9)): + dependencies: + micromatch: 4.0.5 + rollup: 3.14.0 + vite: 4.0.1(@types/node@18.11.9) + + vite@4.0.1(@types/node@18.11.9): + dependencies: + esbuild: 0.16.8 + postcss: 8.4.20 + resolve: 1.22.1 + rollup: 3.14.0 + optionalDependencies: + '@types/node': 18.11.9 + fsevents: 2.3.2 + + vitefu@0.2.3(vite@4.0.1(@types/node@18.11.9)): + optionalDependencies: + vite: 4.0.1(@types/node@18.11.9) + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + word-wrap@1.2.3: {} + + wrappy@1.0.2: {} + + xtend@4.0.2: {} + + yaml@1.10.2: {} + + yaml@2.1.3: {} + + yocto-queue@0.1.0: {} diff --git a/vendor/texthooker-ui/postcss.config.cjs b/vendor/texthooker-ui/postcss.config.cjs new file mode 100644 index 0000000..8bdae1c --- /dev/null +++ b/vendor/texthooker-ui/postcss.config.cjs @@ -0,0 +1,8 @@ +const tailwindcss = require('tailwindcss'); +const autoprefixer = require('autoprefixer'); + +const config = { + plugins: [tailwindcss(), autoprefixer], +}; + +module.exports = config; diff --git a/vendor/texthooker-ui/public/assets/fonts/ackaisyo.ttf b/vendor/texthooker-ui/public/assets/fonts/ackaisyo.ttf new file mode 100644 index 0000000..c4ddb30 Binary files /dev/null and b/vendor/texthooker-ui/public/assets/fonts/ackaisyo.ttf differ diff --git a/vendor/texthooker-ui/public/assets/fonts/cinecaption226.ttf b/vendor/texthooker-ui/public/assets/fonts/cinecaption226.ttf new file mode 100644 index 0000000..0ad3f98 Binary files /dev/null and b/vendor/texthooker-ui/public/assets/fonts/cinecaption226.ttf differ diff --git a/vendor/texthooker-ui/public/icon.svg b/vendor/texthooker-ui/public/icon.svg new file mode 100644 index 0000000..252f491 --- /dev/null +++ b/vendor/texthooker-ui/public/icon.svg @@ -0,0 +1 @@ + diff --git a/vendor/texthooker-ui/public/index.html b/vendor/texthooker-ui/public/index.html new file mode 100644 index 0000000..aaae019 --- /dev/null +++ b/vendor/texthooker-ui/public/index.html @@ -0,0 +1,24 @@ + + + + + + + + + + + Texthooker UI + + + + + + diff --git a/vendor/texthooker-ui/src/app.css b/vendor/texthooker-ui/src/app.css new file mode 100644 index 0000000..4697442 --- /dev/null +++ b/vendor/texthooker-ui/src/app.css @@ -0,0 +1,131 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +@font-face { + font-family: 'Ackaisyo'; + src: local(''), url('./assets/fonts/ackaisyo.ttf') format('truetype'); + font-display: swap; +} + +@font-face { + font-family: 'CineCaption226'; + src: local(''), url('./assets/fonts/cinecaption226.ttf') format('truetype'); + font-display: swap; +} + +body, +html { + margin: 0; + display: flex; + flex: 1; + min-height: 100%; + overflow: auto; +} + +/* SUBMINER_DEFAULT_STYLE_START */ +:root { + --sm-bg: #1a1b2e; + --sm-surface: #222436; + --sm-border: rgba(255, 255, 255, 0.05); + --sm-text: #c8d3f5; + --sm-text-muted: #636da6; + --sm-hover-bg: rgba(130, 170, 255, 0.06); + --sm-scrollbar: rgba(255, 255, 255, 0.08); + --sm-scrollbar-hover: rgba(255, 255, 255, 0.15); +} + +html, +body { + margin: 0; + display: flex; + flex: 1; + min-height: 100%; + overflow: auto; + background: var(--sm-bg); + color: var(--sm-text); +} + +body[data-theme] { + background: var(--sm-bg); + color: var(--sm-text); +} + +main, +header, +#pip-container { + background: transparent; + color: var(--sm-text); +} + +header.bg-base-100, +header.bg-base-200 { + background: transparent; +} + +main, +main.flex { + font-family: 'Noto Sans CJK JP', 'Hiragino Sans', system-ui, sans-serif; + padding: 0.5rem min(4vw, 2rem); + line-height: 1.7; + gap: 0; +} + +p, +p.cursor-pointer { + font-family: 'Noto Sans CJK JP', 'Hiragino Sans', system-ui, sans-serif; + font-size: clamp(18px, 2vw, 26px); + letter-spacing: 0.04em; + line-height: 1.65; + white-space: normal; + margin: 0; + padding: 0.65rem 1rem; + border: none; + border-bottom: 1px solid var(--sm-border); + border-radius: 0; + background: transparent; + transition: background 0.2s ease; +} + +p:hover, +p.cursor-pointer:hover { + background: var(--sm-hover-bg); +} + +p:last-child, +p.cursor-pointer:last-child { + border-bottom: none; +} + +p.cursor-pointer.whitespace-pre-wrap { + white-space: normal; +} + +p.cursor-pointer.my-2 { + margin: 0; +} + +p.cursor-pointer.py-4, +p.cursor-pointer.py-2, +p.cursor-pointer.px-2, +p.cursor-pointer.px-4 { + padding: 0.65rem 1rem; +} + +*::-webkit-scrollbar { + width: 4px; +} + +*::-webkit-scrollbar-track { + background: transparent; +} + +*::-webkit-scrollbar-thumb { + background: var(--sm-scrollbar); + border-radius: 2px; +} + +*::-webkit-scrollbar-thumb:hover { + background: var(--sm-scrollbar-hover); +} +/* SUBMINER_DEFAULT_STYLE_END */ diff --git a/vendor/texthooker-ui/src/components/App.svelte b/vendor/texthooker-ui/src/components/App.svelte new file mode 100644 index 0000000..ad958ff --- /dev/null +++ b/vendor/texthooker-ui/src/components/App.svelte @@ -0,0 +1,747 @@ + + + + +{$visibilityHandler$ ?? ''} +{$handleLine$ ?? ''} +{$pasteHandler$ ?? ''} +{$copyBlocker$ ?? ''} +{$resizeHandler$ ?? ''} + +{#if $showSpinner$} + +{/if} + + + +
+ + {#if $websocketUrl$} + + {/if} + {#if $secondaryWebsocketUrl$} + + {/if} + {#if $isPaused$} +
+ ($isPaused$ = false)} /> +
+ {:else} +
+ ($isPaused$ = true)} /> +
+ {/if} +
+ +
+
+ +
+ {#if selectedLineIds.length} +
+ +
+
+ +
+ {/if} +
+ ($notesOpen$ = true)} /> +
+ {#if pipAvailable} +
+ +
+ {/if} + (settingsOpen = !settingsOpen)} + /> + updateLineData(!!$enabledReplacements$.length)} + on:layoutChange={executeUpdateScroll} + on:maxLinesChange={() => ($lineData$ = applyMaxLinesAndGetRemainingLineData())} + /> + +
+
+ {@html newLineCharacter} + {#each $lineData$ as line, index (line.id)} + { + selectedLineIds = [...selectedLineIds, detail]; + }} + on:deselected={({ detail }) => { + selectedLineIds = selectedLineIds.filter((selectedLineId) => selectedLineId !== detail); + }} + on:edit={handleLineEdit} + /> + {/each} +
+{#if $notesOpen$} +
+ +
+{/if} +
+ {#if pipWindow} + {#each pipLines as line, index (line.id)} + + {/each} + {/if} +
diff --git a/vendor/texthooker-ui/src/components/Dialog.svelte b/vendor/texthooker-ui/src/components/Dialog.svelte new file mode 100644 index 0000000..a1a5d1f --- /dev/null +++ b/vendor/texthooker-ui/src/components/Dialog.svelte @@ -0,0 +1,64 @@ + + +
+
+
+ {#if icon} + + {/if} + + {#if askForData} +
+ {#if askForData === 'text'} + + {/if} +
+ {:else} + {message} + {/if} +
+
+
+ {#if showCancel} + + {/if} + +
+
+
diff --git a/vendor/texthooker-ui/src/components/DialogManager.svelte b/vendor/texthooker-ui/src/components/DialogManager.svelte new file mode 100644 index 0000000..bd4bd4b --- /dev/null +++ b/vendor/texthooker-ui/src/components/DialogManager.svelte @@ -0,0 +1,36 @@ + + +{#if props} + +{/if} diff --git a/vendor/texthooker-ui/src/components/Icon.svelte b/vendor/texthooker-ui/src/components/Icon.svelte new file mode 100644 index 0000000..31fd17d --- /dev/null +++ b/vendor/texthooker-ui/src/components/Icon.svelte @@ -0,0 +1,21 @@ + + + + + diff --git a/vendor/texthooker-ui/src/components/Line.svelte b/vendor/texthooker-ui/src/components/Line.svelte new file mode 100644 index 0000000..2a8324a --- /dev/null +++ b/vendor/texthooker-ui/src/components/Line.svelte @@ -0,0 +1,143 @@ + + +{#key line.text} +

+ {line.text} +

+{/key} +{@html newLineCharacter} +{#if $milestoneLines$.has(line.id)} +
+
+ + {$milestoneLines$.get(line.id)} +
+
+ {@html newLineCharacter} +{/if} + + diff --git a/vendor/texthooker-ui/src/components/Notes.svelte b/vendor/texthooker-ui/src/components/Notes.svelte new file mode 100644 index 0000000..f9ceea5 --- /dev/null +++ b/vendor/texthooker-ui/src/components/Notes.svelte @@ -0,0 +1,26 @@ + + +
+
($notesOpen$ = false)} + on:keyup={dummyFn} + > + +
+
+ + + + +
+ + + diff --git a/vendor/yomitan/permissions.html b/vendor/yomitan/permissions.html new file mode 100644 index 0000000..c28b77b --- /dev/null +++ b/vendor/yomitan/permissions.html @@ -0,0 +1,246 @@ + + + + + + Yomitan Permissions + + + + + + + + + + + + + + + +
+
+
+ + + +

Yomitan Permissions

+ +

+
+
+
+
<all_urls>
+
+ Yomitan requires access to all URLs in order to run scripts to scan text and show the definitions popup, + request audio for playback and download, and connect with Anki. +
+
+
+ +
+
+
+
+
storage and unlimitedStorage
+
+ Yomitan uses storage permissions in order to save extension settings and dictionary data. + unlimitedStorage is used to help prevent web browsers from unexpectedly + deleting dictionary data. +
+
+
+
+
+
declarativeNetRequest
+
+

+ Yomitan uses this permission to ensure certain requests have valid and secure headers. + This sometimes involves removing or changing the Origin request header, + as this can be used to fingerprint browser configuration. +

+

+ Example: Origin: +

+
+
+
+
+
+
scripting
+
+ Yomitan needs to inject content scripts and stylesheets into webpages in order to + properly display the search popup. +
+
+
+
+
+
contextMenus
+
+ Yomitan adds a context menu interface that lets you look up highlighted words. +
+
+
+
+
+
clipboardWrite
+
+ Yomitan supports simulating the Ctrl+C (copy to clipboard) keyboard shortcut + when a definitions popup is open and focused. +
+
+
+
+
+
clipboardRead (optional)
+
+ Yomitan supports automatically opening a search window when text is copied to the clipboard + while the browser is running, depending on how certain settings are configured. + This allows Yomitan to support scanning text from external applications, provided there is a way + to copy text from those applications to the clipboard. +
+
+
+ +
+
+
+
+
nativeMessaging (optional)
+
+ Yomitan has the ability to communicate with an optional native messaging component in order to support + parsing large blocks of Japanese text using + MeCab. + The installation of this component is optional and is not included by default. +
+
+
+ +
+
+
+
+
Allow in private windows (optional)
+
+

+ When enabled, Yomitan is able to scan text and show definitions in private/incognito web browser windows. +

+

+ This option can be configured from the web browser's extension settings pages. +

+

+ This option can be configured from the web browser's extension settings pages. From your browser's address bar, go to about:addons and navigate to the settings for Yomitan. +

+
+
+
+ +
+
+
+
+
Allow access to file URLs (optional)
+
+

+ When enabled, Yomitan is able to scan text and show definitions on local HTML files located using the file://* scheme. +

+

+ This option can be configured from the web browser's extension settings pages. +

+
+
+
+ +
+
+
+
+
Persistent storage
+
+

+ Web browsers will sometimes clear stored data if the device is running low on storage space, + which can result in the imported dictionaries being deleted unexpectedly. + The persistent storage permission tells the browser that the data should not be deleted in those circumstances. +

+

+ It may not be possible to enable this permission on Firefox for Android. +

+

+ Chromium-based browsers should not need to enable this setting since the Yomitan extension has + the unlimitedStorage permission, which should prevent data deletion.[1] +

+
+
+
+ +
+
+
+
+
Configure allowed origins…
+
+
+ +
+
+
+ + + +
+
+
+ + + + + + + + + + + diff --git a/vendor/yomitan/popup-preview.html b/vendor/yomitan/popup-preview.html new file mode 100644 index 0000000..3da26ed --- /dev/null +++ b/vendor/yomitan/popup-preview.html @@ -0,0 +1,36 @@ + + + + + + Yomitan Popup Preview + + + + + + + + + + + + + +
+
+
+
+ + +
+
+
+ +
+ + + diff --git a/vendor/yomitan/popup.html b/vendor/yomitan/popup.html new file mode 100644 index 0000000..592797d --- /dev/null +++ b/vendor/yomitan/popup.html @@ -0,0 +1,104 @@ + + + + + + Yomitan Search + + + + + + + + + + + + + + + +
+
+
+
+
+
+ + + +
+ +
+ +
+ + + + + + +
+
+
+ +
+ +
+
+ +
+ +
+
+ + + +
+ + + + + diff --git a/vendor/yomitan/quick-start-guide.html b/vendor/yomitan/quick-start-guide.html new file mode 100644 index 0000000..ec86fac --- /dev/null +++ b/vendor/yomitan/quick-start-guide.html @@ -0,0 +1,159 @@ + + + + + + Quick Start Guide + + + + + + + + + + + + + + +
+
+
+ + + +

Yomitan Quick Start Guide

+ + +

Quick Actions

+ +
+
+
+ Clicking the Yomitan button in the browser bar will open the quick-actions popup. +
+
+ browser-action-popup +
+
+ The cog button will open the Settings page. +
+
+ The magnifying glass button will open the Search page, + enabling text and terms to be looked up using the installed dictionaries. + This can even be used in offline mode! +
+
+ The question mark button will open the Information page, + which has some helpful information and links about Yomitan. +
+
+
+
+
+ +

Installing Dictionaries

+ +
+
+
+ Yomitan requires one or more dictionaries to be installed in order to look up terms, kanji, and other information. + +

+ + To get started, first select your desired language in the Settings page. + Then, click on Get recommended dictionaries under the Dictionaries section to find dictionaries for your language. + You can also visit Yomitan Wiki to learn more about Yomitan dictionaries. + Once downloaded, dictionaries can be configured and managed from the same Settings page. + +

+ + settings-dictionaries-popup + +
+
+
+ + +

Scanning Text

+ +
+
+
+ After dictionaries have been installed, webpage text can be scanned by moving the cursor while holding a modifier key. + The default key is Shift, which can be disabled or configured in the Settings page. +
+ + scanning + +
+
+ Clicking the speaker button of an entry in the search results + will play an audio clip of a term's pronunciation using an online dictionary, if available. +
+
+ Clicking on a kanji character in a term's definition will show additional information about that character. + (Requires a kanji dictionary to be installed.) +
+
+
+
+ +

Migrating to Yomitan

+ +
+
+
+ You can also import an exported collection of dictionaries from the Backup section of the Settings page. + +

+ + If you are migrating from Yomichan, you may be interested in importing your data into Yomitan. + Please follow instructions from Yomitan Wiki for that. + +

+ + If you are using or planning to use custom templates for Anki note creation, note that some syntax has changed from Yomichan and Yomibaba. + Please ensure that your custom templates are using the updated syntax. +
+
+
+ +

Links

+ + + + + +
+
+
+ + diff --git a/vendor/yomitan/search.html b/vendor/yomitan/search.html new file mode 100644 index 0000000..ec59cdc --- /dev/null +++ b/vendor/yomitan/search.html @@ -0,0 +1,145 @@ + + + + + + Yomitan Search + + + + + + + + + + + + + + + + + +
+
+
+
+
+
+
+
+

Yomitan Search

+
+ +
+
+
+ +
+ +
+
+
+
+
+
+
+
+
+
+
+ + + + +
+ +
+
+
+
+ + + +
+ + + + +
+
+
+ +
+ +
+ + + + + + + + diff --git a/vendor/yomitan/settings.html b/vendor/yomitan/settings.html new file mode 100644 index 0000000..0d60172 --- /dev/null +++ b/vendor/yomitan/settings.html @@ -0,0 +1,2529 @@ + + + + + + Yomitan Settings + + + + + + + + + + + + + + + + +
+ +
+ + + +

Yomitan Settings

+ + +
+
+
+
+

+ This page is taking longer than expected to load. +

+

+ Due to a bug in Safari, it may be necessary to click the Yomitan + button in the browser bar to fully load the page +

+
+
+
+
+ + +
+
+ +
+
+
+
+
Active profile
+
Switch the active profile that is used for scanning.
+
+
+ +
+
+
+
+
Configure profiles…
+
+
+ +
+
+
+ + +
+
+ +
+
+
+
+
Enable Yomitan
+
+
+ +
+
+
+
+
+ Language +
+
+ Language of the text that is being looked up. +
+
+
+ +
+
+
+
+
Show the welcome guide on browser startup
+
+
+ +
+
+
+
+
Show "Lookup in Yomitan" in right-click menu
+
+
+ +
+
+
+
+
Maximum number of results
+
Adjust the maximum number of results shown for lookups.
+
+
+ +
+
+
+
+
+
+
+ Enable Yomitan API +
+
+ Enable support for sending local web requests to fetch data from Yomitan. +
+
+ This option may send data outside of Yomitan to local applications that request it (Privacy Policy). + More… +
+
+
+ +
+
+ + +
+
+ + +
+
+

Dictionaries (# installed, # enabled)

+
+
+
+
+
+
+
Configure installed and enabled dictionaries…
+ +
+
+
+
+ +
+
+
+
+
+
Get recommended dictionaries…
+
+
+ +
+
+
+
+
+
+
Storage
+
+ + Yomitan is using an indeterminate amount of storage. + + + +
+
+
+ +
+
+
+
+
+
+
Frequency sorting dictionary
+
+ Sort results using a frequency dictionary. + More… +
+
+
+ +
+
+ + +
+
+
+
+
Persistent storage
+
+ Enable to help prevent the browser from unexpectedly clearing the database. + More… +
+
+
+ +
+
+ +
+
+ + +
+
+ +
+
+
+
+
+
Scan modifier key
+
+ Hold a key while moving the cursor to scan text. + More… +
+
+
+ +
+
+ +
+
+
+
+
Scan resolution
+
+ Start the lookup scan at the word or character of the cursor position. + More… +
+
+
+ +
+
+ +
+
+
+
Scan using middle mouse button
+
Hold the middle mouse button while moving the cursor to scan text.
+
+
+ +
+
+
+
+
Configure advanced scanning inputs… (# defined)
+
+
+ +
+
+
+
+
Scan delay (in milliseconds)
+
Change the delay before scanning occurs when no modifier key is required.
+
+
+ +
+
+
+
+
Scan without mouse move
+
Allow scanning words under the pointer without the pointer being in motion.
+
+
+ +
+
+
+
+
Select matched text
+
+
+ +
+
+
+
+
Search text with non-Japanese, Chinese, or Korean characters
+
Only applies when language is set to Japanese, Chinese, Cantonese, or Korean.
+
+
+ +
+
+
+
+
Layout-aware scanning
+
Use webpage styling information to determine where line breaks are likely to be.
+
+
+ +
+
+
+
+
Deep content scanning
+
Enable scanning text that is covered by other layers.
+
+
+ +
+
+
+
+
+
Normalize CSS zoom
+
+ Correct the pointer location on webpages where CSS zoom is used. + More… +
+
+
+ +
+
+ +
+
+
+
+
Wildcard scanning
+
+ Enable suffix wildcard when looking up scanned webpage text. + More… +
+
+
+ +
+
+ +
+
+
+
Text scan length
+
Change how many characters are read when scanning for terms.
+
+ Setting this value too high (100+) may impact performance. +
+
+
+ +
+
+
+
+
Configure input action prevention…
+
+
+ +
+
+
+ + + +
+
+
+
Allow scanning search page content
+
Text on the search page can be scanned for definitions, which will open a popup.
+
+
+ +
+
+
+
+
+
Allow scanning popup content
+
Text inside of popups can be scanned for definitions, which will open a new popup.
+
+
+ +
+
+ +
+
+
+
+
Auto-hide search popup
+
When an existing popup is present, upon scanning again, hide the existing popup even if no definitions are found when scanning again.
+
+
+ +
+
+ +
+
+
+
+
Hide popup on cursor exit
+
When the cursor exits the popup, the popup will be hidden.
+
+
+ +
+
+ +
+
+
+
+
Reduced motion scrolling
+
Scrolls by a configurable height (similar to pagination), reducing animations. Useful on e-readers and e-ink screens.
+
+
+ +
+
+ +
+
+
+
Search terms when clicking text from the results list
+
+
+ +
+
+
+
+
+
+ Show iframe popups in the root frame + (?) +
+
+
+ +
+
+ +
+
+ + +
+
+ +
+
+
+
+
Theme
+
Adjust the style of Yomitan.
+
+
+
+
+
Body
+ +
+
+
Shadow
+ +
+
+
+
+
+
+
+
Action bar appearance
+
Control when and where the action bar is visible.
+
+
+
+
+
Visibility
+ +
+
+
Location
+ +
+
+
+
+
+
+
+
+
Font family
+
+ Change the font family used in Yomitan. + More… +
+
+
+
+ +
+
+
+ +
+
+
+
+
Font size
+
Change the font size used in popups, in pixels.
+
+
+
+ +
+
+
+
+
+
+
+
Line height
+
Change the space between lines of text in popups. This will usually be a decimal number between 1 and 2.
+
+
+
+ +
+
+
+
+
+
+
Compact glossaries
+
Display term glossaries using a more compact layout.
+
+
+ +
+
+
+
+
Compact tags
+
Show fewer repeated tags for term glossaries.
+
+
+ +
+
+
+
+
Show tags for expressions and their readings
+
These tags can be scanned if the options for popup content scanning are enabled.
+
+
+ +
+
+
+
+
Show debug information
+
A menu option to log debugging information will be shown in the search results.
+
+
+ +
+
+
+
+
Term display style
+
Change how terms and their readings are displayed.
+
+
+ +
+
+ +
+
+
Frequency display style
+
Change how frequency information is presented.
+
+
+ +
+
+
+
+
+
Selection indicator style
+
Change how the selected definition entry is visually indicated.
+
+
+ +
+
+
+
+
+
+
+ Pitch accent display styles +
+
+ Japanese only. + More… +
+
+
+
+ + + +
+
+
+ +
+
+
+
Configure collapsible dictionaries…
+
+
+ +
+
+
+
+
Configure custom CSS…
+
+
+ +
+
+
+ + + +
+
+
+
+
Result grouping mode
+
+ Change how related results are grouped. + More… +
+
+
+ +
+
+ + +
+
+
+
Average frequencies
+
Compress frequency tags into one "Average" frequency tag based on the harmonic mean.
+
+
+ +
+
+
+ + + +
+
+
+
+
Display mode
+
+ Change the layout of the popup. + More… +
+
+
+ +
+
+ +
+
+
+
+
Scale
+
Control the scaling factor of the popup.
+
+
+ +
+
+
+
+
+
+
+ Auto-scale + (?) +
+
+
+
+ + +
+
+
+ +
+
+
+
+
+
Size
+
Control the size of the popup, in pixels.
+
+
+
+
+
Width
+ +
+
+
Height
+ +
+
+
+
+
+
+
Horizontal text positioning
+
Change where the popup is positioned relative to horizontal text.
+
+
+ +
+
+
+
+
Vertical text positioning
+
Change where the popup is positioned relative to vertical text.
+
+
+ +
+
+
+
+
Horizontal text offset
+
Change the distance the popup is placed relative to horizontal text.
+
+
+
+
+
x
+ +
+
+
y
+ +
+
+
+
+
+
+
Vertical text offset
+
Change the distance the popup is placed relative to vertical text.
+
+
+
+
+
x
+ +
+
+
y
+ +
+
+
+
+
+ + + +
+
+
+
+
Sticky search header
+
Search header stays on the page when scrolling down.
+
+
+ +
+
+
+
+
+
+
+ Use a native browser window instead of an embedded popup + (?) +
+
+
+ +
+
+ +
+
+
+
Size
+
Control the size of the window, in pixels.
+
+
+
+
+
Width
+ +
+
+
Height
+ +
+
+
+
+
+
+
Left position
+
Control the left position of the window, in pixels.
+
+
+
+ +
+
Mode
+ +
+
+
+
+
+
+
Top position
+
Control the top position of the window, in pixels.
+
+
+
+ +
+
Mode
+ +
+
+
+
+
+
+
Window style
+
Change the appearance of the window.
+
+
+
+
+
Type
+ +
+
+
State
+ +
+
+
+
+
+ + +
+
+ +
+
+
+
+
Enable audio playback for terms
+
Show a clickable speaker icon next to search results.
+
+ This option may send term, reading, and/or language outside of Yomitan to fetch audio (Privacy Policy). +
+
+
+ +
+
+
+
+
Auto-play search result audio
+
The audio for the first result will be played automatically.
+
+
+ +
+
+
+
+
+
Audio fallback sound
+
+ The sound to play when Yomitan fails to fetch audio. +
+
+
+ +
+
+
+
+
+
Audio volume
+
Adjust the volume audio is played at, in percent.
+
+
+ +
+
+
+
+
Configure audio playback sources…
+
+
+ +
+
+
+ + +
+ + +
+
+
+
+
+
Parse sentences using Yomitan's internal parser
+
+ Sentence words are parsed using Yomitan's dictionaries. + More… +
+
+
+ +
+
+ +
+ +
+
+
Show space between parsed words
+
+
+ +
+
+
+
+
Sentence scanning extent
+
Adjust how many characters are bidirectionally scanned to form a sentence.
+
+
+ +
+
+
+
+
Sentence termination characters
+
+
+
+ + +
+
+
+
+ + +
+
+
+ +
+
+
+
+
+
Dictionary search resolution
+

"A dog" → search for "A dog","A do", "A d", "A"

or

"A dog" → "A dog", "A"

+
+
+ +
+
+
+
+
Configure custom text replacement patterns…
+
+
+ +
+
+
+ + +
+
+
+ + +
+ +
+
+
+
+
+
Enable Anki integration
+
+ Connection status: + +
+ This option may send limited information about the current webpage, information contained in Yomitan dictionary entries, and/or relevant user settings outside of Yomitan to Anki (Privacy Policy). +
+
+
+
+ +
+
+ +
+

+ Notice for macOS users: + If Yomitan has issues connecting to AnkiConnect, it may be necessary to adjust some system settings. + See this link for details. +

+
+
+
+
+
+
AnkiConnect server address
+
+ Change the URL of the AnkiConnect server. + More… +
+
+
+ +
+
+ +
+
+
+
Card tags
+
List of space or comma separated tags to add to the card.
+
+
+ +
+
+
+
+
API key
+
Pass a secret value to AnkiConnect API calls.
+
+
+ +
+
+
+
+
+
Check for card duplicates
+
+
+ +
+
+ +
+
+
+
Screenshot format
+
Adjust the format and quality of screenshots created for cards.
+
+
+
+ +
+
Format
+ +
+
+
+
+
+
+
+
Idle download timeout (in milliseconds)
+
+ The maximum time before an idle download will be cancelled; 0 = no limit. + More… +
+
+
+ +
+
+ +
+
+
+
Suspend new cards
+
New cards will be suspended when a note is added.
+
+
+ +
+
+
+
+
+
Note viewer window
+
+ Clicking the View added note button shows this window. + More… +
+
+
+ +
+
+ +
+
+
+
+
+ Show card tags and flags + (?) +
+
+
+ +
+
+ +
+
+
+
Force Anki sync on adding card
+
+ May cause issues when using in conjuction with Ankiconnect Android, and/or slow or metered connections. +
+
+
+ +
+
+ +
+
+
Configure Anki flashcards…
+
+
+ +
+
+
+
+
Customize handlebars templates…
+
+
+ +
+
+
+
+
Generate notes (experimental)…
+
+
+ +
+
+
+ + +
+
+
+ + +
+ +
+
+
+
+
+
Enable background clipboard text monitoring
+
Open the search page in a new window when text is copied to the clipboard.
+
+
+ +
+
+
+
+
+
Enable search page clipboard text monitoring
+
The query on the search page will be automatically updated with text in the clipboard.
+
+
+ +
+
+
+
+
Maximum clipboard text search length
+
Limit the number of characters used when searching clipboard text.
+
+
+ +
+
+
+
+
Clipboard text search mode
+
Change how the search page reacts to new text in the clipboard.
+
+
+ +
+
+
+ + +
+
+ +
+
+
+
+
+

+ Yomitan has two categories of keyboard shortcuts: +

+
    +
  • + Standard keyboard shortcuts are controlled by the extension, and can be added, removed, + and configured to work on webpages that Yomitan functions on. +
  • +
  • + Native keyboard shortcuts are controlled by the web browser, and function globally + within the web browser or system-wide. +
  • +
+
+
+
+
+
+
Configure standard keyboard shortcuts…
+
+
+ +
+
+
+
+
Configure native keyboard shortcuts…
+
+
+ +
+
+
+ + +
+
+ +
+
+
+
+
+ Yomitan can import and export settings files which can be + used to restore settings, share settings across devices, + and to help to debug problems. These files will only + contain settings and will not contain dictionaries. + Dictionaries must be imported separately. However, you can + also import a previously exported collection of + dictionaries. See the next section about that. +
+
+
+
+
+
+
+ + +
+
+ +
+
+ +
+
+
+
+
+
+
+ You can try to export the entire collection of your + dictionaries into a single large file that you can try to + import from other browsers or devices. Importing the + collection like that is a destructive operation and will + replace your current database of dictionaries so please + proceed with caution. These operations can take a lot of + time depending on the size of your database, especially to + start and to complete, so have patience. + +

+ + See yomichan-data-exporter for + instructions to export your data from older Yomichan installations. +
+
+
+
+
+
+
+ + +
+
+ +
+
+
+
+
+
+
+ Placeholder text. +
+
+
+
+
+
+ Placeholder text. +
+
+
+
+ + + +
+
+
+
+
+ Enable Google Docs compatibility mode + (?) +
+
+
+ +
+
+ +
+
+ + +
+
+ +
+
+
+
+
Configure Yomitan Permissions
+
+
+ +
+
+
+
+
+
+ Use a secure container around popups + (?) +
+
+
+ +
+
+ +
+
+
+
+
+ Use secure popup frame URL + (?) +
+
+
+ +
+
+ +
+
+ + + +
+
+
+
+ +
+
+
+
+ + + +
+ +
+
+
+
+
+
+ +
+
+ +
+
+
+
+ + + + + + + diff --git a/vendor/yomitan/support.html b/vendor/yomitan/support.html new file mode 100644 index 0000000..21dcb2d --- /dev/null +++ b/vendor/yomitan/support.html @@ -0,0 +1,44 @@ + + + + + + Support Yomitan + + + + + + + + + + + + + + +
+
+
+ + + +

Support Yomitan ❤️

+ +

Here are some ways to support Yomitan:

+
+
+ +
+
+
+
+
+ + + diff --git a/vendor/yomitan/sw.js b/vendor/yomitan/sw.js new file mode 100644 index 0000000..80f7678 --- /dev/null +++ b/vendor/yomitan/sw.js @@ -0,0 +1,17 @@ +/* + * Copyright (C) 2023-2025 Yomitan Authors + * + * 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 . + */ +import './js/background/background-main.js'; diff --git a/vendor/yomitan/template-renderer.html b/vendor/yomitan/template-renderer.html new file mode 100644 index 0000000..d7014a9 --- /dev/null +++ b/vendor/yomitan/template-renderer.html @@ -0,0 +1,19 @@ + + + + + + Yomitan Handlebars Sandbox + + + + + + + + + + + + + diff --git a/vendor/yomitan/templates-display.html b/vendor/yomitan/templates-display.html new file mode 100644 index 0000000..0d31367 --- /dev/null +++ b/vendor/yomitan/templates-display.html @@ -0,0 +1,218 @@ +Templates + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/yomitan/templates-modals.html b/vendor/yomitan/templates-modals.html new file mode 100644 index 0000000..f0339db --- /dev/null +++ b/vendor/yomitan/templates-modals.html @@ -0,0 +1,1694 @@ +Templates + + + + + + diff --git a/vendor/yomitan/templates-settings.html b/vendor/yomitan/templates-settings.html new file mode 100644 index 0000000..3205a59 --- /dev/null +++ b/vendor/yomitan/templates-settings.html @@ -0,0 +1,540 @@ +Templates + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/yomitan/welcome.html b/vendor/yomitan/welcome.html new file mode 100644 index 0000000..fe993f9 --- /dev/null +++ b/vendor/yomitan/welcome.html @@ -0,0 +1,229 @@ + + + + + + Welcome to Yomitan! + + + + + + + + + + + + + + + +
+
+
+ + +

Welcome to Yomitan!

+ +

Recommended Permissions (Important)

+
+
+
+
Enable recommended permissions
+
This will allow Yomitan to scan text from most sites.
+
+
+ +
+
+
+
+
Enable optional permissions
+
This will allow Yomitan to read the clipboard and communicate with external programs.
+
+
+ +
+
+
+
+
Further configuration is available on the Permissions page and the web browser's extension settings page.
+
Further configuration is available on the Permissions page and the web browser's extension settings page.
+ + + + +
+
+
+ + +
+
+
+

+ There are custom Anki templates in your settings. Note that some syntax has changed from previous versions of Yomitan. + Please ensure that your custom templates are using the updated syntax. +

+
+
+
+ + +

Import Dictionaries (Important)

+
+
+
+
+ Language +
+
+ Language of the text that is being looked up. +
+
+
+ +
+
+
+
+
+
Get recommended dictionaries…
+
+
+ +
+
+
+
+
+
+
Configure Installed and enabled dictionaries…
+
+
+ +
+
+
+
+ + +

Data Transmission

+
+
+
+
Enable audio playback for terms
+
Show a clickable speaker icon next to search results.
+
+ This option may send term, reading, and/or language outside of Yomitan to fetch audio when the speaker icon is clicked. Personally identifying information is never sent (Privacy Policy). +
Disabling this option will disallow pronunciation audio playback for any terms searched.
+
+
+
+ +
+
+
+ +

Here are some basics to get started

+ + +

Basic customization

+
+
+
+
Show this welcome guide on browser startup
+
+
+ +
+
+
+
+
+
Scan modifier key
+
Hold a key while moving the cursor to scan text.
+
+
+ +
+
+
+
+
+
Scan using middle mouse button
+
Hold the middle mouse button while moving the cursor to scan text.
+
+
+ +
+
+
+
+
Theme
+
Adjust the style of Yomitan.
+
+
+ +
+
+
+
+
More customization options are available on the Settings page
+
+
+ +
+
+
+ + + +
+
+
+ + + + + + + + + +