mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-02-27 18:22:41 -08:00
initial commit
This commit is contained in:
50
.github/workflows/ci.yml
vendored
Normal file
50
.github/workflows/ci.yml
vendored
Normal file
@@ -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
|
||||
50
.github/workflows/claude.yml
vendored
Normal file
50
.github/workflows/claude.yml
vendored
Normal file
@@ -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:*)'
|
||||
|
||||
200
.github/workflows/release.yml
vendored
Normal file
200
.github/workflows/release.yml
vendored
Normal file
@@ -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<<EOF" >> $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
|
||||
25
.gitignore
vendored
Normal file
25
.gitignore
vendored
Normal file
@@ -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/*
|
||||
4
.gitmodules
vendored
Normal file
4
.gitmodules
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
[submodule "vendor/texthooker-ui"]
|
||||
path = vendor/texthooker-ui
|
||||
url = https://github.com/ksyasuda/texthooker-ui.git
|
||||
branch = subminer
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
190
Makefile
Normal file
190
Makefile
Normal file
@@ -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)"
|
||||
116
README.md
Normal file
116
README.md
Normal file
@@ -0,0 +1,116 @@
|
||||
<div align="center">
|
||||
<img src="assets/SubMiner.png" width="169" alt="SubMiner logo">
|
||||
<h1>SubMiner</h1>
|
||||
</div>
|
||||
|
||||
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
|
||||
|
||||
[](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).
|
||||
BIN
assets/SubMiner.png
Normal file
BIN
assets/SubMiner.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.1 MiB |
BIN
assets/card-mine.mkv
Normal file
BIN
assets/card-mine.mkv
Normal file
Binary file not shown.
BIN
assets/card-mine.webm
Normal file
BIN
assets/card-mine.webm
Normal file
Binary file not shown.
BIN
assets/demo-poster.jpg
Normal file
BIN
assets/demo-poster.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 458 KiB |
BIN
assets/kiku-integration-poster.jpg
Normal file
BIN
assets/kiku-integration-poster.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 308 KiB |
BIN
assets/kiku-integration.mkv
Normal file
BIN
assets/kiku-integration.mkv
Normal file
Binary file not shown.
BIN
assets/kiku-integration.webm
Normal file
BIN
assets/kiku-integration.webm
Normal file
Binary file not shown.
14
build/entitlements.mac.plist
Normal file
14
build/entitlements.mac.plist
Normal file
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
<key>com.apple.security.automation.apple-events</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
210
config.example.jsonc
Normal file
210
config.example.jsonc
Normal file
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
18
docs/README.md
Normal file
18
docs/README.md
Normal file
@@ -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
|
||||
565
docs/configuration.md
Normal file
565
docs/configuration.md
Normal file
@@ -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.
|
||||
|
||||
[](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:<id>[: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.
|
||||
15
docs/development.md
Normal file
15
docs/development.md
Normal file
@@ -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 |
|
||||
246
docs/installation.md
Normal file
246
docs/installation.md
Normal file
@@ -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.
|
||||
|
||||
<!-- ### Maintainer: macOS Release Signing/Notarization
|
||||
|
||||
The GitHub release workflow builds signed and notarized macOS artifacts on `macos-latest`.
|
||||
Set these GitHub Actions secrets before creating a release tag:
|
||||
|
||||
- `CSC_LINK` (base64 `.p12` certificate or file URL for Developer ID Application cert)
|
||||
- `CSC_KEY_PASSWORD` (password for the `.p12`)
|
||||
- `APPLE_ID` (Apple ID email)
|
||||
- `APPLE_APP_SPECIFIC_PASSWORD` (app-specific password for notarization)
|
||||
- `APPLE_TEAM_ID` (Apple Developer Team ID) -->
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
<!-- ### Arch Linux -->
|
||||
|
||||
<!-- ```bash -->
|
||||
<!-- # Using the PKGBUILD -->
|
||||
<!-- makepkg -si -->
|
||||
<!-- ``` -->
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
131
docs/usage.md
Normal file
131
docs/usage.md
Normal file
@@ -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 <profile> ...`):
|
||||
|
||||
```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
|
||||
86
package.json
Normal file
86
package.json
Normal file
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
45
plugin/subminer.conf
Normal file
45
plugin/subminer.conf
Normal file
@@ -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
|
||||
773
plugin/subminer.lua
Normal file
773
plugin/subminer.lua
Normal file
@@ -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()
|
||||
2752
pnpm-lock.yaml
generated
Normal file
2752
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
87
scripts/mkv-to-readme-video.sh
Executable file
87
scripts/mkv-to-readme-video.sh
Executable file
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage:
|
||||
scripts/mkv-to-readme-video.sh <input.mkv>
|
||||
|
||||
Description:
|
||||
Generates two browser-friendly files next to the input file:
|
||||
- <name>.mp4 (H.264 + AAC, prefers NVIDIA GPU if available)
|
||||
- <name>.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"
|
||||
236
scripts/patch-texthooker.sh
Executable file
236
scripts/patch-texthooker.sh
Executable file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
# 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"
|
||||
261
scripts/patch-yomitan.sh
Executable file
261
scripts/patch-yomitan.sh
Executable file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
# 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<boolean>}
|
||||
*/
|
||||
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<boolean>}
|
||||
*/
|
||||
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<chrome.permissions.Permissions>}
|
||||
*/
|
||||
export function getAllPermissions() {
|
||||
// Electron workaround - chrome.permissions.getAll() not available
|
||||
return Promise.resolve({
|
||||
origins: ["<all_urls>"],
|
||||
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'"
|
||||
228
src/anki-connect.ts
Normal file
228
src/anki-connect.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<string, unknown>;
|
||||
}
|
||||
|
||||
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<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
private isRetryableError(error: unknown): boolean {
|
||||
if (!error || typeof error !== "object") return false;
|
||||
|
||||
const code = (error as Record<string, unknown>).code;
|
||||
const message =
|
||||
typeof (error as Record<string, unknown>).message === "string"
|
||||
? ((error as Record<string, unknown>).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<string, unknown> = {},
|
||||
options: { timeout?: number; maxRetries?: number } = {},
|
||||
): Promise<unknown> {
|
||||
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<AnkiConnectResponse>(
|
||||
"",
|
||||
{
|
||||
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<number[]> {
|
||||
const result = await this.invoke("findNotes", { query }, options);
|
||||
return (result as number[]) || [];
|
||||
}
|
||||
|
||||
async notesInfo(noteIds: number[]): Promise<Record<string, unknown>[]> {
|
||||
const result = await this.invoke("notesInfo", { notes: noteIds });
|
||||
return (result as Record<string, unknown>[]) || [];
|
||||
}
|
||||
|
||||
async updateNoteFields(
|
||||
noteId: number,
|
||||
fields: Record<string, string>,
|
||||
): Promise<void> {
|
||||
await this.invoke("updateNoteFields", {
|
||||
note: {
|
||||
id: noteId,
|
||||
fields,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async storeMediaFile(filename: string, data: Buffer): Promise<void> {
|
||||
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<string, string>,
|
||||
): Promise<number> {
|
||||
const result = await this.invoke("addNote", {
|
||||
note: { deckName, modelName, fields },
|
||||
});
|
||||
return result as number;
|
||||
}
|
||||
|
||||
async deleteNotes(noteIds: number[]): Promise<void> {
|
||||
await this.invoke("deleteNotes", { notes: noteIds });
|
||||
}
|
||||
|
||||
async retrieveMediaFile(filename: string): Promise<string> {
|
||||
const result = await this.invoke("retrieveMediaFile", { filename });
|
||||
return (result as string) || "";
|
||||
}
|
||||
|
||||
resetBackoff(): void {
|
||||
this.backoffMs = 200;
|
||||
this.consecutiveFailures = 0;
|
||||
}
|
||||
}
|
||||
2679
src/anki-integration.ts
Normal file
2679
src/anki-integration.ts
Normal file
File diff suppressed because it is too large
Load Diff
79
src/config/config.test.ts
Normal file
79
src/config/config.test.ts
Normal file
@@ -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/);
|
||||
});
|
||||
474
src/config/definitions.ts
Normal file
474
src/config/definitions.ts
Normal file
@@ -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<AnkiConnectConfig>;
|
||||
}
|
||||
|
||||
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<ResolvedConfig["keybindings"]> = [
|
||||
{ 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<string, unknown>;
|
||||
const patchObject = patch as Record<string, unknown>;
|
||||
|
||||
const mergeInto = (
|
||||
target: Record<string, unknown>,
|
||||
source: Record<string, unknown>,
|
||||
): 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<string, unknown>,
|
||||
value as Record<string, unknown>,
|
||||
);
|
||||
} else {
|
||||
target[key] = value;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
mergeInto(clone, patchObject);
|
||||
return clone as RawConfig;
|
||||
}
|
||||
3
src/config/index.ts
Normal file
3
src/config/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from "./definitions";
|
||||
export * from "./service";
|
||||
export * from "./template";
|
||||
600
src/config/service.ts
Normal file
600
src/config/service.ts
Normal file
@@ -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<string, unknown> {
|
||||
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<ResolvedConfig["ankiConnect"]>) : {}),
|
||||
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<string, unknown>;
|
||||
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 };
|
||||
}
|
||||
}
|
||||
78
src/config/template.ts
Normal file
78
src/config/template.ts
Normal file
@@ -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<string, unknown>).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");
|
||||
}
|
||||
12
src/generate-config-example.ts
Normal file
12
src/generate-config-example.ts
Normal file
@@ -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();
|
||||
150
src/logger.ts
Normal file
150
src/logger.ts
Normal file
@@ -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<LogLevel, number> = {
|
||||
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}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
5003
src/main.ts
Normal file
5003
src/main.ts
Normal file
File diff suppressed because it is too large
Load Diff
178
src/mecab-tokenizer.ts
Normal file
178
src/mecab-tokenizer.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<boolean> {
|
||||
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<Token[] | null> {
|
||||
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 };
|
||||
431
src/media-generator.ts
Normal file
431
src/media-generator.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<string | null> | 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<string | null> {
|
||||
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<Buffer> {
|
||||
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<Buffer> {
|
||||
const { format, quality = 92, maxWidth, maxHeight } = options;
|
||||
const ext = format === "webp" ? "webp" : format === "png" ? "png" : "jpg";
|
||||
const codecMap: Record<string, string> = {
|
||||
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<Buffer> {
|
||||
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<Buffer> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
267
src/preload.ts
Normal file
267
src/preload.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<boolean> =>
|
||||
ipcRenderer.invoke("get-overlay-visibility"),
|
||||
getCurrentSubtitle: (): Promise<SubtitleData> =>
|
||||
ipcRenderer.invoke("get-current-subtitle"),
|
||||
getCurrentSubtitleAss: (): Promise<string> =>
|
||||
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<SubtitlePosition | null> =>
|
||||
ipcRenderer.invoke("get-subtitle-position"),
|
||||
saveSubtitlePosition: (position: SubtitlePosition) => {
|
||||
ipcRenderer.send("save-subtitle-position", position);
|
||||
},
|
||||
|
||||
getMecabStatus: (): Promise<MecabStatus> =>
|
||||
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<Keybinding[]> =>
|
||||
ipcRenderer.invoke("get-keybindings"),
|
||||
|
||||
getJimakuMediaInfo: (): Promise<JimakuMediaInfo> =>
|
||||
ipcRenderer.invoke("jimaku:get-media-info"),
|
||||
jimakuSearchEntries: (
|
||||
query: JimakuSearchQuery,
|
||||
): Promise<JimakuApiResponse<JimakuEntry[]>> =>
|
||||
ipcRenderer.invoke("jimaku:search-entries", query),
|
||||
jimakuListFiles: (
|
||||
query: JimakuFilesQuery,
|
||||
): Promise<JimakuApiResponse<JimakuFileEntry[]>> =>
|
||||
ipcRenderer.invoke("jimaku:list-files", query),
|
||||
jimakuDownloadFile: (
|
||||
query: JimakuDownloadQuery,
|
||||
): Promise<JimakuDownloadResult> =>
|
||||
ipcRenderer.invoke("jimaku:download-file", query),
|
||||
|
||||
quitApp: () => {
|
||||
ipcRenderer.send("quit-app");
|
||||
},
|
||||
|
||||
toggleDevTools: () => {
|
||||
ipcRenderer.send("toggle-dev-tools");
|
||||
},
|
||||
|
||||
toggleOverlay: () => {
|
||||
ipcRenderer.send("toggle-overlay");
|
||||
},
|
||||
|
||||
getAnkiConnectStatus: (): Promise<boolean> =>
|
||||
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<SecondarySubMode> =>
|
||||
ipcRenderer.invoke("get-secondary-sub-mode"),
|
||||
getCurrentSecondarySub: (): Promise<string> =>
|
||||
ipcRenderer.invoke("get-current-secondary-sub"),
|
||||
getSubtitleStyle: (): Promise<SubtitleStyleConfig | null> =>
|
||||
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<SubsyncResult> =>
|
||||
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<KikuMergePreviewResponse> =>
|
||||
ipcRenderer.invoke("kiku:build-merge-preview", request),
|
||||
|
||||
kikuFieldGroupingRespond: (choice: KikuFieldGroupingChoice) => {
|
||||
ipcRenderer.send("kiku:field-grouping-respond", choice);
|
||||
},
|
||||
|
||||
getRuntimeOptions: (): Promise<RuntimeOptionState[]> =>
|
||||
ipcRenderer.invoke("runtime-options:get"),
|
||||
setRuntimeOptionValue: (
|
||||
id: RuntimeOptionId,
|
||||
value: RuntimeOptionValue,
|
||||
): Promise<RuntimeOptionApplyResult> =>
|
||||
ipcRenderer.invoke("runtime-options:set", id, value),
|
||||
cycleRuntimeOption: (
|
||||
id: RuntimeOptionId,
|
||||
direction: 1 | -1,
|
||||
): Promise<RuntimeOptionApplyResult> =>
|
||||
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);
|
||||
265
src/renderer/index.html
Normal file
265
src/renderer/index.html
Normal file
@@ -0,0 +1,265 @@
|
||||
<!--
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
-->
|
||||
<!doctype html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self' 'unsafe-inline' chrome-extension:; script-src 'self' 'unsafe-inline' chrome-extension:; style-src 'self' 'unsafe-inline' chrome-extension:;"
|
||||
/>
|
||||
<title>SubMiner</title>
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="overlay">
|
||||
<div id="secondarySubContainer" class="secondary-sub-hidden">
|
||||
<div id="secondarySubRoot"></div>
|
||||
</div>
|
||||
<div id="subtitleContainer">
|
||||
<div id="subtitleRoot"></div>
|
||||
</div>
|
||||
<div id="jimakuModal" class="modal hidden" aria-hidden="true">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<div class="modal-title">Jimaku Subtitles</div>
|
||||
<button id="jimakuClose" class="modal-close" type="button">
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="jimaku-form">
|
||||
<label class="jimaku-field">
|
||||
<span>Title</span>
|
||||
<input id="jimakuTitle" type="text" placeholder="Anime title" />
|
||||
</label>
|
||||
<label class="jimaku-field">
|
||||
<span>Season</span>
|
||||
<input
|
||||
id="jimakuSeason"
|
||||
type="number"
|
||||
min="1"
|
||||
placeholder="1"
|
||||
/>
|
||||
</label>
|
||||
<label class="jimaku-field">
|
||||
<span>Episode</span>
|
||||
<input
|
||||
id="jimakuEpisode"
|
||||
type="number"
|
||||
min="1"
|
||||
placeholder="1"
|
||||
/>
|
||||
</label>
|
||||
<button id="jimakuSearch" class="jimaku-button" type="button">
|
||||
Search
|
||||
</button>
|
||||
</div>
|
||||
<div id="jimakuStatus" class="jimaku-status"></div>
|
||||
<div id="jimakuEntriesSection" class="jimaku-section hidden">
|
||||
<div class="jimaku-section-title">Entries</div>
|
||||
<ul id="jimakuEntries" class="jimaku-list"></ul>
|
||||
</div>
|
||||
<div id="jimakuFilesSection" class="jimaku-section hidden">
|
||||
<div class="jimaku-section-title">Files</div>
|
||||
<ul id="jimakuFiles" class="jimaku-list"></ul>
|
||||
<button
|
||||
id="jimakuBroaden"
|
||||
class="jimaku-link hidden"
|
||||
type="button"
|
||||
>
|
||||
Broaden search (all files)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="kikuFieldGroupingModal" class="modal hidden" aria-hidden="true">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<div class="modal-title">Duplicate Card Detected</div>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div id="kikuSelectionStep">
|
||||
<div class="kiku-info-text">
|
||||
A card with the same expression already exists. Select which
|
||||
card to keep. The other card's content will be merged using Kiku
|
||||
field grouping. You can choose whether to delete the duplicate.
|
||||
</div>
|
||||
<div class="kiku-cards-container">
|
||||
<div id="kikuCard1" class="kiku-card active" tabindex="0">
|
||||
<div class="kiku-card-label">1 — Original Card</div>
|
||||
<div
|
||||
class="kiku-card-expression"
|
||||
id="kikuCard1Expression"
|
||||
></div>
|
||||
<div class="kiku-card-sentence" id="kikuCard1Sentence"></div>
|
||||
<div class="kiku-card-meta" id="kikuCard1Meta"></div>
|
||||
</div>
|
||||
<div id="kikuCard2" class="kiku-card" tabindex="0">
|
||||
<div class="kiku-card-label">2 — New Card</div>
|
||||
<div
|
||||
class="kiku-card-expression"
|
||||
id="kikuCard2Expression"
|
||||
></div>
|
||||
<div class="kiku-card-sentence" id="kikuCard2Sentence"></div>
|
||||
<div class="kiku-card-meta" id="kikuCard2Meta"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="kiku-footer">
|
||||
<label class="kiku-delete-toggle">
|
||||
<input id="kikuDeleteDuplicate" type="checkbox" checked />
|
||||
Delete duplicate card after merge
|
||||
</label>
|
||||
<button
|
||||
id="kikuConfirmButton"
|
||||
class="kiku-confirm-button"
|
||||
type="button"
|
||||
>
|
||||
Continue
|
||||
</button>
|
||||
<button
|
||||
id="kikuCancelButton"
|
||||
class="kiku-cancel-button"
|
||||
type="button"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="kikuPreviewStep" class="hidden">
|
||||
<div class="kiku-preview-header">
|
||||
<div class="kiku-preview-title">Final Merge Preview</div>
|
||||
<div class="kiku-preview-toggle">
|
||||
<button id="kikuPreviewCompact" type="button">Compact</button>
|
||||
<button id="kikuPreviewFull" type="button">Full</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
id="kikuPreviewError"
|
||||
class="kiku-preview-error hidden"
|
||||
></div>
|
||||
<pre id="kikuPreviewJson" class="kiku-preview-json"></pre>
|
||||
<div class="kiku-footer">
|
||||
<button
|
||||
id="kikuBackButton"
|
||||
class="kiku-cancel-button"
|
||||
type="button"
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
<button
|
||||
id="kikuFinalConfirmButton"
|
||||
class="kiku-confirm-button"
|
||||
type="button"
|
||||
>
|
||||
Confirm Merge
|
||||
</button>
|
||||
<button
|
||||
id="kikuFinalCancelButton"
|
||||
class="kiku-cancel-button"
|
||||
type="button"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="kikuHint" class="kiku-hint">
|
||||
Press 1 or 2 to select · Enter to confirm · Esc to
|
||||
cancel
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="runtimeOptionsModal" class="modal hidden" aria-hidden="true">
|
||||
<div class="modal-content runtime-modal-content">
|
||||
<div class="modal-header">
|
||||
<div class="modal-title">Runtime Options</div>
|
||||
<button
|
||||
id="runtimeOptionsClose"
|
||||
class="modal-close"
|
||||
type="button"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div id="runtimeOptionsHint" class="runtime-options-hint">
|
||||
Arrow keys: select/change · Enter or double-click: apply · Esc:
|
||||
close
|
||||
</div>
|
||||
<ul id="runtimeOptionsList" class="runtime-options-list"></ul>
|
||||
<div id="runtimeOptionsStatus" class="runtime-options-status"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="subsyncModal" class="modal hidden" aria-hidden="true">
|
||||
<div class="modal-content subsync-modal-content">
|
||||
<div class="modal-header">
|
||||
<div class="modal-title">Auto Subtitle Sync</div>
|
||||
<button id="subsyncClose" class="modal-close" type="button">
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="subsync-form">
|
||||
<div class="subsync-field">
|
||||
<span>Engine</span>
|
||||
<label class="subsync-radio">
|
||||
<input
|
||||
id="subsyncEngineAlass"
|
||||
type="radio"
|
||||
name="subsyncEngine"
|
||||
checked
|
||||
/>
|
||||
alass
|
||||
</label>
|
||||
<label class="subsync-radio">
|
||||
<input
|
||||
id="subsyncEngineFfsubsync"
|
||||
type="radio"
|
||||
name="subsyncEngine"
|
||||
/>
|
||||
ffsubsync
|
||||
</label>
|
||||
</div>
|
||||
<label id="subsyncSourceLabel" class="subsync-field">
|
||||
<span>Source Subtitle (for alass)</span>
|
||||
<select id="subsyncSourceSelect"></select>
|
||||
</label>
|
||||
</div>
|
||||
<div id="subsyncStatus" class="runtime-options-status"></div>
|
||||
<div class="subsync-footer">
|
||||
<button
|
||||
id="subsyncRun"
|
||||
class="kiku-confirm-button"
|
||||
type="button"
|
||||
>
|
||||
Run Sync
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="renderer.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
2443
src/renderer/renderer.ts
Normal file
2443
src/renderer/renderer.ts
Normal file
File diff suppressed because it is too large
Load Diff
703
src/renderer/style.css
Normal file
703
src/renderer/style.css
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
* {
|
||||
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;
|
||||
}
|
||||
}
|
||||
208
src/runtime-options.ts
Normal file
208
src/runtime-options.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {
|
||||
AnkiConnectConfig,
|
||||
RuntimeOptionApplyResult,
|
||||
RuntimeOptionId,
|
||||
RuntimeOptionState,
|
||||
RuntimeOptionValue,
|
||||
} from "./types";
|
||||
import { RUNTIME_OPTION_REGISTRY, RuntimeOptionRegistryEntry } from "./config";
|
||||
|
||||
type RuntimeOverrides = Record<string, unknown>;
|
||||
|
||||
function deepClone<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T;
|
||||
}
|
||||
|
||||
function getPathValue(source: Record<string, unknown>, 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<string, unknown>)[part];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function setPathValue(target: Record<string, unknown>, 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<string, unknown>;
|
||||
}
|
||||
}
|
||||
|
||||
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<AnkiConnectConfig>) => void;
|
||||
private readonly onOptionsChanged: (options: RuntimeOptionState[]) => void;
|
||||
private runtimeOverrides: RuntimeOverrides = {};
|
||||
private readonly definitions = new Map<RuntimeOptionId, RuntimeOptionRegistryEntry>();
|
||||
|
||||
constructor(
|
||||
getAnkiConfig: () => AnkiConnectConfig,
|
||||
callbacks: {
|
||||
applyAnkiPatch: (patch: Partial<AnkiConnectConfig>) => 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<string, unknown>;
|
||||
|
||||
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<string, unknown>, subPath, override);
|
||||
}
|
||||
|
||||
return effective;
|
||||
}
|
||||
}
|
||||
215
src/subtitle-timing-tracker.ts
Normal file
215
src/subtitle-timing-tracker.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<string, TimingEntry>();
|
||||
private history: HistoryEntry[] = [];
|
||||
private readonly maxHistory = 200;
|
||||
private readonly ttlMs = 5 * 60 * 1000;
|
||||
private cleanupInterval: ReturnType<typeof setInterval> | 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 = [];
|
||||
}
|
||||
}
|
||||
233
src/token-merger.ts
Normal file
233
src/token-merger.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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;
|
||||
}
|
||||
616
src/types.ts
Normal file
616
src/types.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<string, unknown>;
|
||||
full?: Record<string, unknown>;
|
||||
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<WebSocketConfig>;
|
||||
texthooker: Required<TexthookerConfig>;
|
||||
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<ShortcutsConfig>;
|
||||
secondarySub: Required<SecondarySubConfig>;
|
||||
subsync: Required<SubsyncConfig>;
|
||||
subtitleStyle: Required<Omit<SubtitleStyleConfig, "secondary">> & {
|
||||
secondary: Required<NonNullable<SubtitleStyleConfig["secondary"]>>;
|
||||
};
|
||||
auto_start_overlay: boolean;
|
||||
bind_visible_overlay_to_mpv_sub_visibility: boolean;
|
||||
jimaku: JimakuConfig & {
|
||||
apiBaseUrl: string;
|
||||
languagePreference: JimakuLanguagePreference;
|
||||
maxEntryResults: number;
|
||||
};
|
||||
invisibleOverlay: Required<InvisibleOverlayConfig>;
|
||||
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<T> =
|
||||
| { 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<boolean>;
|
||||
getCurrentSubtitle: () => Promise<SubtitleData>;
|
||||
getCurrentSubtitleAss: () => Promise<string>;
|
||||
getMpvSubtitleRenderMetrics: () => Promise<MpvSubtitleRenderMetrics>;
|
||||
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<SubtitlePosition | null>;
|
||||
saveSubtitlePosition: (position: SubtitlePosition) => void;
|
||||
getMecabStatus: () => Promise<MecabStatus>;
|
||||
setMecabEnabled: (enabled: boolean) => void;
|
||||
sendMpvCommand: (command: (string | number)[]) => void;
|
||||
getKeybindings: () => Promise<Keybinding[]>;
|
||||
getJimakuMediaInfo: () => Promise<JimakuMediaInfo>;
|
||||
jimakuSearchEntries: (
|
||||
query: JimakuSearchQuery,
|
||||
) => Promise<JimakuApiResponse<JimakuEntry[]>>;
|
||||
jimakuListFiles: (
|
||||
query: JimakuFilesQuery,
|
||||
) => Promise<JimakuApiResponse<JimakuFileEntry[]>>;
|
||||
jimakuDownloadFile: (
|
||||
query: JimakuDownloadQuery,
|
||||
) => Promise<JimakuDownloadResult>;
|
||||
quitApp: () => void;
|
||||
toggleDevTools: () => void;
|
||||
toggleOverlay: () => void;
|
||||
getAnkiConnectStatus: () => Promise<boolean>;
|
||||
setAnkiConnectEnabled: (enabled: boolean) => void;
|
||||
clearAnkiConnectHistory: () => void;
|
||||
onSecondarySub: (callback: (text: string) => void) => void;
|
||||
onSecondarySubMode: (callback: (mode: SecondarySubMode) => void) => void;
|
||||
getSecondarySubMode: () => Promise<SecondarySubMode>;
|
||||
getCurrentSecondarySub: () => Promise<string>;
|
||||
getSubtitleStyle: () => Promise<SubtitleStyleConfig | null>;
|
||||
onSubsyncManualOpen: (
|
||||
callback: (payload: SubsyncManualPayload) => void,
|
||||
) => void;
|
||||
runSubsyncManual: (
|
||||
request: SubsyncManualRunRequest,
|
||||
) => Promise<SubsyncResult>;
|
||||
onKikuFieldGroupingRequest: (
|
||||
callback: (data: KikuFieldGroupingRequestData) => void,
|
||||
) => void;
|
||||
kikuBuildMergePreview: (
|
||||
request: KikuMergePreviewRequest,
|
||||
) => Promise<KikuMergePreviewResponse>;
|
||||
kikuFieldGroupingRespond: (choice: KikuFieldGroupingChoice) => void;
|
||||
getRuntimeOptions: () => Promise<RuntimeOptionState[]>;
|
||||
setRuntimeOptionValue: (
|
||||
id: RuntimeOptionId,
|
||||
value: RuntimeOptionValue,
|
||||
) => Promise<RuntimeOptionApplyResult>;
|
||||
cycleRuntimeOption: (
|
||||
id: RuntimeOptionId,
|
||||
direction: 1 | -1,
|
||||
) => Promise<RuntimeOptionApplyResult>;
|
||||
onRuntimeOptionsChanged: (
|
||||
callback: (options: RuntimeOptionState[]) => void,
|
||||
) => void;
|
||||
onOpenRuntimeOptions: (callback: () => void) => void;
|
||||
notifyOverlayModalClosed: (modal: "runtime-options" | "subsync") => void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
electronAPI: ElectronAPI;
|
||||
}
|
||||
}
|
||||
68
src/window-trackers/base-tracker.ts
Normal file
68
src/window-trackers/base-tracker.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
114
src/window-trackers/hyprland-tracker.ts
Normal file
114
src/window-trackers/hyprland-tracker.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<typeof setInterval> | 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
|
||||
}
|
||||
}
|
||||
}
|
||||
86
src/window-trackers/index.ts
Normal file
86
src/window-trackers/index.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<Compositor, null>;
|
||||
|
||||
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,
|
||||
};
|
||||
114
src/window-trackers/macos-tracker.ts
Normal file
114
src/window-trackers/macos-tracker.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { execFile } from "child_process";
|
||||
import { BaseWindowTracker } from "./base-tracker";
|
||||
|
||||
export class MacOSWindowTracker extends BaseWindowTracker {
|
||||
private pollInterval: ReturnType<typeof setInterval> | 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;
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
94
src/window-trackers/sway-tracker.ts
Normal file
94
src/window-trackers/sway-tracker.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<typeof setInterval> | 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
|
||||
}
|
||||
}
|
||||
}
|
||||
73
src/window-trackers/x11-tracker.ts
Normal file
73
src/window-trackers/x11-tracker.ts
Normal file
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { execSync } from "child_process";
|
||||
import { BaseWindowTracker } from "./base-tracker";
|
||||
|
||||
export class X11WindowTracker extends BaseWindowTracker {
|
||||
private pollInterval: ReturnType<typeof setInterval> | 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
125
subminer.rasi
Normal file
125
subminer.rasi
Normal file
@@ -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;
|
||||
}
|
||||
19
tsconfig.json
Normal file
19
tsconfig.json
Normal file
@@ -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"]
|
||||
}
|
||||
10
vendor/texthooker-ui/.editorconfig
vendored
Normal file
10
vendor/texthooker-ui/.editorconfig
vendored
Normal file
@@ -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
|
||||
19
vendor/texthooker-ui/.eslintrc.cjs
vendored
Normal file
19
vendor/texthooker-ui/.eslintrc.cjs
vendored
Normal file
@@ -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'),
|
||||
},
|
||||
};
|
||||
27
vendor/texthooker-ui/.gitignore
vendored
Normal file
27
vendor/texthooker-ui/.gitignore
vendored
Normal file
@@ -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
|
||||
1
vendor/texthooker-ui/.npmrc
vendored
Normal file
1
vendor/texthooker-ui/.npmrc
vendored
Normal file
@@ -0,0 +1 @@
|
||||
engine-strict=true
|
||||
6
vendor/texthooker-ui/.prettierrc
vendored
Normal file
6
vendor/texthooker-ui/.prettierrc
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"editorconfig": true,
|
||||
"printWidth": 120,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 4
|
||||
}
|
||||
3
vendor/texthooker-ui/.vscode/extensions.json
vendored
Normal file
3
vendor/texthooker-ui/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["svelte.svelte-vscode"]
|
||||
}
|
||||
21
vendor/texthooker-ui/LICENSE
vendored
Normal file
21
vendor/texthooker-ui/LICENSE
vendored
Normal file
@@ -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.
|
||||
206
vendor/texthooker-ui/README.md
vendored
Normal file
206
vendor/texthooker-ui/README.md
vendored
Normal file
@@ -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 |
|
||||
|-|-|
|
||||
| <kbd>Delete</kbd> | Deletes current highlighted lines on the page. |
|
||||
| <kbd>Esc</kbd> | Deselects Lines. |
|
||||
| <kbd>Alt</kbd> + <kbd>Delete</kbd> | Deletes last line if no lines are highlighted |
|
||||
| <kbd>Alt</kbd> + <kbd>a</kbd> | Deletes all Lines and resets the Timer to 00:00:00. |
|
||||
| <kbd>Alt</kbd> + <kbd>q</kbd> | Deletes all Lines. |
|
||||
| <kbd>Alt</kbd> + <kbd>g</kbd> | Toggles Websocket Icon. |
|
||||
| <kbd>Control</kbd> + <kbd>Space</kbd> | 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.
|
||||
|
||||
<details style="cursor: pointer;">
|
||||
<summary>Settings List</summary>
|
||||
|
||||
| Setting | Description |
|
||||
|-|-|
|
||||
| Presets | Allows you to save the current Settings as a Preset and to quickly switch between them.<br/>**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. |
|
||||
|
||||
</details>
|
||||
|
||||
## 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)
|
||||
BIN
vendor/texthooker-ui/docs/assets/fonts/ackaisyo.ttf
vendored
Normal file
BIN
vendor/texthooker-ui/docs/assets/fonts/ackaisyo.ttf
vendored
Normal file
Binary file not shown.
BIN
vendor/texthooker-ui/docs/assets/fonts/cinecaption226.ttf
vendored
Normal file
BIN
vendor/texthooker-ui/docs/assets/fonts/cinecaption226.ttf
vendored
Normal file
Binary file not shown.
49
vendor/texthooker-ui/docs/index.html
vendored
Normal file
49
vendor/texthooker-ui/docs/index.html
vendored
Normal file
File diff suppressed because one or more lines are too long
60
vendor/texthooker-ui/flake.lock
generated
vendored
Normal file
60
vendor/texthooker-ui/flake.lock
generated
vendored
Normal file
@@ -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
|
||||
}
|
||||
44
vendor/texthooker-ui/flake.nix
vendored
Normal file
44
vendor/texthooker-ui/flake.nix
vendored
Normal file
@@ -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;
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
23
vendor/texthooker-ui/index.html
vendored
Normal file
23
vendor/texthooker-ui/index.html
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head data-version="1.0.0">
|
||||
<meta charset="UTF-8" />
|
||||
<link
|
||||
rel="icon"
|
||||
type="image/svg+xml"
|
||||
href="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pjxzdmcgdmlld0JveD0iMCAwIDI0IDI0IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzPjxzdHlsZT4uY2xzLTF7ZmlsbDojOGQ2ZGU4O30uY2xzLTJ7ZmlsbDojYTc4ZWVmO30uY2xzLTN7ZmlsbDojNmMyZTdjO308L3N0eWxlPjwvZGVmcz48ZyBpZD0iSWNvbnMiPjxyZWN0IGNsYXNzPSJjbHMtMSIgaGVpZ2h0PSIyMiIgcng9IjMiIHdpZHRoPSIyMiIgeD0iMSIgeT0iMSIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgaGVpZ2h0PSIxNyIgcng9IjMiIHdpZHRoPSIyMiIgeD0iMSIgeT0iMSIvPjwvZz48ZyBkYXRhLW5hbWU9IkxheWVyIDQiIGlkPSJMYXllcl80Ij48cGF0aCBjbGFzcz0iY2xzLTMiIGQ9Ik0yMCwwSDRBNCw0LDAsMCwwLDAsNFYyMGE0LDQsMCwwLDAsNCw0SDIwYTQsNCwwLDAsMCw0LTRWNEE0LDQsMCwwLDAsMjAsMFptMiwyMGEyLDIsMCwwLDEtMiwySDRhMiwyLDAsMCwxLTItMlY0QTIsMiwwLDAsMSw0LDJIMjBhMiwyLDAsMCwxLDIsMloiLz48cGF0aCBjbGFzcz0iY2xzLTMiIGQ9Ik01LDE1YTEsMSwwLDAsMCwwLDIsMiwyLDAsMCwxLDIsMiwxLDEsMCwwLDAsMiwwQTQsNCwwLDAsMCw1LDE1WiIvPjxwYXRoIGNsYXNzPSJjbHMtMyIgZD0iTTUsMTFhMSwxLDAsMCwwLDAsMiw2LjAwNiw2LjAwNiwwLDAsMSw2LDYsMSwxLDAsMCwwLDIsMEE4LjAwOSw4LjAwOSwwLDAsMCw1LDExWiIvPjxwYXRoIGNsYXNzPSJjbHMtMyIgZD0iTTUsN0ExLDEsMCwwLDAsNSw5LDEwLjAxMSwxMC4wMTEsMCwwLDEsMTUsMTlhMSwxLDAsMCwwLDIsMEExMi4wMTMsMTIuMDEzLDAsMCwwLDUsN1oiLz48L2c+PC9zdmc+"
|
||||
/>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Klee+One&family=Noto+Serif+JP&family=Shippori+Mincho&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Texthooker UI</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script type="module" src="./src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
44
vendor/texthooker-ui/package.json
vendored
Normal file
44
vendor/texthooker-ui/package.json
vendored
Normal file
@@ -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"
|
||||
}
|
||||
}
|
||||
2096
vendor/texthooker-ui/pnpm-lock.yaml
generated
vendored
Normal file
2096
vendor/texthooker-ui/pnpm-lock.yaml
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
8
vendor/texthooker-ui/postcss.config.cjs
vendored
Normal file
8
vendor/texthooker-ui/postcss.config.cjs
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
const tailwindcss = require('tailwindcss');
|
||||
const autoprefixer = require('autoprefixer');
|
||||
|
||||
const config = {
|
||||
plugins: [tailwindcss(), autoprefixer],
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
BIN
vendor/texthooker-ui/public/assets/fonts/ackaisyo.ttf
vendored
Normal file
BIN
vendor/texthooker-ui/public/assets/fonts/ackaisyo.ttf
vendored
Normal file
Binary file not shown.
BIN
vendor/texthooker-ui/public/assets/fonts/cinecaption226.ttf
vendored
Normal file
BIN
vendor/texthooker-ui/public/assets/fonts/cinecaption226.ttf
vendored
Normal file
Binary file not shown.
1
vendor/texthooker-ui/public/icon.svg
vendored
Normal file
1
vendor/texthooker-ui/public/icon.svg
vendored
Normal file
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" ?><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><defs><style>.cls-1{fill:#8d6de8;}.cls-2{fill:#a78eef;}.cls-3{fill:#6c2e7c;}</style></defs><g id="Icons"><rect class="cls-1" height="22" rx="3" width="22" x="1" y="1"/><rect class="cls-2" height="17" rx="3" width="22" x="1" y="1"/></g><g data-name="Layer 4" id="Layer_4"><path class="cls-3" d="M20,0H4A4,4,0,0,0,0,4V20a4,4,0,0,0,4,4H20a4,4,0,0,0,4-4V4A4,4,0,0,0,20,0Zm2,20a2,2,0,0,1-2,2H4a2,2,0,0,1-2-2V4A2,2,0,0,1,4,2H20a2,2,0,0,1,2,2Z"/><path class="cls-3" d="M5,15a1,1,0,0,0,0,2,2,2,0,0,1,2,2,1,1,0,0,0,2,0A4,4,0,0,0,5,15Z"/><path class="cls-3" d="M5,11a1,1,0,0,0,0,2,6.006,6.006,0,0,1,6,6,1,1,0,0,0,2,0A8.009,8.009,0,0,0,5,11Z"/><path class="cls-3" d="M5,7A1,1,0,0,0,5,9,10.011,10.011,0,0,1,15,19a1,1,0,0,0,2,0A12.013,12.013,0,0,0,5,7Z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 835 B |
24
vendor/texthooker-ui/public/index.html
vendored
Normal file
24
vendor/texthooker-ui/public/index.html
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head data-version="1.0.0">
|
||||
<meta charset="UTF-8" />
|
||||
<link
|
||||
rel="icon"
|
||||
type="image/svg+xml"
|
||||
href="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pjxzdmcgdmlld0JveD0iMCAwIDI0IDI0IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzPjxzdHlsZT4uY2xzLTF7ZmlsbDojOGQ2ZGU4O30uY2xzLTJ7ZmlsbDojYTc4ZWVmO30uY2xzLTN7ZmlsbDojNmMyZTdjO308L3N0eWxlPjwvZGVmcz48ZyBpZD0iSWNvbnMiPjxyZWN0IGNsYXNzPSJjbHMtMSIgaGVpZ2h0PSIyMiIgcng9IjMiIHdpZHRoPSIyMiIgeD0iMSIgeT0iMSIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgaGVpZ2h0PSIxNyIgcng9IjMiIHdpZHRoPSIyMiIgeD0iMSIgeT0iMSIvPjwvZz48ZyBkYXRhLW5hbWU9IkxheWVyIDQiIGlkPSJMYXllcl80Ij48cGF0aCBjbGFzcz0iY2xzLTMiIGQ9Ik0yMCwwSDRBNCw0LDAsMCwwLDAsNFYyMGE0LDQsMCwwLDAsNCw0SDIwYTQsNCwwLDAsMCw0LTRWNEE0LDQsMCwwLDAsMjAsMFptMiwyMGEyLDIsMCwwLDEtMiwySDRhMiwyLDAsMCwxLTItMlY0QTIsMiwwLDAsMSw0LDJIMjBhMiwyLDAsMCwxLDIsMloiLz48cGF0aCBjbGFzcz0iY2xzLTMiIGQ9Ik01LDE1YTEsMSwwLDAsMCwwLDIsMiwyLDAsMCwxLDIsMiwxLDEsMCwwLDAsMiwwQTQsNCwwLDAsMCw1LDE1WiIvPjxwYXRoIGNsYXNzPSJjbHMtMyIgZD0iTTUsMTFhMSwxLDAsMCwwLDAsMiw2LjAwNiw2LjAwNiwwLDAsMSw2LDYsMSwxLDAsMCwwLDIsMEE4LjAwOSw4LjAwOSwwLDAsMCw1LDExWiIvPjxwYXRoIGNsYXNzPSJjbHMtMyIgZD0iTTUsN0ExLDEsMCwwLDAsNSw5LDEwLjAxMSwxMC4wMTEsMCwwLDEsMTUsMTlhMSwxLDAsMCwwLDIsMEExMi4wMTMsMTIuMDEzLDAsMCwwLDUsN1oiLz48L2c+PC9zdmc+"
|
||||
/>
|
||||
<link rel="stylesheet" type="text/css" href="style.css" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Klee+One&family=Noto+Serif+JP&family=Shippori+Mincho&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Texthooker UI</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script src="texthooker-ui.iife.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
131
vendor/texthooker-ui/src/app.css
vendored
Normal file
131
vendor/texthooker-ui/src/app.css
vendored
Normal file
@@ -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 */
|
||||
747
vendor/texthooker-ui/src/components/App.svelte
vendored
Normal file
747
vendor/texthooker-ui/src/components/App.svelte
vendored
Normal file
@@ -0,0 +1,747 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
mdiArrowULeftTop,
|
||||
mdiCancel,
|
||||
mdiCog,
|
||||
mdiDelete,
|
||||
mdiDeleteForever,
|
||||
mdiNoteEdit,
|
||||
mdiPause,
|
||||
mdiPlay,
|
||||
mdiWindowMaximize,
|
||||
mdiWindowRestore,
|
||||
} from '@mdi/js';
|
||||
import { debounceTime, filter, fromEvent, map, NEVER, switchMap, tap } from 'rxjs';
|
||||
import { onMount, tick } from 'svelte';
|
||||
import { quintInOut } from 'svelte/easing';
|
||||
import { fly } from 'svelte/transition';
|
||||
import {
|
||||
actionHistory$,
|
||||
allowNewLineDuringPause$,
|
||||
allowPasteDuringPause$,
|
||||
autoStartTimerDuringPause$,
|
||||
autoStartTimerDuringPausePaste$,
|
||||
blockCopyOnPage$,
|
||||
customCSS$,
|
||||
dialogOpen$,
|
||||
displayVertical$,
|
||||
enabledReplacements$,
|
||||
enablePaste$,
|
||||
filterNonCJKLines$,
|
||||
flashOnMissedLine$,
|
||||
flashOnPauseTimeout$,
|
||||
fontSize$,
|
||||
isPaused$,
|
||||
lastPipHeight$,
|
||||
lastPipWidth$,
|
||||
lineData$,
|
||||
maxLines$,
|
||||
maxPipLines$,
|
||||
mergeEqualLineStarts$,
|
||||
newLine$,
|
||||
notesOpen$,
|
||||
onlineFont$,
|
||||
openDialog$,
|
||||
preventGlobalDuplicate$,
|
||||
preventLastDuplicate$,
|
||||
removeAllWhitespace$,
|
||||
replacements$,
|
||||
reverseLineOrder$,
|
||||
secondaryWebsocketUrl$,
|
||||
showConnectionIcon$,
|
||||
showSpinner$,
|
||||
theme$,
|
||||
websocketUrl$,
|
||||
} from '../stores/stores';
|
||||
import { LineType, OnlineFont, Theme, type LineItem, type LineItemEditEvent } from '../types';
|
||||
import {
|
||||
applyAfkBlur,
|
||||
applyCustomCSS,
|
||||
applyReplacements,
|
||||
generateRandomUUID,
|
||||
newLineCharacter,
|
||||
reduceToEmptyString,
|
||||
updateScroll,
|
||||
} from '../util';
|
||||
import DialogManager from './DialogManager.svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
import Line from './Line.svelte';
|
||||
import Notes from './Notes.svelte';
|
||||
import Presets from './Presets.svelte';
|
||||
import Settings from './Settings.svelte';
|
||||
import SocketConnector from './SocketConnector.svelte';
|
||||
import Spinner from './Spinner.svelte';
|
||||
import Stats from './Stats.svelte';
|
||||
|
||||
let isSmFactor = false;
|
||||
let settingsComponent: Settings;
|
||||
let selectedLineIds: string[] = [];
|
||||
let settingsContainer: HTMLElement;
|
||||
let settingsElement: SVGElement;
|
||||
let settingsOpen = false;
|
||||
let lineContainer: HTMLElement;
|
||||
let lineElements: Line[] = [];
|
||||
let lineInEdit = false;
|
||||
let blockNextExternalLine = false;
|
||||
let wakeLock = null;
|
||||
let pipContainer: HTMLElement;
|
||||
let pipWindow: Window | undefined;
|
||||
let pipResizeTimeout: number;
|
||||
let hasPipFocus = false;
|
||||
|
||||
const wakeLockAvailable = 'wakeLock' in navigator;
|
||||
|
||||
const cjkCharacters = /[\p{scx=Hira}\p{scx=Kana}\p{scx=Han}]/imu;
|
||||
|
||||
const uniqueLines$ = preventGlobalDuplicate$.pipe(
|
||||
map((preventGlobalDuplicate) =>
|
||||
preventGlobalDuplicate ? new Set<string>($lineData$.map((line) => line.text)) : new Set<string>(),
|
||||
),
|
||||
);
|
||||
|
||||
const handleLine$ = newLine$.pipe(
|
||||
filter(([_, lineType]) => {
|
||||
const isPaste = lineType === LineType.PASTE;
|
||||
const hasNoUserInteraction = !isPaste || (!$notesOpen$ && !$dialogOpen$ && !settingsOpen && !lineInEdit);
|
||||
const skipExternalLine = blockNextExternalLine && lineType === LineType.EXTERNAL;
|
||||
|
||||
if (skipExternalLine) {
|
||||
blockNextExternalLine = false;
|
||||
}
|
||||
|
||||
if (
|
||||
(!$isPaused$ ||
|
||||
(($allowPasteDuringPause$ || $autoStartTimerDuringPausePaste$) && isPaste) ||
|
||||
(($allowNewLineDuringPause$ || $autoStartTimerDuringPause$) && !isPaste)) &&
|
||||
hasNoUserInteraction &&
|
||||
!skipExternalLine
|
||||
) {
|
||||
if (
|
||||
$isPaused$ &&
|
||||
(($autoStartTimerDuringPausePaste$ && isPaste) || ($autoStartTimerDuringPause$ && !isPaste))
|
||||
) {
|
||||
$isPaused$ = false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!skipExternalLine && hasNoUserInteraction && $flashOnMissedLine$) {
|
||||
handleMissedLine();
|
||||
}
|
||||
|
||||
return false;
|
||||
}),
|
||||
tap((newLine: [string, LineType]) => {
|
||||
const [lineContent] = newLine;
|
||||
const text = transformLine(lineContent);
|
||||
|
||||
if (text) {
|
||||
$lineData$ = applyEqualLineStartMerge([
|
||||
...applyMaxLinesAndGetRemainingLineData(1),
|
||||
{ id: generateRandomUUID(), text },
|
||||
]);
|
||||
}
|
||||
}),
|
||||
reduceToEmptyString(),
|
||||
);
|
||||
|
||||
const pasteHandler$ = enablePaste$.pipe(
|
||||
switchMap((enablePaste) => (enablePaste ? fromEvent(document, 'paste') : NEVER)),
|
||||
tap((event: ClipboardEvent) => newLine$.next([event.clipboardData.getData('text/plain'), LineType.PASTE])),
|
||||
reduceToEmptyString(),
|
||||
);
|
||||
|
||||
const visibilityHandler$ = fromEvent(document, 'visibilitychange').pipe(
|
||||
tap(() => {
|
||||
if (wakeLockAvailable && wakeLock !== null && document.visibilityState === 'visible') {
|
||||
wakeLock = navigator.wakeLock
|
||||
.request('screen')
|
||||
.then((lock) => {
|
||||
return lock;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(`Unable to aquire screen lock: ${error.message}`);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}),
|
||||
reduceToEmptyString(),
|
||||
);
|
||||
|
||||
const copyBlocker$ = blockCopyOnPage$.pipe(
|
||||
switchMap((blockCopyOnPage) => {
|
||||
blockNextExternalLine = false;
|
||||
|
||||
return blockCopyOnPage ? fromEvent(document, 'copy') : NEVER;
|
||||
}),
|
||||
tap(() => (blockNextExternalLine = true)),
|
||||
reduceToEmptyString(),
|
||||
);
|
||||
|
||||
const resizeHandler$ = fromEvent(window, 'resize').pipe(
|
||||
debounceTime(500),
|
||||
tap(mountFunction),
|
||||
reduceToEmptyString(),
|
||||
);
|
||||
|
||||
$: iconSize = isSmFactor ? '1.5rem' : '1.25rem';
|
||||
|
||||
$: $enabledReplacements$ = $replacements$.filter((replacment) => replacment.enabled);
|
||||
|
||||
$: pipAvailable = 'documentPictureInPicture' in window && !!pipContainer;
|
||||
|
||||
$: pipLines = pipAvailable && $lineData$ ? $lineData$.slice(-$maxPipLines$) : [];
|
||||
|
||||
$: if (pipWindow) {
|
||||
pipWindow.document.body.dataset.theme = $theme$;
|
||||
|
||||
applyCustomCSS(pipWindow.document, $customCSS$);
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
mountFunction();
|
||||
if (wakeLockAvailable) {
|
||||
wakeLock = navigator.wakeLock
|
||||
.request('screen')
|
||||
.then((lock) => {
|
||||
return lock;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(`Unable to aquire screen lock: ${error.message}`);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function mountFunction() {
|
||||
isSmFactor = window.matchMedia('(min-width: 640px)').matches;
|
||||
executeUpdateScroll();
|
||||
}
|
||||
|
||||
function handleKeyPress(event: KeyboardEvent) {
|
||||
if ($notesOpen$ || $dialogOpen$ || settingsOpen || lineInEdit) {
|
||||
return;
|
||||
}
|
||||
|
||||
const key = (event.key || '')?.toLowerCase();
|
||||
|
||||
if (key === 'delete') {
|
||||
if (window.getSelection()?.toString().trim()) {
|
||||
const range = window.getSelection().getRangeAt(0);
|
||||
|
||||
for (let index = 0, { length } = lineElements; index < length; index += 1) {
|
||||
const lineElement = lineElements[index];
|
||||
const selectedId = lineElement?.getIdIfSelected(range);
|
||||
|
||||
if (selectedId) {
|
||||
selectedLineIds.push(selectedId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedLineIds.length) {
|
||||
removeLines();
|
||||
} else if (event.altKey) {
|
||||
removeLastLine();
|
||||
}
|
||||
} else if (selectedLineIds.length && key === 'escape') {
|
||||
deselectLines();
|
||||
} else if (event.altKey && key === 'a') {
|
||||
settingsComponent.handleReset(false);
|
||||
} else if (event.altKey && key === 'q') {
|
||||
settingsComponent.handleReset(true);
|
||||
} else if ((event.ctrlKey || event.metaKey) && key === ' ') {
|
||||
$isPaused$ = !$isPaused$;
|
||||
} else if (event.altKey && key === 'g') {
|
||||
$showConnectionIcon$ = !$showConnectionIcon$;
|
||||
}
|
||||
}
|
||||
|
||||
async function undoLastAction() {
|
||||
if (!$actionHistory$.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const linesToRevert = $actionHistory$.pop();
|
||||
|
||||
let lineToRevert = linesToRevert.pop();
|
||||
|
||||
while (lineToRevert) {
|
||||
const text = transformLine(lineToRevert.text, false);
|
||||
|
||||
if (text) {
|
||||
const { id, index } = lineToRevert;
|
||||
|
||||
if (index > $lineData$.length - 1) {
|
||||
$lineData$.push({ id, text });
|
||||
} else if ($lineData$[index].id === id) {
|
||||
$lineData$[index] = { id, text };
|
||||
} else {
|
||||
$lineData$.splice(index, 0, { id, text });
|
||||
}
|
||||
}
|
||||
|
||||
lineToRevert = linesToRevert.pop();
|
||||
}
|
||||
|
||||
await tick();
|
||||
|
||||
$lineData$ = applyEqualLineStartMerge(applyMaxLinesAndGetRemainingLineData());
|
||||
$actionHistory$ = $actionHistory$;
|
||||
}
|
||||
|
||||
function removeLastLine() {
|
||||
if (!$lineData$.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [removedLine] = $lineData$.splice($lineData$.length - 1, 1);
|
||||
|
||||
selectedLineIds = selectedLineIds.filter((selectedLineId) => selectedLineId !== removedLine.id);
|
||||
$lineData$ = $lineData$;
|
||||
$actionHistory$ = [...$actionHistory$, [{ ...removedLine, index: $lineData$.length }]];
|
||||
|
||||
$uniqueLines$.delete(removedLine.text);
|
||||
}
|
||||
|
||||
function removeLines() {
|
||||
const linesToDelete = new Set(selectedLineIds);
|
||||
const newActionHistory: LineItem[] = [];
|
||||
|
||||
$lineData$ = $lineData$.filter((oldLine, index) => {
|
||||
const hasLine = linesToDelete.has(oldLine.id);
|
||||
|
||||
linesToDelete.delete(oldLine.id);
|
||||
|
||||
if (hasLine) {
|
||||
newActionHistory.push({ ...oldLine, index: index - newActionHistory.length });
|
||||
$uniqueLines$.delete(oldLine.text);
|
||||
}
|
||||
|
||||
return !hasLine;
|
||||
});
|
||||
|
||||
selectedLineIds = linesToDelete.size ? [...linesToDelete] : [];
|
||||
|
||||
if (newActionHistory.length) {
|
||||
$actionHistory$ = [...$actionHistory$, newActionHistory];
|
||||
}
|
||||
}
|
||||
|
||||
function deselectLines() {
|
||||
for (let index = 0, { length } = lineElements; index < length; index += 1) {
|
||||
lineElements[index]?.deselect();
|
||||
}
|
||||
|
||||
selectedLineIds = [];
|
||||
}
|
||||
|
||||
async function handlePipAction() {
|
||||
if (pipWindow) {
|
||||
return pipWindow.close();
|
||||
}
|
||||
|
||||
pipWindow = await window.documentPictureInPicture
|
||||
.requestWindow(
|
||||
$lastPipHeight$ > 0 && $lastPipWidth$ > 0
|
||||
? { height: $lastPipHeight$, width: $lastPipWidth$, preferInitialWindowPlacement: false }
|
||||
: { preferInitialWindowPlacement: false },
|
||||
)
|
||||
.catch(({ message }) => {
|
||||
$openDialog$ = {
|
||||
message: `Error opening floating window: ${message}`,
|
||||
showCancel: false,
|
||||
};
|
||||
|
||||
return undefined;
|
||||
});
|
||||
|
||||
if (!pipWindow) {
|
||||
return;
|
||||
}
|
||||
|
||||
pipWindow.document.body.appendChild(pipContainer);
|
||||
|
||||
pipWindow.addEventListener('pagehide', onPipHide, { once: true });
|
||||
pipWindow.addEventListener('resize', onPipResize, false);
|
||||
pipWindow.addEventListener('blur', onPipFocusBlur, false);
|
||||
pipWindow.addEventListener('focus', onPipFocusBlur, false);
|
||||
|
||||
[...document.styleSheets].forEach((styleSheet) => {
|
||||
if (styleSheet.ownerNode instanceof Element && styleSheet.ownerNode.id === 'user-css') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const cssRules = [...styleSheet.cssRules].map((rule) => rule.cssText).join('');
|
||||
const style = document.createElement('style');
|
||||
|
||||
style.textContent = cssRules;
|
||||
pipWindow.document.head.appendChild(style);
|
||||
} catch (_error) {
|
||||
const link = document.createElement('link');
|
||||
|
||||
link.rel = 'stylesheet';
|
||||
link.type = styleSheet.type;
|
||||
link.media = styleSheet.media.toString();
|
||||
link.href = styleSheet.href;
|
||||
pipWindow.document.head.appendChild(link);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function onPipHide() {
|
||||
updatePipDimensions();
|
||||
|
||||
pipWindow.removeEventListener('resize', onPipResize, false);
|
||||
pipWindow.removeEventListener('blur', onPipFocusBlur, false);
|
||||
pipWindow.removeEventListener('focus', onPipFocusBlur, false);
|
||||
|
||||
hasPipFocus = false;
|
||||
pipWindow = undefined;
|
||||
}
|
||||
|
||||
function onPipResize() {
|
||||
window.clearTimeout(pipResizeTimeout);
|
||||
|
||||
pipResizeTimeout = window.setTimeout(updatePipDimensions, 500);
|
||||
}
|
||||
|
||||
function updatePipDimensions() {
|
||||
if (!pipWindow) {
|
||||
return;
|
||||
}
|
||||
|
||||
$lastPipHeight$ = pipWindow.document.body.clientHeight;
|
||||
$lastPipWidth$ = pipWindow.document.body.clientWidth;
|
||||
}
|
||||
|
||||
function onPipFocusBlur(event: Event) {
|
||||
hasPipFocus = event.type === 'focus';
|
||||
}
|
||||
|
||||
function onAfkBlur({ detail: isAfk }: CustomEvent<boolean>) {
|
||||
applyAfkBlur(document, isAfk);
|
||||
|
||||
if (pipWindow) {
|
||||
applyAfkBlur(pipWindow.document, isAfk);
|
||||
}
|
||||
}
|
||||
|
||||
function executeUpdateScroll() {
|
||||
updateScroll(window, lineContainer, $reverseLineOrder$, $displayVertical$);
|
||||
|
||||
if (pipWindow) {
|
||||
updateScroll(pipWindow, pipContainer, $reverseLineOrder$, false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleMissedLine() {
|
||||
clearTimeout($flashOnPauseTimeout$);
|
||||
|
||||
if ($theme$ === Theme.GARDEN) {
|
||||
settingsContainer.classList.add('bg-base-200');
|
||||
settingsContainer.classList.remove('bg-base-100');
|
||||
document.body.classList.add('bg-base-200');
|
||||
}
|
||||
|
||||
document.body.classList.add('animate-[pulse_0.5s_cubic-bezier(0.4,0,0.6,1)_1]');
|
||||
|
||||
$flashOnPauseTimeout$ = window.setTimeout(() => {
|
||||
if ($theme$ === Theme.GARDEN) {
|
||||
settingsContainer.classList.add('bg-base-100');
|
||||
settingsContainer.classList.remove('bg-base-200');
|
||||
document.body.classList.remove('bg-base-200');
|
||||
}
|
||||
|
||||
document.body.classList.remove('animate-[pulse_0.5s_cubic-bezier(0.4,0,0.6,1)_1]');
|
||||
}, 500);
|
||||
}
|
||||
|
||||
function transformLine(text: string, useReplacements = true) {
|
||||
const textToAppend = useReplacements ? applyReplacements(text, $enabledReplacements$) : text;
|
||||
|
||||
let canAppend = true;
|
||||
let lineToAppend = $removeAllWhitespace$ ? textToAppend.replace(/\s/gm, '').trim() : textToAppend;
|
||||
|
||||
if ($filterNonCJKLines$ && !lineToAppend.match(cjkCharacters)) {
|
||||
lineToAppend = '';
|
||||
}
|
||||
|
||||
if (!lineToAppend) {
|
||||
canAppend = false;
|
||||
} else if ($preventGlobalDuplicate$) {
|
||||
canAppend = !$uniqueLines$.has(lineToAppend);
|
||||
$uniqueLines$.add(lineToAppend);
|
||||
} else if ($preventLastDuplicate$ && $lineData$.length) {
|
||||
canAppend = $lineData$.slice(-$preventLastDuplicate$).every((line) => line.text !== lineToAppend);
|
||||
}
|
||||
|
||||
return canAppend ? lineToAppend : undefined;
|
||||
}
|
||||
|
||||
function handleLineEdit(event) {
|
||||
const { inEdit, data } = event.detail as LineItemEditEvent;
|
||||
|
||||
if (data && data.originalText !== data.newText) {
|
||||
const text = transformLine(data.newText);
|
||||
|
||||
$lineData$[data.lineIndex] = {
|
||||
id: data.line.id,
|
||||
text,
|
||||
};
|
||||
|
||||
if (text) {
|
||||
$actionHistory$ = [...$actionHistory$, [{ ...data.line, index: data.lineIndex }]];
|
||||
$uniqueLines$.delete(data.originalText);
|
||||
$uniqueLines$.add(text);
|
||||
} else {
|
||||
tick().then(
|
||||
() =>
|
||||
($lineData$[data.lineIndex] = {
|
||||
id: data.line.id,
|
||||
text: data.originalText,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
lineInEdit = inEdit;
|
||||
}
|
||||
|
||||
function applyMaxLinesAndGetRemainingLineData(diffMod = 0) {
|
||||
const oldLinesToRemove = new Set<string>();
|
||||
const startIndex = $maxLines$ ? $lineData$.length - $maxLines$ + diffMod : 0;
|
||||
const remainingLineData =
|
||||
startIndex > 0
|
||||
? $lineData$.filter((oldLine, index) => {
|
||||
if (index < startIndex) {
|
||||
oldLinesToRemove.add(oldLine.id);
|
||||
|
||||
$uniqueLines$.delete(oldLine.text);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
})
|
||||
: $lineData$;
|
||||
|
||||
if (oldLinesToRemove.size) {
|
||||
selectedLineIds = selectedLineIds.filter((selectedLineId) => !oldLinesToRemove.has(selectedLineId));
|
||||
}
|
||||
|
||||
return remainingLineData;
|
||||
}
|
||||
|
||||
function updateLineData(executeUpdate: boolean) {
|
||||
if (!executeUpdate) {
|
||||
return;
|
||||
}
|
||||
|
||||
$showSpinner$ = true;
|
||||
|
||||
try {
|
||||
for (let index = 0, { length } = $lineData$; index < length; index += 1) {
|
||||
const line = $lineData$[index];
|
||||
const newText = transformLine(line.text);
|
||||
|
||||
if (newText && newText !== line.text) {
|
||||
$uniqueLines$.delete(line.text);
|
||||
|
||||
$lineData$[index] = { ...line, text: newText };
|
||||
}
|
||||
}
|
||||
|
||||
$openDialog$ = {
|
||||
message: `Operation executed`,
|
||||
showCancel: false,
|
||||
};
|
||||
} catch ({ message }) {
|
||||
$openDialog$ = {
|
||||
type: 'error',
|
||||
message: `An Error occured: ${message}`,
|
||||
showCancel: false,
|
||||
};
|
||||
}
|
||||
|
||||
$lineData$ = applyEqualLineStartMerge(applyMaxLinesAndGetRemainingLineData());
|
||||
|
||||
$showSpinner$ = false;
|
||||
}
|
||||
|
||||
function applyEqualLineStartMerge(currentLineData: LineItem[]) {
|
||||
if (!$mergeEqualLineStarts$ || currentLineData.length < 2) {
|
||||
return currentLineData;
|
||||
}
|
||||
|
||||
const lastIndex = currentLineData.length - 1;
|
||||
const comparisonIndex = lastIndex - 1;
|
||||
const lastLine = currentLineData[lastIndex];
|
||||
const comparisonLine = currentLineData[comparisonIndex].text;
|
||||
|
||||
if (lastLine.text.startsWith(comparisonLine)) {
|
||||
$uniqueLines$.delete(comparisonLine);
|
||||
|
||||
selectedLineIds = selectedLineIds.filter(
|
||||
(selectedLineId) => selectedLineId !== currentLineData[comparisonIndex].id,
|
||||
);
|
||||
|
||||
currentLineData.splice(comparisonIndex, 2, lastLine);
|
||||
}
|
||||
|
||||
return currentLineData;
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window on:keyup={handleKeyPress} />
|
||||
|
||||
{$visibilityHandler$ ?? ''}
|
||||
{$handleLine$ ?? ''}
|
||||
{$pasteHandler$ ?? ''}
|
||||
{$copyBlocker$ ?? ''}
|
||||
{$resizeHandler$ ?? ''}
|
||||
|
||||
{#if $showSpinner$}
|
||||
<Spinner />
|
||||
{/if}
|
||||
|
||||
<DialogManager />
|
||||
|
||||
<header class="fixed top-0 right-0 flex justify-end items-center p-2 bg-base-100" bind:this={settingsContainer}>
|
||||
<Stats on:afkBlur={onAfkBlur} />
|
||||
{#if $websocketUrl$}
|
||||
<SocketConnector />
|
||||
{/if}
|
||||
{#if $secondaryWebsocketUrl$}
|
||||
<SocketConnector isPrimary={false} />
|
||||
{/if}
|
||||
{#if $isPaused$}
|
||||
<div
|
||||
role="button"
|
||||
title="Continue"
|
||||
class="mr-1 animate-[pulse_1.25s_cubic-bezier(0.4,0,0.6,1)_infinite] hover:text-primary sm:mr-2"
|
||||
>
|
||||
<Icon path={mdiPlay} width={iconSize} height={iconSize} on:click={() => ($isPaused$ = false)} />
|
||||
</div>
|
||||
{:else}
|
||||
<div role="button" title="Pause" class="mr-1 hover:text-primary sm:mr-2">
|
||||
<Icon path={mdiPause} width={iconSize} height={iconSize} on:click={() => ($isPaused$ = true)} />
|
||||
</div>
|
||||
{/if}
|
||||
<div
|
||||
role="button"
|
||||
title="Delete last Line"
|
||||
class="mr-1 hover:text-primary sm:mr-2"
|
||||
class:opacity-50={!$lineData$.length}
|
||||
class:cursor-not-allowed={!$lineData$.length}
|
||||
class:hover:text-primary={$lineData$.length}
|
||||
>
|
||||
<Icon path={mdiDeleteForever} width={iconSize} height={iconSize} on:click={removeLastLine} />
|
||||
</div>
|
||||
<div
|
||||
role="button"
|
||||
title="Undo last Action"
|
||||
class="mr-1 hover:text-primary sm:mr-2"
|
||||
class:opacity-50={!$actionHistory$.length}
|
||||
class:cursor-not-allowed={!$actionHistory$.length}
|
||||
class:hover:text-primary={$actionHistory$.length}
|
||||
>
|
||||
<Icon path={mdiArrowULeftTop} width={iconSize} height={iconSize} on:click={undoLastAction} />
|
||||
</div>
|
||||
{#if selectedLineIds.length}
|
||||
<div role="button" title="Remove selected Lines" class="mr-1 hover:text-primary sm:mr-2">
|
||||
<Icon path={mdiDelete} width={iconSize} height={iconSize} on:click={removeLines} />
|
||||
</div>
|
||||
<div role="button" title="Deselect Lines" class="mr-1 hover:text-primary sm:mr-2">
|
||||
<Icon path={mdiCancel} width={iconSize} height={iconSize} on:click={deselectLines} />
|
||||
</div>
|
||||
{/if}
|
||||
<div role="button" title="Open Notes" class="mr-1 hover:text-primary sm:mr-2">
|
||||
<Icon path={mdiNoteEdit} width={iconSize} height={iconSize} on:click={() => ($notesOpen$ = true)} />
|
||||
</div>
|
||||
{#if pipAvailable}
|
||||
<div
|
||||
role="button"
|
||||
class="mr-1 hover:text-primary sm:mr-2"
|
||||
title={pipWindow ? 'Close Floating Window' : 'Open Floating Window'}
|
||||
>
|
||||
<Icon
|
||||
width={iconSize}
|
||||
height={iconSize}
|
||||
path={pipWindow ? mdiWindowMaximize : mdiWindowRestore}
|
||||
on:click={handlePipAction}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<Icon
|
||||
class="cursor-pointer mr-1 hover:text-primary md:mr-2"
|
||||
path={mdiCog}
|
||||
width={iconSize}
|
||||
height={iconSize}
|
||||
bind:element={settingsElement}
|
||||
on:click={() => (settingsOpen = !settingsOpen)}
|
||||
/>
|
||||
<Settings
|
||||
{settingsElement}
|
||||
{pipAvailable}
|
||||
bind:settingsOpen
|
||||
bind:selectedLineIds
|
||||
bind:this={settingsComponent}
|
||||
on:applyReplacements={() => updateLineData(!!$enabledReplacements$.length)}
|
||||
on:layoutChange={executeUpdateScroll}
|
||||
on:maxLinesChange={() => ($lineData$ = applyMaxLinesAndGetRemainingLineData())}
|
||||
/>
|
||||
<Presets isQuickSwitch={true} on:layoutChange={executeUpdateScroll} />
|
||||
</header>
|
||||
<main
|
||||
class="flex flex-col flex-1 break-all px-4 w-full h-full overflow-auto"
|
||||
class:py-16={!$displayVertical$}
|
||||
class:py-8={$displayVertical$}
|
||||
class:opacity-50={$notesOpen$}
|
||||
class:flex-col-reverse={$reverseLineOrder$}
|
||||
style:font-size={`${$fontSize$}px`}
|
||||
style:font-family={$onlineFont$ !== OnlineFont.OFF ? $onlineFont$ : undefined}
|
||||
style:writing-mode={$displayVertical$ ? 'vertical-rl' : 'horizontal-tb'}
|
||||
bind:this={lineContainer}
|
||||
>
|
||||
{@html newLineCharacter}
|
||||
{#each $lineData$ as line, index (line.id)}
|
||||
<Line
|
||||
{line}
|
||||
{index}
|
||||
isLast={$lineData$.length - 1 === index}
|
||||
bind:this={lineElements[index]}
|
||||
on:selected={({ detail }) => {
|
||||
selectedLineIds = [...selectedLineIds, detail];
|
||||
}}
|
||||
on:deselected={({ detail }) => {
|
||||
selectedLineIds = selectedLineIds.filter((selectedLineId) => selectedLineId !== detail);
|
||||
}}
|
||||
on:edit={handleLineEdit}
|
||||
/>
|
||||
{/each}
|
||||
</main>
|
||||
{#if $notesOpen$}
|
||||
<div
|
||||
class="bg-base-200 fixed top-0 right-0 z-[60] flex h-full w-full max-w-3xl flex-col justify-between"
|
||||
in:fly|local={{ x: 100, duration: 100, easing: quintInOut }}
|
||||
>
|
||||
<Notes />
|
||||
</div>
|
||||
{/if}
|
||||
<div
|
||||
id="pip-container"
|
||||
class="flex flex-col flex-1 flex flex-col break-all px-4 w-full h-full overflow-auto"
|
||||
class:flex-col-reverse={$reverseLineOrder$}
|
||||
class:hidden={!pipWindow}
|
||||
style:font-size={`${$fontSize$}px`}
|
||||
style:font-family={$onlineFont$ !== OnlineFont.OFF ? $onlineFont$ : undefined}
|
||||
bind:this={pipContainer}
|
||||
>
|
||||
{#if pipWindow}
|
||||
{#each pipLines as line, index (line.id)}
|
||||
<Line {line} {index} {pipWindow} isLast={pipLines.length - 1 === index} />
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
64
vendor/texthooker-ui/src/components/Dialog.svelte
vendored
Normal file
64
vendor/texthooker-ui/src/components/Dialog.svelte
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
<script lang="ts">
|
||||
import { createEventDispatcher } from 'svelte';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
export let icon: string | undefined;
|
||||
export let message: string | undefined;
|
||||
export let type = 'info';
|
||||
export let showCancel = true;
|
||||
export let askForData = '';
|
||||
export let dataValue: string | number | undefined;
|
||||
export let callback: <T>(param: { canceled: boolean; data: T }) => void;
|
||||
|
||||
const dispatch = createEventDispatcher<{ close: void }>();
|
||||
|
||||
function handleChange(event: Event) {
|
||||
const target = event.target as HTMLInputElement;
|
||||
|
||||
dataValue = target.value;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="fixed top-12 flex justify-center w-full z-30">
|
||||
<div class="alert shadow-lg max-w-xl" class:alert-info={type === 'info'} class:alert-error={type === 'error'}>
|
||||
<div>
|
||||
{#if icon}
|
||||
<Icon path={icon} />
|
||||
{/if}
|
||||
<span>
|
||||
{#if askForData}
|
||||
<div>
|
||||
{#if askForData === 'text'}
|
||||
<input
|
||||
type={askForData}
|
||||
class="input input-bordered h-8 ml-2"
|
||||
value={dataValue}
|
||||
on:change={handleChange}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
{message}
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-none">
|
||||
{#if showCancel}
|
||||
<button
|
||||
class="btn btn-sm btn-ghost"
|
||||
on:click={() => {
|
||||
callback?.({ canceled: true, data: dataValue });
|
||||
dispatch('close');
|
||||
}}>Cancel</button
|
||||
>
|
||||
{/if}
|
||||
<button
|
||||
class="btn btn-sm btn-primary"
|
||||
on:click={() => {
|
||||
callback?.({ canceled: false, data: dataValue });
|
||||
dispatch('close');
|
||||
}}>Confirm</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
36
vendor/texthooker-ui/src/components/DialogManager.svelte
vendored
Normal file
36
vendor/texthooker-ui/src/components/DialogManager.svelte
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte';
|
||||
import { dialogOpen$, openDialog$ } from '../stores/stores';
|
||||
import Dialog from './Dialog.svelte';
|
||||
|
||||
let props: any;
|
||||
let dialogPropsQueue: any[] = [];
|
||||
|
||||
const sub = openDialog$.subscribe((d) => {
|
||||
if (
|
||||
!d ||
|
||||
((d.message.includes('Lost Connection to') || d.message.includes('Unable to connect to')) &&
|
||||
(props?.message === d.message || dialogPropsQueue.find((dialog) => dialog.message === d.message)))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
dialogPropsQueue.unshift(d);
|
||||
|
||||
if (!props) {
|
||||
handleDialog();
|
||||
}
|
||||
});
|
||||
|
||||
function handleDialog() {
|
||||
props = dialogPropsQueue.pop();
|
||||
|
||||
$dialogOpen$ = !!props;
|
||||
}
|
||||
|
||||
onDestroy(() => sub?.unsubscribe());
|
||||
</script>
|
||||
|
||||
{#if props}
|
||||
<Dialog {...props} on:close={handleDialog} />
|
||||
{/if}
|
||||
21
vendor/texthooker-ui/src/components/Icon.svelte
vendored
Normal file
21
vendor/texthooker-ui/src/components/Icon.svelte
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
<script lang="ts">
|
||||
export let path: string;
|
||||
export let width = '1.5rem';
|
||||
export let height = '1.5rem';
|
||||
export let element: SVGElement | undefined = undefined;
|
||||
export { _class as class };
|
||||
|
||||
let _class = '';
|
||||
</script>
|
||||
|
||||
<svg
|
||||
style="width: {width}; height: {height};"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
class={_class}
|
||||
bind:this={element}
|
||||
on:click
|
||||
on:keyup
|
||||
>
|
||||
<path d={path} />
|
||||
</svg>
|
||||
143
vendor/texthooker-ui/src/components/Line.svelte
vendored
Normal file
143
vendor/texthooker-ui/src/components/Line.svelte
vendored
Normal file
@@ -0,0 +1,143 @@
|
||||
<script lang="ts">
|
||||
import { mdiTrophy } from '@mdi/js';
|
||||
import { createEventDispatcher, onDestroy, onMount, tick } from 'svelte';
|
||||
import { fly } from 'svelte/transition';
|
||||
import {
|
||||
displayVertical$,
|
||||
enableLineAnimation$,
|
||||
milestoneLines$,
|
||||
preserveWhitespace$,
|
||||
reverseLineOrder$,
|
||||
} from '../stores/stores';
|
||||
import type { LineItem, LineItemEditEvent } from '../types';
|
||||
import { dummyFn, newLineCharacter, updateScroll } from '../util';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
export let line: LineItem;
|
||||
export let index: number;
|
||||
export let isLast: boolean;
|
||||
export let pipWindow: Window = undefined;
|
||||
|
||||
export function deselect() {
|
||||
isSelected = false;
|
||||
}
|
||||
|
||||
export function getIdIfSelected(range: Range) {
|
||||
return isSelected || range.intersectsNode(paragraph) ? line.id : undefined;
|
||||
}
|
||||
|
||||
const dispatch = createEventDispatcher<{ deselected: string; selected: string; edit: LineItemEditEvent }>();
|
||||
|
||||
let paragraph: HTMLElement;
|
||||
let originalText = '';
|
||||
let isSelected = false;
|
||||
let isEditable = false;
|
||||
|
||||
$: isVerticalDisplay = !pipWindow && $displayVertical$;
|
||||
|
||||
onMount(() => {
|
||||
if (isLast) {
|
||||
updateScroll(
|
||||
pipWindow || window,
|
||||
paragraph.parentElement,
|
||||
$reverseLineOrder$,
|
||||
isVerticalDisplay,
|
||||
$enableLineAnimation$ ? 'smooth' : 'auto',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
document.removeEventListener('click', clickOutsideHandler, false);
|
||||
dispatch('edit', { inEdit: false });
|
||||
});
|
||||
|
||||
function handleDblClick(event: MouseEvent) {
|
||||
if (pipWindow) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.getSelection()?.removeAllRanges();
|
||||
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
if (isSelected) {
|
||||
isSelected = false;
|
||||
dispatch('deselected', line.id);
|
||||
} else {
|
||||
isSelected = true;
|
||||
dispatch('selected', line.id);
|
||||
}
|
||||
} else {
|
||||
originalText = paragraph.innerText;
|
||||
isEditable = true;
|
||||
|
||||
dispatch('edit', { inEdit: true });
|
||||
|
||||
document.addEventListener('click', clickOutsideHandler, false);
|
||||
|
||||
tick().then(() => {
|
||||
paragraph.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function clickOutsideHandler(event: MouseEvent) {
|
||||
const target = event.target as Node;
|
||||
|
||||
if (!paragraph.contains(target)) {
|
||||
isEditable = false;
|
||||
document.removeEventListener('click', clickOutsideHandler, false);
|
||||
|
||||
dispatch('edit', {
|
||||
inEdit: false,
|
||||
data: { originalText, newText: paragraph.innerText, lineIndex: index, line },
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#key line.text}
|
||||
<p
|
||||
class="my-2 cursor-pointer border-2"
|
||||
class:py-4={!isVerticalDisplay}
|
||||
class:px-2={!isVerticalDisplay}
|
||||
class:py-2={isVerticalDisplay}
|
||||
class:px-4={isVerticalDisplay}
|
||||
class:border-transparent={!isSelected}
|
||||
class:cursor-text={isEditable}
|
||||
class:border-primary={isSelected}
|
||||
class:border-accent-focus={isEditable}
|
||||
class:whitespace-pre-wrap={$preserveWhitespace$}
|
||||
contenteditable={isEditable}
|
||||
on:dblclick={handleDblClick}
|
||||
on:keyup={dummyFn}
|
||||
bind:this={paragraph}
|
||||
in:fly={{ x: isVerticalDisplay ? 100 : -100, duration: $enableLineAnimation$ ? 250 : 0 }}
|
||||
>
|
||||
{line.text}
|
||||
</p>
|
||||
{/key}
|
||||
{@html newLineCharacter}
|
||||
{#if $milestoneLines$.has(line.id)}
|
||||
<div
|
||||
class="flex justify-center text-xs my-2 py-2 border-primary border-dashed milestone"
|
||||
class:border-x-2={$displayVertical$}
|
||||
class:border-y-2={!$displayVertical$}
|
||||
class:py-4={!isVerticalDisplay}
|
||||
class:px-2={!isVerticalDisplay}
|
||||
class:py-2={isVerticalDisplay}
|
||||
class:px-4={isVerticalDisplay}
|
||||
>
|
||||
<div class="flex items-center">
|
||||
<Icon class={$displayVertical$ ? '' : 'mr-2'} path={mdiTrophy}></Icon>
|
||||
<span class:mt-2={$displayVertical$}>{$milestoneLines$.get(line.id)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{@html newLineCharacter}
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
p:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
</style>
|
||||
26
vendor/texthooker-ui/src/components/Notes.svelte
vendored
Normal file
26
vendor/texthooker-ui/src/components/Notes.svelte
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
<script lang="ts">
|
||||
import { mdiClose } from '@mdi/js';
|
||||
import { notesOpen$, userNotes$ } from '../stores/stores';
|
||||
import { dummyFn } from '../util';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
function handleBlur(event: FocusEvent) {
|
||||
$userNotes$ = (event.target as HTMLTextAreaElement).value;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex justify-end p-4">
|
||||
<div
|
||||
class="flex cursor-pointer items-end md:items-center"
|
||||
on:click={() => ($notesOpen$ = false)}
|
||||
on:keyup={dummyFn}
|
||||
>
|
||||
<Icon path={mdiClose} />
|
||||
</div>
|
||||
</div>
|
||||
<textarea
|
||||
class="flex-1 overflow-auto ml-10 mr-2 mb-4 p-1 pb-2"
|
||||
style="resize: none;"
|
||||
value={$userNotes$}
|
||||
on:blur={handleBlur}
|
||||
/>
|
||||
330
vendor/texthooker-ui/src/components/Presets.svelte
vendored
Normal file
330
vendor/texthooker-ui/src/components/Presets.svelte
vendored
Normal file
@@ -0,0 +1,330 @@
|
||||
<script lang="ts">
|
||||
import { mdiContentSave, mdiDatabaseSync, mdiDelete, mdiHelpCircle, mdiReload } from '@mdi/js';
|
||||
import { createEventDispatcher, tick } from 'svelte';
|
||||
import {
|
||||
adjustTimerOnAfk$,
|
||||
afkTimer$,
|
||||
allowNewLineDuringPause$,
|
||||
allowPasteDuringPause$,
|
||||
autoStartTimerDuringPause$,
|
||||
autoStartTimerDuringPausePaste$,
|
||||
blockCopyOnPage$,
|
||||
blurStats$,
|
||||
characterMilestone$,
|
||||
continuousReconnect$,
|
||||
customCSS$,
|
||||
defaultSettings,
|
||||
displayVertical$,
|
||||
enableAfkBlur$,
|
||||
enableAfkBlurRestart$,
|
||||
enableExternalClipboardMonitor$,
|
||||
enableLineAnimation$,
|
||||
enablePaste$,
|
||||
filterNonCJKLines$,
|
||||
flashOnMissedLine$,
|
||||
fontSize$,
|
||||
lastSettingPreset$,
|
||||
maxLines$,
|
||||
maxPipLines$,
|
||||
mergeEqualLineStarts$,
|
||||
milestoneLines$,
|
||||
onlineFont$,
|
||||
openDialog$,
|
||||
persistActionHistory$,
|
||||
persistLines$,
|
||||
persistNotes$,
|
||||
persistStats$,
|
||||
preserveWhitespace$,
|
||||
preventGlobalDuplicate$,
|
||||
preventLastDuplicate$,
|
||||
reconnectSecondarySocket$,
|
||||
reconnectSocket$,
|
||||
removeAllWhitespace$,
|
||||
replacements$,
|
||||
reverseLineOrder$,
|
||||
secondarySocketState$,
|
||||
secondaryWebsocketUrl$,
|
||||
settingPresets$,
|
||||
showCharacterCount$,
|
||||
showConnectionErrors$,
|
||||
showConnectionIcon$,
|
||||
showLineCount$,
|
||||
showPresetQuickSwitch$,
|
||||
showSpeed$,
|
||||
showTimer$,
|
||||
skipResetConfirmations$,
|
||||
socketState$,
|
||||
theme$,
|
||||
websocketUrl$,
|
||||
windowTitle$,
|
||||
} from '../stores/stores';
|
||||
import type { DialogResult, SettingPreset, Settings } from '../types';
|
||||
import { dummyFn } from '../util';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
export let isQuickSwitch = false;
|
||||
|
||||
export function getCurrentSettings(): Settings {
|
||||
return {
|
||||
theme$: $theme$,
|
||||
replacements$: $replacements$,
|
||||
windowTitle$: $windowTitle$,
|
||||
websocketUrl$: $websocketUrl$,
|
||||
secondaryWebsocketUrl$: $secondaryWebsocketUrl$,
|
||||
fontSize$: $fontSize$,
|
||||
characterMilestone$: $characterMilestone$,
|
||||
onlineFont$: $onlineFont$,
|
||||
preventLastDuplicate$: $preventLastDuplicate$,
|
||||
maxLines$: $maxLines$,
|
||||
maxPipLines$: $maxPipLines$,
|
||||
afkTimer$: $afkTimer$,
|
||||
adjustTimerOnAfk$: $adjustTimerOnAfk$,
|
||||
enableExternalClipboardMonitor$: $enableExternalClipboardMonitor$,
|
||||
showPresetQuickSwitch$: $showPresetQuickSwitch$,
|
||||
skipResetConfirmations$: $skipResetConfirmations$,
|
||||
persistStats$: $persistStats$,
|
||||
persistNotes$: $persistNotes$,
|
||||
persistLines$: $persistLines$,
|
||||
persistActionHistory$: $persistActionHistory$,
|
||||
enablePaste$: $enablePaste$,
|
||||
blockCopyOnPage$: $blockCopyOnPage$,
|
||||
allowPasteDuringPause$: $allowPasteDuringPause$,
|
||||
allowNewLineDuringPause$: $allowNewLineDuringPause$,
|
||||
autoStartTimerDuringPausePaste$: $autoStartTimerDuringPausePaste$,
|
||||
autoStartTimerDuringPause$: $autoStartTimerDuringPause$,
|
||||
preventGlobalDuplicate$: $preventGlobalDuplicate$,
|
||||
mergeEqualLineStarts$: $mergeEqualLineStarts$,
|
||||
filterNonCJKLines: $filterNonCJKLines$,
|
||||
flashOnMissedLine$: $flashOnMissedLine$,
|
||||
displayVertical$: $displayVertical$,
|
||||
reverseLineOrder$: $reverseLineOrder$,
|
||||
preserveWhitespace$: $preserveWhitespace$,
|
||||
removeAllWhitespace$: $removeAllWhitespace$,
|
||||
showTimer$: $showTimer$,
|
||||
showSpeed$: $showSpeed$,
|
||||
showCharacterCount$: $showCharacterCount$,
|
||||
showLineCount$: $showLineCount$,
|
||||
blurStats$: $blurStats$,
|
||||
enableLineAnimation$: $enableLineAnimation$,
|
||||
enableAfkBlur$: $enableAfkBlur$,
|
||||
enableAfkBlurRestart$: $enableAfkBlurRestart$,
|
||||
continuousReconnect$: $continuousReconnect$,
|
||||
showConnectionErrors$: $showConnectionErrors$,
|
||||
showConnectionIcon$: $showConnectionIcon$,
|
||||
customCSS$: $customCSS$,
|
||||
};
|
||||
}
|
||||
|
||||
export function updateSettingsWithPreset(preset: SettingPreset, updateLastPreset = true) {
|
||||
theme$.next(preset.settings.theme$ ?? defaultSettings.theme$);
|
||||
replacements$.next(preset.settings.replacements$ ?? defaultSettings.replacements$);
|
||||
windowTitle$.next(preset.settings.windowTitle$ ?? defaultSettings.windowTitle$);
|
||||
websocketUrl$.next(preset.settings.websocketUrl$ ?? defaultSettings.websocketUrl$);
|
||||
secondaryWebsocketUrl$.next(preset.settings.secondaryWebsocketUrl$ ?? '');
|
||||
fontSize$.next(preset.settings.fontSize$ ?? defaultSettings.fontSize$);
|
||||
characterMilestone$.next(preset.settings.characterMilestone$ ?? defaultSettings.characterMilestone$);
|
||||
onlineFont$.next(preset.settings.onlineFont$ ?? defaultSettings.onlineFont$);
|
||||
preventLastDuplicate$.next(preset.settings.preventLastDuplicate$ ?? defaultSettings.preventLastDuplicate$);
|
||||
maxLines$.next(preset.settings.maxLines$ ?? defaultSettings.maxLines$);
|
||||
maxPipLines$.next(preset.settings.maxPipLines$ ?? defaultSettings.maxPipLines$);
|
||||
afkTimer$.next(preset.settings.afkTimer$ ?? defaultSettings.afkTimer$);
|
||||
adjustTimerOnAfk$.next(preset.settings.adjustTimerOnAfk$ ?? defaultSettings.adjustTimerOnAfk$);
|
||||
enableExternalClipboardMonitor$.next(
|
||||
preset.settings.enableExternalClipboardMonitor$ ?? defaultSettings.enableExternalClipboardMonitor$,
|
||||
);
|
||||
showPresetQuickSwitch$.next(preset.settings.showPresetQuickSwitch$ ?? defaultSettings.showPresetQuickSwitch$);
|
||||
skipResetConfirmations$.next(
|
||||
preset.settings.skipResetConfirmations$ ?? defaultSettings.skipResetConfirmations$,
|
||||
);
|
||||
persistStats$.next(preset.settings.persistStats$ ?? defaultSettings.persistStats$);
|
||||
persistNotes$.next(preset.settings.persistNotes$ ?? defaultSettings.persistNotes$);
|
||||
persistLines$.next(preset.settings.persistLines$ ?? defaultSettings.persistLines$);
|
||||
persistActionHistory$.next(preset.settings.persistActionHistory$ ?? defaultSettings.persistActionHistory$);
|
||||
enablePaste$.next(preset.settings.enablePaste$ ?? defaultSettings.enablePaste$);
|
||||
blockCopyOnPage$.next(preset.settings.blockCopyOnPage$ ?? defaultSettings.blockCopyOnPage$);
|
||||
allowPasteDuringPause$.next(preset.settings.allowPasteDuringPause$ ?? defaultSettings.allowPasteDuringPause$);
|
||||
allowNewLineDuringPause$.next(
|
||||
preset.settings.allowNewLineDuringPause$ ?? defaultSettings.allowNewLineDuringPause$,
|
||||
);
|
||||
autoStartTimerDuringPausePaste$.next(
|
||||
preset.settings.autoStartTimerDuringPausePaste$ ?? defaultSettings.autoStartTimerDuringPausePaste$,
|
||||
);
|
||||
autoStartTimerDuringPause$.next(
|
||||
preset.settings.autoStartTimerDuringPause$ ?? defaultSettings.autoStartTimerDuringPause$,
|
||||
);
|
||||
preventGlobalDuplicate$.next(
|
||||
preset.settings.preventGlobalDuplicate$ ?? defaultSettings.preventGlobalDuplicate$,
|
||||
);
|
||||
mergeEqualLineStarts$.next(preset.settings.mergeEqualLineStarts$ ?? defaultSettings.mergeEqualLineStarts$);
|
||||
filterNonCJKLines$.next(preset.settings.filterNonCJKLines ?? defaultSettings.filterNonCJKLines);
|
||||
flashOnMissedLine$.next(preset.settings.flashOnMissedLine$ ?? defaultSettings.flashOnMissedLine$);
|
||||
displayVertical$.next(preset.settings.displayVertical$ ?? defaultSettings.displayVertical$);
|
||||
reverseLineOrder$.next(preset.settings.reverseLineOrder$ ?? defaultSettings.reverseLineOrder$);
|
||||
preserveWhitespace$.next(preset.settings.preserveWhitespace$ ?? defaultSettings.preserveWhitespace$);
|
||||
removeAllWhitespace$.next(preset.settings.removeAllWhitespace$ ?? defaultSettings.removeAllWhitespace$);
|
||||
showTimer$.next(preset.settings.showTimer$ ?? defaultSettings.showTimer$);
|
||||
showSpeed$.next(preset.settings.showSpeed$ ?? defaultSettings.showSpeed$);
|
||||
showCharacterCount$.next(preset.settings.showCharacterCount$ ?? defaultSettings.showCharacterCount$);
|
||||
showLineCount$.next(preset.settings.showLineCount$ ?? defaultSettings.showLineCount$);
|
||||
blurStats$.next(preset.settings.blurStats$ ?? defaultSettings.blurStats$);
|
||||
enableLineAnimation$.next(preset.settings.enableLineAnimation$ ?? defaultSettings.enableLineAnimation$);
|
||||
enableAfkBlur$.next(preset.settings.enableAfkBlur$ ?? defaultSettings.enableAfkBlur$);
|
||||
enableAfkBlurRestart$.next(preset.settings.enableAfkBlurRestart$ ?? defaultSettings.enableAfkBlurRestart$);
|
||||
continuousReconnect$.next(preset.settings.continuousReconnect$ ?? defaultSettings.continuousReconnect$);
|
||||
showConnectionErrors$.next(preset.settings.showConnectionErrors$ ?? defaultSettings.showConnectionErrors$);
|
||||
showConnectionIcon$.next(preset.settings.showConnectionIcon$ ?? defaultSettings.showConnectionIcon$);
|
||||
customCSS$.next(preset.settings.customCSS$ ?? defaultSettings.customCSS$);
|
||||
|
||||
if (updateLastPreset) {
|
||||
$lastSettingPreset$ = preset.name;
|
||||
}
|
||||
|
||||
if ($characterMilestone$ === 0) {
|
||||
$milestoneLines$ = new Map<string, string>();
|
||||
}
|
||||
|
||||
tick().then(() => {
|
||||
dispatch('layoutChange');
|
||||
|
||||
if ($socketState$ !== 1 && $continuousReconnect$) {
|
||||
reconnectSocket$.next();
|
||||
}
|
||||
|
||||
if ($secondarySocketState$ !== 1 && $continuousReconnect$) {
|
||||
reconnectSecondarySocket$.next();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const fallbackPresetEntry = [{ name: '' }];
|
||||
const dispatch = createEventDispatcher<{ layoutChange: void; exportImportPreset: MouseEvent }>();
|
||||
|
||||
function selectPreset(event: Event) {
|
||||
const target = event.target as HTMLSelectElement;
|
||||
|
||||
changePreset(target.selectedOptions[0].value);
|
||||
}
|
||||
|
||||
function changePreset(presetName: string) {
|
||||
const existingEntry = $settingPresets$.find((entry) => entry.name === presetName);
|
||||
|
||||
if (existingEntry) {
|
||||
updateSettingsWithPreset(existingEntry);
|
||||
}
|
||||
}
|
||||
|
||||
async function savePreset() {
|
||||
const { canceled, data } = await new Promise<DialogResult<string>>((resolve) => {
|
||||
$openDialog$ = {
|
||||
icon: mdiHelpCircle,
|
||||
askForData: 'text',
|
||||
dataValue: $lastSettingPreset$ || 'Preset Name',
|
||||
message: '',
|
||||
callback: resolve,
|
||||
};
|
||||
});
|
||||
|
||||
if (canceled || !data) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingEntryIndex = $settingPresets$.findIndex((entry) => entry.name === data);
|
||||
const entry: SettingPreset = {
|
||||
name: data,
|
||||
settings: getCurrentSettings(),
|
||||
};
|
||||
|
||||
if (existingEntryIndex > -1) {
|
||||
$settingPresets$[existingEntryIndex] = entry;
|
||||
} else {
|
||||
$settingPresets$ = [...$settingPresets$, entry];
|
||||
}
|
||||
|
||||
$lastSettingPreset$ = data;
|
||||
}
|
||||
|
||||
async function deletePreset() {
|
||||
if (!$skipResetConfirmations$) {
|
||||
const { canceled } = await new Promise<DialogResult>((resolve) => {
|
||||
$openDialog$ = {
|
||||
icon: mdiHelpCircle,
|
||||
message: 'Preset will be deleted',
|
||||
callback: resolve,
|
||||
};
|
||||
});
|
||||
|
||||
if (canceled) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$settingPresets$ = $settingPresets$.filter((entry) => entry.name !== $lastSettingPreset$);
|
||||
$lastSettingPreset$ = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if isQuickSwitch}
|
||||
<select
|
||||
class="w-48 hidden sm:block"
|
||||
class:sm:hidden={!$showPresetQuickSwitch$ || $settingPresets$.length < 2}
|
||||
value={$lastSettingPreset$}
|
||||
on:change={selectPreset}
|
||||
>
|
||||
{#each $settingPresets$.length ? $settingPresets$ : fallbackPresetEntry as preset (preset.name)}
|
||||
<option value={preset.name}>
|
||||
{preset.name}
|
||||
</option>
|
||||
{/each}
|
||||
</select>
|
||||
{:else}
|
||||
<details role="button" class="col-span-4 mb-2">
|
||||
<summary>Presets</summary>
|
||||
<div class="flex items-center justify-between mt-2">
|
||||
<select class="select flex-1 max-w-md" value={$lastSettingPreset$} on:change={selectPreset}>
|
||||
{#each $settingPresets$.length ? $settingPresets$ : fallbackPresetEntry as preset (preset.name)}
|
||||
<option value={preset.name}>
|
||||
{preset.name || 'No Presets stored'}
|
||||
</option>
|
||||
{/each}
|
||||
</select>
|
||||
<div
|
||||
role="button"
|
||||
class="flex flex-col items-center hover:text-primary ml-3"
|
||||
on:click={savePreset}
|
||||
on:keyup={dummyFn}
|
||||
>
|
||||
<Icon path={mdiContentSave} />
|
||||
<span class="label-text">Save</span>
|
||||
</div>
|
||||
<div
|
||||
role="button"
|
||||
class="flex flex-col items-center hover:text-primary ml-3"
|
||||
on:click={(event) => dispatch('exportImportPreset', event)}
|
||||
on:keyup={dummyFn}
|
||||
>
|
||||
<Icon path={mdiDatabaseSync} />
|
||||
<span class="label-text">Export/Import</span>
|
||||
</div>
|
||||
<div
|
||||
role="button"
|
||||
class="flex flex-col items-center hover:text-primary ml-3"
|
||||
class:invisible={!$lastSettingPreset$}
|
||||
on:click={() => changePreset($lastSettingPreset$)}
|
||||
on:keyup={dummyFn}
|
||||
>
|
||||
<Icon path={mdiReload} />
|
||||
<span class="label-text">Reload</span>
|
||||
</div>
|
||||
<div
|
||||
role="button"
|
||||
class="flex flex-col items-center hover:text-primary ml-3"
|
||||
class:invisible={!$lastSettingPreset$}
|
||||
on:click={deletePreset}
|
||||
on:keyup={dummyFn}
|
||||
>
|
||||
<Icon path={mdiDelete} />
|
||||
<span class="label-text">Delete</span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
{/if}
|
||||
52
vendor/texthooker-ui/src/components/ReplacementSettings.svelte
vendored
Normal file
52
vendor/texthooker-ui/src/components/ReplacementSettings.svelte
vendored
Normal file
@@ -0,0 +1,52 @@
|
||||
<script lang="ts">
|
||||
import { mdiPlus } from '@mdi/js';
|
||||
import { replacements$ } from '../stores/stores';
|
||||
import type { ReplacementItem } from '../types';
|
||||
import Icon from './Icon.svelte';
|
||||
import ReplacementSettingsInput from './ReplacementSettingsInput.svelte';
|
||||
import ReplacementSettingsList from './ReplacementSettingsList.svelte';
|
||||
|
||||
let inEditMode = false;
|
||||
|
||||
let currentReplacement: ReplacementItem | undefined;
|
||||
|
||||
$: hasReplacements = !!$replacements$.length;
|
||||
|
||||
$: resetEditMode($replacements$);
|
||||
|
||||
function resetEditMode(_replacements: ReplacementItem[]) {
|
||||
inEditMode = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<details class="col-span-4 mb-2 cursor-pointer max-w-lg">
|
||||
<summary>Replacements</summary>
|
||||
<div class="mb-8">
|
||||
{#if inEditMode}
|
||||
<ReplacementSettingsInput
|
||||
{currentReplacement}
|
||||
on:close={() => {
|
||||
inEditMode = false;
|
||||
currentReplacement = undefined;
|
||||
}}
|
||||
/>
|
||||
{:else if hasReplacements}
|
||||
{#key $replacements$}
|
||||
<ReplacementSettingsList
|
||||
on:edit={({ detail }) => {
|
||||
currentReplacement = detail;
|
||||
inEditMode = true;
|
||||
}}
|
||||
on:applyReplacements
|
||||
/>
|
||||
{/key}
|
||||
{:else}
|
||||
<div class="flex justify-end my-2">
|
||||
<button title="Add replacement" class="ml-2 hover:text-primary" on:click={() => (inEditMode = true)}>
|
||||
<Icon path={mdiPlus} />
|
||||
</button>
|
||||
</div>
|
||||
<div>You have currently no replacements configured</div>
|
||||
{/if}
|
||||
</div>
|
||||
</details>
|
||||
132
vendor/texthooker-ui/src/components/ReplacementSettingsInput.svelte
vendored
Normal file
132
vendor/texthooker-ui/src/components/ReplacementSettingsInput.svelte
vendored
Normal file
@@ -0,0 +1,132 @@
|
||||
<script lang="ts">
|
||||
import { mdiCancel, mdiFloppy, mdiInformation } from '@mdi/js';
|
||||
import { debounceTime, Subject, tap } from 'rxjs';
|
||||
import { createEventDispatcher } from 'svelte';
|
||||
import { replacements$ } from '../stores/stores';
|
||||
import type { ReplacementItem } from '../types';
|
||||
import { applyReplacements, reduceToEmptyString } from '../util';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
export let currentReplacement: ReplacementItem | undefined;
|
||||
|
||||
const dispatch = createEventDispatcher<{ close: void }>();
|
||||
|
||||
const applyPattern$ = new Subject<void>();
|
||||
const replacement: ReplacementItem = currentReplacement
|
||||
? JSON.parse(JSON.stringify(currentReplacement))
|
||||
: { pattern: '', replaces: '', flags: [], enabled: true };
|
||||
const flags = [
|
||||
{ label: 'global', value: 'g' },
|
||||
{ label: 'multiline', value: 'm' },
|
||||
{ label: 'insensitive', value: 'i' },
|
||||
{ label: 'unicode', value: 'u' },
|
||||
];
|
||||
|
||||
const executePattern$ = applyPattern$.pipe(
|
||||
debounceTime(500),
|
||||
tap(() => {
|
||||
try {
|
||||
currentPatternError = '';
|
||||
|
||||
if (!replacement.pattern || !currentTestValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentTestOutcome = applyReplacements(currentTestValue, [replacement]);
|
||||
} catch ({ message }) {
|
||||
currentPatternError = `Error: ${message}`;
|
||||
}
|
||||
}),
|
||||
reduceToEmptyString(),
|
||||
);
|
||||
|
||||
let patternInput: HTMLInputElement;
|
||||
let currentTestValue = '';
|
||||
let currentTestOutcome = '';
|
||||
let currentPatternError = '';
|
||||
|
||||
function onExecutePattern() {
|
||||
patternInput.setCustomValidity(currentPatternError);
|
||||
|
||||
applyPattern$.next();
|
||||
}
|
||||
|
||||
function onSave() {
|
||||
if (!currentReplacement && $replacements$.find((entry) => entry.pattern === replacement.pattern)) {
|
||||
patternInput.setCustomValidity('This pattern already exists');
|
||||
|
||||
return patternInput.reportValidity();
|
||||
}
|
||||
|
||||
if (currentReplacement) {
|
||||
$replacements$ = $replacements$.map((entry) => {
|
||||
if (entry.pattern === currentReplacement.pattern) {
|
||||
return replacement;
|
||||
}
|
||||
|
||||
return entry;
|
||||
});
|
||||
} else {
|
||||
$replacements$ = [...$replacements$, replacement];
|
||||
}
|
||||
|
||||
dispatch('close');
|
||||
}
|
||||
</script>
|
||||
|
||||
{$executePattern$ ?? ''}
|
||||
<div class="flex justify-end my-2">
|
||||
{#if replacement.pattern}
|
||||
<button title="Save" class="hover:text-primary" on:click={onSave}>
|
||||
<Icon path={mdiFloppy} />
|
||||
</button>
|
||||
{/if}
|
||||
<button title="Cancel" class="ml-2 hover:text-primary" on:click={() => dispatch('close')}>
|
||||
<Icon path={mdiCancel} />
|
||||
</button>
|
||||
<button
|
||||
title="Cancel"
|
||||
class="ml-2 hover:text-primary"
|
||||
on:click={() =>
|
||||
window.open(
|
||||
'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#description',
|
||||
'_blank',
|
||||
)}
|
||||
>
|
||||
<Icon path={mdiInformation} />
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<input
|
||||
placeholder="text pattern"
|
||||
class="w-full my-2"
|
||||
bind:value={replacement.pattern}
|
||||
bind:this={patternInput}
|
||||
on:input={onExecutePattern}
|
||||
/>
|
||||
<input
|
||||
placeholder="replacement pattern"
|
||||
class="w-full my-2"
|
||||
bind:value={replacement.replaces}
|
||||
on:input={onExecutePattern}
|
||||
/>
|
||||
<div class="flex justify-between my-4">
|
||||
{#each flags as flag (flag.value)}
|
||||
<label>
|
||||
<input type="checkbox" value={flag.value} bind:group={replacement.flags} on:change={onExecutePattern} />
|
||||
{flag.label}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
<textarea
|
||||
name="test-value"
|
||||
placeholder="test value"
|
||||
class="w-full my-4"
|
||||
rows="3"
|
||||
bind:value={currentTestValue}
|
||||
on:input={onExecutePattern}
|
||||
/>
|
||||
<div class="whitespace-pre-wrap break-all">
|
||||
{@html currentPatternError || currentTestOutcome}
|
||||
</div>
|
||||
</div>
|
||||
118
vendor/texthooker-ui/src/components/ReplacementSettingsList.svelte
vendored
Normal file
118
vendor/texthooker-ui/src/components/ReplacementSettingsList.svelte
vendored
Normal file
@@ -0,0 +1,118 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
mdiDownloadMultiple,
|
||||
mdiPencil,
|
||||
mdiPlus,
|
||||
mdiToggleSwitchOffOutline,
|
||||
mdiToggleSwitchOutline,
|
||||
mdiTrashCanOutline,
|
||||
} from '@mdi/js';
|
||||
import Sortable, { Swap } from 'sortablejs';
|
||||
import { createEventDispatcher, onMount } from 'svelte';
|
||||
import { enabledReplacements$, lineData$, replacements$ } from '../stores/stores';
|
||||
import type { ReplacementItem } from '../types';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
const dispatch = createEventDispatcher<{ edit: ReplacementItem | undefined; applyReplacements: void }>();
|
||||
|
||||
let sortableInstance: Sortable;
|
||||
let listContainer: HTMLDivElement;
|
||||
let listItems = JSON.parse(JSON.stringify($replacements$));
|
||||
|
||||
$: canApplyReplacements = !!$lineData$.length && !!$enabledReplacements$.length;
|
||||
|
||||
onMount(() => {
|
||||
try {
|
||||
Sortable.mount(new Swap());
|
||||
} catch (_) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
sortableInstance = Sortable.create(listContainer, {
|
||||
swap: true,
|
||||
swapClass: 'swap',
|
||||
animation: 150,
|
||||
store: {
|
||||
get: getSortableList,
|
||||
set: onUpdateList,
|
||||
},
|
||||
});
|
||||
|
||||
return () => sortableInstance?.destroy();
|
||||
});
|
||||
|
||||
function onToggle(newValue: boolean) {
|
||||
const sortedList = getSortedList();
|
||||
|
||||
listItems = sortedList.map((replacement) => ({ ...replacement, enabled: newValue }));
|
||||
$replacements$ = listItems;
|
||||
}
|
||||
|
||||
function onUpdateList() {
|
||||
$replacements$ = getSortedList();
|
||||
}
|
||||
|
||||
function onReplaceItems(newReplacements: ReplacementItem[]) {
|
||||
listItems = newReplacements;
|
||||
$replacements$ = newReplacements;
|
||||
|
||||
sortableInstance.sort(getSortableList(), false);
|
||||
}
|
||||
|
||||
function getSortableList() {
|
||||
return [...listItems.map((replacments) => replacments.pattern)];
|
||||
}
|
||||
|
||||
function getSortedList() {
|
||||
const sortedList = sortableInstance.toArray();
|
||||
|
||||
return listItems.slice().sort((a, b) => sortedList.indexOf(a.pattern) - sortedList.indexOf(b.pattern));
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex justify-end my-2">
|
||||
<button
|
||||
title="Apply to current lines"
|
||||
class:hover:text-primary={canApplyReplacements}
|
||||
class:cursor-not-allowed={!canApplyReplacements}
|
||||
disabled={!canApplyReplacements}
|
||||
on:click={() => dispatch('applyReplacements')}
|
||||
>
|
||||
<Icon path={mdiDownloadMultiple} />
|
||||
</button>
|
||||
<button title="Add replacement" class="ml-2 hover:text-primary" on:click={() => dispatch('edit', undefined)}>
|
||||
<Icon path={mdiPlus} />
|
||||
</button>
|
||||
<button title="Enable all" class="ml-2 hover:text-primary" on:click={() => onToggle(true)}>
|
||||
<Icon path={mdiToggleSwitchOutline} />
|
||||
</button>
|
||||
<button title="Disable all" class="ml-2 hover:text-primary" on:click={() => onToggle(false)}>
|
||||
<Icon path={mdiToggleSwitchOffOutline} />
|
||||
</button>
|
||||
<button title="Remove all" class="ml-2 hover:text-primary" on:click={() => onReplaceItems([])}>
|
||||
<Icon path={mdiTrashCanOutline} />
|
||||
</button>
|
||||
</div>
|
||||
<div class="max-h-72 overflow-auto" bind:this={listContainer}>
|
||||
{#each listItems as replacement (replacement.pattern)}
|
||||
<div class="border my-2 p-2 flex items-center justify-between" data-id={replacement.pattern}>
|
||||
<div class="break-all">
|
||||
{replacement.pattern}
|
||||
</div>
|
||||
<div class="min-w-max ml-2">
|
||||
<button title="Edit" class="hover:text-primary" on:click={() => dispatch('edit', replacement)}>
|
||||
<Icon path={mdiPencil} height="1rem" />
|
||||
</button>
|
||||
<button
|
||||
title="Remove"
|
||||
class="hover:text-primary"
|
||||
on:click={() =>
|
||||
onReplaceItems($replacements$.filter((entry) => entry.pattern !== replacement.pattern))}
|
||||
>
|
||||
<Icon path={mdiTrashCanOutline} height="1rem" />
|
||||
</button>
|
||||
<input type="checkbox" class="ml-1" bind:checked={replacement.enabled} on:change={onUpdateList} />
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
1013
vendor/texthooker-ui/src/components/Settings.svelte
vendored
Normal file
1013
vendor/texthooker-ui/src/components/Settings.svelte
vendored
Normal file
File diff suppressed because it is too large
Load Diff
121
vendor/texthooker-ui/src/components/SocketConnector.svelte
vendored
Normal file
121
vendor/texthooker-ui/src/components/SocketConnector.svelte
vendored
Normal file
@@ -0,0 +1,121 @@
|
||||
<script lang="ts">
|
||||
import { mdiConnection } from '@mdi/js';
|
||||
import { onMount } from 'svelte';
|
||||
import { SocketConnection } from '../socket';
|
||||
import {
|
||||
continuousReconnect$,
|
||||
isPaused$,
|
||||
openDialog$,
|
||||
reconnectSecondarySocket$,
|
||||
reconnectSocket$,
|
||||
secondarySocketState$,
|
||||
secondaryWebsocketUrl$,
|
||||
showConnectionErrors$,
|
||||
showConnectionIcon$,
|
||||
socketState$,
|
||||
websocketUrl$,
|
||||
} from '../stores/stores';
|
||||
import Icon from './Icon.svelte';
|
||||
|
||||
export let isPrimary = true;
|
||||
|
||||
let socketConnection: SocketConnection | undefined;
|
||||
let intitialAttemptDone = false;
|
||||
let wasConnected = false;
|
||||
let closeRequested = false;
|
||||
let socketState = isPrimary ? socketState$ : secondarySocketState$;
|
||||
|
||||
$: connectedWithLabel = updateConnectedWithLabel(wasConnected);
|
||||
|
||||
$: handleSocketState($socketState);
|
||||
|
||||
onMount(() => {
|
||||
toggleSocket();
|
||||
|
||||
return () => {
|
||||
closeRequested = true;
|
||||
socketConnection?.cleanUp();
|
||||
};
|
||||
});
|
||||
|
||||
function handleSocketState(socketStateValue) {
|
||||
switch (socketStateValue) {
|
||||
case 0:
|
||||
wasConnected = false;
|
||||
closeRequested = false;
|
||||
break;
|
||||
case 1:
|
||||
intitialAttemptDone = true;
|
||||
wasConnected = true;
|
||||
break;
|
||||
case 3:
|
||||
const socketType = isPrimary ? 'primary' : 'secondary';
|
||||
const socketUrl = isPrimary ? $websocketUrl$ : $secondaryWebsocketUrl$;
|
||||
|
||||
if (
|
||||
$showConnectionErrors$ &&
|
||||
!closeRequested &&
|
||||
intitialAttemptDone &&
|
||||
socketUrl &&
|
||||
(wasConnected || !$continuousReconnect$)
|
||||
) {
|
||||
$openDialog$ = {
|
||||
type: 'error',
|
||||
message: wasConnected
|
||||
? `Lost Connection to ${socketType} Websocket`
|
||||
: `Unable to connect to ${socketType} Websocket`,
|
||||
showCancel: false,
|
||||
};
|
||||
}
|
||||
|
||||
$isPaused$ = true;
|
||||
|
||||
intitialAttemptDone = true;
|
||||
wasConnected = false;
|
||||
|
||||
if (!closeRequested) {
|
||||
(isPrimary ? reconnectSocket$ : reconnectSecondarySocket$).next();
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
connectedWithLabel = updateConnectedWithLabel(wasConnected);
|
||||
}
|
||||
|
||||
function updateConnectedWithLabel(hasConnection: boolean) {
|
||||
return hasConnection
|
||||
? `Connected with ${isPrimary ? $websocketUrl$ : $secondaryWebsocketUrl$}`
|
||||
: 'Not Connected';
|
||||
}
|
||||
|
||||
async function toggleSocket() {
|
||||
if ($socketState === 1 && socketConnection) {
|
||||
closeRequested = true;
|
||||
socketConnection.disconnect();
|
||||
} else {
|
||||
socketConnection = socketConnection || new SocketConnection(isPrimary);
|
||||
socketConnection.connect();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if $socketState !== 0}
|
||||
<div
|
||||
class="hover:text-primary"
|
||||
class:text-red-500={$socketState !== -1}
|
||||
class:text-green-700={$socketState === 1}
|
||||
class:hidden={!$showConnectionIcon$}
|
||||
title={connectedWithLabel}
|
||||
>
|
||||
<Icon path={mdiConnection} class="cursor-pointer mx-2" on:click={toggleSocket} />
|
||||
</div>
|
||||
{:else}
|
||||
<span
|
||||
class="animate-ping relative inline-flex rounded-full h-3 w-3 mx-3 bg-primary"
|
||||
class:hidden={!$showConnectionIcon$}
|
||||
/>
|
||||
{/if}
|
||||
23
vendor/texthooker-ui/src/components/Spinner.svelte
vendored
Normal file
23
vendor/texthooker-ui/src/components/Spinner.svelte
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
<div class="tap-highlight-transparent absolute inset-0 bg-black/[.3] z-20" />
|
||||
<div class="fixed inset-0 flex h-full w-full items-center justify-center z-50">
|
||||
<div role="status">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600"
|
||||
viewBox="0 0 100 101"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
|
||||
fill="currentFill"
|
||||
/>
|
||||
</svg>
|
||||
<span class="sr-only">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div />
|
||||
216
vendor/texthooker-ui/src/components/Stats.svelte
vendored
Normal file
216
vendor/texthooker-ui/src/components/Stats.svelte
vendored
Normal file
@@ -0,0 +1,216 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
combineLatest,
|
||||
debounceTime,
|
||||
fromEvent,
|
||||
interval,
|
||||
merge,
|
||||
NEVER,
|
||||
startWith,
|
||||
switchMap,
|
||||
tap,
|
||||
throttleTime,
|
||||
} from 'rxjs';
|
||||
import { createEventDispatcher } from 'svelte';
|
||||
import {
|
||||
adjustTimerOnAfk$,
|
||||
afkTimer$,
|
||||
blurStats$,
|
||||
characterMilestone$,
|
||||
enableAfkBlur$,
|
||||
enableAfkBlurRestart$,
|
||||
isPaused$,
|
||||
lineData$,
|
||||
milestoneLines$,
|
||||
newLine$,
|
||||
showCharacterCount$,
|
||||
showLineCount$,
|
||||
showSpeed$,
|
||||
showTimer$,
|
||||
timeValue$,
|
||||
} from '../stores/stores';
|
||||
import { reduceToEmptyString, toTimeString } from '../util';
|
||||
|
||||
let lastTick = 0;
|
||||
let idleTime = 0;
|
||||
|
||||
const dispatch = createEventDispatcher<{ afkBlur: boolean }>();
|
||||
|
||||
const isNotJapaneseRegex = /[^0-9A-Z○◯々-〇〻ぁ-ゖゝ-ゞァ-ヺー0-9A-Zヲ-ン\p{Radical}\p{Unified_Ideograph}]+/gimu;
|
||||
|
||||
const timer$ = isPaused$.pipe(
|
||||
switchMap((isPaused) => {
|
||||
if (isPaused) {
|
||||
idleTime = 0;
|
||||
|
||||
return NEVER;
|
||||
}
|
||||
|
||||
lastTick = performance.now();
|
||||
|
||||
return interval(1000);
|
||||
}),
|
||||
tap(updateElapsedTime),
|
||||
reduceToEmptyString(),
|
||||
);
|
||||
|
||||
const waitForIdle$ = combineLatest([isPaused$, afkTimer$]).pipe(
|
||||
switchMap(([isPaused, afkTimer]) =>
|
||||
isPaused || afkTimer < 1
|
||||
? NEVER
|
||||
: merge(
|
||||
newLine$,
|
||||
fromEvent<PointerEvent>(window, 'pointermove'),
|
||||
fromEvent<Event>(document, 'selectionchange'),
|
||||
).pipe(
|
||||
startWith(true),
|
||||
throttleTime(1000),
|
||||
tap(() => (idleTime = performance.now() + $afkTimer$ * 1000)),
|
||||
debounceTime($afkTimer$ * 1000),
|
||||
),
|
||||
),
|
||||
reduceToEmptyString(),
|
||||
);
|
||||
|
||||
let timerElm: HTMLElement;
|
||||
let speed = 0;
|
||||
let characters = 0;
|
||||
let statstring = '';
|
||||
|
||||
$: if (($showCharacterCount$ || $characterMilestone$ > 1) && $lineData$) {
|
||||
const newMilestoneLines = new Map<string, string>();
|
||||
|
||||
let newCount = 0;
|
||||
let nextMilestone = $characterMilestone$ > 1 ? $characterMilestone$ : 0;
|
||||
|
||||
for (let index = 0, { length } = $lineData$; index < length; index += 1) {
|
||||
newCount += getCharacterCount($lineData$[index].text);
|
||||
|
||||
if (nextMilestone && newCount >= nextMilestone) {
|
||||
let currentCount = newCount;
|
||||
let achievedMilestone = nextMilestone;
|
||||
|
||||
newMilestoneLines.set($lineData$[index].id, `Milestone ${achievedMilestone} (${newCount})`);
|
||||
|
||||
while (currentCount >= nextMilestone) {
|
||||
nextMilestone += $characterMilestone$;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$milestoneLines$ = newMilestoneLines;
|
||||
|
||||
characters = newCount;
|
||||
speed = $timeValue$ ? Math.ceil((3600 * characters) / $timeValue$) : 0;
|
||||
}
|
||||
|
||||
$: if ($timeValue$ > -1 && ($showTimer$ || $showSpeed$ || $showCharacterCount$ || $showLineCount$)) {
|
||||
buildString($timeValue$, speed, characters, $lineData$.length);
|
||||
} else {
|
||||
statstring = '';
|
||||
}
|
||||
|
||||
function handlePointerLeave() {
|
||||
const selection = window.getSelection();
|
||||
|
||||
if (selection?.toString() && selection.getRangeAt(0).intersectsNode(timerElm)) {
|
||||
selection.removeAllRanges();
|
||||
}
|
||||
}
|
||||
|
||||
function updateElapsedTime() {
|
||||
const now = idleTime ? Math.min(idleTime, performance.now()) : performance.now();
|
||||
const elapsed = Math.round((now - lastTick + Number.EPSILON) / 1000);
|
||||
|
||||
if (idleTime && now >= idleTime) {
|
||||
$isPaused$ = true;
|
||||
|
||||
if ($adjustTimerOnAfk$) {
|
||||
$timeValue$ = Math.max(0, $timeValue$ + elapsed - $afkTimer$);
|
||||
} else {
|
||||
$timeValue$ += elapsed;
|
||||
}
|
||||
|
||||
if ($enableAfkBlur$) {
|
||||
dispatch('afkBlur', true);
|
||||
|
||||
document.addEventListener(
|
||||
'dblclick',
|
||||
(event) => {
|
||||
event.stopPropagation();
|
||||
|
||||
window.getSelection().removeAllRanges();
|
||||
|
||||
dispatch('afkBlur', false);
|
||||
|
||||
if ($enableAfkBlurRestart$) {
|
||||
$isPaused$ = false;
|
||||
}
|
||||
},
|
||||
{ once: true, capture: false },
|
||||
);
|
||||
}
|
||||
} else {
|
||||
lastTick = now;
|
||||
$timeValue$ += elapsed;
|
||||
}
|
||||
}
|
||||
|
||||
function getCharacterCount(text: string) {
|
||||
if (!text) return 0;
|
||||
return countUnicodeCharacters(text.replace(isNotJapaneseRegex, ''));
|
||||
}
|
||||
|
||||
function countUnicodeCharacters(s: string) {
|
||||
return Array.from(s).length;
|
||||
}
|
||||
|
||||
function buildString(currentTime: number, currentSpeed: number, currentCharacters: number, currentLines: number) {
|
||||
let newString = '';
|
||||
|
||||
if ($showTimer$) {
|
||||
newString += toTimeString(currentTime);
|
||||
}
|
||||
|
||||
if ($showSpeed$) {
|
||||
newString += ` (${currentSpeed}/h) `;
|
||||
}
|
||||
|
||||
if ($showCharacterCount$) {
|
||||
newString += ` ${currentCharacters}`;
|
||||
}
|
||||
|
||||
if ($showLineCount$) {
|
||||
newString += $showCharacterCount$ ? ' /' : '';
|
||||
newString += ` ${currentLines}`;
|
||||
}
|
||||
|
||||
statstring = newString.replace(/[ ]+/g, ' ').trim();
|
||||
}
|
||||
</script>
|
||||
|
||||
{$timer$ ?? ''}
|
||||
{$waitForIdle$ ?? ''}
|
||||
|
||||
<div
|
||||
class="text-sm timer mr-1 sm:text-base sm:mr-2"
|
||||
class:blur={$blurStats$}
|
||||
bind:this={timerElm}
|
||||
on:pointerleave={handlePointerLeave}
|
||||
>
|
||||
<div>{statstring}</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.timer {
|
||||
transition: 0.1s filter linear;
|
||||
}
|
||||
|
||||
.blur:hover {
|
||||
filter: blur(0);
|
||||
}
|
||||
|
||||
.blur:not(:hover) {
|
||||
filter: blur(0.25rem);
|
||||
}
|
||||
</style>
|
||||
14
vendor/texthooker-ui/src/global.d.ts
vendored
Normal file
14
vendor/texthooker-ui/src/global.d.ts
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
declare global {
|
||||
interface Window {
|
||||
documentPictureInPicture: {
|
||||
requestWindow: (arg?: {
|
||||
height?: number;
|
||||
width?: number;
|
||||
preferInitialWindowPlacement?: boolean;
|
||||
}) => Promise<Window | undefined>;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export { };
|
||||
|
||||
9
vendor/texthooker-ui/src/main.ts
vendored
Normal file
9
vendor/texthooker-ui/src/main.ts
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import './app.css';
|
||||
|
||||
import App from './components/App.svelte';
|
||||
|
||||
const app = new App({
|
||||
target: document.body,
|
||||
});
|
||||
|
||||
export default app;
|
||||
112
vendor/texthooker-ui/src/socket.ts
vendored
Normal file
112
vendor/texthooker-ui/src/socket.ts
vendored
Normal file
@@ -0,0 +1,112 @@
|
||||
import { BehaviorSubject, NEVER, Subscription, filter, switchMap } from 'rxjs';
|
||||
import {
|
||||
continuousReconnect$,
|
||||
newLine$,
|
||||
reconnectSecondarySocket$,
|
||||
reconnectSocket$,
|
||||
secondarySocketState$,
|
||||
secondaryWebsocketUrl$,
|
||||
socketState$,
|
||||
websocketUrl$,
|
||||
} from './stores/stores';
|
||||
|
||||
import { LineType } from './types';
|
||||
|
||||
export class SocketConnection {
|
||||
private websocketUrl: string;
|
||||
|
||||
private socket: WebSocket | undefined;
|
||||
|
||||
private socketState: BehaviorSubject<number>;
|
||||
|
||||
private subscriptions: Subscription[] = [];
|
||||
|
||||
constructor(isPrimary = true) {
|
||||
this.socketState = isPrimary ? socketState$ : secondarySocketState$;
|
||||
this.subscriptions.push(
|
||||
(isPrimary ? websocketUrl$ : secondaryWebsocketUrl$).subscribe((websocketUrl) => {
|
||||
if (websocketUrl !== this.websocketUrl) {
|
||||
this.websocketUrl = websocketUrl;
|
||||
this.reloadSocket();
|
||||
}
|
||||
}),
|
||||
continuousReconnect$
|
||||
.pipe(
|
||||
switchMap((continuousReconnect) =>
|
||||
continuousReconnect
|
||||
? (isPrimary ? reconnectSocket$ : reconnectSecondarySocket$).pipe(
|
||||
filter(() => this.socket?.readyState === 3)
|
||||
)
|
||||
: NEVER
|
||||
)
|
||||
)
|
||||
.subscribe(() => this.reloadSocket())
|
||||
);
|
||||
}
|
||||
|
||||
getCurrentUrl() {
|
||||
return this.websocketUrl;
|
||||
}
|
||||
|
||||
connect() {
|
||||
if (this.socket?.readyState < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.websocketUrl) {
|
||||
this.socketState.next(3);
|
||||
return;
|
||||
}
|
||||
|
||||
this.socketState.next(0);
|
||||
|
||||
try {
|
||||
this.socket = new WebSocket(this.websocketUrl);
|
||||
this.socket.onopen = this.updateSocketState.bind(this);
|
||||
this.socket.onclose = this.updateSocketState.bind(this);
|
||||
this.socket.onmessage = this.handleMessage.bind(this);
|
||||
} catch (error) {
|
||||
this.socketState.next(3);
|
||||
}
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
if (this.socket?.readyState === 1) {
|
||||
this.socket.close(1000, 'User Request');
|
||||
}
|
||||
}
|
||||
|
||||
cleanUp() {
|
||||
this.disconnect();
|
||||
|
||||
for (let index = 0, { length } = this.subscriptions; index < length; index += 1) {
|
||||
this.subscriptions[index].unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
private reloadSocket() {
|
||||
this.disconnect();
|
||||
this.socket = undefined;
|
||||
this.connect();
|
||||
}
|
||||
|
||||
private updateSocketState() {
|
||||
if (!this.socket) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.socketState.next(this.socket.readyState);
|
||||
}
|
||||
|
||||
private handleMessage(event: MessageEvent) {
|
||||
let line = event.data;
|
||||
|
||||
try {
|
||||
line = JSON.parse(event.data)?.sentence || event.data;
|
||||
} catch (_) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
newLine$.next([line, LineType.SOCKET]);
|
||||
}
|
||||
}
|
||||
369
vendor/texthooker-ui/src/stores/stores.ts
vendored
Normal file
369
vendor/texthooker-ui/src/stores/stores.ts
vendored
Normal file
@@ -0,0 +1,369 @@
|
||||
import {
|
||||
LineType,
|
||||
OnlineFont,
|
||||
Theme,
|
||||
type DialogResult,
|
||||
type LineItem,
|
||||
type ReplacementItem,
|
||||
type SettingPreset,
|
||||
type Settings,
|
||||
} from './../types';
|
||||
|
||||
import { mdiHelpCircle } from '@mdi/js';
|
||||
import { Subject } from 'rxjs';
|
||||
import { writable } from 'svelte/store';
|
||||
import { writableBooleanSubject } from './transformer/writeable-boolean-subject';
|
||||
import { writableNumberSubject } from './transformer/writeable-number-subject';
|
||||
import { writeableArraySubject } from './transformer/writeable-object-sibject';
|
||||
import { writableStringSubject } from './transformer/writeable-string-subject';
|
||||
import { writableSubject } from './transformer/writeable-subject';
|
||||
|
||||
export const defaultSettings: Settings = {
|
||||
theme$: Theme.BUSINESS,
|
||||
replacements$: [],
|
||||
windowTitle$: 'SubMiner Texthooker',
|
||||
websocketUrl$: 'ws://localhost:6677',
|
||||
secondaryWebsocketUrl$: '',
|
||||
fontSize$: 24,
|
||||
characterMilestone$: 0,
|
||||
onlineFont$: OnlineFont.OFF,
|
||||
preventLastDuplicate$: 0,
|
||||
maxLines$: 0,
|
||||
maxPipLines$: 1,
|
||||
afkTimer$: 0,
|
||||
adjustTimerOnAfk$: false,
|
||||
enableExternalClipboardMonitor$: false,
|
||||
showPresetQuickSwitch$: false,
|
||||
skipResetConfirmations$: false,
|
||||
persistStats$: true,
|
||||
persistNotes$: true,
|
||||
persistLines$: true,
|
||||
persistActionHistory$: false,
|
||||
enablePaste$: false,
|
||||
blockCopyOnPage$: false,
|
||||
allowPasteDuringPause$: false,
|
||||
allowNewLineDuringPause$: false,
|
||||
autoStartTimerDuringPausePaste$: false,
|
||||
autoStartTimerDuringPause$: false,
|
||||
preventGlobalDuplicate$: false,
|
||||
mergeEqualLineStarts$: false,
|
||||
filterNonCJKLines: false,
|
||||
flashOnMissedLine$: true,
|
||||
displayVertical$: false,
|
||||
reverseLineOrder$: false,
|
||||
preserveWhitespace$: false,
|
||||
removeAllWhitespace$: true,
|
||||
showTimer$: true,
|
||||
showSpeed$: true,
|
||||
showCharacterCount$: true,
|
||||
showLineCount$: true,
|
||||
blurStats$: false,
|
||||
enableLineAnimation$: true,
|
||||
enableAfkBlur$: false,
|
||||
enableAfkBlurRestart$: false,
|
||||
continuousReconnect$: true,
|
||||
showConnectionErrors$: true,
|
||||
showConnectionIcon$: true,
|
||||
customCSS$: '',
|
||||
};
|
||||
|
||||
export const theme$ = writableStringSubject()('bannou-texthooker-theme', defaultSettings.theme$);
|
||||
|
||||
export const settingPresets$ = writeableArraySubject<SettingPreset>()('bannou-texthooker-settingPresets', []);
|
||||
|
||||
export const replacements$ = writeableArraySubject<ReplacementItem>()('bannou-texthooker-replacements', []);
|
||||
|
||||
export const windowTitle$ = writableStringSubject()('bannou-texthooker-windowTitle', defaultSettings.windowTitle$);
|
||||
|
||||
export const websocketUrl$ = writableStringSubject()('bannou-texthooker-websocketUrl', defaultSettings.websocketUrl$);
|
||||
|
||||
export const secondaryWebsocketUrl$ = writableStringSubject()(
|
||||
'bannou-texthooker-secondary-websocketUrl',
|
||||
defaultSettings.secondaryWebsocketUrl$
|
||||
);
|
||||
|
||||
export const fontSize$ = writableNumberSubject()('bannou-texthooker-fontSize', defaultSettings.fontSize$);
|
||||
|
||||
export const characterMilestone$ = writableNumberSubject()(
|
||||
'bannou-texthooker-characterMilestone',
|
||||
defaultSettings.characterMilestone$
|
||||
);
|
||||
|
||||
export const onlineFont$ = writableStringSubject()('bannou-texthooker-onlineFont', defaultSettings.onlineFont$);
|
||||
|
||||
export const preventLastDuplicate$ = writableNumberSubject()(
|
||||
'bannou-texthooker-preventLastDuplicate',
|
||||
defaultSettings.preventLastDuplicate$
|
||||
);
|
||||
|
||||
export const maxLines$ = writableNumberSubject()('bannou-texthooker-maxLines', defaultSettings.maxLines$);
|
||||
|
||||
export const maxPipLines$ = writableNumberSubject()('bannou-texthooker-maxPipLines', defaultSettings.maxPipLines$);
|
||||
|
||||
export const afkTimer$ = writableNumberSubject()('bannou-texthooker-afkTimer', defaultSettings.afkTimer$);
|
||||
|
||||
export const adjustTimerOnAfk$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-adjustTimerOnAfk',
|
||||
defaultSettings.adjustTimerOnAfk$
|
||||
);
|
||||
|
||||
export const enableExternalClipboardMonitor$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-enableExternalClipboardMonitor',
|
||||
defaultSettings.enableExternalClipboardMonitor$
|
||||
);
|
||||
|
||||
export const showPresetQuickSwitch$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-showPresetQuickSwitch',
|
||||
defaultSettings.showPresetQuickSwitch$
|
||||
);
|
||||
|
||||
export const skipResetConfirmations$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-skipResetConfirmations',
|
||||
defaultSettings.skipResetConfirmations$
|
||||
);
|
||||
|
||||
export const persistStats$ = writableBooleanSubject()('bannou-texthooker-persistStats', defaultSettings.persistStats$);
|
||||
|
||||
export const persistNotes$ = writableBooleanSubject()('bannou-texthooker-persistNotes', defaultSettings.persistNotes$);
|
||||
|
||||
export const persistLines$ = writableBooleanSubject()('bannou-texthooker-persistLines', defaultSettings.persistLines$);
|
||||
|
||||
export const persistActionHistory$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-persistActionHistory',
|
||||
defaultSettings.persistActionHistory$
|
||||
);
|
||||
|
||||
export const enablePaste$ = writableBooleanSubject()('bannou-texthooker-enablePaste', defaultSettings.enablePaste$);
|
||||
|
||||
export const blockCopyOnPage$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-blockCopyOnPage',
|
||||
defaultSettings.blockCopyOnPage$
|
||||
);
|
||||
|
||||
export const allowPasteDuringPause$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-allowPasteDuringPause',
|
||||
defaultSettings.allowPasteDuringPause$
|
||||
);
|
||||
|
||||
export const allowNewLineDuringPause$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-allowNewLineDuringPause',
|
||||
defaultSettings.allowNewLineDuringPause$
|
||||
);
|
||||
|
||||
export const autoStartTimerDuringPausePaste$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-autoStartTimerDuringPausePaste',
|
||||
defaultSettings.autoStartTimerDuringPausePaste$
|
||||
);
|
||||
|
||||
export const autoStartTimerDuringPause$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-autoStartTimerDuringPause',
|
||||
defaultSettings.autoStartTimerDuringPause$
|
||||
);
|
||||
|
||||
export const preventGlobalDuplicate$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-preventGlobalDuplicate',
|
||||
defaultSettings.preventGlobalDuplicate$
|
||||
);
|
||||
|
||||
export const mergeEqualLineStarts$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-mergeEqualLineStarts',
|
||||
defaultSettings.mergeEqualLineStarts$
|
||||
);
|
||||
|
||||
export const filterNonCJKLines$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-filterNonCJKLines',
|
||||
defaultSettings.mergeEqualLineStarts$
|
||||
);
|
||||
|
||||
export const flashOnMissedLine$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-flashOnMissedLine',
|
||||
defaultSettings.flashOnMissedLine$
|
||||
);
|
||||
|
||||
export const displayVertical$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-displayVertical',
|
||||
defaultSettings.displayVertical$
|
||||
);
|
||||
|
||||
export const reverseLineOrder$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-reverseLineOrder',
|
||||
defaultSettings.reverseLineOrder$
|
||||
);
|
||||
|
||||
export const preserveWhitespace$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-preserveWhitespace',
|
||||
defaultSettings.preserveWhitespace$
|
||||
);
|
||||
|
||||
export const removeAllWhitespace$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-removeAllWhitespace',
|
||||
defaultSettings.removeAllWhitespace$
|
||||
);
|
||||
|
||||
export const showTimer$ = writableBooleanSubject()('bannou-texthooker-showTimer', defaultSettings.showTimer$);
|
||||
|
||||
export const showSpeed$ = writableBooleanSubject()('bannou-texthooker-showSpeed', defaultSettings.showSpeed$);
|
||||
|
||||
export const showCharacterCount$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-showCharacterCount',
|
||||
defaultSettings.showCharacterCount$
|
||||
);
|
||||
|
||||
export const showLineCount$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-showLineCount',
|
||||
defaultSettings.showLineCount$
|
||||
);
|
||||
|
||||
export const blurStats$ = writableBooleanSubject()('bannou-texthooker-blurStats', defaultSettings.blurStats$);
|
||||
|
||||
export const enableLineAnimation$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-enableLineAnimation',
|
||||
defaultSettings.enableLineAnimation$
|
||||
);
|
||||
|
||||
export const enableAfkBlur$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-enableAfkBlur',
|
||||
defaultSettings.enableAfkBlur$
|
||||
);
|
||||
|
||||
export const enableAfkBlurRestart$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-enableAfkBlurRestart',
|
||||
defaultSettings.enableAfkBlurRestart$
|
||||
);
|
||||
|
||||
export const continuousReconnect$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-continuousReconnect',
|
||||
defaultSettings.continuousReconnect$
|
||||
);
|
||||
|
||||
export const showConnectionErrors$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-showConnectionErrors',
|
||||
defaultSettings.showConnectionErrors$
|
||||
);
|
||||
|
||||
export const showConnectionIcon$ = writableBooleanSubject()(
|
||||
'bannou-texthooker-showConnectionIcon',
|
||||
defaultSettings.showConnectionIcon$
|
||||
);
|
||||
|
||||
export const customCSS$ = writableStringSubject()('bannou-texthooker-customCSS', defaultSettings.customCSS$);
|
||||
|
||||
export const timeValue$ = writableNumberSubject()('bannou-texthooker-timeValue', 0, persistStats$);
|
||||
|
||||
export const notesOpen$ = writableBooleanSubject()('bannou-texthooker-notesOpen', false);
|
||||
|
||||
export const userNotes$ = writableStringSubject()('bannou-texthooker-userNotes', '', persistNotes$);
|
||||
|
||||
export const socketState$ = writableSubject<number>(-1);
|
||||
|
||||
export const secondarySocketState$ = writableSubject<number>(-1);
|
||||
|
||||
export const openDialog$ = writableSubject<Record<string, any>>(undefined);
|
||||
|
||||
export const dialogOpen$ = writableSubject<boolean>(false);
|
||||
|
||||
export const lastSettingPreset$ = writableStringSubject()('bannou-texthooker-lastSettingPreset', '');
|
||||
|
||||
export const lineData$ = writeableArraySubject<LineItem>()('bannou-texthooker-lineData', [], persistLines$);
|
||||
|
||||
export const milestoneLines$ = writable<Map<string, string>>(new Map<string, string>());
|
||||
|
||||
export const actionHistory$ = writeableArraySubject<LineItem[]>()(
|
||||
'bannou-texthooker-actionHistory',
|
||||
[],
|
||||
persistActionHistory$
|
||||
);
|
||||
|
||||
export const flashOnPauseTimeout$ = writable<number>(undefined);
|
||||
|
||||
export const isPaused$ = writableSubject<boolean>(true);
|
||||
|
||||
export const newLine$ = new Subject<[string, LineType]>();
|
||||
|
||||
export const reconnectSocket$ = new Subject<void>();
|
||||
|
||||
export const reconnectSecondarySocket$ = new Subject<void>();
|
||||
|
||||
export const showSpinner$ = writable<boolean>(false);
|
||||
|
||||
export const enabledReplacements$ = writable<ReplacementItem[]>([]);
|
||||
|
||||
export const lastPipHeight$ = writableNumberSubject()('bannou-texthooker-lastPipHeight', 0);
|
||||
|
||||
export const lastPipWidth$ = writableNumberSubject()('bannou-texthooker-lastPipWidth', 0);
|
||||
|
||||
export async function resetAllData() {
|
||||
if (!skipResetConfirmations$.getValue()) {
|
||||
const { canceled } = await new Promise<DialogResult>((resolve) => {
|
||||
openDialog$.next({
|
||||
icon: mdiHelpCircle,
|
||||
message: 'All Settings and Data will be reset',
|
||||
callback: resolve,
|
||||
});
|
||||
});
|
||||
|
||||
if (canceled) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
lastSettingPreset$.next('');
|
||||
settingPresets$.next([]);
|
||||
isPaused$.next(true);
|
||||
timeValue$.next(0);
|
||||
userNotes$.next('');
|
||||
lineData$.next([]);
|
||||
actionHistory$.next([]);
|
||||
flashOnPauseTimeout$.set(undefined);
|
||||
|
||||
window.localStorage.removeItem('bannou-texthooker-timeValue');
|
||||
window.localStorage.removeItem('bannou-texthooker-userNotes');
|
||||
window.localStorage.removeItem('bannou-texthooker-lineData');
|
||||
window.localStorage.removeItem('bannou-texthooker-actionHistory');
|
||||
|
||||
theme$.next(defaultSettings.theme$);
|
||||
replacements$.next(defaultSettings.replacements$);
|
||||
windowTitle$.next(defaultSettings.windowTitle$);
|
||||
websocketUrl$.next(defaultSettings.websocketUrl$);
|
||||
secondaryWebsocketUrl$.next(defaultSettings.secondaryWebsocketUrl$);
|
||||
fontSize$.next(defaultSettings.fontSize$);
|
||||
characterMilestone$.next(defaultSettings.characterMilestone$);
|
||||
onlineFont$.next(defaultSettings.onlineFont$);
|
||||
preventLastDuplicate$.next(defaultSettings.preventLastDuplicate$);
|
||||
maxPipLines$.next(defaultSettings.maxPipLines$);
|
||||
afkTimer$.next(defaultSettings.afkTimer$);
|
||||
adjustTimerOnAfk$.next(defaultSettings.adjustTimerOnAfk$);
|
||||
enableExternalClipboardMonitor$.next(defaultSettings.enableExternalClipboardMonitor$);
|
||||
showPresetQuickSwitch$.next(defaultSettings.showPresetQuickSwitch$);
|
||||
skipResetConfirmations$.next(defaultSettings.skipResetConfirmations$);
|
||||
persistStats$.next(defaultSettings.persistStats$);
|
||||
persistNotes$.next(defaultSettings.persistNotes$);
|
||||
persistLines$.next(defaultSettings.persistLines$);
|
||||
persistActionHistory$.next(defaultSettings.persistActionHistory$);
|
||||
enablePaste$.next(defaultSettings.enablePaste$);
|
||||
blockCopyOnPage$.next(defaultSettings.blockCopyOnPage$);
|
||||
allowPasteDuringPause$.next(defaultSettings.allowPasteDuringPause$);
|
||||
allowNewLineDuringPause$.next(defaultSettings.allowNewLineDuringPause$);
|
||||
autoStartTimerDuringPausePaste$.next(defaultSettings.autoStartTimerDuringPausePaste$);
|
||||
autoStartTimerDuringPause$.next(defaultSettings.autoStartTimerDuringPause$);
|
||||
preventGlobalDuplicate$.next(defaultSettings.preventGlobalDuplicate$);
|
||||
mergeEqualLineStarts$.next(defaultSettings.mergeEqualLineStarts$);
|
||||
filterNonCJKLines$.next(defaultSettings.filterNonCJKLines);
|
||||
flashOnMissedLine$.next(defaultSettings.flashOnMissedLine$);
|
||||
displayVertical$.next(defaultSettings.displayVertical$);
|
||||
reverseLineOrder$.next(defaultSettings.reverseLineOrder$);
|
||||
preserveWhitespace$.next(defaultSettings.preserveWhitespace$);
|
||||
removeAllWhitespace$.next(defaultSettings.removeAllWhitespace$);
|
||||
showTimer$.next(defaultSettings.showTimer$);
|
||||
showSpeed$.next(defaultSettings.showSpeed$);
|
||||
showCharacterCount$.next(defaultSettings.showCharacterCount$);
|
||||
showLineCount$.next(defaultSettings.showLineCount$);
|
||||
blurStats$.next(defaultSettings.blurStats$);
|
||||
enableLineAnimation$.next(defaultSettings.enableLineAnimation$);
|
||||
enableAfkBlur$.next(defaultSettings.enableAfkBlur$);
|
||||
enableAfkBlurRestart$.next(defaultSettings.enableAfkBlurRestart$);
|
||||
continuousReconnect$.next(defaultSettings.continuousReconnect$);
|
||||
showConnectionErrors$.next(defaultSettings.showConnectionErrors$);
|
||||
showConnectionIcon$.next(defaultSettings.showConnectionIcon$);
|
||||
customCSS$.next(defaultSettings.customCSS$);
|
||||
}
|
||||
7
vendor/texthooker-ui/src/stores/transformer/subject-to-writeable.ts
vendored
Normal file
7
vendor/texthooker-ui/src/stores/transformer/subject-to-writeable.ts
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
import type { Subject } from 'rxjs';
|
||||
|
||||
export function subjectToSvelteWritable<S extends Subject<any>>(subject: S) {
|
||||
// @ts-expect-error Svelte uses `set` like `next`
|
||||
subject.set = subject.next;
|
||||
return subject;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user