Compare commits

...

11 Commits

Author SHA1 Message Date
sudacode 43ebc7d371 chore: prepare 0.15.0-beta.8 prerelease 2026-05-25 20:34:56 -07:00
sudacode 639e331f24 fix(character-dictionary): add surname honorifics for Japanese localized aliases (#87) 2026-05-25 20:12:27 -07:00
sudacode 78be72e32f chore: prepare 0.15.0-beta.7 prerelease 2026-05-25 18:37:03 -07:00
sudacode 3932e53ced feat(character-dictionary): add manager modal and scope name matching to current media (#86) 2026-05-25 18:29:20 -07:00
sudacode 097b619d71 fix: settings window z-order on Hyprland and Linux app detach (#85) 2026-05-25 13:21:38 -07:00
sudacode f7abcedd75 chore: prepare 0.15.0-beta.6 prerelease 2026-05-25 03:25:34 -07:00
sudacode 807c0ff3db Add inline character portraits and dictionary search workflow (#83) 2026-05-25 03:16:25 -07:00
sudacode 7e6f9672cf fix: suppress overlay subtitle immediately when character dictionary modal opens (#84) 2026-05-25 02:30:33 -07:00
sudacode 9fe13601fb Launch macOS app background-detached when no args passed
- Add `launchAppBackgroundDetached` that spawns with `--start --background` and `SUBMINER_BACKGROUND_CHILD=1`
- On darwin with empty appArgs, use detached background launch instead of inherited process
- Add `extraEnv` param to `launchAppCommandDetached` for env injection
- Inject deps into `runAppPassthroughCommand` for testability
- Bump vendor/subminer-yomitan submodule
2026-05-25 02:12:41 -07:00
sudacode 920cbab1bc Fix Windows mpv handoff and tray setup (#82) 2026-05-25 01:34:01 -07:00
sudacode 17d97f0b7e fix: rename Windows ZIPs and fix macOS manual update checks (#81) 2026-05-24 23:47:02 -07:00
163 changed files with 5827 additions and 591 deletions
@@ -0,0 +1,4 @@
type: changed
area: dictionary
- Keep character dictionary lookup entries scoped to generated Japanese name aliases instead of surfacing raw romanized/English aliases as separate results, and refresh cached v15 snapshots so old English-name entries are regenerated.
+4
View File
@@ -0,0 +1,4 @@
type: changed
area: character-dictionary
- Character dictionary entries are now scoped to the current AniList media for name matching and inline portraits, and a new `Ctrl/Cmd+D` manager modal can remove, reorder, or override loaded dictionary entries.
@@ -0,0 +1,4 @@
type: changed
area: character-dictionary
- **Character Dictionary:** Changed the in-app AniList selector to wait for an explicit title search. The search box is prefilled from the current filename guess, so you can edit it before choosing an override.
+7
View File
@@ -0,0 +1,7 @@
type: added
area: subtitles
- Added optional inline AniList portraits for character-name subtitle matches, including automatic refresh of cached character dictionary snapshots that do not contain portrait data.
- Scoped manual AniList overrides by parent media directory, so separate season folders can keep separate character dictionary selections.
- Fixed large character dictionary imports by serving the merged ZIP through a local URL when supported, with a base64 fallback for older bundled Yomitan builds.
- Allowed subtitle overlay data image sources so inline character portraits render instead of showing a broken image icon.
@@ -0,0 +1,4 @@
type: fixed
area: character-dictionary
- Added surname honorific matches for Japanese localized character aliases embedded in AniList alternative names, such as Korean-source characters with Japanese names in parentheses, and refresh cached snapshots so those aliases are regenerated.
@@ -0,0 +1,4 @@
type: fixed
area: overlay
- Hid the visible subtitle overlay as soon as the character dictionary modal opens, including while AniList lookup is still loading or returns no results.
@@ -0,0 +1,4 @@
type: fixed
area: desktop
- Fixed Hyprland settings windows opening behind the subtitle overlay by promoting SubMiner and Yomitan settings above the overlay without hiding subtitles.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: launcher
- Fixed `subminer app` on Linux so launching the tray app returns control to the terminal immediately instead of waiting for the tray process to exit.
@@ -0,0 +1,4 @@
type: fixed
area: overlay
- Fixed Windows managed mpv launches from a background SubMiner instance so the existing warm app receives the start command, retargets the new mpv socket, binds to the player window, and receives startup overlay options.
+1 -1
View File
@@ -1,4 +1,4 @@
type: fixed
area: updater
- Fixed tray update checks for builds that cannot install native app updates, showing a manual install message instead of a restart prompt that cannot apply the update.
- Fixed macOS tray update checks for builds that cannot install native app updates, so newer stable or prerelease GitHub releases are reported instead of incorrectly saying the current build is up to date.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: release
- Fixed macOS updater metadata mismatches by giving macOS and Windows ZIP release assets distinct build-time filenames.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: tray
- Fixed the Windows tray "Open SubMiner Setup" action so it opens the setup window after first-run setup is already complete.
+2 -1
View File
@@ -187,7 +187,7 @@
"multiCopyTimeoutMs": 3000, // Timeout for multi-copy/mine modes.
"toggleSecondarySub": "CommandOrControl+Shift+V", // Accelerator that toggles the secondary subtitle bar visibility.
"markAudioCard": "CommandOrControl+Shift+A", // Accelerator that marks the last mined card as an audio card.
"openCharacterDictionary": "CommandOrControl+Alt+A", // Accelerator that opens the character dictionary modal.
"openCharacterDictionaryManager": "CommandOrControl+D", // Accelerator that opens the character dictionary manager modal.
"openRuntimeOptions": "CommandOrControl+Shift+O", // Accelerator that opens the runtime options modal.
"openJimaku": "Ctrl+Shift+J", // Accelerator that opens the Jimaku subtitle search modal.
"openSessionHelp": "CommandOrControl+Slash", // Accelerator that opens the session help / keybinding cheatsheet.
@@ -384,6 +384,7 @@
"autoPauseVideoOnHover": true, // Automatically pause mpv playback while hovering subtitle text, then resume on leave. Values: true | false
"autoPauseVideoOnYomitanPopup": true, // Automatically pause mpv playback while Yomitan popup is open, then resume when popup closes. Values: true | false
"nameMatchEnabled": false, // Enable subtitle token coloring for matches from the SubMiner character dictionary. Values: true | false
"nameMatchImagesEnabled": false, // Show small character portraits beside subtitle tokens matched from the SubMiner character dictionary. Values: true | false
"nameMatchColor": "#f5bde6", // Hex color used when a subtitle token matches an entry from the SubMiner character dictionary.
"nPlusOneColor": "#c6a0f6", // Color used for the single N+1 target token subtitle highlight.
"knownWordColor": "#a6da95", // Color used for known-word subtitle highlights.
+4
View File
@@ -1,5 +1,9 @@
# Changelog
## Unreleased
- **Character Dictionary:** Loaded entries are now scoped to the current AniList media for subtitle name matching and inline portraits. Added a character dictionary manager at `Ctrl/Cmd+D`; AniList overrides now live inside that manager instead of using a separate default shortcut.
## v0.14.0 (2026-05-12)
SubMiner no longer requires a globally-installed mpv plugin. The bundled plugin is injected at runtime only when SubMiner launches mpv — through the `subminer` launcher, the app's managed launch, or the packaged Windows SubMiner mpv shortcut. When you open mpv on its own, SubMiner is not involved and the plugin is never loaded. If you have a legacy global SubMiner plugin under mpv's `scripts` directory, first-run setup detects it and prompts you to remove it before playback starts.
+33 -12
View File
@@ -14,7 +14,7 @@ The feature has three stages: **snapshot**, **merge**, and **match**.
2. **Merge** — SubMiner maintains a most-recently-used list of media IDs (default: 3). Snapshots from those titles are merged into a single Yomitan ZIP — `character-dictionaries/merged.zip` — which is always named "SubMiner Character Dictionary" so Yomitan treats it as a single stable dictionary across rebuilds.
3. **Match** — During subtitle rendering, Yomitan scans subtitle text against all loaded dictionaries including the character dictionary. Tokens that match a character entry are flagged with `isNameMatch` and highlighted in the overlay with a distinct color.
3. **Match** — During subtitle rendering, Yomitan scans subtitle text against all loaded dictionaries including the character dictionary. SubMiner only accepts character entries for the current AniList media when that media ID is known, then flags matching tokens with `isNameMatch` and highlights them in the overlay with a distinct color.
## Enabling the Feature
@@ -89,23 +89,29 @@ Name matching runs inside Yomitan's scanning pipeline during subtitle tokenizati
1. Yomitan receives subtitle text and scans for dictionary matches.
2. Entries from "SubMiner Character Dictionary" are checked with exact primary-source matching — the token must match the entry's `originalText` with `isPrimary: true` and `matchType: 'exact'`.
3. Matched tokens are flagged `isNameMatch: true` and forwarded to the renderer.
4. If `subtitleStyle.nameMatchEnabled` is enabled, the renderer applies the name-match highlight color (default: `#f5bde6`).
3. When the current AniList media ID is known, entries whose embedded media ID belongs to a different title are ignored for name matching and inline portraits.
4. Matched tokens are flagged `isNameMatch: true` and forwarded to the renderer.
5. If `subtitleStyle.nameMatchEnabled` is enabled, the renderer applies the name-match highlight color (default: `#f5bde6`).
6. If `subtitleStyle.nameMatchImagesEnabled` is enabled, the renderer also injects a small circular AniList portrait from the cached snapshot image data.
Older snapshot schema versions are regenerated automatically. Current-version snapshots are normally reused, but when `subtitleStyle.nameMatchImagesEnabled` is enabled SubMiner also checks whether the cached snapshot contains usable character portrait data. If it does not, the snapshot is refreshed so the merged dictionary can include images.
Name matches are visually distinct from [N+1 targeting, frequency highlighting, and JLPT tags](/subtitle-annotations) so you can tell at a glance whether a highlighted word is a character name or a vocabulary target.
**Key settings:**
| Option | Default | Description |
| -------------------------------- | --------- | ---------------------------------- |
| `subtitleStyle.nameMatchEnabled` | `false` | Toggle character-name highlighting |
| `subtitleStyle.nameMatchColor` | `#f5bde6` | Highlight color for matched names |
| Option | Default | Description |
| -------------------------------------- | --------- | ----------------------------------------- |
| `subtitleStyle.nameMatchEnabled` | `false` | Toggle character-name highlighting |
| `subtitleStyle.nameMatchImagesEnabled` | `false` | Show small AniList portraits beside names |
| `subtitleStyle.nameMatchColor` | `#f5bde6` | Highlight color for matched names |
## Dictionary Entries
Each character entry in the Yomitan dictionary includes structured content:
- **Name** — native (Japanese) and romanized forms
- **Name** — the matched Japanese name form
- **Known names** — generated non-honorific Japanese aliases for that character, excluding raw romanized/English aliases from lookup results
- **Role badge** — color-coded by role: main (score 100), supporting (90), side (80), background (70)
- **Portrait** — character image from AniList, embedded in the ZIP
- **Description** — biography text from AniList (collapsible)
@@ -169,10 +175,13 @@ This creates a standalone dictionary ZIP for the target media and saves it along
## Correcting AniList Matches
SubMiner uses `guessit` to infer the anime title from the active filename, then searches AniList. Some filenames can still resolve to the wrong title. For example, `Re - ZERO, Starting Life in Another World (2016)` can be misread as a different `Re...` series.
SubMiner uses `guessit` to infer the anime title from the active filename before searching AniList. Some filenames can still resolve to the wrong title. For example, `Re - ZERO, Starting Life in Another World (2016)` can be misread as a different `Re...` series.
Use the in-app selector or CLI to pin the correct AniList media for the whole series:
- In-app: open the manager with `Ctrl/Cmd+D`, use the **Override** tab/button, edit the prefilled title if needed, then search and choose the correct result. The CLI flag `--open-character-dictionary` still opens the selector directly.
- CLI: `--dictionary-candidates` still lists matches for the current filename guess.
```bash
# List candidate AniList matches for a file
subminer dictionary --candidates "/path/to/episode.mkv"
@@ -188,7 +197,17 @@ SubMiner.AppImage --dictionary-select --dictionary-anilist-id 21355 --dictionary
subminer app --open-character-dictionary
```
Manual selections are stored in `character-dictionaries/anilist-overrides.json` using a series key derived from the filename guess. Later episodes with the same series key use the selected AniList ID automatically. When the override replaces a previous wrong match, SubMiner removes that stale media ID from the merged dictionary's active set and rebuilds/imports the merged character dictionary.
Manual selections are stored in `character-dictionaries/anilist-overrides.json` using a series key derived from the episode's parent directory plus the filename guess. Later episodes in the same directory use the selected AniList ID automatically, while separate season directories can keep separate overrides and character dictionaries. When the override replaces a previous wrong match, SubMiner removes that stale media ID from the merged dictionary's active set and rebuilds/imports the merged character dictionary.
## Managing Loaded Entries
Open the manager with `Ctrl/Cmd+D` (`shortcuts.openCharacterDictionaryManager`). The manager shows the merged dictionary's active MRU entries, marks the current anime, and lets you adjust eviction priority for the other loaded entries.
- **Remove** drops a non-current entry from the active merged dictionary and rebuilds/imports once.
- **Up/Down** changes MRU order for future eviction without rebuilding.
- **Override** opens the AniList selector for that entry's title so you can replace a saved loaded entry.
The current anime cannot be removed while you are watching it; it stays loaded until playback changes.
## File Structure
@@ -207,7 +226,7 @@ character-dictionaries/
m170942-va67890.jpg # Voice actor portrait
```
**Snapshot format** (v15): each snapshot contains the media ID, title, entry count, timestamp, an array of Yomitan term entries, and base64-encoded images.
**Snapshot format** (v17): each snapshot contains the media ID, title, entry count, timestamp, an array of Yomitan term entries, and base64-encoded images.
**ZIP structure** follows the Yomitan dictionary format:
@@ -231,6 +250,7 @@ merged.zip
| `anilist.characterDictionary.collapsibleSections.characterInformation` | `false` | Start Character Information section expanded |
| `anilist.characterDictionary.collapsibleSections.voicedBy` | `false` | Start Voiced By section expanded |
| `subtitleStyle.nameMatchEnabled` | `false` | Toggle character-name highlighting in subtitles |
| `subtitleStyle.nameMatchImagesEnabled` | `false` | Show small AniList portraits beside matched names |
| `subtitleStyle.nameMatchColor` | `#f5bde6` | Highlight color for character-name matches |
## Reference Implementation
@@ -253,8 +273,9 @@ If you work with visual novels or want a standalone dictionary generator indepen
## Troubleshooting
- **Names not highlighting:** Confirm `anilist.characterDictionary.enabled` is `true` and `subtitleStyle.nameMatchEnabled` is `true`. Check that the current media has an AniList entry — SubMiner needs a media ID to fetch characters.
- **Inline portraits missing:** Confirm `subtitleStyle.nameMatchImagesEnabled` is `true`. On the next character dictionary sync, SubMiner refreshes current-version snapshots that do not contain usable cached character portrait data. Portraits still require AniList to return an image and the image download to succeed.
- **Sync seems stuck:** The auto-sync debounces for 800ms after media changes and throttles image downloads at 250ms per image. Large casts (50+ characters) take longer. Check the status bar for the current sync phase.
- **Wrong characters showing:** Open the in-app character dictionary selector (`--open-character-dictionary`) or run `--dictionary-candidates`, then save the correct media with `--dictionary-select --dictionary-anilist-id <id>`. This replaces stale wrong-title entries for that series. If names are only from an older unrelated show, they'll rotate out once you watch enough new titles to push it past `maxLoaded`.
- **Wrong characters showing:** Open the in-app character dictionary manager (`Ctrl/Cmd+D`) to remove/reorder loaded titles, then use **Override** to correct the active AniList match. You can also run `--dictionary-candidates`, then save the correct media with `--dictionary-select --dictionary-anilist-id <id>`. SubMiner ignores character entries from other loaded titles for subtitle name matching and inline portraits once the current media ID is known.
- **Yomitan import fails:** SubMiner waits up to 7 seconds for Yomitan to be ready for mutations. If Yomitan is still loading dictionaries or performing another import, the operation may time out. Restarting the overlay typically resolves this.
- **Portraits missing:** Images are downloaded from AniList CDN during snapshot generation. If the network was unavailable during the initial sync, delete the snapshot file from `character-dictionaries/snapshots/` and let it regenerate.
+46 -44
View File
@@ -371,34 +371,35 @@ See `config.example.jsonc` for detailed configuration options.
}
```
| Option | Values | Description |
| ---------------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------- |
| `fontFamily` | string | CSS font-family value (default: `"Hiragino Sans, M PLUS 1, Source Han Sans JP, Noto Sans CJK JP"`) |
| `fontSize` | number (px) | Font size in pixels (default: `35`) |
| `fontColor` | string | Any CSS color value (default: `"#cad3f5"`) |
| `css` | object | CSS declarations applied to subtitles after normal style defaults; the settings window writes textbox edits here |
| `fontWeight` | string | CSS font-weight, e.g. `"bold"`, `"normal"`, `"600"` (default: `"600"`) |
| `fontStyle` | string | `"normal"` or `"italic"` (default: `"normal"`) |
| `backgroundColor` | string | Any CSS color, including `"transparent"` (default: `"transparent"`) |
| `enableJlpt` | boolean | Enable JLPT level underline styling (`false` by default) |
| `preserveLineBreaks` | boolean | Preserve line breaks in visible overlay subtitle rendering (`false` by default). Enable to mirror mpv line layout. |
| `autoPauseVideoOnHover` | boolean | Pause playback while mouse hovers subtitle text, then resume on leave (`true` by default). |
| `autoPauseVideoOnYomitanPopup` | boolean | Pause playback while the Yomitan popup is open, then resume when the popup closes (`true` by default). |
| `hoverTokenColor` | string | Hex color used for hovered subtitle token highlight in mpv (default: catppuccin mauve) |
| Option | Values | Description |
| ---------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `fontFamily` | string | CSS font-family value (default: `"Hiragino Sans, M PLUS 1, Source Han Sans JP, Noto Sans CJK JP"`) |
| `fontSize` | number (px) | Font size in pixels (default: `35`) |
| `fontColor` | string | Any CSS color value (default: `"#cad3f5"`) |
| `css` | object | CSS declarations applied to subtitles after normal style defaults; the settings window writes textbox edits here |
| `fontWeight` | string | CSS font-weight, e.g. `"bold"`, `"normal"`, `"600"` (default: `"600"`) |
| `fontStyle` | string | `"normal"` or `"italic"` (default: `"normal"`) |
| `backgroundColor` | string | Any CSS color, including `"transparent"` (default: `"transparent"`) |
| `enableJlpt` | boolean | Enable JLPT level underline styling (`false` by default) |
| `preserveLineBreaks` | boolean | Preserve line breaks in visible overlay subtitle rendering (`false` by default). Enable to mirror mpv line layout. |
| `autoPauseVideoOnHover` | boolean | Pause playback while mouse hovers subtitle text, then resume on leave (`true` by default). |
| `autoPauseVideoOnYomitanPopup` | boolean | Pause playback while the Yomitan popup is open, then resume when the popup closes (`true` by default). |
| `hoverTokenColor` | string | Hex color used for hovered subtitle token highlight in mpv (default: catppuccin mauve) |
| `hoverTokenBackgroundColor` | string | CSS color used for hovered subtitle token background highlight (default: `"transparent"`); `hoverBackground` is accepted as an alias |
| `nameMatchEnabled` | boolean | Enable subtitle token coloring for matches from the SubMiner character dictionary (`false` by default) |
| `nameMatchColor` | string | Hex color used for subtitle tokens matched from the SubMiner character dictionary (default: `#f5bde6`) |
| `knownWordColor` | string | Hex color used for known-word subtitle highlights (default: `#a6da95`) |
| `nPlusOneColor` | string | Hex color used for the single N+1 target subtitle highlight (default: `#c6a0f6`) |
| `frequencyDictionary.enabled` | boolean | Enable frequency highlighting from dictionary lookups (`false` by default) |
| `frequencyDictionary.sourcePath` | string | Path to a local frequency dictionary root. Leave empty or omit to use installed/default frequency-dictionary search paths. |
| `frequencyDictionary.topX` | number | Only color tokens whose frequency rank is `<= topX` (`1000` by default) |
| `frequencyDictionary.mode` | string | `"single"` or `"banded"` (`"single"` by default) |
| `frequencyDictionary.matchMode` | string | `"headword"` or `"surface"` (`"headword"` by default) |
| `frequencyDictionary.singleColor` | string | Color used for all highlighted tokens in single mode |
| `frequencyDictionary.bandedColors` | string[] | Array of five hex colors used for ranked bands in banded mode |
| `jlptColors` | object | JLPT level underline colors object (`N1`..`N5`) |
| `secondary` | object | Override any of the above for secondary subtitles (optional), including `secondary.css` declarations |
| `nameMatchEnabled` | boolean | Enable subtitle token coloring for matches from the SubMiner character dictionary (`false` by default) |
| `nameMatchImagesEnabled` | boolean | Show small cached AniList character portraits beside matched character-name tokens (`false` by default) |
| `nameMatchColor` | string | Hex color used for subtitle tokens matched from the SubMiner character dictionary (default: `#f5bde6`) |
| `knownWordColor` | string | Hex color used for known-word subtitle highlights (default: `#a6da95`) |
| `nPlusOneColor` | string | Hex color used for the single N+1 target subtitle highlight (default: `#c6a0f6`) |
| `frequencyDictionary.enabled` | boolean | Enable frequency highlighting from dictionary lookups (`false` by default) |
| `frequencyDictionary.sourcePath` | string | Path to a local frequency dictionary root. Leave empty or omit to use installed/default frequency-dictionary search paths. |
| `frequencyDictionary.topX` | number | Only color tokens whose frequency rank is `<= topX` (`1000` by default) |
| `frequencyDictionary.mode` | string | `"single"` or `"banded"` (`"single"` by default) |
| `frequencyDictionary.matchMode` | string | `"headword"` or `"surface"` (`"headword"` by default) |
| `frequencyDictionary.singleColor` | string | Color used for all highlighted tokens in single mode |
| `frequencyDictionary.bandedColors` | string[] | Array of five hex colors used for ranked bands in banded mode |
| `jlptColors` | object | JLPT level underline colors object (`N1`..`N5`) |
| `secondary` | object | Override any of the above for secondary subtitles (optional), including `secondary.css` declarations |
The Settings window keeps subtitle color controls separate, then saves CSS textboxes to
`subtitleStyle.css`, `subtitleStyle.secondary.css`, and `subtitleSidebar.css`. The generated example
@@ -420,6 +421,7 @@ In `single` mode all highlights use `singleColor`; in `banded` mode tokens map t
Character-name highlighting is separate from N+1 and frequency highlighting:
- `nameMatchEnabled` controls whether SubMiner includes character-dictionary name matches in subtitle token metadata and renderer styling.
- `nameMatchImagesEnabled` adds small circular portraits beside matched names using the AniList images already cached with character dictionary snapshots.
- `nameMatchColor` sets the highlight color for those matched character names.
- Matches come from the bundled SubMiner character dictionary, including AniList-synced merged dictionaries when enabled.
@@ -616,7 +618,7 @@ See `config.example.jsonc` for detailed configuration options.
"mineSentence": "CommandOrControl+S",
"mineSentenceMultiple": "CommandOrControl+Shift+S",
"markAudioCard": "CommandOrControl+Shift+A",
"openCharacterDictionary": "CommandOrControl+Alt+A",
"openCharacterDictionaryManager": "CommandOrControl+D",
"openRuntimeOptions": "CommandOrControl+Shift+O",
"openSessionHelp": "CommandOrControl+Slash",
"openControllerSelect": "Alt+C",
@@ -641,7 +643,7 @@ See `config.example.jsonc` for detailed configuration options.
| `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"`) |
| `openCharacterDictionary` | string \| `null` | Opens the character dictionary AniList selector (default: `"CommandOrControl+Alt+A"`) |
| `openCharacterDictionaryManager` | string \| `null` | Opens the loaded character dictionary manager (default: `"CommandOrControl+D"`) |
| `openRuntimeOptions` | string \| `null` | Opens runtime options palette for live session-only toggles (default: `"CommandOrControl+Shift+O"`) |
| `openSessionHelp` | string \| `null` | Opens the in-overlay session help modal (default: `"CommandOrControl+Slash"`) |
| `openControllerSelect` | string \| `null` | Opens the controller config/remap modal (default: `"Alt+C"`) |
@@ -785,7 +787,7 @@ When `behavior.autoUpdateNewCards` is set to `false`, new cards are detected but
| `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+Alt+A` | Open character dictionary AniList selector |
| `Ctrl+D` | Open loaded character dictionary manager |
| `Ctrl+Shift+O` | Open runtime options palette (session-only live toggles) |
| `Ctrl/Cmd+A` | Append clipboard video path to MPV playlist (fixed, not currently configurable) |
@@ -865,15 +867,15 @@ This is the single, shared connection to an OpenAI-compatible LLM endpoint. Conf
}
```
| Option | Values | Description |
| ------------------ | -------------------- | ---------------------------------------------------------------------------------- |
| `enabled` | `true`, `false` | Enable shared AI provider features (default: `false`) |
| `apiKey` | string | Static API key for the shared provider |
| `apiKeyCommand` | string | Shell command used to resolve the API key (preferred over a plaintext `apiKey`) |
| Option | Values | Description |
| ------------------ | -------------------- | ------------------------------------------------------------------------------------ |
| `enabled` | `true`, `false` | Enable shared AI provider features (default: `false`) |
| `apiKey` | string | Static API key for the shared provider |
| `apiKeyCommand` | string | Shell command used to resolve the API key (preferred over a plaintext `apiKey`) |
| `model` | string | Default model identifier requested from the provider (default: `openai/gpt-4o-mini`) |
| `baseUrl` | string (URL) | OpenAI-compatible base URL (default: `https://openrouter.ai/api`) |
| `systemPrompt` | string | Default system prompt sent with requests (default: a translation-engine prompt) |
| `requestTimeoutMs` | integer milliseconds | Shared request timeout (default: `15000`) |
| `baseUrl` | string (URL) | OpenAI-compatible base URL (default: `https://openrouter.ai/api`) |
| `systemPrompt` | string | Default system prompt sent with requests (default: a translation-engine prompt) |
| `requestTimeoutMs` | integer milliseconds | Shared request timeout (default: `15000`) |
SubMiner uses the shared provider for:
@@ -1125,12 +1127,12 @@ Sync the active subtitle track from the overlay picker using `alass` or `ffsubsy
}
```
| Option | Values | Description |
| ---------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `alass_path` | string path | Path to `alass` executable. Empty or `null` resolves from `PATH`. `alass` must be installed separately. |
| `ffsubsync_path` | string path | Path to `ffsubsync` executable. Empty or `null` resolves from `PATH`. `ffsubsync` must be installed separately. |
| `ffmpeg_path` | string path | Path to `ffmpeg` (used for internal subtitle extraction). Empty or `null` falls back to `/usr/bin/ffmpeg`. |
| `replace` | `true`, `false` | When `true` (default), overwrite the active subtitle file on successful sync. When `false`, write `<name>_retimed.<ext>`. |
| Option | Values | Description |
| ---------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `alass_path` | string path | Path to `alass` executable. Empty or `null` resolves from `PATH`. `alass` must be installed separately. |
| `ffsubsync_path` | string path | Path to `ffsubsync` executable. Empty or `null` resolves from `PATH`. `ffsubsync` must be installed separately. |
| `ffmpeg_path` | string path | Path to `ffmpeg` (used for internal subtitle extraction). Empty or `null` falls back to `/usr/bin/ffmpeg`. |
| `replace` | `true`, `false` | When `true` (default), overwrite the active subtitle file on successful sync. When `false`, write `<name>_retimed.<ext>`. |
Default trigger is `Ctrl+Alt+S` via `shortcuts.triggerSubsync`.
Customize it there, or set it to `null` to disable.
+1 -1
View File
@@ -173,7 +173,7 @@ If you prefer to install it manually, see [manual launcher install](#manual-laun
Download the latest installer from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest):
- `SubMiner-<version>.exe` — installer (recommended)
- `SubMiner-<version>.zip` — portable fallback
- `SubMiner-<version>-win.zip` — portable fallback
Make sure `mpv.exe` is on your `PATH`, or set `mpv.executablePath` in the config during first-run setup.
+2 -1
View File
@@ -187,7 +187,7 @@
"multiCopyTimeoutMs": 3000, // Timeout for multi-copy/mine modes.
"toggleSecondarySub": "CommandOrControl+Shift+V", // Accelerator that toggles the secondary subtitle bar visibility.
"markAudioCard": "CommandOrControl+Shift+A", // Accelerator that marks the last mined card as an audio card.
"openCharacterDictionary": "CommandOrControl+Alt+A", // Accelerator that opens the character dictionary modal.
"openCharacterDictionaryManager": "CommandOrControl+D", // Accelerator that opens the character dictionary manager modal.
"openRuntimeOptions": "CommandOrControl+Shift+O", // Accelerator that opens the runtime options modal.
"openJimaku": "Ctrl+Shift+J", // Accelerator that opens the Jimaku subtitle search modal.
"openSessionHelp": "CommandOrControl+Slash", // Accelerator that opens the session help / keybinding cheatsheet.
@@ -384,6 +384,7 @@
"autoPauseVideoOnHover": true, // Automatically pause mpv playback while hovering subtitle text, then resume on leave. Values: true | false
"autoPauseVideoOnYomitanPopup": true, // Automatically pause mpv playback while Yomitan popup is open, then resume when popup closes. Values: true | false
"nameMatchEnabled": false, // Enable subtitle token coloring for matches from the SubMiner character dictionary. Values: true | false
"nameMatchImagesEnabled": false, // Show small character portraits beside subtitle tokens matched from the SubMiner character dictionary. Values: true | false
"nameMatchColor": "#f5bde6", // Hex color used when a subtitle token matches an entry from the SubMiner character dictionary.
"nPlusOneColor": "#c6a0f6", // Color used for the single N+1 target token subtitle highlight.
"knownWordColor": "#a6da95", // Color used for known-word subtitle highlights.
+12 -12
View File
@@ -75,17 +75,17 @@ Mouse-hover playback behavior is configured separately from shortcuts: `subtitle
## Subtitle & Feature Shortcuts
| Shortcut | Action | Config key |
| ------------------ | -------------------------------------------------------- | ----------------------------------- |
| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle mode (hidden → visible → hover) | `shortcuts.toggleSecondarySub` |
| `Ctrl/Cmd+Alt+A` | Open character dictionary AniList selector | `shortcuts.openCharacterDictionary` |
| `Ctrl/Cmd+Shift+O` | Open runtime options palette | `shortcuts.openRuntimeOptions` |
| `Ctrl/Cmd+/` | Open session help modal | `shortcuts.openSessionHelp` |
| `Ctrl+Shift+J` | Open Jimaku subtitle search modal | `shortcuts.openJimaku` |
| `Ctrl+Alt+C` | Open the manual YouTube subtitle picker | `keybindings` |
| `Ctrl+Alt+S` | Open subtitle sync (subsync) modal | `shortcuts.triggerSubsync` |
| `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` |
| `` ` `` | Toggle stats overlay | `stats.toggleKey` |
| Shortcut | Action | Config key |
| ------------------ | -------------------------------------------------------- | ----------------------------------------------- |
| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle mode (hidden → visible → hover) | `shortcuts.toggleSecondarySub` |
| `Ctrl/Cmd+D` | Open loaded character dictionary manager | `shortcuts.openCharacterDictionaryManager` |
| `Ctrl/Cmd+Shift+O` | Open runtime options palette | `shortcuts.openRuntimeOptions` |
| `Ctrl/Cmd+/` | Open session help modal | `shortcuts.openSessionHelp` |
| `Ctrl+Shift+J` | Open Jimaku subtitle search modal | `shortcuts.openJimaku` |
| `Ctrl+Alt+C` | Open the manual YouTube subtitle picker | `keybindings` |
| `Ctrl+Alt+S` | Open subtitle sync (subsync) modal | `shortcuts.triggerSubsync` |
| `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` |
| `` ` `` | Toggle stats overlay | `stats.toggleKey` |
The stats toggle is handled inside the focused visible overlay window. It is configurable through the top-level `stats.toggleKey` setting and defaults to `Backquote`.
@@ -131,7 +131,7 @@ When the overlay has focus, press `y` then `d` to toggle DevTools (debugging hel
## Customizing Shortcuts
All `shortcuts.*` keys accept [Electron accelerator strings](https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts), for example `"CommandOrControl+Alt+A"`. Use `null` to disable a shortcut.
All `shortcuts.*` keys accept [Electron accelerator strings](https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts), for example `"CommandOrControl+D"`. Use `null` to disable a shortcut.
```jsonc
{
+16 -13
View File
@@ -37,20 +37,22 @@ Set `refreshMinutes` to `1440` (24 hours) for daily sync if your Anki collection
## Character-Name Highlighting
Character-name matches are built from the active merged SubMiner character dictionary, which auto-syncs character data from AniList for your recently-watched titles. Matching names are highlighted in subtitles and become available for hover-driven Yomitan character profiles — portraits, roles, voice actors, and biographical detail.
Character-name matches are built from the active merged SubMiner character dictionary, which auto-syncs character data from AniList for your recently-watched titles. When the current AniList media ID is known, SubMiner ignores loaded entries from other titles for subtitle name matching and inline portraits. Matching names are highlighted in subtitles and become available for hover-driven Yomitan character profiles — portraits, roles, voice actors, and biographical detail.
**How it works:**
1. Subtitles are tokenized, then candidate name tokens are matched against the character dictionary via Yomitan's scanning pipeline.
2. Matching tokens receive a dedicated style distinct from N+1 and frequency layers.
3. This layer can be independently toggled with `subtitleStyle.nameMatchEnabled`.
4. When `subtitleStyle.nameMatchImagesEnabled` is also enabled, SubMiner shows the cached AniList portrait beside matched names.
**Key settings:**
| Option | Default | Description |
| -------------------------------- | --------- | ---------------------------------------- |
| `subtitleStyle.nameMatchEnabled` | `false` | Enable character-name token highlighting |
| `subtitleStyle.nameMatchColor` | `#f5bde6` | Color used for character-name matches |
| Option | Default | Description |
| -------------------------------------- | --------- | ------------------------------------------------ |
| `subtitleStyle.nameMatchEnabled` | `false` | Enable character-name token highlighting |
| `subtitleStyle.nameMatchImagesEnabled` | `false` | Show small AniList portraits next to name tokens |
| `subtitleStyle.nameMatchColor` | `#f5bde6` | Color used for character-name matches |
For full details on dictionary generation, name variant expansion, auto-sync lifecycle, and configuration, see the dedicated [Character Dictionary](/character-dictionary) page.
@@ -67,14 +69,14 @@ SubMiner looks up each token's `frequencyRank` from `term_meta_bank_*.json` file
**Key settings:**
| Option | Default | Description |
| ------------------------------------------------ | ------------ | ---------------------------------------- |
| `subtitleStyle.frequencyDictionary.enabled` | `false` | Enable frequency highlighting |
| `subtitleStyle.frequencyDictionary.topX` | `1000` | Max frequency rank to highlight |
| `subtitleStyle.frequencyDictionary.mode` | `"single"` | `"single"` or `"banded"` |
| `subtitleStyle.frequencyDictionary.matchMode` | `"headword"` | `"headword"` or `"surface"` |
| `subtitleStyle.frequencyDictionary.singleColor` | `#f5a97f` | Color for single mode |
| `subtitleStyle.frequencyDictionary.bandedColors` | 5 colors[^1] | Array of five hex colors for banded mode |
| Option | Default | Description |
| ------------------------------------------------ | ------------ | ---------------------------------------------------------------- |
| `subtitleStyle.frequencyDictionary.enabled` | `false` | Enable frequency highlighting |
| `subtitleStyle.frequencyDictionary.topX` | `1000` | Max frequency rank to highlight |
| `subtitleStyle.frequencyDictionary.mode` | `"single"` | `"single"` or `"banded"` |
| `subtitleStyle.frequencyDictionary.matchMode` | `"headword"` | `"headword"` or `"surface"` |
| `subtitleStyle.frequencyDictionary.singleColor` | `#f5a97f` | Color for single mode |
| `subtitleStyle.frequencyDictionary.bandedColors` | 5 colors[^1] | Array of five hex colors for banded mode |
| `subtitleStyle.frequencyDictionary.sourcePath` | `""` | Custom path to frequency dictionary root (empty = auto-discover) |
[^1]: Default banded palette (most common → least common): `#ed8796`, `#f5a97f`, `#f9e2af`, `#8bd5ca`, `#8aadf4`.
@@ -122,6 +124,7 @@ All annotation layers can be toggled at runtime via the mpv command menu without
- `ankiConnect.knownWords.highlightEnabled` (`On` / `Off`)
- `subtitleStyle.nameMatchEnabled` (`On` / `Off`)
- `subtitleStyle.nameMatchImagesEnabled` (`On` / `Off`)
- `subtitleStyle.enableJlpt` (`On` / `Off`)
- `subtitleStyle.frequencyDictionary.enabled` (`On` / `Off`)
+3 -2
View File
@@ -88,10 +88,11 @@ Notes:
- AUR publish is best-effort: the workflow retries transient SSH clone/push failures, then warns and leaves the GitHub Release green if AUR still fails. Follow up with a manual `git push aur master` from the AUR checkout when needed.
- Required GitHub Actions secret: `AUR_SSH_PRIVATE_KEY`. Add the matching public key to your AUR account before relying on the automation.
- Release and prerelease workflows upload updater metadata (`*.yml`) and blockmaps (`*.blockmap`) alongside platform artifacts. Do not remove those files while `electron-updater` is enabled.
- macOS tray app updates use the standard `electron-updater`/Squirrel path. Keep `latest-mac.yml`, the macOS ZIP, and ZIP blockmap published; Squirrel uses the ZIP payload even when the DMG remains the user-facing installer.
- macOS tray app updates use the standard `electron-updater`/Squirrel path. Keep `latest-mac.yml`, the macOS `SubMiner-<version>-mac.zip`, and ZIP blockmap published; Squirrel uses the ZIP payload even when the DMG remains the user-facing installer.
- macOS update metadata and full ZIP downloads are routed through `/usr/bin/curl` before Squirrel installation to avoid Electron main-process network crashes on update checks.
- Windows tray app updates use the standard `electron-updater`/NSIS path. Keep `latest.yml`, the Windows NSIS installer, and installer blockmap published; updater HTTP is routed through main-process fetch to avoid Electron main-process network crashes during update checks.
- Build config emits distinct ZIP names: `SubMiner-<version>-mac.zip` for the macOS Squirrel updater payload and `SubMiner-<version>-win.zip` for the Windows portable fallback. The user-facing DMG and Windows installer keep the unqualified `SubMiner-<version>` basename.
- Linux GitHub release metadata and asset downloads also use `/usr/bin/curl` instead of Electron networking for the same reason.
- Local macOS build-output apps outside `/Applications` or `~/Applications` skip native update checks. To validate auto-update end to end, install the signed and notarized app bundle into one of those Applications folders and point it at a published updater feed.
- Local macOS build-output apps outside `/Applications` or `~/Applications` skip native update checks. Manual tray and launcher checks still use GitHub release metadata to report newer releases, but automatic notifications stay quiet when native app installation is unsupported. To validate auto-update end to end, install the signed and notarized app bundle into one of those Applications folders and point it at a published updater feed.
- The first updater-enabled release cannot update older installs automatically. Users need one manual install to get the updater code.
- Stable auto-update checks ignore beta/RC prereleases by default. Set `updates.channel` to `"prerelease"` on a test install when validating beta/RC updater behavior.
+28 -4
View File
@@ -1,19 +1,43 @@
import { launchTexthookerOnly, runAppCommandWithInherit } from '../mpv.js';
import {
launchAppBackgroundDetached,
launchTexthookerOnly,
runAppCommandWithInherit,
} from '../mpv.js';
import type { LauncherCommandContext } from './context.js';
export function runAppPassthroughCommand(context: LauncherCommandContext): boolean {
type AppCommandDeps = {
runAppCommandWithInherit: (appPath: string, appArgs: string[]) => void;
launchAppBackgroundDetached: (
appPath: string,
logLevel: LauncherCommandContext['args']['logLevel'],
) => void;
};
const defaultAppCommandDeps: AppCommandDeps = {
runAppCommandWithInherit,
launchAppBackgroundDetached,
};
export function runAppPassthroughCommand(
context: LauncherCommandContext,
deps: AppCommandDeps = defaultAppCommandDeps,
): boolean {
const { args, appPath } = context;
if (!appPath) {
return false;
}
if (args.settings) {
runAppCommandWithInherit(appPath, ['--settings']);
deps.runAppCommandWithInherit(appPath, ['--settings']);
return true;
}
if (!args.appPassthrough) {
return false;
}
runAppCommandWithInherit(appPath, args.appArgs);
if (args.appArgs.length === 0) {
deps.launchAppBackgroundDetached(appPath, args.logLevel);
return true;
}
deps.runAppCommandWithInherit(appPath, args.appArgs);
return true;
}
+60
View File
@@ -7,6 +7,7 @@ import { runConfigCommand } from './config-command.js';
import { runDictionaryCommand } from './dictionary-command.js';
import { runDoctorCommand } from './doctor-command.js';
import { runMpvPreAppCommand } from './mpv-command.js';
import { runAppPassthroughCommand } from './app-command.js';
import { runStatsCommand } from './stats-command.js';
import { runUpdateCommand } from './update-command.js';
@@ -168,6 +169,65 @@ test('doctor command forwards refresh-known-words to app binary', () => {
assert.deepEqual(forwarded, [['--refresh-known-words']]);
});
test('app command starts default macOS background app detached from launcher', () => {
const context = createContext();
context.args.appPassthrough = true;
context.args.appArgs = [];
const calls: string[] = [];
const handled = runAppPassthroughCommand(context, {
runAppCommandWithInherit: () => {
calls.push('attached');
},
launchAppBackgroundDetached: (appPath, logLevel) => {
calls.push(`detached:${appPath}:${logLevel}`);
},
});
assert.equal(handled, true);
assert.deepEqual(calls, ['detached:/tmp/subminer.app:info']);
});
test('app command starts default Linux background app detached from launcher', () => {
const context = createContext();
context.args.appPassthrough = true;
context.args.appArgs = [];
const calls: string[] = [];
const handled = runAppPassthroughCommand(context, {
runAppCommandWithInherit: () => {
calls.push('attached');
},
launchAppBackgroundDetached: (appPath, logLevel) => {
calls.push(`detached:${appPath}:${logLevel}`);
},
});
assert.equal(handled, true);
assert.deepEqual(calls, ['detached:/tmp/subminer.app:info']);
});
test('app command keeps explicit passthrough args attached', () => {
const context = createContext();
context.args.appPassthrough = true;
context.args.appArgs = ['--settings'];
const forwarded: string[][] = [];
const detached: string[] = [];
const handled = runAppPassthroughCommand(context, {
runAppCommandWithInherit: (_appPath, appArgs) => {
forwarded.push(appArgs);
},
launchAppBackgroundDetached: () => {
detached.push('detached');
},
});
assert.equal(handled, true);
assert.deepEqual(forwarded, [['--settings']]);
assert.deepEqual(detached, []);
});
test('mpv pre-app command exits non-zero when socket is not ready', async () => {
const context = createContext();
context.args.mpvStatus = true;
+30
View File
@@ -14,6 +14,7 @@ import {
buildMpvEnv,
cleanupPlaybackSession,
detectBackend,
launchAppBackgroundDetached,
findAppBinary,
launchAppCommandDetached,
launchTexthookerOnly,
@@ -256,6 +257,7 @@ test('buildConfiguredMpvDefaultArgs appends maximized launch mode to configured
'--sub-file-paths=.;subs;subtitles',
'--sid=auto',
'--secondary-sid=auto',
'--sub-visibility=no',
'--secondary-sub-visibility=no',
'--alang=ja,jp,jpn,japanese,en,eng,english,enus,en-us',
'--slang=ja,jp,jpn,japanese,en,eng,english,enus,en-us',
@@ -424,6 +426,34 @@ test('launchAppCommandDetached handles child process spawn errors', async () =>
}
});
test('launchAppBackgroundDetached starts background child directly', async () => {
const { dir } = createTempSocketPath();
const appPath = path.join(dir, 'fake-subminer.sh');
const argsPath = path.join(dir, 'args.txt');
const envPath = path.join(dir, 'env.txt');
fs.writeFileSync(
appPath,
[
'#!/bin/sh',
`printf '%s\\n' "$@" > ${JSON.stringify(argsPath)}`,
`printf '%s\\n' "$SUBMINER_BACKGROUND_CHILD" > ${JSON.stringify(envPath)}`,
'',
].join('\n'),
);
fs.chmodSync(appPath, 0o755);
launchAppBackgroundDetached(appPath, 'info');
const deadline = Date.now() + 1000;
while ((!fs.existsSync(argsPath) || !fs.existsSync(envPath)) && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 20));
}
assert.equal(fs.readFileSync(argsPath, 'utf8').trim(), '--start\n--background');
assert.equal(fs.readFileSync(envPath, 'utf8').trim(), '1');
fs.rmSync(dir, { recursive: true, force: true });
});
test('stopOverlay logs a warning when stop command cannot be spawned', () => {
const originalWrite = process.stdout.write;
const writes: string[] = [];
+24 -5
View File
@@ -47,13 +47,17 @@ type SpawnTarget = {
env?: NodeJS.ProcessEnv;
};
type PathModule = Pick<typeof path, 'join' | 'extname' | 'delimiter' | 'sep' | 'resolve'>;
type PathModule = Pick<
typeof path,
'dirname' | 'join' | 'extname' | 'delimiter' | 'sep' | 'resolve' | 'isAbsolute' | 'normalize'
>;
const DETACHED_IDLE_MPV_PID_FILE = path.join(os.tmpdir(), 'subminer-idle-mpv.pid');
const OVERLAY_START_SOCKET_READY_TIMEOUT_MS = 900;
const OVERLAY_START_COMMAND_SETTLE_TIMEOUT_MS = 700;
const TRANSPORTED_APP_ARGC_ENV = 'SUBMINER_APP_ARGC';
const TRANSPORTED_APP_ARG_PREFIX = 'SUBMINER_APP_ARG_';
const BACKGROUND_CHILD_ENV = 'SUBMINER_BACKGROUND_CHILD';
export interface LauncherRuntimePluginPlan {
scriptPath: string | null;
@@ -62,6 +66,12 @@ export interface LauncherRuntimePluginPlan {
errorMessage: string | null;
}
function resolvePluginCandidatePath(candidate: string, pathModule: PathModule): string {
return pathModule.isAbsolute(candidate)
? pathModule.normalize(candidate)
: pathModule.resolve(candidate);
}
export function parseMpvArgString(input: string): string[] {
const chars = input;
const args: string[] = [];
@@ -291,12 +301,12 @@ export function resolveLauncherRuntimePluginPath(options: {
pathModule?: typeof path;
existsSync?: (candidate: string) => boolean;
}): string | null {
const platform = options.platform ?? process.platform;
const pathModule = options.pathModule ?? path;
const existsSync = options.existsSync ?? fs.existsSync;
const env = options.env ?? process.env;
const dirname = options.dirname ?? __dirname;
const cwd = options.cwd ?? process.cwd();
const platform = options.platform ?? process.platform;
const homeDir = options.homeDir ?? os.homedir();
const candidates: string[] = [];
@@ -344,7 +354,7 @@ export function resolveLauncherRuntimePluginPath(options: {
const seen = new Set<string>();
for (const candidate of candidates) {
const resolved = pathModule.resolve(candidate);
const resolved = resolvePluginCandidatePath(candidate, pathModule);
if (seen.has(resolved)) continue;
seen.add(resolved);
const entrypoint = normalizeRuntimePluginEntrypoint(resolved, { pathModule, existsSync });
@@ -1580,11 +1590,20 @@ export function launchAppStartDetached(appPath: string, logLevel: LogLevel): voi
launchAppCommandDetached(appPath, startArgs, logLevel, 'start');
}
export function launchAppBackgroundDetached(appPath: string, logLevel: LogLevel): void {
const startArgs = ['--start', '--background'];
if (logLevel !== 'info') startArgs.push('--log-level', logLevel);
launchAppCommandDetached(appPath, startArgs, logLevel, 'app', {
[BACKGROUND_CHILD_ENV]: '1',
});
}
export function launchAppCommandDetached(
appPath: string,
appArgs: string[],
logLevel: LogLevel,
label: string,
extraEnv: NodeJS.ProcessEnv = {},
): void {
if (maybeCaptureAppArgs(appArgs)) {
return;
@@ -1603,7 +1622,7 @@ export function launchAppCommandDetached(
const proc = spawn(target.command, target.args, {
stdio: ['ignore', stdoutFd, stderrFd],
detached: true,
env: buildAppEnv(process.env, target.env),
env: buildAppEnv(process.env, { ...target.env, ...extraEnv }),
});
proc.once('error', (error) => {
log('warn', logLevel, `${label}: failed to launch detached app: ${error.message}`);
@@ -1704,7 +1723,7 @@ export async function waitForUnixSocketReady(
const deadline = nowMs() + timeoutMs;
while (nowMs() < deadline) {
try {
if (fs.existsSync(socketPath)) {
if (process.platform === 'win32' || fs.existsSync(socketPath)) {
const ready = await canConnectUnixSocket(socketPath);
if (ready) return true;
}
+2 -2
View File
@@ -365,8 +365,8 @@ export function findRofiTheme(scriptPath: string): string | null {
} else {
const xdgDataHome = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local/share');
candidates.push(path.join(xdgDataHome, 'SubMiner/themes', ROFI_THEME_FILE));
candidates.push(path.join('/usr/local/share/SubMiner/themes', ROFI_THEME_FILE));
candidates.push(path.join('/usr/share/SubMiner/themes', ROFI_THEME_FILE));
candidates.push(path.posix.join('/usr/local/share/SubMiner/themes', ROFI_THEME_FILE));
candidates.push(path.posix.join('/usr/share/SubMiner/themes', ROFI_THEME_FILE));
}
candidates.push(path.join(scriptDir, 'assets', 'themes', ROFI_THEME_FILE));
+28 -8
View File
@@ -40,6 +40,19 @@ function writeExecutable(filePath: string, body: string): void {
fs.chmodSync(filePath, 0o755);
}
function writeFixtureExecutable(basePath: string, body: string): string {
if (process.platform !== 'win32') {
writeExecutable(basePath, body);
return basePath;
}
const scriptPath = `${basePath}.js`;
const commandPath = `${basePath}.cmd`;
fs.writeFileSync(scriptPath, body);
fs.writeFileSync(commandPath, `@echo off\r\n"${process.execPath}" "${scriptPath}" %*\r\n`);
return commandPath;
}
function createSmokeCase(name: string): SmokeCase {
const baseDir = path.join(process.cwd(), '.tmp', 'launcher-smoke');
fs.mkdirSync(baseDir, { recursive: true });
@@ -52,8 +65,8 @@ function createSmokeCase(name: string): SmokeCase {
const socketDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-smoke-sock-'));
const socketPath = path.join(socketDir, 'subminer.sock');
const videoPath = path.join(root, 'video.mkv');
const fakeAppPath = path.join(binDir, 'fake-subminer');
const fakeMpvPath = path.join(binDir, 'mpv');
const fakeAppBasePath = path.join(binDir, 'fake-subminer');
const fakeMpvBasePath = path.join(binDir, 'mpv');
const mpvOverlayLogPath = path.join(artifactsDir, 'mpv-overlay.log');
fs.mkdirSync(artifactsDir, { recursive: true });
@@ -74,8 +87,8 @@ function createSmokeCase(name: string): SmokeCase {
const fakeAppStartLogPath = path.join(artifactsDir, 'fake-app-start.log');
const fakeAppStopLogPath = path.join(artifactsDir, 'fake-app-stop.log');
writeExecutable(
fakeMpvPath,
const fakeMpvPath = writeFixtureExecutable(
fakeMpvBasePath,
`#!/usr/bin/env bun
const fs = require('node:fs');
const net = require('node:net');
@@ -113,8 +126,8 @@ process.on('SIGTERM', closeAndExit);
`,
);
writeExecutable(
fakeAppPath,
const fakeAppPath = writeFixtureExecutable(
fakeAppBasePath,
`#!/usr/bin/env bun
const fs = require('node:fs');
@@ -157,14 +170,21 @@ process.exit(0);
}
function makeTestEnv(smokeCase: SmokeCase): NodeJS.ProcessEnv {
return {
const env: NodeJS.ProcessEnv = {
...process.env,
HOME: smokeCase.homeDir,
XDG_CONFIG_HOME: smokeCase.xdgConfigHome,
SUBMINER_APPIMAGE_PATH: smokeCase.fakeAppPath,
SUBMINER_MPV_LOG: smokeCase.mpvOverlayLogPath,
PATH: `${smokeCase.binDir}${path.delimiter}${process.env.PATH || ''}`,
};
const pathKey = Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'PATH';
env[pathKey] = `${smokeCase.binDir}${path.delimiter}${env[pathKey] || ''}`;
for (const key of Object.keys(env)) {
if (key !== pathKey && key.toLowerCase() === 'path') {
delete env[key];
}
}
return env;
}
function runLauncher(
+1
View File
@@ -60,6 +60,7 @@ export const DEFAULT_MPV_SUBMINER_ARGS = [
'--sub-file-paths=.;subs;subtitles',
'--sid=auto',
'--secondary-sid=auto',
'--sub-visibility=no',
'--secondary-sub-visibility=no',
'--alang=ja,jp,jpn,japanese,en,eng,english,enus,en-us',
'--slang=ja,jp,jpn,japanese,en,eng,english,enus,en-us',
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "subminer",
"version": "0.15.0-beta.5",
"version": "0.15.0-beta.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "subminer",
"version": "0.15.0-beta.5",
"version": "0.15.0-beta.8",
"license": "GPL-3.0-or-later",
"dependencies": {
"@fontsource-variable/geist": "^5.2.8",
+8 -2
View File
@@ -2,7 +2,7 @@
"name": "subminer",
"productName": "SubMiner",
"desktopName": "SubMiner.desktop",
"version": "0.15.0-beta.5",
"version": "0.15.0-beta.8",
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
"packageManager": "bun@1.3.5",
"main": "dist/main-entry.js",
@@ -50,7 +50,7 @@
"test:plugin:src": "lua scripts/test-plugin-lua-compat.lua && lua scripts/test-plugin-start-gate.lua && lua scripts/test-plugin-session-bindings.lua && lua scripts/test-plugin-binary-windows.lua",
"test:launcher:smoke:src": "bun test launcher/smoke.e2e.test.ts",
"test:launcher:src": "bun test launcher/config.test.ts launcher/config-domain-parsers.test.ts launcher/config/cli-parser-builder.test.ts launcher/config/args-normalizer.test.ts launcher/mpv.test.ts launcher/picker.test.ts launcher/parse-args.test.ts launcher/main.test.ts launcher/commands/command-modules.test.ts launcher/commands/update-command.test.ts launcher/smoke.e2e.test.ts && bun run test:plugin:src",
"test:core:src": "bun test src/preload-settings.test.ts src/settings/settings-anki-controls.test.ts src/settings/settings-model.test.ts src/settings/settings-field-layout.test.ts src/cli/args.test.ts src/cli/help.test.ts src/shared/setup-state.test.ts src/core/services/cli-command.test.ts src/core/services/ipc.test.ts src/core/services/anki-jimaku-ipc.test.ts src/core/services/field-grouping-overlay.test.ts src/core/services/numeric-shortcut-session.test.ts src/core/services/secondary-subtitle.test.ts src/core/services/mpv-render-metrics.test.ts src/core/services/overlay-content-measurement.test.ts src/core/services/mpv-control.test.ts src/core/services/mpv.test.ts src/core/services/runtime-options-ipc.test.ts src/core/services/runtime-config.test.ts src/core/services/yomitan-extension-paths.test.ts src/core/services/yomitan-extension-loader.test.ts src/core/services/yomitan-settings.test.ts src/core/services/config-hot-reload.test.ts src/core/services/discord-presence.test.ts src/core/services/tokenizer.test.ts src/core/services/tokenizer/annotation-stage.test.ts src/core/services/tokenizer/parser-selection-stage.test.ts src/core/services/tokenizer/parser-enrichment-stage.test.ts src/core/services/subsync.test.ts src/core/services/overlay-bridge.test.ts src/core/services/overlay-shortcut-handler.test.ts src/core/services/stats-window.test.ts src/core/services/stats-window-lifecycle.test.ts src/core/services/__tests__/stats-server.test.ts src/main/runtime/stats-server-routing.test.ts src/core/services/mining.test.ts src/core/services/anki-jimaku.test.ts src/core/services/jimaku-download-path.test.ts src/core/services/jellyfin.test.ts src/core/services/jellyfin-remote.test.ts src/core/services/immersion-tracker-service.test.ts src/core/services/overlay-runtime-init.test.ts src/core/services/app-ready.test.ts src/core/services/startup-bootstrap.test.ts src/core/services/subtitle-processing-controller.test.ts src/main/runtime/current-subtitle-snapshot.test.ts src/main/runtime/autoplay-tokenization-warm-release.test.ts src/main/runtime/autoplay-subtitle-primer.test.ts src/core/services/anilist/anilist-update-queue.test.ts src/core/services/anilist/rate-limiter.test.ts src/core/services/jlpt-token-filter.test.ts src/core/services/subtitle-position.test.ts src/core/utils/shortcut-config.test.ts src/main/runtime/startup-mode-flags.test.ts src/main/runtime/first-run-setup-plugin.test.ts src/main/runtime/first-run-setup-service.test.ts src/main/runtime/first-run-setup-window.test.ts src/main/runtime/command-line-launcher.test.ts src/main/runtime/tray-runtime.test.ts src/main/runtime/tray-main-actions.test.ts src/main/runtime/tray-main-deps.test.ts src/main/runtime/tray-runtime-handlers.test.ts src/main/runtime/cli-command-context-main-deps.test.ts src/main/runtime/app-ready-main-deps.test.ts src/main/runtime/update/appimage-updater.test.ts src/main/runtime/update/fetch-adapter.test.ts src/main/runtime/update/release-metadata-policy.test.ts src/main/runtime/update/update-dialogs.test.ts src/main/runtime/update/support-assets.test.ts src/renderer/error-recovery.test.ts src/renderer/subtitle-render.test.ts src/renderer/subtitle-render-word-class.test.ts src/renderer/handlers/mouse.test.ts src/renderer/handlers/keyboard.test.ts src/renderer/modals/jimaku.test.ts src/subsync/utils.test.ts src/main/anilist-url-guard.test.ts src/window-trackers/hyprland-tracker.test.ts src/window-trackers/x11-tracker.test.ts src/window-trackers/windows-helper.test.ts src/window-trackers/windows-tracker.test.ts launcher/config.test.ts launcher/config-domain-parsers.test.ts launcher/config/cli-parser-builder.test.ts launcher/config/args-normalizer.test.ts launcher/parse-args.test.ts launcher/main.test.ts launcher/commands/command-modules.test.ts launcher/commands/update-command.test.ts launcher/setup-gate.test.ts stats/src/lib/api-client.test.ts stats/src/hooks/useExcludedWords.test.ts",
"test:core:src": "bun test src/preload-settings.test.ts src/settings/settings-anki-controls.test.ts src/settings/settings-model.test.ts src/settings/settings-field-layout.test.ts src/cli/args.test.ts src/cli/help.test.ts src/shared/setup-state.test.ts src/core/services/cli-command.test.ts src/core/services/ipc.test.ts src/core/services/anki-jimaku-ipc.test.ts src/core/services/field-grouping-overlay.test.ts src/core/services/numeric-shortcut-session.test.ts src/core/services/secondary-subtitle.test.ts src/core/services/mpv-render-metrics.test.ts src/core/services/overlay-content-measurement.test.ts src/core/services/mpv-control.test.ts src/core/services/mpv.test.ts src/core/services/runtime-options-ipc.test.ts src/core/services/runtime-config.test.ts src/core/services/yomitan-extension-paths.test.ts src/core/services/yomitan-extension-loader.test.ts src/core/services/yomitan-settings.test.ts src/core/services/settings-window-z-order.test.ts src/core/services/hyprland-window-placement.test.ts src/core/services/config-hot-reload.test.ts src/core/services/discord-presence.test.ts src/core/services/tokenizer.test.ts src/core/services/tokenizer/annotation-stage.test.ts src/core/services/tokenizer/parser-selection-stage.test.ts src/core/services/tokenizer/parser-enrichment-stage.test.ts src/core/services/subsync.test.ts src/core/services/overlay-bridge.test.ts src/core/services/overlay-manager.test.ts src/core/services/overlay-shortcut-handler.test.ts src/core/services/stats-window.test.ts src/core/services/stats-window-lifecycle.test.ts src/core/services/__tests__/stats-server.test.ts src/main/runtime/stats-server-routing.test.ts src/core/services/mining.test.ts src/core/services/anki-jimaku.test.ts src/core/services/jimaku-download-path.test.ts src/core/services/jellyfin.test.ts src/core/services/jellyfin-remote.test.ts src/core/services/immersion-tracker-service.test.ts src/core/services/overlay-runtime-init.test.ts src/core/services/app-ready.test.ts src/core/services/startup-bootstrap.test.ts src/core/services/subtitle-processing-controller.test.ts src/main/runtime/current-subtitle-snapshot.test.ts src/main/runtime/autoplay-tokenization-warm-release.test.ts src/main/runtime/autoplay-subtitle-primer.test.ts src/core/services/anilist/anilist-update-queue.test.ts src/core/services/anilist/rate-limiter.test.ts src/core/services/jlpt-token-filter.test.ts src/core/services/subtitle-position.test.ts src/core/utils/shortcut-config.test.ts src/main/runtime/startup-mode-flags.test.ts src/main/runtime/config-settings-window.test.ts src/main/runtime/settings-window-z-order.test.ts src/main/runtime/setup-window-factory.test.ts src/main/runtime/first-run-setup-plugin.test.ts src/main/runtime/first-run-setup-service.test.ts src/main/runtime/first-run-setup-window.test.ts src/main/runtime/command-line-launcher.test.ts src/main/runtime/tray-runtime.test.ts src/main/runtime/tray-main-actions.test.ts src/main/runtime/tray-main-deps.test.ts src/main/runtime/tray-runtime-handlers.test.ts src/main/runtime/cli-command-context-main-deps.test.ts src/main/runtime/app-ready-main-deps.test.ts src/main/runtime/update/appimage-updater.test.ts src/main/runtime/update/fetch-adapter.test.ts src/main/runtime/update/release-metadata-policy.test.ts src/main/runtime/update/update-dialogs.test.ts src/main/runtime/update/support-assets.test.ts src/renderer/error-recovery.test.ts src/renderer/subtitle-render.test.ts src/renderer/subtitle-render-word-class.test.ts src/renderer/handlers/mouse.test.ts src/renderer/handlers/keyboard.test.ts src/renderer/modals/jimaku.test.ts src/subsync/utils.test.ts src/main/anilist-url-guard.test.ts src/main/character-dictionary-runtime/term-building.test.ts src/window-trackers/hyprland-tracker.test.ts src/window-trackers/x11-tracker.test.ts src/window-trackers/windows-helper.test.ts src/window-trackers/windows-tracker.test.ts launcher/config.test.ts launcher/config-domain-parsers.test.ts launcher/config/cli-parser-builder.test.ts launcher/config/args-normalizer.test.ts launcher/parse-args.test.ts launcher/main.test.ts launcher/commands/command-modules.test.ts launcher/commands/update-command.test.ts launcher/setup-gate.test.ts stats/src/lib/api-client.test.ts stats/src/hooks/useExcludedWords.test.ts",
"test:core:dist": "bun test dist/preload-settings.test.js dist/settings/settings-anki-controls.test.js dist/settings/settings-model.test.js dist/settings/settings-field-layout.test.js dist/cli/args.test.js dist/cli/help.test.js dist/core/services/cli-command.test.js dist/core/services/ipc.test.js dist/core/services/anki-jimaku-ipc.test.js dist/core/services/field-grouping-overlay.test.js dist/core/services/numeric-shortcut-session.test.js dist/core/services/secondary-subtitle.test.js dist/core/services/mpv-render-metrics.test.js dist/core/services/overlay-content-measurement.test.js dist/core/services/mpv-control.test.js dist/core/services/mpv.test.js dist/core/services/runtime-options-ipc.test.js dist/core/services/runtime-config.test.js dist/core/services/yomitan-extension-paths.test.js dist/core/services/config-hot-reload.test.js dist/core/services/discord-presence.test.js dist/core/services/tokenizer.test.js dist/core/services/tokenizer/annotation-stage.test.js dist/core/services/tokenizer/parser-selection-stage.test.js dist/core/services/tokenizer/parser-enrichment-stage.test.js dist/core/services/subsync.test.js dist/core/services/overlay-bridge.test.js dist/core/services/overlay-manager.test.js dist/core/services/overlay-shortcut-handler.test.js dist/core/services/stats-window-lifecycle.test.js dist/core/services/mining.test.js dist/core/services/anki-jimaku.test.js dist/core/services/jimaku-download-path.test.js dist/core/services/jellyfin.test.js dist/core/services/jellyfin-remote.test.js dist/core/services/immersion-tracker-service.test.js dist/core/services/overlay-runtime-init.test.js dist/core/services/app-ready.test.js dist/core/services/startup-bootstrap.test.js dist/core/services/subtitle-processing-controller.test.js dist/main/runtime/current-subtitle-snapshot.test.js dist/main/runtime/autoplay-tokenization-warm-release.test.js dist/main/runtime/autoplay-subtitle-primer.test.js dist/core/services/anilist/anilist-token-store.test.js dist/core/services/anilist/anilist-update-queue.test.js dist/core/services/anilist/rate-limiter.test.js dist/core/services/jlpt-token-filter.test.js dist/core/services/subtitle-position.test.js dist/renderer/error-recovery.test.js dist/renderer/subtitle-render.test.js dist/renderer/subtitle-render-word-class.test.js dist/renderer/handlers/mouse.test.js dist/renderer/handlers/keyboard.test.js dist/renderer/modals/jimaku.test.js dist/subsync/utils.test.js dist/main/anilist-url-guard.test.js dist/window-trackers/hyprland-tracker.test.js dist/window-trackers/x11-tracker.test.js dist/window-trackers/windows-helper.test.js dist/window-trackers/windows-tracker.test.js",
"test:core:smoke:dist": "bun test dist/cli/help.test.js dist/core/services/runtime-config.test.js dist/core/services/ipc.test.js dist/core/services/overlay-manager.test.js dist/core/services/anilist/anilist-token-store.test.js dist/core/services/startup-bootstrap.test.js dist/renderer/error-recovery.test.js dist/main/anilist-url-guard.test.js dist/window-trackers/x11-tracker.test.js",
"test:smoke:dist": "bun run test:config:smoke:dist && bun run test:core:smoke:dist",
@@ -158,6 +158,7 @@
]
},
"mac": {
"artifactName": "SubMiner-${version}-mac.${ext}",
"target": [
"dmg",
"zip"
@@ -174,7 +175,11 @@
}
]
},
"dmg": {
"artifactName": "SubMiner-${version}.${ext}"
},
"win": {
"artifactName": "SubMiner-${version}-win.${ext}",
"target": [
"nsis",
"zip"
@@ -182,6 +187,7 @@
"icon": "assets/SubMiner.ico"
},
"nsis": {
"artifactName": "SubMiner-${version}.${ext}",
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
+10
View File
@@ -13,6 +13,16 @@ function M.create(ctx)
local APP_RUNNING_CACHE_TTL_SECONDS = 2
local function is_windows()
local platform = mp.get_property("platform") or ""
if platform ~= "" then
local normalized = platform:lower()
if normalized == "windows" or normalized == "win32" then
return true
end
if normalized == "macos" or normalized == "darwin" or normalized == "osx" or normalized == "linux" then
return false
end
end
return package.config:sub(1, 1) == "\\"
end
+72 -9
View File
@@ -33,6 +33,30 @@ local MODIFIER_MAP = {
meta = "Meta",
}
local SHIFTED_KEY_NAME_MAP = {
Digit1 = "!",
Digit2 = "@",
Digit3 = "SHARP",
Digit4 = "$",
Digit5 = "%",
Digit6 = "^",
Digit7 = "&",
Digit8 = "*",
Digit9 = "(",
Digit0 = ")",
Minus = "_",
Equal = "+",
BracketLeft = "{",
BracketRight = "}",
Backslash = "|",
Semicolon = ":",
Quote = '"',
Comma = "<",
Period = ">",
Slash = "?",
Backquote = "~",
}
function M.create(ctx)
local mp = ctx.mp
local utils = ctx.utils
@@ -84,7 +108,22 @@ function M.create(ctx)
return nil
end
local function key_spec_to_mpv_binding(key)
local function contains_value(values, target)
for _, value in ipairs(values) do
if value == target then
return true
end
end
return false
end
local function append_unique(values, value)
if not contains_value(values, value) then
values[#values + 1] = value
end
end
local function key_spec_to_mpv_bindings(key)
if type(key) ~= "table" then
return nil
end
@@ -123,7 +162,24 @@ function M.create(ctx)
end
end
parts[#parts + 1] = key_name
return table.concat(parts, "+")
local bindings = { table.concat(parts, "+") }
local shifted_key_name = SHIFTED_KEY_NAME_MAP[key.code]
if has_shift and shifted_key_name then
local shifted_parts = {}
for _, modifier in ipairs(key.modifiers) do
if modifier ~= "shift" then
local mapped = MODIFIER_MAP[modifier]
if mapped then
shifted_parts[#shifted_parts + 1] = mapped
end
end
end
shifted_parts[#shifted_parts + 1] = shifted_key_name
append_unique(bindings, table.concat(shifted_parts, "+"))
end
return bindings
end
local function build_cli_args(action_id, payload)
@@ -294,13 +350,20 @@ function M.create(ctx)
local generation = state.session_binding_generation
for index, binding in ipairs(artifact.bindings) do
local key_name = key_spec_to_mpv_binding(binding.key)
if key_name then
local name = "subminer-session-binding-" .. tostring(generation) .. "-" .. tostring(index)
next_binding_names[#next_binding_names + 1] = name
mp.add_forced_key_binding(key_name, name, function()
handle_binding(binding)
end)
local key_names = key_spec_to_mpv_bindings(binding.key)
if key_names then
for key_index, key_name in ipairs(key_names) do
local name = "subminer-session-binding-"
.. tostring(generation)
.. "-"
.. tostring(index)
.. "-"
.. tostring(key_index)
next_binding_names[#next_binding_names + 1] = name
mp.add_forced_key_binding(key_name, name, function()
handle_binding(binding)
end)
end
else
subminer_log(
"warn",
+17 -13
View File
@@ -5,18 +5,22 @@
- **Settings Window:** A dedicated Settings window is now available via `subminer --settings` or `subminer settings`, organized into Appearance, Behavior, Anki, Input, and Integration sections. Includes click-to-learn keybinding controls, AnkiConnect-backed deck/field/note-type pickers, and live reload for stats keys, logging level, Jimaku, Subsync, YouTube language defaults, and Anki field mappings. AI and translation settings remain config-file only.
- **Auto-Updater:** SubMiner can now check for and apply updates from the system tray or by running `subminer -u`, with checksum verification, configurable notifications, and an opt-in prerelease channel. The `subminer` launcher and Linux rofi theme update automatically.
- **Auto-Updater:** SubMiner can now check for and apply updates from the system tray or by running `subminer -u`, with checksum verification, configurable update notifications, and an opt-in prerelease channel. The `subminer` launcher and Linux rofi theme update automatically. Set `updates.channel` to `"prerelease"` to receive beta and RC builds.
- **First-Run Setup:** A new optional setup flow installs Bun and the `subminer` command-line launcher on Linux, macOS, and Windows. Windows users get a `subminer.cmd` PATH shim so `subminer` works in any terminal without manually adding `SubMiner.exe` to PATH. First-run setup includes an Open SubMiner Settings button.
- **First-Run Setup:** A new optional setup flow installs Bun and the `subminer` command-line launcher on Linux, macOS, and Windows, with an Open SubMiner Settings button on completion. Windows users get a `subminer.cmd` PATH shim so `subminer` works in any terminal without manually adding `SubMiner.exe` to PATH.
- **Launcher:** `subminer --version` / `subminer -v` now prints the installed app version. The new `mpv.profile` config option passes an mpv profile to SubMiner-managed mpv launches. Bundled mpv plugin startup options are now configurable from SubMiner config.
- **Character Portraits:** Character-name subtitle matches can now show optional inline AniList character portraits. Manual AniList title overrides are scoped per media directory so separate season folders keep independent character dictionary selections.
### Changed
- **Subtitle Appearance:** Primary and secondary subtitle appearance now use color controls plus CSS declaration editors, saved as `subtitleStyle.css` and `subtitleStyle.secondary.css`. Sidebar appearance is configured via `subtitleSidebar.css`. The default subtitle font stack is updated to `Hiragino Sans, M PLUS 1, Source Han Sans JP, Noto Sans CJK JP`. Existing configs are migrated automatically.
- **Known-Word Colors:** Known-word and N+1 annotation colors moved to `subtitleStyle.knownWordColor` and `subtitleStyle.nPlusOneColor`. Legacy Anki color keys remain accepted with deprecation warnings. N+1 highlighting is preserved for configs that already had it enabled; new configs leave it disabled unless `ankiConnect.nPlusOne.enabled` is set explicitly.
- **Character Dictionary:** A new `Ctrl/Cmd+D` manager modal lets you remove, reorder, or override loaded dictionary entries. The in-app AniList title selector now waits for an explicit search rather than triggering automatically; the search box is prefilled from the current filename guess so it can be edited before confirming an override. Lookup entries are scoped to generated Japanese name aliases only, so raw romanized or English aliases no longer appear as separate results.
- **Linux Updater:** Tray "Check for Updates" now installs the new AppImage automatically via `electron-updater`, matching the macOS and Windows update flow. System-package-managed AppImages (e.g. AUR `/opt/SubMiner`) and non-AppImage launches fall back to the GitHub-asset flow.
- **Subsync:** The subtitle sync dialog now always opens the manual picker; the `subsync.defaultMode` config option has been removed.
@@ -33,22 +37,24 @@
### Fixed
- **macOS Overlay:** Significantly improved overlay focus and stability: the overlay hides when mpv loses focus or is minimized, stays stable through transient window-tracking misses, remains correctly layered during stats mouse passthrough, and opens over fullscreen mpv without switching Spaces. Passthrough is fixed so mpv controls stay clickable before hovering a subtitle bar. The overlay also stays stable when clicking from the overlay back into mpv. Background tracking overhead is reduced while mpv is stably focused.
- **macOS Overlay:** Significantly improved overlay focus and stability: the overlay hides when mpv loses focus, is minimized, or is no longer the foreground target; stays stable through transient window-tracking misses; remains correctly layered during stats mouse passthrough; opens over fullscreen mpv without switching Spaces; and stays stable when mpv remains frontmost but window geometry temporarily disappears from macOS APIs. Passthrough is fixed so mpv controls stay clickable before hovering a subtitle bar. The overlay stays stable when clicking from the overlay back into mpv. Background tracking overhead is reduced while mpv is stably focused.
- **Linux/Hyprland Overlay:** Overlay placement refreshes after leaving mpv fullscreen so the visible overlay stays aligned to the player. The visible overlay remains stacked above mpv after mpv regains focus from clicks, and is suspended while the in-player stats window is open.
- **Linux/Hyprland Overlay:** Overlay placement refreshes after leaving mpv fullscreen so the visible overlay stays aligned to the player. The visible overlay remains stacked above mpv after mpv regains focus from clicks, and is suspended while the in-player stats window is open. Settings windows (SubMiner and Yomitan) now open above the subtitle overlay on Hyprland instead of behind it.
- **Jellyfin Playback:** Resolved a wide range of Jellyfin discovery issues: the active item is no longer reloaded during startup, paused mpv is no longer misreported as playing, startup unpause no longer repeats after a manual pause or `y-t` toggle, duplicate ready signals no longer re-show the overlay, and long-lived sidebar ffmpeg extractors no longer run against stream URLs. Discovery now correctly handles delayed Japanese subtitle selection and prevents later-loading foreign tracks from stealing the active Japanese track.
- **Jellyfin Playback:** Resolved a wide range of Jellyfin discovery and playback issues: the active item is no longer reloaded during startup, paused mpv is no longer misreported as playing, startup unpause no longer repeats after a manual pause or `y-t` toggle, duplicate ready signals no longer re-show the overlay, and long-lived sidebar ffmpeg extractors no longer run against stream URLs. Discovery now correctly handles delayed Japanese subtitle selection and prevents later-loading foreign tracks from stealing the active Japanese track. Discovery resume correctly handles `StartPositionTicks: 0` for items with saved progress.
- **Jellyfin Subtitles:** Improved subtitle timing by preferring default embedded streams over external sidecars, stripping Jellyfin's server-selected stream from playback URLs, suppressing mpv auto-selection while SubMiner stages managed tracks, and automatically correcting clear Japanese-vs-English cue timeline offsets. Per-stream subtitle delay shifts are restored on load. Track selection now tolerates transient `track-list` read failures and numeric string track IDs on Linux.
- **Jellyfin Overlay:** The visible subtitle overlay now shows automatically during Jellyfin playback so `subtitleStyle` appearance applies. The bundled mpv plugin is injected when SubMiner auto-launches mpv for Jellyfin so mpv-side keybindings work without overlay focus. The `y-t` overlay toggle is reliable and remains sticky across stream redirects. Passive Linux/Hyprland overlay shows no longer steal keyboard focus from mpv.
- **Jellyfin Remote Progress:** Fixed progress sync for mpv/SubMiner seek jumps, stopped sessions, startup path changes, and Linux websocket reconnect windows. Play and Resume are now distinct: Play starts from the beginning while Resume starts at the saved position. Final progress reports use SubMiner's last known position when mpv resets during stop. Discovery resume correctly handles `StartPositionTicks: 0` for items with saved progress.
- **Jellyfin Remote Progress:** Fixed progress sync for mpv/SubMiner seek jumps, stopped sessions, startup path changes, and Linux websocket reconnect windows. Play and Resume are now distinct: Play starts from the beginning while Resume starts at the saved position. Final progress reports use SubMiner's last known position when mpv resets during stop.
- **Jellyfin Identity:** Cast device identity is now derived from the OS hostname. Multiple SubMiner installs no longer share the same remote-session identity, and SubMiner always reports itself as the client regardless of legacy configurable identity fields.
- **Jellyfin Tray:** The discovery tray checkbox stays in sync on Linux after tray, CLI, or startup remote-session changes. Stale discovery sessions restart automatically when the server no longer lists the SubMiner cast target. Library discovery works correctly when the app log level is set above info.
- **Jellyfin Setup:** Fixed the Jellyfin setup login flow on Windows: login now uses an IPC bridge with immediate progress feedback, and unreachable servers time out with an inline error instead of hanging.
- **Subtitle Sync Modal:** Fixed a macOS issue where opening the subtitle sync modal would flash and disappear on the first attempt, or leave stale state after syncing.
- **Controller:** Controller config and debug shortcuts now stay closed while controller support is disabled, with a notice to enable `controller.enabled`. Learn mode can be entered from the edit pencil or binding badge, remaps are saved per controller profile, and individual bindings can be reset to their defaults.
@@ -59,21 +65,21 @@
- **YouTube:** Primary subtitles are now downloaded to temporary local files so the primary bar and sidebar read the same source, with cleanup on reload and quit. False subtitle load failure notifications are suppressed after SubMiner confirms the selected track loaded. Launcher-managed playback commands create the tray icon even when attaching to an already-running process, and app-owned YouTube playback no longer lets the mpv plugin start a second SubMiner instance.
- **Character Dictionary:** Cached media matches are reused when loading a title with an existing snapshot, avoiding redundant AniList search requests on repeat visits.
- **Character Dictionary:** Surname honorifics are now matched for Japanese localized aliases embedded in AniList alternative names (e.g. Korean-source characters whose Japanese name appears in parentheses), and cached snapshots are regenerated to include them. Cached media matches are reused when loading a title with an existing snapshot, avoiding redundant AniList search requests on repeat visits. The visible subtitle overlay is suppressed as soon as the character dictionary modal opens, including while AniList lookup is loading or returns no results.
- **Updater:** Update checks are more stable across platforms: Linux uses GitHub release metadata instead of the native Electron updater; `subminer -u` can update independently of the tray app; macOS update dialogs reliably appear in the foreground; builds that cannot apply native updates show a manual-install message instead of a restart prompt; and Windows retains the native NSIS update path while routing updater HTTP through the main process. GitHub release lookups avoid Electron networking on Linux and macOS. Set `updates.channel` to `"prerelease"` to receive beta and RC builds.
- **Updater:** Update checks are more stable across platforms: Linux uses GitHub release metadata instead of the native Electron updater; `subminer -u` can update independently of the tray app; macOS update dialogs reliably appear in the foreground; builds that cannot apply native updates show a manual-install message instead of a restart prompt; Windows retains the native NSIS update path while routing updater HTTP through the main process; and macOS updater metadata mismatches from conflicting ZIP filenames are resolved.
- **Setup - macOS:** First-run setup now recognizes existing `subminer` installs in Homebrew or user PATH directories, and manual setup avoids writing into Homebrew-owned paths. `subminer app --setup` opens the setup flow even when SubMiner is already running in the background. The standalone setup app quits after completing first-run setup, and `subminer settings` exits cleanly when the window is closed.
- **Tray App:** Fixed several lifecycle issues with tray-launched Yomitan settings: the tray stays running when settings are closed; settings loading no longer blocks other tray actions; the settings window uses a close-only menu to prevent accidentally quitting the tray app; an in-page close button is available on Hyprland where native window controls are unavailable; the embedded popup preview is disabled to prevent renderer hangs during sidebar navigation; extension refreshes at startup are serialized to prevent race conditions; and the session help modal can close correctly without mpv running.
- **Tray App:** Fixed several lifecycle issues with tray-launched Yomitan settings: the tray stays running when settings are closed; settings loading no longer blocks other tray actions; a close-only menu prevents accidentally quitting the tray app; an in-page close button is available on Hyprland where native window controls are unavailable; the embedded popup preview is disabled to prevent renderer hangs during sidebar navigation; extension refreshes at startup are serialized to prevent race conditions; and the session help modal can close correctly without mpv running. On Windows, the tray "Open SubMiner Setup" action now correctly opens the setup window after first-run setup is complete.
- **Launcher:** Launcher-opened videos reuse an already-running background SubMiner instance and correctly reapply preferred subtitles on warm launches. Videos stay paused when attaching to a running background app until subtitle priming and tokenization readiness complete. Launcher-owned tray apps close after playback ends. `subminer settings` on macOS no longer emits Electron menu diagnostics. Linux first-run launcher installs now build with a valid Bun shebang.
- **Launcher:** Launcher-opened videos reuse an already-running background SubMiner instance and correctly reapply preferred subtitles on warm launches. Videos stay paused when attaching to a running background app until subtitle priming and tokenization readiness complete. Launcher-owned tray apps close after playback ends. `subminer settings` on macOS no longer emits Electron menu diagnostics. Linux first-run launcher installs now build with a valid Bun shebang. `subminer app` on Linux returns control to the terminal immediately. On Windows, managed mpv launches from a background SubMiner instance correctly retarget the new mpv socket, bind to the player window, and receive startup overlay options.
- **Playback:** The first subtitle is primed before autoplay resumes so the overlay renders text before video playback begins. Launcher-owned videos quit SubMiner when playback ends while background and tray sessions stay alive.
- **Subtitle Frequency:** Frequency highlighting is preserved for determiner-led noun compounds like `その場` while standalone determiners are still filtered.
- **Shortcuts:** Native mpv menu shortcuts are disabled during managed macOS playback so configured SubMiner shortcuts work while mpv has focus. Session shortcuts including `stats.markWatchedKey` are correctly wired through mpv. The visible overlay receives focus when entering multi-line copy/mine selection so number keys work on macOS and Windows.
- **Shortcuts:** Native mpv menu shortcuts are disabled during managed macOS playback so configured SubMiner shortcuts also work while mpv has focus. Session shortcuts including `stats.markWatchedKey` are correctly wired through mpv. The visible overlay receives focus when entering multi-line copy/mine selection so number keys work on macOS and Windows.
- **Overlay Restart:** The visible overlay and subtitle stream stay alive after restarting SubMiner from the `y-r` shortcut, with correct bounds reapplication on Linux and user-paused playback preserved through readiness gates.
@@ -91,8 +97,6 @@
- **Settings:** Search now works across all categories, narrows correctly on multi-word terms, and hides settings with dedicated editors. Live saves for subtitle CSS declarations apply immediately to open overlays. Legacy subtitle appearance options and hover token colors are automatically migrated into `subtitleStyle.css`. The note-fields note type picker defaults to the configured Anki deck's note type, then `Kiku`, then `Lapis`, leaving it blank for manual selection otherwise. User config files are preserved during legacy config compatibility handling. The generated example config uses the same CSS declaration paths written by the Settings window.
- **Build - Linux:** Fixed one-shot `make clean build install` flows so the install step correctly picks up the AppImage produced earlier in the same invocation.
### Docs
- **Versioned Docs:** Stable docs are now published at the site root with current development docs under `/main/`. Fixed versioned docs navigation so archived pages keep local links under the selected version, the version switcher no longer nests paths incorrectly, local dev version routes serve warmed archive files instead of redirecting to production, and internal README files no longer break archived builds.
+2
View File
@@ -322,7 +322,9 @@ end
local expected_cli_bindings = {
{ keys = "Shift+]", flag = "--shift-sub-delay-next-line" },
{ keys = "}", flag = "--shift-sub-delay-next-line" },
{ keys = "Shift+[", flag = "--shift-sub-delay-prev-line" },
{ keys = "{", flag = "--shift-sub-delay-prev-line" },
{ keys = "Ctrl+Alt+c", flag = "--open-youtube-picker" },
{ keys = "Ctrl+Alt+p", flag = "--open-playlist-browser" },
{ keys = "Ctrl+H", flag = "--replay-current-subtitle" },
+1 -1
View File
@@ -43,7 +43,7 @@ ${B}Mining${R}
--toggle-subtitle-sidebar Toggle subtitle sidebar panel
--open-runtime-options Open runtime options palette
--open-session-help Open session help modal
--open-character-dictionary Open character dictionary anime selection modal
--open-character-dictionary Open character dictionary management modal
--open-controller-select Open controller select modal
--open-controller-debug Open controller debug modal
+42 -2
View File
@@ -64,6 +64,7 @@ test('loads defaults when config is missing', () => {
assert.equal(config.ankiConnect.media.audioPadding, 0);
assert.equal(config.anilist.enabled, false);
assert.equal(config.anilist.characterDictionary.enabled, false);
assert.equal(config.subtitleStyle.nameMatchImagesEnabled, false);
assert.equal(config.anilist.characterDictionary.refreshTtlHours, 168);
assert.equal(config.anilist.characterDictionary.maxLoaded, 3);
assert.equal(config.anilist.characterDictionary.evictionPolicy, 'delete');
@@ -95,7 +96,8 @@ test('loads defaults when config is missing', () => {
assert.equal(config.startupWarmups.subtitleDictionaries, true);
assert.equal(config.startupWarmups.jellyfinRemoteSession, false);
assert.equal(config.shortcuts.markAudioCard, 'CommandOrControl+Shift+A');
assert.equal(config.shortcuts.openCharacterDictionary, 'CommandOrControl+Alt+A');
assert.equal('openCharacterDictionary' in config.shortcuts, false);
assert.equal(config.shortcuts.openCharacterDictionaryManager, 'CommandOrControl+D');
assert.equal(config.shortcuts.toggleSubtitleSidebar, 'Backslash');
assert.equal(config.discordPresence.enabled, true);
assert.equal(config.discordPresence.updateIntervalMs, 3_000);
@@ -152,7 +154,7 @@ test('loads defaults when config is missing', () => {
assert.equal(config.updates.checkIntervalHours, 24);
assert.equal(config.updates.notificationType, 'system');
assert.equal(config.updates.channel, 'stable');
assert.equal(config.mpv.socketPath, '/tmp/subminer-socket');
assert.equal(config.mpv.socketPath, DEFAULT_CONFIG.mpv.socketPath);
assert.equal(config.mpv.backend, 'auto');
assert.equal(config.mpv.profile, '');
assert.equal(config.mpv.autoStartSubMiner, true);
@@ -740,6 +742,44 @@ test('parses subtitleStyle.nameMatchEnabled and warns on invalid values', () =>
);
});
test('parses subtitleStyle.nameMatchImagesEnabled and warns on invalid values', () => {
const validDir = makeTempDir();
fs.writeFileSync(
path.join(validDir, 'config.jsonc'),
`{
"subtitleStyle": {
"nameMatchImagesEnabled": true
}
}`,
'utf-8',
);
const validService = new ConfigService(validDir);
assert.equal(validService.getConfig().subtitleStyle.nameMatchImagesEnabled, true);
const invalidDir = makeTempDir();
fs.writeFileSync(
path.join(invalidDir, 'config.jsonc'),
`{
"subtitleStyle": {
"nameMatchImagesEnabled": "yes"
}
}`,
'utf-8',
);
const invalidService = new ConfigService(invalidDir);
assert.equal(
invalidService.getConfig().subtitleStyle.nameMatchImagesEnabled,
DEFAULT_CONFIG.subtitleStyle.nameMatchImagesEnabled,
);
assert.ok(
invalidService
.getWarnings()
.some((warning) => warning.path === 'subtitleStyle.nameMatchImagesEnabled'),
);
});
test('parses anilist.enabled and warns for invalid value', () => {
const dir = makeTempDir();
fs.writeFileSync(
+1 -1
View File
@@ -88,7 +88,7 @@ export const CORE_DEFAULT_CONFIG: Pick<
multiCopyTimeoutMs: 3000,
toggleSecondarySub: 'CommandOrControl+Shift+V',
markAudioCard: 'CommandOrControl+Shift+A',
openCharacterDictionary: 'CommandOrControl+Alt+A',
openCharacterDictionaryManager: 'CommandOrControl+D',
openRuntimeOptions: 'CommandOrControl+Shift+O',
openJimaku: 'Ctrl+Shift+J',
openSessionHelp: 'CommandOrControl+Slash',
@@ -11,6 +11,7 @@ export const SUBTITLE_DEFAULT_CONFIG: Pick<ResolvedConfig, 'subtitleStyle' | 'su
hoverTokenColor: '#f4dbd6',
hoverTokenBackgroundColor: 'transparent',
nameMatchEnabled: false,
nameMatchImagesEnabled: false,
nameMatchColor: '#f5bde6',
fontFamily: 'Hiragino Sans, M PLUS 1, Source Han Sans JP, Noto Sans CJK JP',
fontSize: 35,
+3 -3
View File
@@ -542,10 +542,10 @@ export function buildCoreConfigOptionRegistry(
description: 'Accelerator that marks the last mined card as an audio card.',
},
{
path: 'shortcuts.openCharacterDictionary',
path: 'shortcuts.openCharacterDictionaryManager',
kind: 'string',
defaultValue: defaultConfig.shortcuts.openCharacterDictionary,
description: 'Accelerator that opens the character dictionary modal.',
defaultValue: defaultConfig.shortcuts.openCharacterDictionaryManager,
description: 'Accelerator that opens the character dictionary manager modal.',
},
{
path: 'shortcuts.openRuntimeOptions',
@@ -76,6 +76,13 @@ export function buildSubtitleConfigOptionRegistry(
description:
'Enable subtitle token coloring for matches from the SubMiner character dictionary.',
},
{
path: 'subtitleStyle.nameMatchImagesEnabled',
kind: 'boolean',
defaultValue: defaultConfig.subtitleStyle.nameMatchImagesEnabled,
description:
'Show small character portraits beside subtitle tokens matched from the SubMiner character dictionary.',
},
{
path: 'subtitleStyle.nameMatchColor',
kind: 'string',
+1 -1
View File
@@ -207,7 +207,7 @@ export function applyCoreDomainConfig(context: ResolveContext): void {
'mineSentenceMultiple',
'toggleSecondarySub',
'markAudioCard',
'openCharacterDictionary',
'openCharacterDictionaryManager',
'openRuntimeOptions',
'openJimaku',
] as const;
+20
View File
@@ -190,6 +190,8 @@ export function applySubtitleDomainConfig(context: ResolveContext): void {
const fallbackSubtitleStyleHoverTokenBackgroundColor =
resolved.subtitleStyle.hoverTokenBackgroundColor;
const fallbackSubtitleStyleNameMatchEnabled = resolved.subtitleStyle.nameMatchEnabled;
const fallbackSubtitleStyleNameMatchImagesEnabled =
resolved.subtitleStyle.nameMatchImagesEnabled;
const fallbackSubtitleStyleNameMatchColor = resolved.subtitleStyle.nameMatchColor;
const fallbackSubtitleStyleKnownWordColor = resolved.subtitleStyle.knownWordColor;
const fallbackSubtitleStyleNPlusOneColor = resolved.subtitleStyle.nPlusOneColor;
@@ -390,6 +392,24 @@ export function applySubtitleDomainConfig(context: ResolveContext): void {
);
}
const nameMatchImagesEnabled = asBoolean(
(src.subtitleStyle as { nameMatchImagesEnabled?: unknown }).nameMatchImagesEnabled,
);
if (nameMatchImagesEnabled !== undefined) {
resolved.subtitleStyle.nameMatchImagesEnabled = nameMatchImagesEnabled;
} else if (
(src.subtitleStyle as { nameMatchImagesEnabled?: unknown }).nameMatchImagesEnabled !==
undefined
) {
resolved.subtitleStyle.nameMatchImagesEnabled = fallbackSubtitleStyleNameMatchImagesEnabled;
warn(
'subtitleStyle.nameMatchImagesEnabled',
(src.subtitleStyle as { nameMatchImagesEnabled?: unknown }).nameMatchImagesEnabled,
resolved.subtitleStyle.nameMatchImagesEnabled,
'Expected boolean.',
);
}
if (nameMatchColor !== undefined) {
resolved.subtitleStyle.nameMatchColor = nameMatchColor;
} else if ((src.subtitleStyle as { nameMatchColor?: unknown }).nameMatchColor !== undefined) {
+25
View File
@@ -172,6 +172,31 @@ test('subtitleStyle nameMatchEnabled falls back on invalid value', () => {
);
});
test('subtitleStyle nameMatchImagesEnabled accepts boolean and warns on invalid', () => {
const valid = createResolveContext({
subtitleStyle: {
nameMatchImagesEnabled: true,
},
});
applySubtitleDomainConfig(valid.context);
assert.equal(valid.context.resolved.subtitleStyle.nameMatchImagesEnabled, true);
const invalid = createResolveContext({
subtitleStyle: {
nameMatchImagesEnabled: 'yes' as unknown as boolean,
},
});
applySubtitleDomainConfig(invalid.context);
assert.equal(invalid.context.resolved.subtitleStyle.nameMatchImagesEnabled, false);
assert.ok(
invalid.warnings.some(
(warning) =>
warning.path === 'subtitleStyle.nameMatchImagesEnabled' &&
warning.message === 'Expected boolean.',
),
);
});
test('subtitleStyle frequencyDictionary defaults to the teal fourth band color', () => {
const { context } = createResolveContext({});
+14
View File
@@ -54,9 +54,22 @@ test('settings registry moves AniSkip button key into input shortcuts and hot re
assert.equal(field('mpv.aniskipButtonKey').restartBehavior, 'hot-reload');
});
test('settings registry exposes character dictionary panel shortcuts dynamically', () => {
assert.equal(
fields.some((candidate) => candidate.configPath === 'shortcuts.openCharacterDictionary'),
false,
);
assert.equal(
field('shortcuts.openCharacterDictionaryManager').label,
'Open Character Dictionary Manager',
);
assert.equal(field('shortcuts.openCharacterDictionaryManager').subsection, 'Open Panels');
});
test('settings registry hides removed modal-only fields', () => {
for (const path of [
'shortcuts.multiCopyTimeoutMs',
'shortcuts.openCharacterDictionary',
'anilist.characterDictionary.profileScope',
'jellyfin.directPlayContainers',
]) {
@@ -173,6 +186,7 @@ test('settings registry exposes css declaration editor for primary and secondary
assert.equal(field('subtitleStyle.WebkitTextStroke').settingsHidden, true);
assert.equal(field('subtitleStyle.knownWordColor').settingsHidden, false);
assert.equal(field('subtitleStyle.nPlusOneColor').settingsHidden, false);
assert.equal(field('subtitleStyle.nameMatchImagesEnabled').settingsHidden, false);
assert.equal(field('subtitleStyle.nameMatchColor').settingsHidden, false);
assert.equal(field('subtitleStyle.jlptColors.N1').settingsHidden, false);
assert.equal(field('subtitleStyle.frequencyDictionary.singleColor').settingsHidden, false);
+8 -3
View File
@@ -208,7 +208,7 @@ const LABEL_OVERRIDES: Record<string, string> = {
'ankiConnect.isLapis.enabled': 'Enable Lapis Features',
'ankiConnect.isKiku.enabled': 'Enable Kiku Features',
'stats.toggleKey': 'Toggle Stats Overlay',
'shortcuts.openCharacterDictionary': 'Open AniList Override',
'shortcuts.openCharacterDictionaryManager': 'Open Character Dictionary Manager',
'subtitleSidebar.pauseVideoOnHover': 'Pause Video On Hover - Sidebar',
'subtitleStyle.autoPauseVideoOnHover': 'Pause Video On Hover - Subtitles',
'subtitleStyle.autoPauseVideoOnYomitanPopup': 'Pause Video On Yomitan Popup',
@@ -345,6 +345,7 @@ function categoryAndSection(path: string): { category: ConfigSettingsCategory; s
path === 'subtitleStyle.knownWordColor' ||
path === 'subtitleStyle.nPlusOneColor' ||
path === 'subtitleStyle.nameMatchEnabled' ||
path === 'subtitleStyle.nameMatchImagesEnabled' ||
path === 'subtitleStyle.nameMatchColor'
) {
return { category: 'appearance', section: 'Annotation Display' };
@@ -524,7 +525,11 @@ function subsectionForPath(path: string): string | undefined {
) {
return 'Frequency Highlighting';
}
if (path === 'subtitleStyle.nameMatchEnabled' || path === 'subtitleStyle.nameMatchColor') {
if (
path === 'subtitleStyle.nameMatchEnabled' ||
path === 'subtitleStyle.nameMatchImagesEnabled' ||
path === 'subtitleStyle.nameMatchColor'
) {
return 'Character Names';
}
if (path === 'anilist.characterDictionary.collapsibleSections.description') {
@@ -565,7 +570,7 @@ function subsectionForPath(path: string): string | undefined {
return 'Toggle & Visibility';
}
if (
leaf === 'openCharacterDictionary' ||
leaf === 'openCharacterDictionaryManager' ||
leaf === 'openRuntimeOptions' ||
leaf === 'openJimaku' ||
leaf === 'openSessionHelp' ||
+16
View File
@@ -801,6 +801,22 @@ test('handleCliCommand dispatches mark-watched session action', async () => {
});
});
test('handleCliCommand opens character dictionary manager from CLI flag', async () => {
let request: unknown = null;
const { deps } = createDeps({
dispatchSessionAction: async (nextRequest) => {
request = nextRequest;
},
});
handleCliCommand(makeArgs({ openCharacterDictionary: true }), 'initial', deps);
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(request, {
actionId: 'openCharacterDictionaryManager',
});
});
test('handleCliCommand logs AniList status details', () => {
const { deps, calls } = createDeps();
handleCliCommand(makeArgs({ anilistStatus: true }), 'initial', deps);
+2 -2
View File
@@ -492,8 +492,8 @@ export function handleCliCommand(
);
} else if (args.openCharacterDictionary) {
dispatchCliSessionAction(
{ actionId: 'openCharacterDictionary' },
'openCharacterDictionary',
{ actionId: 'openCharacterDictionaryManager' },
'openCharacterDictionaryManager',
'Open character dictionary failed',
);
} else if (args.openControllerSelect) {
@@ -106,6 +106,40 @@ test('buildHyprlandPlacementDispatches does not pin already floating overlay win
);
});
test('buildHyprlandPlacementDispatches can update placement without raising z-order', () => {
const buildDispatches = buildHyprlandPlacementDispatches as (
client: Parameters<typeof buildHyprlandPlacementDispatches>[0],
bounds: Parameters<typeof buildHyprlandPlacementDispatches>[1],
options: { promote: false },
) => string[][];
assert.deepEqual(
buildDispatches(
{
address: '0xabc',
floating: true,
pinned: false,
},
{
x: 0,
y: 0,
width: 1920,
height: 1080,
},
{ promote: false },
),
[
['dispatch', 'movewindowpixel', 'exact 0 0,address:0xabc'],
['dispatch', 'resizewindowpixel', 'exact 1920 1080,address:0xabc'],
['dispatch', 'setprop', 'address:0xabc rounding 0'],
['dispatch', 'setprop', 'address:0xabc border_size 0'],
['dispatch', 'setprop', 'address:0xabc no_shadow 1'],
['dispatch', 'setprop', 'address:0xabc no_blur 1'],
['dispatch', 'setprop', 'address:0xabc decorate 0'],
],
);
});
test('buildHyprlandPlacementDispatches unpins previously pinned overlay windows', () => {
assert.deepEqual(
buildHyprlandPlacementDispatches({
+12 -2
View File
@@ -18,6 +18,10 @@ export interface HyprlandPlacementBounds {
height: number;
}
export interface HyprlandPlacementDispatchOptions {
promote?: boolean;
}
type ExecFileSync = typeof execFileSync;
export function shouldAttemptHyprlandWindowPlacement(
@@ -64,6 +68,7 @@ export function findHyprlandWindowForPlacement(
export function buildHyprlandPlacementDispatches(
client: HyprlandPlacementClient,
bounds?: HyprlandPlacementBounds | null,
options: HyprlandPlacementDispatchOptions = {},
): string[][] {
if (!client.address) {
return [];
@@ -95,7 +100,9 @@ export function buildHyprlandPlacementDispatches(
dispatches.push(['dispatch', 'setprop', `${windowAddress} no_blur 1`]);
dispatches.push(['dispatch', 'setprop', `${windowAddress} decorate 0`]);
}
dispatches.push(['dispatch', 'alterzorder', `top,${windowAddress}`]);
if (options.promote !== false) {
dispatches.push(['dispatch', 'alterzorder', `top,${windowAddress}`]);
}
return dispatches;
}
@@ -127,6 +134,7 @@ export function ensureHyprlandWindowFloatingByTitle(options: {
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
pid?: number;
promote?: boolean;
execFileSync?: ExecFileSync;
}): boolean {
if (!shouldAttemptHyprlandWindowPlacement(options.platform, options.env)) {
@@ -146,7 +154,9 @@ export function ensureHyprlandWindowFloatingByTitle(options: {
return false;
}
const dispatches = buildHyprlandPlacementDispatches(client, options.bounds);
const dispatches = buildHyprlandPlacementDispatches(client, options.bounds, {
promote: options.promote,
});
for (const args of dispatches) {
run('hyprctl', args, { stdio: 'ignore' });
}
+6 -1
View File
@@ -28,6 +28,7 @@ export {
shouldAutoInitializeOverlayRuntimeFromConfig,
} from './startup';
export { destroyYomitanSettingsWindow, openYomitanSettingsWindow } from './yomitan-settings';
export { promoteSettingsWindowAboveOverlay } from './settings-window-z-order';
export { createTokenizerDepsRuntime, tokenizeSubtitle } from './tokenizer';
export {
addYomitanNoteViaSearch,
@@ -80,7 +81,11 @@ export {
handleOverlayWindowBeforeInputEvent,
isTabInputForMpvForwarding,
} from './overlay-window-input';
export { initializeOverlayAnkiIntegration, initializeOverlayRuntime } from './overlay-runtime-init';
export {
initializeOverlayAnkiIntegration,
initializeOverlayRuntime,
startOverlayWindowTracker,
} from './overlay-runtime-init';
export { setVisibleOverlayVisible, updateVisibleOverlayVisibility } from './overlay-visibility';
export {
MPV_REQUEST_ID_SECONDARY_SUB_VISIBILITY,
+15 -10
View File
@@ -1191,18 +1191,22 @@ test('registerIpcHandlers rejects malformed controller preference payloads', asy
test('registerIpcHandlers exposes character dictionary selection handlers', async () => {
const { registrar, handlers } = createFakeIpcRegistrar();
const calls: number[] = [];
const searches: Array<string | undefined> = [];
registerIpcHandlers(
createRegisterIpcDeps({
getCharacterDictionarySelection: async () => ({
seriesKey: 're-zero-starting-life-in-another-world-2016',
guessTitle: 'Re ZERO, Starting Life in Another World',
current: { id: 10607, title: 'Rerere no Tensai Bakabon', episodes: 24 },
override: null,
candidates: [
{ id: 21355, title: 'Re:ZERO -Starting Life in Another World-', episodes: 25 },
],
}),
getCharacterDictionarySelection: async (searchTitle) => {
searches.push(searchTitle);
return {
seriesKey: 're-zero-starting-life-in-another-world-2016',
guessTitle: 'Re ZERO, Starting Life in Another World',
current: { id: 10607, title: 'Rerere no Tensai Bakabon', episodes: 24 },
override: null,
candidates: [
{ id: 21355, title: 'Re:ZERO -Starting Life in Another World-', episodes: 25 },
],
};
},
setCharacterDictionarySelection: async (mediaId) => {
calls.push(mediaId);
return {
@@ -1223,7 +1227,7 @@ test('registerIpcHandlers exposes character dictionary selection handlers', asyn
const getHandler = handlers.handle.get(IPC_CHANNELS.request.getCharacterDictionarySelection);
const setHandler = handlers.handle.get(IPC_CHANNELS.request.setCharacterDictionarySelection);
assert.deepEqual(await getHandler!({}), {
assert.deepEqual(await getHandler!({}, ' Re:ZERO '), {
seriesKey: 're-zero-starting-life-in-another-world-2016',
guessTitle: 'Re ZERO, Starting Life in Another World',
current: { id: 10607, title: 'Rerere no Tensai Bakabon', episodes: 24 },
@@ -1241,4 +1245,5 @@ test('registerIpcHandlers exposes character dictionary selection handlers', asyn
staleMediaIds: [10607],
});
assert.deepEqual(calls, [21355]);
assert.deepEqual(searches, ['Re:ZERO']);
});
+87 -8
View File
@@ -95,8 +95,15 @@ export interface IpcServiceDeps {
getAnilistQueueStatus: () => unknown;
retryAnilistQueueNow: () => Promise<{ ok: boolean; message: string }>;
runAnilistPostWatchUpdateOnManualMark?: () => Promise<void>;
getCharacterDictionarySelection?: () => Promise<unknown>;
setCharacterDictionarySelection?: (mediaId: number) => Promise<unknown>;
getCharacterDictionarySelection?: (searchTitle?: string) => Promise<unknown>;
setCharacterDictionarySelection?: (
mediaId: number,
replaceManagedMediaId?: number,
mediaTitle?: string,
) => Promise<unknown>;
getCharacterDictionaryManagerSnapshot?: () => Promise<unknown>;
removeCharacterDictionaryManagedEntry?: (mediaId: number) => Promise<unknown>;
moveCharacterDictionaryManagedEntry?: (mediaId: number, direction: 1 | -1) => Promise<unknown>;
appendClipboardVideoToQueue: () => { ok: boolean; message: string };
getPlaylistBrowserSnapshot: () => Promise<PlaylistBrowserSnapshot>;
appendPlaylistBrowserFile: (filePath: string) => Promise<PlaylistBrowserMutationResult>;
@@ -223,8 +230,15 @@ export interface IpcDepsRuntimeOptions {
getAnilistQueueStatus: () => unknown;
retryAnilistQueueNow: () => Promise<{ ok: boolean; message: string }>;
runAnilistPostWatchUpdateOnManualMark?: () => Promise<void>;
getCharacterDictionarySelection?: () => Promise<unknown>;
setCharacterDictionarySelection?: (mediaId: number) => Promise<unknown>;
getCharacterDictionarySelection?: (searchTitle?: string) => Promise<unknown>;
setCharacterDictionarySelection?: (
mediaId: number,
replaceManagedMediaId?: number,
mediaTitle?: string,
) => Promise<unknown>;
getCharacterDictionaryManagerSnapshot?: () => Promise<unknown>;
removeCharacterDictionaryManagedEntry?: (mediaId: number) => Promise<unknown>;
moveCharacterDictionaryManagedEntry?: (mediaId: number, direction: 1 | -1) => Promise<unknown>;
appendClipboardVideoToQueue: () => { ok: boolean; message: string };
getPlaylistBrowserSnapshot: () => Promise<PlaylistBrowserSnapshot>;
appendPlaylistBrowserFile: (filePath: string) => Promise<PlaylistBrowserMutationResult>;
@@ -317,6 +331,22 @@ export function createIpcDepsRuntime(options: IpcDepsRuntimeOptions): IpcService
selected: { id: 0, title: '', episodes: null },
staleMediaIds: [],
})),
getCharacterDictionaryManagerSnapshot:
options.getCharacterDictionaryManagerSnapshot ?? (async () => ({ entries: [] })),
removeCharacterDictionaryManagedEntry:
options.removeCharacterDictionaryManagedEntry ??
(async () => ({
ok: false,
message: 'Character dictionary manager unavailable.',
entries: [],
})),
moveCharacterDictionaryManagedEntry:
options.moveCharacterDictionaryManagedEntry ??
(async () => ({
ok: false,
message: 'Character dictionary manager unavailable.',
entries: [],
})),
appendClipboardVideoToQueue: options.appendClipboardVideoToQueue,
getPlaylistBrowserSnapshot: options.getPlaylistBrowserSnapshot,
appendPlaylistBrowserFile: options.appendPlaylistBrowserFile,
@@ -615,8 +645,9 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
return await deps.retryAnilistQueueNow();
});
ipc.handle(IPC_CHANNELS.request.getCharacterDictionarySelection, async () => {
return await (deps.getCharacterDictionarySelection?.() ??
ipc.handle(IPC_CHANNELS.request.getCharacterDictionarySelection, async (_event, searchTitle) => {
const normalizedSearchTitle = typeof searchTitle === 'string' ? searchTitle.trim() : undefined;
return await (deps.getCharacterDictionarySelection?.(normalizedSearchTitle) ??
Promise.resolve({
seriesKey: '',
guessTitle: null,
@@ -628,11 +659,21 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
ipc.handle(
IPC_CHANNELS.request.setCharacterDictionarySelection,
async (_event, mediaId: unknown) => {
async (_event, mediaId: unknown, replaceManagedMediaId: unknown, mediaTitle: unknown) => {
if (!Number.isSafeInteger(mediaId) || (mediaId as number) <= 0) {
return { ok: false, message: 'Invalid AniList media ID.' };
}
return await (deps.setCharacterDictionarySelection?.(mediaId as number) ??
const normalizedReplaceManagedMediaId =
Number.isSafeInteger(replaceManagedMediaId) && (replaceManagedMediaId as number) > 0
? (replaceManagedMediaId as number)
: undefined;
const normalizedMediaTitle =
typeof mediaTitle === 'string' && mediaTitle.trim() ? mediaTitle.trim() : undefined;
return await (deps.setCharacterDictionarySelection?.(
mediaId as number,
normalizedReplaceManagedMediaId,
normalizedMediaTitle,
) ??
Promise.resolve({
ok: false,
message: 'Character dictionary selection unavailable.',
@@ -640,6 +681,44 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
},
);
ipc.handle(IPC_CHANNELS.request.getCharacterDictionaryManagerSnapshot, async () => {
return await (deps.getCharacterDictionaryManagerSnapshot?.() ??
Promise.resolve({ entries: [] }));
});
ipc.handle(
IPC_CHANNELS.request.removeCharacterDictionaryManagedEntry,
async (_event, mediaId: unknown) => {
if (!Number.isSafeInteger(mediaId) || (mediaId as number) <= 0) {
return { ok: false, message: 'Invalid AniList media ID.', entries: [] };
}
return await (deps.removeCharacterDictionaryManagedEntry?.(mediaId as number) ??
Promise.resolve({
ok: false,
message: 'Character dictionary manager unavailable.',
entries: [],
}));
},
);
ipc.handle(
IPC_CHANNELS.request.moveCharacterDictionaryManagedEntry,
async (_event, mediaId: unknown, direction: unknown) => {
if (!Number.isSafeInteger(mediaId) || (mediaId as number) <= 0) {
return { ok: false, message: 'Invalid AniList media ID.', entries: [] };
}
if (direction !== 1 && direction !== -1) {
return { ok: false, message: 'Invalid move direction.', entries: [] };
}
return await (deps.moveCharacterDictionaryManagedEntry?.(mediaId as number, direction) ??
Promise.resolve({
ok: false,
message: 'Character dictionary manager unavailable.',
entries: [],
}));
},
);
ipc.handle(IPC_CHANNELS.request.appendClipboardVideoToQueue, () => {
return deps.appendClipboardVideoToQueue();
});
+6 -3
View File
@@ -10,7 +10,7 @@ import {
test('showMpvOsdRuntime sends show-text when connected', () => {
const commands: (string | number)[][] = [];
showMpvOsdRuntime(
const shown = showMpvOsdRuntime(
{
connected: true,
send: ({ command }) => {
@@ -19,12 +19,13 @@ test('showMpvOsdRuntime sends show-text when connected', () => {
},
'hello',
);
assert.equal(shown, true);
assert.deepEqual(commands, [['show-text', 'hello', '3000']]);
});
test('showMpvOsdRuntime enables property expansion for placeholder-based messages', () => {
const commands: (string | number)[][] = [];
showMpvOsdRuntime(
const shown = showMpvOsdRuntime(
{
connected: true,
send: ({ command }) => {
@@ -33,6 +34,7 @@ test('showMpvOsdRuntime enables property expansion for placeholder-based message
},
'Subtitle delay: ${sub-delay}',
);
assert.equal(shown, true);
assert.deepEqual(commands, [
['expand-properties', 'show-text', 'Subtitle delay: ${sub-delay}', '3000'],
]);
@@ -40,7 +42,7 @@ test('showMpvOsdRuntime enables property expansion for placeholder-based message
test('showMpvOsdRuntime logs fallback when disconnected', () => {
const logs: string[] = [];
showMpvOsdRuntime(
const shown = showMpvOsdRuntime(
{
connected: false,
send: () => {},
@@ -50,6 +52,7 @@ test('showMpvOsdRuntime logs fallback when disconnected', () => {
logs.push(line);
},
);
assert.equal(shown, false);
assert.deepEqual(logs, ['OSD (MPV not connected): hello']);
});
+3 -2
View File
@@ -51,15 +51,16 @@ export function showMpvOsdRuntime(
mpvClient: MpvRuntimeClientLike | null,
text: string,
fallbackLog: (text: string) => void = (line) => logger.info(line),
): void {
): boolean {
if (mpvClient && mpvClient.connected) {
const command = text.includes('${')
? ['expand-properties', 'show-text', text, '3000']
: ['show-text', text, '3000'];
mpvClient.send({ command });
return;
return true;
}
fallbackLog(`OSD (MPV not connected): ${text}`);
return false;
}
export function replayCurrentSubtitleRuntime(mpvClient: MpvRuntimeClientLike | null): void {
+26
View File
@@ -110,6 +110,32 @@ test('overlay manager applies bounds for main and modal windows', () => {
assert.deepEqual(modalCalls, [{ x: 80, y: 90, width: 100, height: 110 }]);
});
test('overlay manager can suppress z-order promotion during bounds updates', () => {
const calls: string[] = [];
const createManager = createOverlayManager as unknown as (options: {
updateOverlayWindowBounds: (
geometry: Electron.Rectangle,
window: Electron.BrowserWindow | null,
options: { promote: boolean },
) => void;
shouldPromoteWindowOnBoundsUpdate: (window: Electron.BrowserWindow) => boolean;
}) => ReturnType<typeof createOverlayManager>;
const manager = createManager({
updateOverlayWindowBounds: (_geometry, _window, options) => {
calls.push(`promote:${options.promote}`);
},
shouldPromoteWindowOnBoundsUpdate: () => false,
});
manager.setMainWindow({
isDestroyed: () => false,
} as unknown as Electron.BrowserWindow);
manager.setOverlayWindowBounds({ x: 1, y: 2, width: 3, height: 4 });
assert.deepEqual(calls, ['promote:false']);
});
test('runtime-option broadcast still uses expected channel', () => {
const broadcasts: unknown[][] = [];
broadcastRuntimeOptionsChangedRuntime(
+16 -3
View File
@@ -16,10 +16,23 @@ export interface OverlayManager {
broadcastToOverlayWindows: (channel: string, ...args: unknown[]) => void;
}
export function createOverlayManager(): OverlayManager {
type UpdateOverlayWindowBounds = typeof updateOverlayWindowBounds;
export interface OverlayManagerOptions {
updateOverlayWindowBounds?: UpdateOverlayWindowBounds;
shouldPromoteWindowOnBoundsUpdate?: (window: BrowserWindow) => boolean;
}
export function createOverlayManager(options: OverlayManagerOptions = {}): OverlayManager {
let mainWindow: BrowserWindow | null = null;
let modalWindow: BrowserWindow | null = null;
let visibleOverlayVisible = false;
const applyOverlayBounds = options.updateOverlayWindowBounds ?? updateOverlayWindowBounds;
const updateWindowBounds = (geometry: WindowGeometry, window: BrowserWindow | null): void => {
const promote = window ? (options.shouldPromoteWindowOnBoundsUpdate?.(window) ?? true) : true;
applyOverlayBounds(geometry, window, { promote });
};
return {
getMainWindow: () => mainWindow,
@@ -32,10 +45,10 @@ export function createOverlayManager(): OverlayManager {
},
getOverlayWindow: () => mainWindow,
setOverlayWindowBounds: (geometry) => {
updateOverlayWindowBounds(geometry, mainWindow);
updateWindowBounds(geometry, mainWindow);
},
setModalWindowBounds: (geometry) => {
updateOverlayWindowBounds(geometry, modalWindow);
updateWindowBounds(geometry, modalWindow);
},
getVisibleOverlayVisible: () => visibleOverlayVisible,
setVisibleOverlayVisible: (visible) => {
+60 -1
View File
@@ -1,6 +1,65 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { initializeOverlayAnkiIntegration, initializeOverlayRuntime } from './overlay-runtime-init';
import {
initializeOverlayAnkiIntegration,
initializeOverlayRuntime,
startOverlayWindowTracker,
} from './overlay-runtime-init';
test('startOverlayWindowTracker starts tracker for the current mpv socket', () => {
const calls: string[] = [];
const tracker = {
onGeometryChange: null as ((...args: unknown[]) => void) | null,
onWindowFound: null as ((...args: unknown[]) => void) | null,
onWindowLost: null as (() => void) | null,
onWindowFocusChange: null as ((focused: boolean) => void) | null,
isTargetWindowMinimized: () => false,
start: () => {
calls.push('start');
},
};
const result = startOverlayWindowTracker({
backendOverride: 'windows',
getMpvSocketPath: () => '\\\\.\\pipe\\subminer-socket',
createWindowTracker: (override, socketPath) => {
calls.push(`create:${override}:${socketPath}`);
return tracker as never;
},
setWindowTracker: (nextTracker) => {
calls.push(nextTracker === tracker ? 'set-tracker' : 'clear-tracker');
},
updateVisibleOverlayBounds: () => {
calls.push('bounds');
},
isVisibleOverlayVisible: () => true,
updateVisibleOverlayVisibility: () => {
calls.push('visibility');
},
refreshCurrentSubtitle: () => {
calls.push('refresh-subtitle');
},
getOverlayWindows: () => [],
syncOverlayShortcuts: () => {
calls.push('sync-shortcuts');
},
});
assert.equal(result, tracker);
tracker.onWindowFound?.({ x: 10, y: 20, width: 300, height: 200 });
tracker.onWindowFocusChange?.(true);
assert.deepEqual(calls, [
'create:windows:\\\\.\\pipe\\subminer-socket',
'set-tracker',
'start',
'bounds',
'visibility',
'refresh-subtitle',
'visibility',
'sync-shortcuts',
]);
});
test('initializeOverlayRuntime skips Anki integration when ankiConnect.enabled is false', () => {
let createdIntegrations = 0;
+83 -67
View File
@@ -25,6 +25,24 @@ type CreateAnkiIntegrationArgs = {
knownWordCacheStatePath: string;
};
export type OverlayWindowTrackerOptions = {
backendOverride: string | null;
getMpvSocketPath: () => string;
updateVisibleOverlayBounds: (geometry: WindowGeometry) => void;
isVisibleOverlayVisible: () => boolean;
updateVisibleOverlayVisibility: () => void;
refreshCurrentSubtitle?: () => void;
getOverlayWindows: () => BrowserWindow[];
syncOverlayShortcuts: () => void;
setWindowTracker: (tracker: BaseWindowTracker | null) => void;
createWindowTracker?: (
override?: string | null,
targetMpvSocketPath?: string | null,
) => BaseWindowTracker | null;
bindOverlayOwner?: () => void;
releaseOverlayOwner?: () => void;
};
function createDefaultAnkiIntegration(args: CreateAnkiIntegrationArgs): AnkiIntegrationLike {
const { AnkiIntegration } =
require('../../anki-integration') as typeof import('../../anki-integration');
@@ -46,82 +64,80 @@ function createDefaultAnkiIntegration(args: CreateAnkiIntegrationArgs): AnkiInte
);
}
export function initializeOverlayRuntime(options: {
getMpvSocketPath: () => string;
getResolvedConfig: () => { ankiConnect?: AnkiConnectConfig; ai?: AiConfig };
getSubtitleTimingTracker: () => unknown | null;
getMpvClient: () => {
send?: (payload: { command: string[] }) => void;
} | null;
getRuntimeOptionsManager: () => {
getEffectiveAnkiConnectConfig: (config?: AnkiConnectConfig) => AnkiConnectConfig;
} | null;
getAnkiIntegration?: () => unknown | null;
setAnkiIntegration: (integration: unknown | null) => void;
showDesktopNotification: (title: string, options: { body?: string; icon?: string }) => void;
createFieldGroupingCallback: () => (
data: KikuFieldGroupingRequestData,
) => Promise<KikuFieldGroupingChoice>;
getKnownWordCacheStatePath: () => string;
shouldStartAnkiIntegration?: () => boolean;
createAnkiIntegration?: (args: CreateAnkiIntegrationArgs) => AnkiIntegrationLike;
backendOverride: string | null;
createMainWindow: () => void;
registerGlobalShortcuts: () => void;
updateVisibleOverlayBounds: (geometry: WindowGeometry) => void;
isVisibleOverlayVisible: () => boolean;
updateVisibleOverlayVisibility: () => void;
refreshCurrentSubtitle?: () => void;
getOverlayWindows: () => BrowserWindow[];
syncOverlayShortcuts: () => void;
setWindowTracker: (tracker: BaseWindowTracker | null) => void;
createWindowTracker?: (
override?: string | null,
targetMpvSocketPath?: string | null,
) => BaseWindowTracker | null;
bindOverlayOwner?: () => void;
releaseOverlayOwner?: () => void;
}): void {
options.createMainWindow();
options.registerGlobalShortcuts();
export function startOverlayWindowTracker(
options: OverlayWindowTrackerOptions,
): BaseWindowTracker | null {
const createWindowTrackerHandler = options.createWindowTracker ?? createWindowTracker;
const windowTracker = createWindowTrackerHandler(
options.backendOverride,
options.getMpvSocketPath(),
);
options.setWindowTracker(windowTracker);
if (windowTracker) {
windowTracker.onGeometryChange = (geometry: WindowGeometry) => {
options.updateVisibleOverlayBounds(geometry);
};
windowTracker.onWindowFound = (geometry: WindowGeometry) => {
options.updateVisibleOverlayBounds(geometry);
options.bindOverlayOwner?.();
if (options.isVisibleOverlayVisible()) {
options.updateVisibleOverlayVisibility();
options.refreshCurrentSubtitle?.();
}
};
windowTracker.onWindowLost = () => {
options.releaseOverlayOwner?.();
if (windowTracker.isTargetWindowMinimized()) {
for (const window of options.getOverlayWindows()) {
window.hide();
}
options.syncOverlayShortcuts();
return;
}
if (!windowTracker) {
return null;
}
windowTracker.onGeometryChange = (geometry: WindowGeometry) => {
options.updateVisibleOverlayBounds(geometry);
};
windowTracker.onWindowFound = (geometry: WindowGeometry) => {
options.updateVisibleOverlayBounds(geometry);
options.bindOverlayOwner?.();
if (options.isVisibleOverlayVisible()) {
options.updateVisibleOverlayVisibility();
};
windowTracker.onWindowFocusChange = () => {
if (options.isVisibleOverlayVisible()) {
options.updateVisibleOverlayVisibility();
options.refreshCurrentSubtitle?.();
}
};
windowTracker.onWindowLost = () => {
options.releaseOverlayOwner?.();
if (windowTracker.isTargetWindowMinimized()) {
for (const window of options.getOverlayWindows()) {
window.hide();
}
options.syncOverlayShortcuts();
};
windowTracker.start();
}
return;
}
options.updateVisibleOverlayVisibility();
};
windowTracker.onWindowFocusChange = () => {
if (options.isVisibleOverlayVisible()) {
options.updateVisibleOverlayVisibility();
}
options.syncOverlayShortcuts();
};
windowTracker.start();
return windowTracker;
}
export function initializeOverlayRuntime(
options: OverlayWindowTrackerOptions & {
getMpvSocketPath: () => string;
getResolvedConfig: () => { ankiConnect?: AnkiConnectConfig; ai?: AiConfig };
getSubtitleTimingTracker: () => unknown | null;
getMpvClient: () => {
send?: (payload: { command: string[] }) => void;
} | null;
getRuntimeOptionsManager: () => {
getEffectiveAnkiConnectConfig: (config?: AnkiConnectConfig) => AnkiConnectConfig;
} | null;
getAnkiIntegration?: () => unknown | null;
setAnkiIntegration: (integration: unknown | null) => void;
showDesktopNotification: (title: string, options: { body?: string; icon?: string }) => void;
createFieldGroupingCallback: () => (
data: KikuFieldGroupingRequestData,
) => Promise<KikuFieldGroupingChoice>;
getKnownWordCacheStatePath: () => string;
shouldStartAnkiIntegration?: () => boolean;
createAnkiIntegration?: (args: CreateAnkiIntegrationArgs) => AnkiIntegrationLike;
backendOverride: string | null;
createMainWindow: () => void;
registerGlobalShortcuts: () => void;
},
): void {
options.createMainWindow();
options.registerGlobalShortcuts();
startOverlayWindowTracker(options);
initializeOverlayAnkiIntegration(options);
@@ -25,7 +25,7 @@ function makeShortcuts(overrides: Partial<ConfiguredShortcuts> = {}): Configured
multiCopyTimeoutMs: 2500,
toggleSecondarySub: null,
markAudioCard: null,
openCharacterDictionary: null,
openCharacterDictionaryManager: null,
openRuntimeOptions: null,
openJimaku: null,
openSessionHelp: null,
@@ -49,6 +49,9 @@ function createDeps(overrides: Partial<OverlayShortcutRuntimeDeps> = {}) {
openCharacterDictionary: () => {
calls.push('openCharacterDictionary');
},
openCharacterDictionaryManager: () => {
calls.push('openCharacterDictionaryManager');
},
openJimaku: () => {
calls.push('openJimaku');
},
@@ -93,6 +96,7 @@ test('createOverlayShortcutRuntimeHandlers dispatches sync and async handlers',
overlayHandlers.copySubtitleMultiple(1111);
overlayHandlers.toggleSecondarySub();
overlayHandlers.openRuntimeOptions();
overlayHandlers.openCharacterDictionaryManager();
overlayHandlers.openJimaku();
overlayHandlers.mineSentenceMultiple(2222);
overlayHandlers.updateLastCardFromClipboard();
@@ -104,6 +108,7 @@ test('createOverlayShortcutRuntimeHandlers dispatches sync and async handlers',
'copySubtitleMultiple:1111',
'toggleSecondarySub',
'openRuntimeOptions',
'openCharacterDictionaryManager',
'openJimaku',
'mineSentenceMultiple:2222',
'updateLastCardFromClipboard',
@@ -159,6 +164,7 @@ test('runOverlayShortcutLocalFallback dispatches matching single-step actions',
{
openRuntimeOptions: () => handled.push('openRuntimeOptions'),
openCharacterDictionary: () => handled.push('openCharacterDictionary'),
openCharacterDictionaryManager: () => handled.push('openCharacterDictionaryManager'),
openJimaku: () => handled.push('openJimaku'),
markAudioCard: () => handled.push('markAudioCard'),
copySubtitleMultiple: (timeoutMs) => handled.push(`copySubtitleMultiple:${timeoutMs}`),
@@ -192,6 +198,7 @@ test('runOverlayShortcutLocalFallback leaves multi-step numeric shortcuts for re
{
openRuntimeOptions: () => handled.push('openRuntimeOptions'),
openCharacterDictionary: () => handled.push('openCharacterDictionary'),
openCharacterDictionaryManager: () => handled.push('openCharacterDictionaryManager'),
openJimaku: () => handled.push('openJimaku'),
markAudioCard: () => handled.push('markAudioCard'),
copySubtitleMultiple: (timeoutMs) => handled.push(`copySubtitleMultiple:${timeoutMs}`),
@@ -212,6 +219,7 @@ test('runOverlayShortcutLocalFallback leaves multi-step numeric shortcuts for re
{
openRuntimeOptions: () => handled.push('openRuntimeOptions'),
openCharacterDictionary: () => handled.push('openCharacterDictionary'),
openCharacterDictionaryManager: () => handled.push('openCharacterDictionaryManager'),
openJimaku: () => handled.push('openJimaku'),
markAudioCard: () => handled.push('markAudioCard'),
copySubtitleMultiple: (timeoutMs) => handled.push(`copySubtitleMultiple:${timeoutMs}`),
@@ -249,6 +257,7 @@ test('runOverlayShortcutLocalFallback passes allowWhenRegistered for secondary-s
{
openRuntimeOptions: () => {},
openCharacterDictionary: () => {},
openCharacterDictionaryManager: () => {},
openJimaku: () => {},
markAudioCard: () => {},
copySubtitleMultiple: () => {},
@@ -285,6 +294,7 @@ test('runOverlayShortcutLocalFallback allows registered-global jimaku shortcut',
{
openRuntimeOptions: () => {},
openCharacterDictionary: () => {},
openCharacterDictionaryManager: () => {},
openJimaku: () => {},
markAudioCard: () => {},
copySubtitleMultiple: () => {},
@@ -315,6 +325,9 @@ test('runOverlayShortcutLocalFallback returns false when no action matches', ()
openCharacterDictionary: () => {
called = true;
},
openCharacterDictionaryManager: () => {
called = true;
},
openJimaku: () => {
called = true;
},
@@ -398,6 +411,7 @@ test('registerOverlayShortcutsRuntime reports active shortcuts when configured',
toggleSecondarySub: () => {},
markAudioCard: () => {},
openCharacterDictionary: () => {},
openCharacterDictionaryManager: () => {},
openRuntimeOptions: () => {},
openJimaku: () => {},
}),
@@ -425,6 +439,7 @@ test('unregisterOverlayShortcutsRuntime clears pending shortcut work when active
toggleSecondarySub: () => {},
markAudioCard: () => {},
openCharacterDictionary: () => {},
openCharacterDictionaryManager: () => {},
openRuntimeOptions: () => {},
openJimaku: () => {},
}),
@@ -7,6 +7,7 @@ const logger = createLogger('main:overlay-shortcut-handler');
export interface OverlayShortcutFallbackHandlers {
openRuntimeOptions: () => void;
openCharacterDictionary: () => void;
openCharacterDictionaryManager: () => void;
openJimaku: () => void;
markAudioCard: () => void;
copySubtitleMultiple: (timeoutMs: number) => void;
@@ -23,6 +24,7 @@ export interface OverlayShortcutRuntimeDeps {
showMpvOsd: (text: string) => void;
openRuntimeOptions: () => void;
openCharacterDictionary: () => void;
openCharacterDictionaryManager: () => void;
openJimaku: () => void;
markAudioCard: () => Promise<void>;
copySubtitleMultiple: (timeoutMs: number) => void;
@@ -100,6 +102,9 @@ export function createOverlayShortcutRuntimeHandlers(deps: OverlayShortcutRuntim
openCharacterDictionary: () => {
deps.openCharacterDictionary();
},
openCharacterDictionaryManager: () => {
deps.openCharacterDictionaryManager();
},
openJimaku: () => {
deps.openJimaku();
},
@@ -108,6 +113,7 @@ export function createOverlayShortcutRuntimeHandlers(deps: OverlayShortcutRuntim
const fallbackHandlers: OverlayShortcutFallbackHandlers = {
openRuntimeOptions: overlayHandlers.openRuntimeOptions,
openCharacterDictionary: overlayHandlers.openCharacterDictionary,
openCharacterDictionaryManager: overlayHandlers.openCharacterDictionaryManager,
openJimaku: overlayHandlers.openJimaku,
markAudioCard: overlayHandlers.markAudioCard,
copySubtitleMultiple: overlayHandlers.copySubtitleMultiple,
@@ -141,9 +147,9 @@ export function runOverlayShortcutLocalFallback(
},
},
{
accelerator: shortcuts.openCharacterDictionary,
accelerator: shortcuts.openCharacterDictionaryManager,
run: () => {
handlers.openCharacterDictionary();
handlers.openCharacterDictionaryManager();
},
},
{
+4 -1
View File
@@ -20,7 +20,7 @@ function createShortcuts(overrides: Partial<ConfiguredShortcuts> = {}): Configur
multiCopyTimeoutMs: 2500,
toggleSecondarySub: null,
markAudioCard: null,
openCharacterDictionary: null,
openCharacterDictionaryManager: null,
openRuntimeOptions: null,
openJimaku: null,
openSessionHelp: null,
@@ -44,6 +44,7 @@ test('registerOverlayShortcuts reports active overlay shortcuts when configured'
toggleSecondarySub: () => {},
markAudioCard: () => {},
openCharacterDictionary: () => {},
openCharacterDictionaryManager: () => {},
openRuntimeOptions: () => {},
openJimaku: () => {},
}),
@@ -64,6 +65,7 @@ test('registerOverlayShortcuts stays inactive when overlay shortcuts are absent'
toggleSecondarySub: () => {},
markAudioCard: () => {},
openCharacterDictionary: () => {},
openCharacterDictionaryManager: () => {},
openRuntimeOptions: () => {},
openJimaku: () => {},
}),
@@ -86,6 +88,7 @@ test('syncOverlayShortcutsRuntime deactivates cleanly when shortcuts were active
toggleSecondarySub: () => {},
markAudioCard: () => {},
openCharacterDictionary: () => {},
openCharacterDictionaryManager: () => {},
openRuntimeOptions: () => {},
openJimaku: () => {},
}),
+2 -1
View File
@@ -11,6 +11,7 @@ export interface OverlayShortcutHandlers {
toggleSecondarySub: () => void;
markAudioCard: () => void;
openCharacterDictionary: () => void;
openCharacterDictionaryManager: () => void;
openRuntimeOptions: () => void;
openJimaku: () => void;
}
@@ -32,7 +33,7 @@ const OVERLAY_SHORTCUT_KEYS: Array<keyof Omit<ConfiguredShortcuts, 'multiCopyTim
'mineSentenceMultiple',
'toggleSecondarySub',
'markAudioCard',
'openCharacterDictionary',
'openCharacterDictionaryManager',
'openRuntimeOptions',
'openJimaku',
];
+8 -1
View File
@@ -51,11 +51,18 @@ function loadOverlayWindowLayer(window: BrowserWindow, layer: OverlayWindowKind)
export function updateOverlayWindowBounds(
geometry: WindowGeometry,
window: BrowserWindow | null,
options: {
promote?: boolean;
} = {},
): void {
if (!geometry || !window || window.isDestroyed()) return;
const bounds = normalizeOverlayWindowBoundsForPlatform(geometry, process.platform, screen);
window.setBounds(bounds);
ensureHyprlandWindowFloatingByTitle({ title: window.getTitle(), bounds });
ensureHyprlandWindowFloatingByTitle({
title: window.getTitle(),
bounds,
promote: options.promote,
});
}
export function ensureOverlayWindowLevel(window: BrowserWindow): void {
@@ -35,6 +35,7 @@ function createDeps(overrides: Partial<SessionActionExecutorDeps> = {}) {
openRuntimeOptionsPalette: () => calls.push('runtime-options'),
openSessionHelp: () => calls.push('session-help'),
openCharacterDictionary: () => calls.push('character-dictionary'),
openCharacterDictionaryManager: () => calls.push('character-dictionary-manager'),
openControllerSelect: () => calls.push('controller-select'),
openControllerDebug: () => calls.push('controller-debug'),
openJimaku: () => calls.push('jimaku'),
@@ -77,3 +78,11 @@ test('dispatchSessionAction does not advance playlist when mark watched no-ops',
assert.deepEqual(calls, ['mark-watched']);
});
test('dispatchSessionAction opens the character dictionary manager', async () => {
const { calls, deps } = createDeps();
await dispatchSessionAction({ actionId: 'openCharacterDictionaryManager' }, deps);
assert.deepEqual(calls, ['character-dictionary-manager']);
});
+5 -1
View File
@@ -19,6 +19,7 @@ export interface SessionActionExecutorDeps {
openRuntimeOptionsPalette: () => void;
openSessionHelp: () => void;
openCharacterDictionary: () => void;
openCharacterDictionaryManager: () => void;
openControllerSelect: () => void;
openControllerDebug: () => void;
openJimaku: () => void;
@@ -97,7 +98,10 @@ export async function dispatchSessionAction(
deps.openSessionHelp();
return;
case 'openCharacterDictionary':
deps.openCharacterDictionary();
deps.openCharacterDictionaryManager();
return;
case 'openCharacterDictionaryManager':
deps.openCharacterDictionaryManager();
return;
case 'openControllerSelect':
deps.openControllerSelect();
+37 -2
View File
@@ -19,7 +19,7 @@ function createShortcuts(overrides: Partial<ConfiguredShortcuts> = {}): Configur
multiCopyTimeoutMs: 2500,
toggleSecondarySub: null,
markAudioCard: null,
openCharacterDictionary: null,
openCharacterDictionaryManager: null,
openRuntimeOptions: null,
openJimaku: null,
openSessionHelp: null,
@@ -209,6 +209,41 @@ test('compileSessionBindings keeps default replay and next subtitle session acti
assert.equal(next?.actionId, 'playNextSubtitle');
});
test('compileSessionBindings keeps only the character dictionary manager bound by default', () => {
const result = compileSessionBindings({
shortcuts: resolveConfiguredShortcuts(DEFAULT_CONFIG, DEFAULT_CONFIG),
keybindings: DEFAULT_KEYBINDINGS,
statsToggleKey: DEFAULT_CONFIG.stats.toggleKey,
platform: 'linux',
rawConfig: DEFAULT_CONFIG,
});
const characterDictionaryBindings = result.bindings.flatMap((binding) => {
if (binding.actionType !== 'session-action') return [];
if (
binding.actionId !== 'openCharacterDictionary' &&
binding.actionId !== 'openCharacterDictionaryManager'
) {
return [];
}
return [
{
sourcePath: binding.sourcePath,
originalKey: binding.originalKey,
actionId: binding.actionId,
},
];
});
assert.deepEqual(characterDictionaryBindings, [
{
sourcePath: 'shortcuts.openCharacterDictionaryManager',
originalKey: 'CommandOrControl+D',
actionId: 'openCharacterDictionaryManager',
},
]);
});
test('compileSessionBindings wires every default keybinding to an overlay or mpv action', () => {
const expectedSpecialActions: Record<string, string> = {
[SPECIAL_COMMANDS.SHIFT_SUB_DELAY_TO_PREVIOUS_SUBTITLE_START]: 'shiftSubDelayPrevLine',
@@ -411,7 +446,7 @@ test('compileSessionBindings wires every configured shortcut key into the shared
'mineSentenceMultiple',
'toggleSecondarySub',
'markAudioCard',
'openCharacterDictionary',
'openCharacterDictionaryManager',
'openRuntimeOptions',
'openJimaku',
'openSessionHelp',
+1 -1
View File
@@ -44,7 +44,7 @@ const SESSION_SHORTCUT_ACTIONS: Array<{
{ key: 'mineSentenceMultiple', actionId: 'mineSentenceMultiple' },
{ key: 'toggleSecondarySub', actionId: 'toggleSecondarySub' },
{ key: 'markAudioCard', actionId: 'markAudioCard' },
{ key: 'openCharacterDictionary', actionId: 'openCharacterDictionary' },
{ key: 'openCharacterDictionaryManager', actionId: 'openCharacterDictionaryManager' },
{ key: 'openRuntimeOptions', actionId: 'openRuntimeOptions' },
{ key: 'openJimaku', actionId: 'openJimaku' },
{ key: 'openSessionHelp', actionId: 'openSessionHelp' },
@@ -0,0 +1,65 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
promoteSettingsWindowAboveOverlay,
shouldPromoteSettingsWindowAboveOverlay,
} from './settings-window-z-order';
test('settings window promotion only applies to Hyprland sessions', () => {
assert.equal(
shouldPromoteSettingsWindowAboveOverlay('linux', { HYPRLAND_INSTANCE_SIGNATURE: 'hypr' }),
true,
);
assert.equal(
shouldPromoteSettingsWindowAboveOverlay('linux', { WAYLAND_DISPLAY: 'wayland-1' }),
false,
);
assert.equal(
shouldPromoteSettingsWindowAboveOverlay('darwin', { HYPRLAND_INSTANCE_SIGNATURE: 'hypr' }),
false,
);
});
test('promoteSettingsWindowAboveOverlay raises Hyprland settings windows above the overlay', () => {
const calls: string[] = [];
const promoted = promoteSettingsWindowAboveOverlay(
{
isDestroyed: () => false,
getTitle: () => 'SubMiner Settings',
setAlwaysOnTop: (flag: boolean) => calls.push(`always-on-top:${flag}`),
moveTop: () => calls.push('move-top'),
} as never,
{
platform: 'linux',
env: { HYPRLAND_INSTANCE_SIGNATURE: 'hypr' },
ensureHyprlandWindowFloatingByTitle: ({ title }) => {
calls.push(`hyprland-top:${title}`);
return true;
},
},
);
assert.equal(promoted, true);
assert.deepEqual(calls, ['always-on-top:true', 'move-top', 'hyprland-top:SubMiner Settings']);
});
test('promoteSettingsWindowAboveOverlay skips destroyed windows', () => {
const calls: string[] = [];
const promoted = promoteSettingsWindowAboveOverlay(
{
isDestroyed: () => true,
getTitle: () => 'SubMiner Settings',
setAlwaysOnTop: () => calls.push('always-on-top'),
moveTop: () => calls.push('move-top'),
} as never,
{
platform: 'linux',
env: { HYPRLAND_INSTANCE_SIGNATURE: 'hypr' },
},
);
assert.equal(promoted, false);
assert.deepEqual(calls, []);
});
@@ -0,0 +1,48 @@
import type { BrowserWindow } from 'electron';
import {
ensureHyprlandWindowFloatingByTitle,
shouldAttemptHyprlandWindowPlacement,
} from './hyprland-window-placement';
type SettingsWindowLevelController = Pick<
BrowserWindow,
'getTitle' | 'isDestroyed' | 'moveTop' | 'setAlwaysOnTop'
>;
type PromoteSettingsWindowOptions = {
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
ensureHyprlandWindowFloatingByTitle?: typeof ensureHyprlandWindowFloatingByTitle;
};
export function shouldPromoteSettingsWindowAboveOverlay(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): boolean {
return shouldAttemptHyprlandWindowPlacement(platform, env);
}
export function promoteSettingsWindowAboveOverlay(
window: SettingsWindowLevelController,
options: PromoteSettingsWindowOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
if (window.isDestroyed() || !shouldPromoteSettingsWindowAboveOverlay(platform, env)) {
return false;
}
window.setAlwaysOnTop(true);
window.moveTop();
const title = window.getTitle().trim();
if (title) {
(options.ensureHyprlandWindowFloatingByTitle ?? ensureHyprlandWindowFloatingByTitle)({
title,
platform,
env,
});
}
return true;
}
+64
View File
@@ -149,6 +149,70 @@ test('tokenizeSubtitle preserves Yomitan name-match metadata on tokens', async (
assert.equal((result.tokens?.[1] as { isNameMatch?: boolean } | undefined)?.isNameMatch, false);
});
test('tokenizeSubtitle attaches character image metadata to name matches when enabled', async () => {
const result = await tokenizeSubtitle(
'アクアです',
makeDepsFromYomitanTokens(
[
{ surface: 'アクア', reading: 'あくあ', headword: 'アクア', isNameMatch: true },
{ surface: 'です', reading: 'です', headword: 'です' },
],
{
getNameMatchImagesEnabled: () => true,
getCharacterNameImage: (term) =>
term === 'アクア'
? {
src: 'data:image/png;base64,AAAA',
alt: 'アクア',
}
: null,
} as Partial<TokenizerServiceDeps>,
),
);
assert.deepEqual(result.tokens?.[0]?.characterImage, {
src: 'data:image/png;base64,AAAA',
alt: 'アクア',
});
assert.equal(result.tokens?.[1]?.characterImage, undefined);
});
test('tokenizeSubtitle keeps tokens when character image lookup throws', async () => {
const result = await tokenizeSubtitle(
'アクア',
makeDepsFromYomitanTokens(
[{ surface: 'アクア', reading: 'あくあ', headword: 'アクア', isNameMatch: true }],
{
getNameMatchImagesEnabled: () => true,
getCharacterNameImage: () => {
throw new Error('image lookup failed');
},
} as Partial<TokenizerServiceDeps>,
),
);
assert.equal(result.tokens?.[0]?.surface, 'アクア');
assert.equal(result.tokens?.[0]?.characterImage, undefined);
});
test('tokenizeSubtitle omits character image metadata when name-match images are disabled', async () => {
const result = await tokenizeSubtitle(
'アクア',
makeDepsFromYomitanTokens(
[{ surface: 'アクア', reading: 'あくあ', headword: 'アクア', isNameMatch: true }],
{
getNameMatchImagesEnabled: () => false,
getCharacterNameImage: () => ({
src: 'data:image/png;base64,AAAA',
alt: 'アクア',
}),
} as Partial<TokenizerServiceDeps>,
),
);
assert.equal(result.tokens?.[0]?.characterImage, undefined);
});
test('tokenizeSubtitle caches JLPT lookups across repeated tokens', async () => {
let lookupCalls = 0;
const result = await tokenizeSubtitle(
+62 -1
View File
@@ -3,6 +3,7 @@ import { mergeTokens } from '../../token-merger';
import { createLogger } from '../../logger';
import {
FrequencyDictionaryMatchMode,
CharacterNameImage,
MergedToken,
NPlusOneMatchMode,
SubtitleData,
@@ -48,6 +49,9 @@ export interface TokenizerServiceDeps {
getNPlusOneEnabled?: () => boolean;
getJlptEnabled?: () => boolean;
getNameMatchEnabled?: () => boolean;
getNameMatchImagesEnabled?: () => boolean;
getCharacterNameImage?: (term: string) => CharacterNameImage | null;
getCurrentCharacterDictionaryMediaId?: () => number | null;
getFrequencyDictionaryEnabled?: () => boolean;
getFrequencyDictionaryMatchMode?: () => FrequencyDictionaryMatchMode;
getFrequencyRank?: FrequencyDictionaryLookup;
@@ -80,6 +84,9 @@ export interface TokenizerDepsRuntimeOptions {
getNPlusOneEnabled?: () => boolean;
getJlptEnabled?: () => boolean;
getNameMatchEnabled?: () => boolean;
getNameMatchImagesEnabled?: () => boolean;
getCharacterNameImage?: (term: string) => CharacterNameImage | null;
getCurrentCharacterDictionaryMediaId?: () => number | null;
getFrequencyDictionaryEnabled?: () => boolean;
getFrequencyDictionaryMatchMode?: () => FrequencyDictionaryMatchMode;
getFrequencyRank?: FrequencyDictionaryLookup;
@@ -94,6 +101,7 @@ interface TokenizerAnnotationOptions {
nPlusOneEnabled: boolean;
jlptEnabled: boolean;
nameMatchEnabled: boolean;
nameMatchImagesEnabled: boolean;
frequencyEnabled: boolean;
frequencyMatchMode: FrequencyDictionaryMatchMode;
minSentenceWordsForNPlusOne: number | undefined;
@@ -229,6 +237,9 @@ export function createTokenizerDepsRuntime(
getNPlusOneEnabled: options.getNPlusOneEnabled,
getJlptEnabled: options.getJlptEnabled,
getNameMatchEnabled: options.getNameMatchEnabled,
getNameMatchImagesEnabled: options.getNameMatchImagesEnabled,
getCharacterNameImage: options.getCharacterNameImage,
getCurrentCharacterDictionaryMediaId: options.getCurrentCharacterDictionaryMediaId,
getFrequencyDictionaryEnabled: options.getFrequencyDictionaryEnabled,
getFrequencyDictionaryMatchMode: options.getFrequencyDictionaryMatchMode ?? (() => 'headword'),
getFrequencyRank: options.getFrequencyRank,
@@ -684,6 +695,7 @@ function getAnnotationOptions(deps: TokenizerServiceDeps): TokenizerAnnotationOp
nPlusOneEnabled,
jlptEnabled: deps.getJlptEnabled?.() !== false,
nameMatchEnabled: deps.getNameMatchEnabled?.() !== false,
nameMatchImagesEnabled: deps.getNameMatchImagesEnabled?.() === true,
frequencyEnabled: deps.getFrequencyDictionaryEnabled?.() !== false,
frequencyMatchMode: deps.getFrequencyDictionaryMatchMode?.() ?? 'headword',
minSentenceWordsForNPlusOne: deps.getMinSentenceWordsForNPlusOne?.(),
@@ -699,6 +711,7 @@ async function parseWithYomitanInternalParser(
): Promise<MergedToken[] | null> {
const selectedTokens = await requestYomitanScanTokens(text, deps, logger, {
includeNameMatchMetadata: options.nameMatchEnabled,
currentCharacterDictionaryMediaId: deps.getCurrentCharacterDictionaryMediaId?.() ?? null,
});
if (!selectedTokens || selectedTokens.length === 0) {
return null;
@@ -780,6 +793,53 @@ async function parseWithYomitanInternalParser(
return enrichedTokens;
}
function resolveCharacterNameImageForToken(
token: MergedToken,
getCharacterNameImage: (term: string) => CharacterNameImage | null,
): CharacterNameImage | null {
const terms = [token.headword, token.surface]
.map((term) => term.trim())
.filter((term, index, list) => term.length > 0 && list.indexOf(term) === index);
for (const term of terms) {
const image = getCharacterNameImage(term);
if (image) {
return image;
}
}
return null;
}
function applyCharacterNameImages(
tokens: MergedToken[],
deps: TokenizerServiceDeps,
options: TokenizerAnnotationOptions,
): MergedToken[] {
if (
!options.nameMatchEnabled ||
!options.nameMatchImagesEnabled ||
typeof deps.getCharacterNameImage !== 'function'
) {
return tokens.map((token) => ({ ...token, characterImage: undefined }));
}
const getCharacterNameImage = deps.getCharacterNameImage;
return tokens.map((token) => {
if (token.isNameMatch !== true) {
return { ...token, characterImage: undefined };
}
let characterImage: CharacterNameImage | undefined;
try {
characterImage = resolveCharacterNameImageForToken(token, getCharacterNameImage) ?? undefined;
} catch (err) {
logger.warn('Failed to resolve character name image:', (err as Error).message);
}
return {
...token,
characterImage,
};
});
}
export async function tokenizeSubtitle(
text: string,
deps: TokenizerServiceDeps,
@@ -805,9 +865,10 @@ export async function tokenizeSubtitle(
const yomitanTokens = await parseWithYomitanInternalParser(tokenizeText, deps, annotationOptions);
if (yomitanTokens && yomitanTokens.length > 0) {
const annotatedTokens = await applyAnnotationStage(yomitanTokens, deps, annotationOptions);
const renderedTokens = applyCharacterNameImages(annotatedTokens, deps, annotationOptions);
return {
text: displayText,
tokens: annotatedTokens.length > 0 ? annotatedTokens : null,
tokens: renderedTokens.length > 0 ? renderedTokens : null,
};
}
@@ -788,6 +788,30 @@ test('stripSubtitleAnnotationMetadata keeps known hover data while clearing non-
});
});
test('stripSubtitleAnnotationMetadata clears character image metadata from excluded name matches', () => {
const token = makeToken({
surface: 'は',
headword: 'は',
reading: 'ハ',
partOfSpeech: PartOfSpeech.particle,
pos1: '助詞',
isNameMatch: true,
});
token.characterImage = {
src: 'data:image/png;base64,AAAA',
alt: 'は',
};
assert.deepEqual(stripSubtitleAnnotationMetadata(token), {
...token,
isNPlusOneTarget: false,
isNameMatch: false,
characterImage: undefined,
jlptLevel: undefined,
frequencyRank: undefined,
});
});
test('stripSubtitleAnnotationMetadata leaves content tokens unchanged', () => {
const token = makeToken({
surface: '猫',
@@ -508,11 +508,17 @@ export function stripSubtitleAnnotationMetadata(
return token;
}
return {
const strippedToken = {
...token,
isNPlusOneTarget: false,
isNameMatch: false,
jlptLevel: undefined,
frequencyRank: undefined,
};
if ('characterImage' in strippedToken) {
strippedToken.characterImage = undefined;
}
return strippedToken;
}
@@ -1281,6 +1281,158 @@ test('requestYomitanScanTokens marks grouped entries when SubMiner dictionary al
assert.equal((result as Array<{ isNameMatch?: boolean }>)[0]?.isNameMatch, true);
});
test('requestYomitanScanTokens ignores SubMiner character entries from other media', async () => {
let scannerScript = '';
const deps = createDeps(async (script) => {
if (script.includes('termsFind')) {
scannerScript = script;
return [];
}
if (script.includes('optionsGetFull')) {
return {
profileCurrent: 0,
profiles: [
{
options: {
scanning: { length: 40 },
},
},
],
};
}
return null;
});
await requestYomitanScanTokens(
'カズ',
deps,
{ error: () => undefined },
{ includeNameMatchMetadata: true, currentCharacterDictionaryMediaId: 21202 },
);
const result = await runInjectedYomitanScript(scannerScript, (action, params) => {
if (action !== 'termsFind') {
throw new Error(`unexpected action: ${action}`);
}
const text = (params as { text?: string } | undefined)?.text;
if (text !== 'カズ') {
return { originalTextLength: 0, dictionaryEntries: [] };
}
return {
originalTextLength: 2,
dictionaryEntries: [
{
headwords: [
{
term: 'カズ',
reading: 'かず',
sources: [{ originalText: 'カズ', isPrimary: true, matchType: 'exact' }],
},
],
definitions: [
{
dictionary: 'SubMiner Character Dictionary',
dictionaryAlias: 'SubMiner Character Dictionary',
entries: [
{
type: 'structured-content',
content: {
tag: 'img',
path: 'img/m115230-c9.png',
alt: 'Kaz',
},
},
],
},
],
},
],
};
});
assert.deepEqual(result, []);
});
test('requestYomitanScanTokens accepts SubMiner character entries with structured-content media data', async () => {
let scannerScript = '';
const deps = createDeps(async (script) => {
if (script.includes('termsFind')) {
scannerScript = script;
return [];
}
if (script.includes('optionsGetFull')) {
return {
profileCurrent: 0,
profiles: [
{
options: {
scanning: { length: 40 },
},
},
],
};
}
return null;
});
await requestYomitanScanTokens(
'アクア',
deps,
{ error: () => undefined },
{ includeNameMatchMetadata: true, currentCharacterDictionaryMediaId: 21699 },
);
const result = await runInjectedYomitanScript(scannerScript, (action, params) => {
if (action !== 'termsFind') {
throw new Error(`unexpected action: ${action}`);
}
const text = (params as { text?: string } | undefined)?.text;
if (text !== 'アクア') {
return { originalTextLength: 0, dictionaryEntries: [] };
}
return {
originalTextLength: 3,
dictionaryEntries: [
{
headwords: [
{
term: 'アクア',
reading: 'あくあ',
sources: [{ originalText: 'アクア', isPrimary: true, matchType: 'exact' }],
},
],
definitions: [
{
dictionary: 'SubMiner Character Dictionary',
dictionaryAlias: 'SubMiner Character Dictionary',
entries: [
{
type: 'structured-content',
content: {
tag: 'div',
data: { subminerMediaId: '21699' },
content: [
{
tag: 'img',
path: 'img/m115230-c1.png',
alt: 'アクア',
},
],
},
},
],
},
],
},
],
};
});
assert.equal(Array.isArray(result), true);
assert.equal((result as Array<{ surface?: string }>)[0]?.surface, 'アクア');
assert.equal((result as Array<{ isNameMatch?: boolean }>)[0]?.isNameMatch, true);
});
test('requestYomitanScanTokens preserves matched headword word classes', async () => {
let scannerScript = '';
const deps = createDeps(async (script) => {
@@ -1577,18 +1729,24 @@ test('dictionary settings helpers upsert and remove dictionary entries without r
assert.match(upsertScript ?? '', /"enabled":true/);
});
test('importYomitanDictionaryFromZip uses settings automation bridge instead of custom backend action', async () => {
test('importYomitanDictionaryFromZip imports via localhost URL instead of embedding archive bytes in script', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-yomitan-import-'));
const zipPath = path.join(tempDir, 'dict.zip');
fs.writeFileSync(zipPath, Buffer.from('zip-bytes'));
const scripts: string[] = [];
const servedArchives: string[] = [];
const settingsWindow = {
isDestroyed: () => false,
destroy: () => undefined,
webContents: {
executeJavaScript: async (script: string) => {
scripts.push(script);
const urlMatch = script.match(/importDictionaryArchiveUrl\(\s*"([^"]+)"/);
if (urlMatch) {
const response = await fetch(JSON.parse(`"${urlMatch[1]}"`) as string);
servedArchives.push(await response.text());
}
return true;
},
},
@@ -1611,15 +1769,103 @@ test('importYomitanDictionaryFromZip uses settings automation bridge instead of
true,
);
assert.equal(
scripts.some((script) => script.includes('importDictionaryArchiveBase64')),
scripts.some((script) => script.includes('importDictionaryArchiveUrl')),
true,
);
assert.deepEqual(servedArchives, ['zip-bytes']);
assert.equal(
scripts.some((script) => script.includes('emlwLWJ5dGVz')),
false,
);
assert.equal(
scripts.some((script) => script.includes('subminerImportDictionary')),
false,
);
});
test('importYomitanDictionaryFromZip falls back to base64 import for older Yomitan bridge', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-yomitan-import-'));
const zipPath = path.join(tempDir, 'dict.zip');
fs.writeFileSync(zipPath, Buffer.from('zip-bytes'));
const scripts: string[] = [];
const settingsWindow = {
isDestroyed: () => false,
destroy: () => undefined,
webContents: {
executeJavaScript: async (script: string) => {
scripts.push(script);
if (
script.includes(
'typeof globalThis.__subminerYomitanSettingsAutomation.importDictionaryArchiveUrl',
)
) {
return false;
}
return true;
},
},
};
const deps = createDeps(async () => true, {
createYomitanExtensionWindow: async (pageName: string) => {
assert.equal(pageName, 'settings.html');
return settingsWindow;
},
});
const imported = await importYomitanDictionaryFromZip(zipPath, deps, {
error: () => undefined,
});
assert.equal(imported, true);
assert.equal(
scripts.some((script) => script.includes('importDictionaryArchiveBase64')),
true,
);
assert.equal(
scripts.some((script) => script.includes('importDictionaryArchiveUrl(')),
false,
);
assert.equal(
scripts.some((script) => script.includes('emlwLWJ5dGVz')),
true,
);
});
test('importYomitanDictionaryFromZip returns false when served archive cannot be read', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-yomitan-import-'));
const zipPath = path.join(tempDir, 'dict.zip');
fs.writeFileSync(zipPath, Buffer.from('zip-bytes'));
const settingsWindow = {
isDestroyed: () => false,
destroy: () => undefined,
webContents: {
executeJavaScript: async (script: string) => {
const urlMatch = script.match(/importDictionaryArchiveUrl\(\s*"([^"]+)"/);
if (!urlMatch) return true;
fs.unlinkSync(zipPath);
const response = await fetch(JSON.parse(`"${urlMatch[1]}"`) as string);
return response.ok;
},
},
};
const deps = createDeps(async () => true, {
createYomitanExtensionWindow: async (pageName: string) => {
assert.equal(pageName, 'settings.html');
return settingsWindow;
},
});
const imported = await importYomitanDictionaryFromZip(zipPath, deps, {
error: () => undefined,
});
assert.equal(imported, false);
});
test('deleteYomitanDictionaryByTitle uses settings automation bridge instead of custom backend action', async () => {
const scripts: string[] = [];
const settingsWindow = {
@@ -1,5 +1,6 @@
import type { BrowserWindow, Extension, Session } from 'electron';
import * as fs from 'fs';
import * as http from 'http';
import * as path from 'path';
import { selectYomitanParseTokens } from './parser-selection-stage';
@@ -705,6 +706,70 @@ async function invokeYomitanSettingsAutomation<T>(
}
}
async function serveDictionaryZipOnce<T>(
zipPath: string,
callback: (url: string) => Promise<T>,
): Promise<T> {
const fileName = path.basename(zipPath);
const token = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
const requestPath = `/${token}/${encodeURIComponent(fileName)}`;
let served = false;
const server = http.createServer((request, response) => {
if (request.method === 'OPTIONS') {
response.writeHead(204, {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, OPTIONS',
});
response.end();
return;
}
if (request.method !== 'GET' || request.url !== requestPath || served) {
response.writeHead(404, { 'access-control-allow-origin': '*' });
response.end();
return;
}
served = true;
let size = 0;
try {
size = fs.statSync(zipPath).size;
} catch {
response.writeHead(500, { 'access-control-allow-origin': '*' });
response.end();
return;
}
response.writeHead(200, {
'access-control-allow-origin': '*',
'content-length': String(size),
'content-type': 'application/zip',
});
const stream = fs.createReadStream(zipPath);
stream.on('error', () => {
if (!response.headersSent) {
response.writeHead(500, { 'access-control-allow-origin': '*' });
response.end();
return;
}
response.destroy();
});
stream.pipe(response);
});
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => resolve());
});
try {
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error('Dictionary import server did not bind to a TCP port.');
}
return await callback(`http://127.0.0.1:${address.port}${requestPath}`);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}
const YOMITAN_SCANNING_HELPERS = String.raw`
const HIRAGANA_CONVERSION_RANGE = [0x3041, 0x3096];
const KATAKANA_CONVERSION_RANGE = [0x30a1, 0x30f6];
@@ -1041,11 +1106,85 @@ const YOMITAN_SCANNING_HELPERS = String.raw`
}
return getDictionaryEntryNames(entry).some((name) => name.startsWith("SubMiner Character Dictionary"));
}
const exactPrimaryMatches = collectExactHeadwordMatches(dictionaryEntries, token, true);
function parseSubMinerMediaIdFromString(value) {
const imageMatch = value.match(/\bimg\/m(\d+)-/i);
if (imageMatch) {
const parsed = Number.parseInt(imageMatch[1], 10);
if (Number.isSafeInteger(parsed) && parsed > 0) { return parsed; }
}
const titleMatch = value.match(/SubMiner Character Dictionary[^\d]*(?:AniList\s*)?(\d+)/i);
if (titleMatch) {
const parsed = Number.parseInt(titleMatch[1], 10);
if (Number.isSafeInteger(parsed) && parsed > 0) { return parsed; }
}
return null;
}
function parseSubMinerMediaIdCandidate(value) {
if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) {
return value;
}
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
const parsed = Number.parseInt(value.trim(), 10);
if (Number.isSafeInteger(parsed) && parsed > 0) { return parsed; }
}
return null;
}
function collectSubMinerMediaIds(value, target) {
if (typeof value === 'string') {
const parsed = parseSubMinerMediaIdFromString(value);
if (parsed !== null) { target.add(parsed); }
return;
}
if (!value || typeof value !== 'object') {
return;
}
if (Array.isArray(value)) {
for (const item of value) { collectSubMinerMediaIds(item, target); }
return;
}
const mediaIdCandidates = [
value.subminerMediaId,
value.subMinerMediaId,
value.characterDictionaryMediaId,
value.data?.subminerMediaId,
value.data?.subMinerMediaId,
value.data?.characterDictionaryMediaId
];
for (const candidate of mediaIdCandidates) {
const parsed = parseSubMinerMediaIdCandidate(candidate);
if (parsed !== null) { target.add(parsed); }
}
for (const child of Object.values(value)) {
collectSubMinerMediaIds(child, target);
}
}
function getSubMinerMediaIds(entry) {
const mediaIds = new Set();
collectSubMinerMediaIds(entry, mediaIds);
return mediaIds;
}
function isCurrentMediaNameDictionaryEntry(entry) {
if (!isNameDictionaryEntry(entry)) {
return false;
}
if (currentCharacterDictionaryMediaId === null) {
return true;
}
const mediaIds = getSubMinerMediaIds(entry);
return mediaIds.size === 0 || mediaIds.has(currentCharacterDictionaryMediaId);
}
const currentMediaDictionaryEntries =
currentCharacterDictionaryMediaId === null
? (dictionaryEntries || [])
: (dictionaryEntries || []).filter((entry) => {
if (!isNameDictionaryEntry(entry)) { return true; }
return isCurrentMediaNameDictionaryEntry(entry);
});
const exactPrimaryMatches = collectExactHeadwordMatches(currentMediaDictionaryEntries, token, true);
let matchedNameDictionary = false;
if (includeNameMatchMetadata) {
for (const dictionaryEntry of dictionaryEntries || []) {
if (!isNameDictionaryEntry(dictionaryEntry)) { continue; }
for (const dictionaryEntry of currentMediaDictionaryEntries || []) {
if (!isCurrentMediaNameDictionaryEntry(dictionaryEntry)) { continue; }
for (const match of exactPrimaryMatches) {
if (match.dictionaryEntry !== dictionaryEntry) { continue; }
matchedNameDictionary = true;
@@ -1056,13 +1195,14 @@ const YOMITAN_SCANNING_HELPERS = String.raw`
}
const preferredMatch = exactPrimaryMatches[0];
if (preferredMatch) {
const exactFrequencyMatches = collectExactHeadwordMatches(dictionaryEntries, token, false)
const exactFrequencyMatches = collectExactHeadwordMatches(currentMediaDictionaryEntries, token, false)
.filter((match) => sameHeadword(match, preferredMatch));
return {
term: preferredMatch.headword.term,
reading: preferredMatch.headword.reading,
wordClasses: normalizeWordClasses(preferredMatch.headword),
isNameMatch: matchedNameDictionary || isNameDictionaryEntry(preferredMatch.dictionaryEntry),
isNameMatch:
matchedNameDictionary || isCurrentMediaNameDictionaryEntry(preferredMatch.dictionaryEntry),
frequencyRank: getBestFrequencyRankForMatches(
exactFrequencyMatches.length > 0 ? exactFrequencyMatches : exactPrimaryMatches,
dictionaryPriorityByName,
@@ -1079,6 +1219,7 @@ function buildYomitanScanningScript(
profileIndex: number,
scanLength: number,
includeNameMatchMetadata: boolean,
currentCharacterDictionaryMediaId: number | null,
dictionaryPriorityByName: Record<string, number>,
dictionaryFrequencyModeByName: Partial<Record<string, YomitanFrequencyMode>>,
): string {
@@ -1104,6 +1245,11 @@ function buildYomitanScanningScript(
});
${YOMITAN_SCANNING_HELPERS}
const includeNameMatchMetadata = ${includeNameMatchMetadata ? 'true' : 'false'};
const currentCharacterDictionaryMediaId = ${
currentCharacterDictionaryMediaId !== null
? String(currentCharacterDictionaryMediaId)
: 'null'
};
const dictionaryPriorityByName = ${JSON.stringify(dictionaryPriorityByName)};
const dictionaryFrequencyModeByName = ${JSON.stringify(dictionaryFrequencyModeByName)};
const text = ${JSON.stringify(text)};
@@ -1255,6 +1401,7 @@ export async function requestYomitanScanTokens(
logger: LoggerLike,
options?: {
includeNameMatchMetadata?: boolean;
currentCharacterDictionaryMediaId?: number | null;
},
): Promise<YomitanScanToken[] | null> {
const yomitanExt = deps.getYomitanExt();
@@ -1290,6 +1437,11 @@ export async function requestYomitanScanTokens(
profileIndex,
scanLength,
options?.includeNameMatchMetadata === true,
typeof options?.currentCharacterDictionaryMediaId === 'number' &&
Number.isFinite(options.currentCharacterDictionaryMediaId) &&
options.currentCharacterDictionaryMediaId > 0
? Math.floor(options.currentCharacterDictionaryMediaId)
: null,
metadata?.dictionaryPriorityByName ?? {},
metadata?.dictionaryFrequencyModeByName ?? {},
),
@@ -1863,17 +2015,43 @@ export async function importYomitanDictionaryFromZip(
return false;
}
const archiveBase64 = fs.readFileSync(normalizedZipPath).toString('base64');
const script = `
(async () => {
await globalThis.__subminerYomitanSettingsAutomation.importDictionaryArchiveBase64(
${JSON.stringify(archiveBase64)},
${JSON.stringify(path.basename(normalizedZipPath))}
);
return true;
})();
`;
const result = await invokeYomitanSettingsAutomation<boolean>(script, deps, logger);
const supportsUrlImport = await invokeYomitanSettingsAutomation<boolean>(
`
(() => typeof globalThis.__subminerYomitanSettingsAutomation.importDictionaryArchiveUrl === "function")();
`,
deps,
logger,
);
const result =
supportsUrlImport === true
? await serveDictionaryZipOnce(normalizedZipPath, async (archiveUrl) =>
invokeYomitanSettingsAutomation<boolean>(
`
(async () => {
await globalThis.__subminerYomitanSettingsAutomation.importDictionaryArchiveUrl(
${JSON.stringify(archiveUrl)}
);
return true;
})();
`,
deps,
logger,
),
)
: await invokeYomitanSettingsAutomation<boolean>(
`
(async () => {
await globalThis.__subminerYomitanSettingsAutomation.importDictionaryArchiveBase64(
${JSON.stringify(fs.readFileSync(normalizedZipPath).toString('base64'))},
${JSON.stringify(path.basename(normalizedZipPath))}
);
return true;
})();
`,
deps,
logger,
);
return result === true;
}
+24 -12
View File
@@ -106,20 +106,32 @@ test('yomitan settings URL disables the embedded popup preview', () => {
test('showYomitanSettingsWindow restores, repaints, shows, and focuses an existing window', () => {
const calls: string[] = [];
showYomitanSettingsWindow({
isDestroyed: () => false,
isMinimized: () => true,
restore: () => calls.push('restore'),
getSize: () => [1200, 800],
setSize: (width: number, height: number) => calls.push(`set-size:${width}x${height}`),
webContents: {
invalidate: () => calls.push('invalidate'),
showYomitanSettingsWindow(
{
isDestroyed: () => false,
isMinimized: () => true,
restore: () => calls.push('restore'),
getSize: () => [1200, 800],
setSize: (width: number, height: number) => calls.push(`set-size:${width}x${height}`),
webContents: {
invalidate: () => calls.push('invalidate'),
},
show: () => calls.push('show'),
focus: () => calls.push('focus'),
} as never,
{
promoteSettingsWindowAboveOverlay: () => calls.push('promote'),
},
show: () => calls.push('show'),
focus: () => calls.push('focus'),
} as never);
);
assert.deepEqual(calls, ['restore', 'set-size:1200x800', 'invalidate', 'show', 'focus']);
assert.deepEqual(calls, [
'restore',
'set-size:1200x800',
'invalidate',
'show',
'focus',
'promote',
]);
});
test('destroyYomitanSettingsWindow destroys a live settings window before app quit', () => {
+9 -1
View File
@@ -1,6 +1,7 @@
import electron from 'electron';
import type { BrowserWindow, Extension, Menu, MenuItemConstructorOptions, Session } from 'electron';
import { createLogger } from '../../logger';
import { promoteSettingsWindowAboveOverlay } from './settings-window-z-order';
const { BrowserWindow: ElectronBrowserWindow, Menu: ElectronMenu, session } = electron;
const logger = createLogger('main:yomitan-settings');
@@ -136,7 +137,12 @@ export function buildYomitanSettingsUrl(extensionId: string): string {
return `chrome-extension://${extensionId}/settings.html?popup-preview=false`;
}
export function showYomitanSettingsWindow(settingsWindow: BrowserWindow): void {
export function showYomitanSettingsWindow(
settingsWindow: BrowserWindow,
options: {
promoteSettingsWindowAboveOverlay?: (settingsWindow: BrowserWindow) => void;
} = {},
): void {
if (settingsWindow.isDestroyed()) {
return;
}
@@ -148,6 +154,7 @@ export function showYomitanSettingsWindow(settingsWindow: BrowserWindow): void {
settingsWindow.webContents.invalidate();
settingsWindow.show();
settingsWindow.focus();
(options.promoteSettingsWindowAboveOverlay ?? promoteSettingsWindowAboveOverlay)(settingsWindow);
}
export function destroyYomitanSettingsWindow(settingsWindow: BrowserWindow | null): boolean {
@@ -177,6 +184,7 @@ export function openYomitanSettingsWindow(options: OpenYomitanSettingsWindowOpti
logger.info('Creating new settings window for extension:', options.yomitanExt.id);
const settingsWindow = new ElectronBrowserWindow({
title: 'Yomitan Settings',
width: 1200,
height: 800,
show: false,
+2 -2
View File
@@ -66,7 +66,7 @@ test('normalizes fallback shortcuts when AnkiConnect flag is unset', () => {
shortcuts: {
mineSentence: 'KeyQ',
openRuntimeOptions: 'Digit9',
openCharacterDictionary: 'Ctrl+Shift+KeyA',
openCharacterDictionaryManager: 'Ctrl+KeyD',
},
};
@@ -74,7 +74,7 @@ test('normalizes fallback shortcuts when AnkiConnect flag is unset', () => {
assert.equal(resolved.mineSentence, 'Q');
assert.equal(resolved.openRuntimeOptions, '9');
assert.equal(resolved.openCharacterDictionary, 'Ctrl+Shift+A');
assert.equal(resolved.openCharacterDictionaryManager, 'Ctrl+D');
});
test('preserves null shortcut overrides so defaults can be disabled', () => {
+4 -2
View File
@@ -12,7 +12,7 @@ export interface ConfiguredShortcuts {
multiCopyTimeoutMs: number;
toggleSecondarySub: string | null | undefined;
markAudioCard: string | null | undefined;
openCharacterDictionary: string | null | undefined;
openCharacterDictionaryManager: string | null | undefined;
openRuntimeOptions: string | null | undefined;
openJimaku: string | null | undefined;
openSessionHelp: string | null | undefined;
@@ -58,7 +58,9 @@ export function resolveConfiguredShortcuts(
config.shortcuts?.multiCopyTimeoutMs ?? defaultConfig.shortcuts?.multiCopyTimeoutMs ?? 5000,
toggleSecondarySub: normalizeShortcut(shortcutValue('toggleSecondarySub')),
markAudioCard: normalizeShortcut(isAnkiConnectDisabled ? null : shortcutValue('markAudioCard')),
openCharacterDictionary: normalizeShortcut(shortcutValue('openCharacterDictionary')),
openCharacterDictionaryManager: normalizeShortcut(
shortcutValue('openCharacterDictionaryManager'),
),
openRuntimeOptions: normalizeShortcut(shortcutValue('openRuntimeOptions')),
openJimaku: normalizeShortcut(shortcutValue('openJimaku')),
openSessionHelp: normalizeShortcut(shortcutValue('openSessionHelp')),
+43
View File
@@ -0,0 +1,43 @@
import path from 'node:path';
import { loadRawConfigStrict } from './config/load';
import { resolveConfig } from './config/resolve';
import type { MpvLaunchMode, ResolvedConfig } from './types/config';
import type { SubminerPluginRuntimeScriptOptConfig } from './shared/subminer-plugin-script-opts';
export interface ConfiguredWindowsMpvLaunch {
executablePath: string;
launchMode: MpvLaunchMode;
pluginRuntimeConfig: SubminerPluginRuntimeScriptOptConfig;
}
export function buildWindowsMpvPluginRuntimeConfig(
config: Pick<ResolvedConfig, 'auto_start_overlay' | 'mpv' | 'texthooker'>,
): SubminerPluginRuntimeScriptOptConfig {
return {
socketPath: config.mpv.socketPath,
binaryPath: config.mpv.subminerBinaryPath,
backend: config.mpv.backend,
autoStart: config.mpv.autoStartSubMiner,
autoStartVisibleOverlay: config.auto_start_overlay,
autoStartPauseUntilReady: config.mpv.pauseUntilOverlayReady,
texthookerEnabled: config.texthooker.launchAtStartup,
aniskipEnabled: config.mpv.aniskipEnabled,
aniskipButtonKey: config.mpv.aniskipButtonKey,
};
}
export function readConfiguredWindowsMpvLaunch(configDir: string): ConfiguredWindowsMpvLaunch {
const loadResult = loadRawConfigStrict({
configDir,
configFileJsonc: path.join(configDir, 'config.jsonc'),
configFileJson: path.join(configDir, 'config.json'),
});
const rawConfig = loadResult.ok ? loadResult.config : {};
const { resolved } = resolveConfig(rawConfig);
return {
executablePath: resolved.mpv.executablePath,
launchMode: resolved.mpv.launchMode,
pluginRuntimeConfig: buildWindowsMpvPluginRuntimeConfig(resolved),
};
}
+106 -2
View File
@@ -1,5 +1,10 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { DEFAULT_CONFIG } from './config/definitions';
import { readConfiguredWindowsMpvLaunch } from './main-entry-launch-config';
import {
configureEarlyAppPaths,
normalizeLaunchMpvExtraArgs,
@@ -146,7 +151,7 @@ test('applyEarlyLinuxCommandLineSwitches appends password store before main star
]);
});
test('transported AppImage visibility commands should forward through app control', () => {
test('transported AppImage visibility commands forward through app control', () => {
assert.equal(
shouldForwardStartupArgvViaAppControl(['SubMiner.AppImage', '--hide-visible-overlay'], {
SUBMINER_APP_ARGC: '1',
@@ -156,9 +161,35 @@ test('transported AppImage visibility commands should forward through app contro
);
});
test('app control forwarding is only for transported runtime commands', () => {
test('direct runtime commands forward through app control', () => {
assert.equal(
shouldForwardStartupArgvViaAppControl(['SubMiner.AppImage', '--hide-visible-overlay'], {}),
true,
);
assert.equal(
shouldForwardStartupArgvViaAppControl(
['SubMiner.exe', '--start', '--socket', '\\\\.\\pipe\\subminer-socket'],
{},
),
true,
);
assert.equal(shouldForwardStartupArgvViaAppControl(['SubMiner.exe', '--settings'], {}), true);
assert.equal(shouldForwardStartupArgvViaAppControl(['SubMiner.exe', '--stop'], {}), true);
});
test('entry-only and internal commands do not forward through app control', () => {
assert.equal(shouldForwardStartupArgvViaAppControl(['SubMiner.exe'], {}), false);
assert.equal(shouldForwardStartupArgvViaAppControl(['SubMiner.exe', '--help'], {}), false);
assert.equal(
shouldForwardStartupArgvViaAppControl(['SubMiner.exe', '--generate-config'], {}),
false,
);
assert.equal(
shouldForwardStartupArgvViaAppControl(['SubMiner.exe', '--stats-daemon-start'], {}),
false,
);
assert.equal(
shouldForwardStartupArgvViaAppControl(['SubMiner.exe', '--stats', '--stats-background'], {}),
false,
);
assert.equal(
@@ -175,6 +206,12 @@ test('app control forwarding is only for transported runtime commands', () => {
}),
false,
);
assert.equal(
shouldForwardStartupArgvViaAppControl(['SubMiner.exe', '--start'], {
ELECTRON_RUN_AS_NODE: '1',
}),
false,
);
});
test('shouldHandleHelpOnlyAtEntry detects help-only invocation', () => {
@@ -269,6 +306,73 @@ test('launch-mpv entry helpers detect and normalize targets', () => {
);
});
test('readConfiguredWindowsMpvLaunch includes defaults for runtime plugin script opts', () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-entry-config-'));
try {
const launch = readConfiguredWindowsMpvLaunch(tempDir);
assert.equal(launch.executablePath, DEFAULT_CONFIG.mpv.executablePath);
assert.equal(launch.launchMode, DEFAULT_CONFIG.mpv.launchMode);
assert.deepEqual(launch.pluginRuntimeConfig, {
socketPath: DEFAULT_CONFIG.mpv.socketPath,
binaryPath: DEFAULT_CONFIG.mpv.subminerBinaryPath,
backend: DEFAULT_CONFIG.mpv.backend,
autoStart: DEFAULT_CONFIG.mpv.autoStartSubMiner,
autoStartVisibleOverlay: DEFAULT_CONFIG.auto_start_overlay,
autoStartPauseUntilReady: DEFAULT_CONFIG.mpv.pauseUntilOverlayReady,
texthookerEnabled: DEFAULT_CONFIG.texthooker.launchAtStartup,
aniskipEnabled: DEFAULT_CONFIG.mpv.aniskipEnabled,
aniskipButtonKey: DEFAULT_CONFIG.mpv.aniskipButtonKey,
});
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
test('readConfiguredWindowsMpvLaunch preserves configured runtime plugin script opts', () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-entry-config-'));
try {
fs.writeFileSync(
path.join(tempDir, 'config.jsonc'),
JSON.stringify({
auto_start_overlay: false,
texthooker: {
launchAtStartup: true,
},
mpv: {
executablePath: ' C:\\tools\\mpv.exe ',
launchMode: 'maximized',
socketPath: '\\\\.\\pipe\\custom-subminer-socket',
backend: 'windows',
autoStartSubMiner: false,
pauseUntilOverlayReady: false,
subminerBinaryPath: 'C:\\SubMiner\\Custom.exe',
aniskipEnabled: false,
aniskipButtonKey: 'F8',
},
}),
);
const launch = readConfiguredWindowsMpvLaunch(tempDir);
assert.equal(launch.executablePath, 'C:\\tools\\mpv.exe');
assert.equal(launch.launchMode, 'maximized');
assert.deepEqual(launch.pluginRuntimeConfig, {
socketPath: '\\\\.\\pipe\\custom-subminer-socket',
binaryPath: 'C:\\SubMiner\\Custom.exe',
backend: 'windows',
autoStart: false,
autoStartVisibleOverlay: false,
autoStartPauseUntilReady: false,
texthookerEnabled: true,
aniskipEnabled: false,
aniskipButtonKey: 'F8',
});
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
test('stats-daemon entry helper detects internal daemon commands', () => {
assert.equal(
shouldHandleStatsDaemonCommandAtEntry(['SubMiner.AppImage', '--stats-daemon-start'], {}),
+1 -2
View File
@@ -154,10 +154,9 @@ export function shouldForwardStartupArgvViaAppControl(
env: NodeJS.ProcessEnv,
): boolean {
if (env.ELECTRON_RUN_AS_NODE === '1') return false;
if (!hasTransportedStartupArgs(env)) return false;
const args = parseCliArgs(argv);
if (args.help || args.appPing || args.launchMpv) return false;
if (args.help || args.appPing || args.launchMpv || args.generateConfig) return false;
if (resolveStatsDaemonCommandAction(argv) !== null) return false;
return hasExplicitCommand(args);
+45 -65
View File
@@ -1,9 +1,7 @@
import path from 'node:path';
import os from 'node:os';
import { spawn } from 'node:child_process';
import { app, dialog, shell } from 'electron';
import { printHelp } from './cli/help';
import { loadRawConfigStrict } from './config/load';
import {
configureEarlyAppPaths,
normalizeLaunchMpvExtraArgs,
@@ -22,6 +20,7 @@ import {
shouldHandleStatsDaemonCommandAtEntry,
} from './main-entry-runtime';
import { requestSingleInstanceLockEarly } from './main/early-single-instance';
import { readConfiguredWindowsMpvLaunch } from './main-entry-launch-config';
import { sendAppControlCommand } from './shared/app-control-client';
import {
detectInstalledFirstRunPluginCandidates,
@@ -30,7 +29,6 @@ import {
resolvePackagedRuntimePluginPath,
} from './main/runtime/first-run-setup-plugin';
import { createWindowsMpvLaunchDeps, launchWindowsMpv } from './main/runtime/windows-mpv-launch';
import { parseMpvLaunchMode } from './shared/mpv-launch-mode';
import { runStatsDaemonControlFromProcess } from './stats-daemon-entry';
import { createFatalErrorReporter, registerFatalErrorHandlers } from './main/fatal-error';
@@ -150,31 +148,6 @@ function createWindowsRuntimePluginPolicy() {
};
}
function readConfiguredWindowsMpvLaunch(configDir: string): {
executablePath: string;
launchMode: 'normal' | 'maximized' | 'fullscreen';
} {
const loadResult = loadRawConfigStrict({
configDir,
configFileJsonc: path.join(configDir, 'config.jsonc'),
configFileJson: path.join(configDir, 'config.json'),
});
if (!loadResult.ok) {
return {
executablePath: '',
launchMode: 'normal',
};
}
return {
executablePath:
typeof loadResult.config.mpv?.executablePath === 'string'
? loadResult.config.mpv.executablePath.trim()
: '',
launchMode: parseMpvLaunchMode(loadResult.config.mpv?.launchMode) ?? 'normal',
};
}
process.argv = normalizeStartupArgv(process.argv, process.env);
applyEarlyLinuxCommandLineSwitches(app.commandLine, process.argv);
applySanitizedEnv(sanitizeStartupEnv(process.env));
@@ -226,31 +199,22 @@ async function forwardStartupArgvViaAppControlIfAvailable(): Promise<boolean> {
return false;
}
if (shouldDetachBackgroundLaunch(process.argv, process.env)) {
const childArgs = hasTransportedStartupArgs(process.env) ? [] : process.argv.slice(1);
const child = spawn(process.execPath, childArgs, {
detached: true,
stdio: 'ignore',
env: sanitizeBackgroundEnv(process.env),
});
child.unref();
process.exit(0);
}
if (shouldHandleHelpOnlyAtEntry(process.argv, process.env)) {
const sanitizedEnv = sanitizeHelpEnv(process.env);
process.env.NODE_NO_WARNINGS = sanitizedEnv.NODE_NO_WARNINGS;
if (!sanitizedEnv.VK_INSTANCE_LAYERS) {
delete process.env.VK_INSTANCE_LAYERS;
async function runEntryProcess(): Promise<void> {
if (shouldHandleHelpOnlyAtEntry(process.argv, process.env)) {
const sanitizedEnv = sanitizeHelpEnv(process.env);
process.env.NODE_NO_WARNINGS = sanitizedEnv.NODE_NO_WARNINGS;
if (!sanitizedEnv.VK_INSTANCE_LAYERS) {
delete process.env.VK_INSTANCE_LAYERS;
}
printHelp(DEFAULT_TEXTHOOKER_PORT);
process.exit(0);
return;
}
printHelp(DEFAULT_TEXTHOOKER_PORT);
process.exit(0);
}
if (shouldHandleLaunchMpvAtEntry(process.argv, process.env)) {
const sanitizedEnv = sanitizeLaunchMpvEnv(process.env);
applySanitizedEnv(sanitizedEnv);
void app.whenReady().then(async () => {
if (shouldHandleLaunchMpvAtEntry(process.argv, process.env)) {
const sanitizedEnv = sanitizeLaunchMpvEnv(process.env);
applySanitizedEnv(sanitizedEnv);
await app.whenReady();
const configuredMpvLaunch = readConfiguredWindowsMpvLaunch(userDataPath);
const result = await launchWindowsMpv(
normalizeLaunchMpvTargets(process.argv),
@@ -266,23 +230,39 @@ if (shouldHandleLaunchMpvAtEntry(process.argv, process.env)) {
configuredMpvLaunch.executablePath,
configuredMpvLaunch.launchMode,
createWindowsRuntimePluginPolicy(),
configuredMpvLaunch.pluginRuntimeConfig,
);
app.exit(result.ok ? 0 : 1);
});
} else if (shouldHandleStatsDaemonCommandAtEntry(process.argv, process.env)) {
void app.whenReady().then(async () => {
return;
}
if (shouldHandleStatsDaemonCommandAtEntry(process.argv, process.env)) {
await app.whenReady();
const exitCode = await runStatsDaemonControlFromProcess(app.getPath('userData'));
app.exit(exitCode);
});
} else {
void forwardStartupArgvViaAppControlIfAvailable()
.then((forwarded) => {
if (!forwarded) {
startMainProcess();
}
})
.catch((error) => {
console.error('SubMiner app-control handoff failed:', error);
startMainProcess();
return;
}
if (await forwardStartupArgvViaAppControlIfAvailable()) {
return;
}
if (shouldDetachBackgroundLaunch(process.argv, process.env)) {
const childArgs = hasTransportedStartupArgs(process.env) ? [] : process.argv.slice(1);
const child = spawn(process.execPath, childArgs, {
detached: true,
stdio: 'ignore',
env: sanitizeBackgroundEnv(process.env),
});
child.unref();
process.exit(0);
return;
}
startMainProcess();
}
void runEntryProcess().catch((error) => {
console.error('SubMiner app-control handoff failed:', error);
startMainProcess();
});
+236 -57
View File
@@ -332,6 +332,7 @@ import {
mineSentenceCard as mineSentenceCardCore,
openYomitanSettingsWindow,
playNextSubtitleRuntime,
promoteSettingsWindowAboveOverlay,
registerGlobalShortcuts as registerGlobalShortcutsCore,
replayCurrentSubtitleRuntime,
resolveJellyfinPlaybackPlanRuntime,
@@ -347,6 +348,7 @@ import {
syncOverlayWindowLayer,
setVisibleOverlayVisible as setVisibleOverlayVisibleCore,
showMpvOsdRuntime,
startOverlayWindowTracker as startOverlayWindowTrackerCore,
tokenizeSubtitle as tokenizeSubtitleCore,
triggerFieldGrouping as triggerFieldGroupingCore,
upsertYomitanDictionarySettings,
@@ -498,7 +500,10 @@ import { openRuntimeOptionsModal as openRuntimeOptionsModalRuntime } from './mai
import { openJimakuModal as openJimakuModalRuntime } from './main/runtime/jimaku-open';
import { openSubsyncManualModal as openSubsyncManualModalRuntime } from './main/runtime/subsync-open';
import { openSessionHelpModal as openSessionHelpModalRuntime } from './main/runtime/session-help-open';
import { openCharacterDictionaryModal as openCharacterDictionaryModalRuntime } from './main/runtime/character-dictionary-open';
import {
openCharacterDictionaryManagerModal as openCharacterDictionaryManagerModalRuntime,
openCharacterDictionaryModal as openCharacterDictionaryModalRuntime,
} from './main/runtime/character-dictionary-open';
import { openControllerSelectModal as openControllerSelectModalRuntime } from './main/runtime/controller-select-open';
import { openControllerDebugModal as openControllerDebugModalRuntime } from './main/runtime/controller-debug-open';
import { createPlaylistBrowserIpcRuntime } from './main/runtime/playlist-browser-ipc';
@@ -517,7 +522,14 @@ import { createOverlayVisibilityRuntimeService } from './main/overlay-visibility
import { createStatsOverlayVisibilityChangeHandler } from './main/runtime/stats-overlay-visibility';
import { createDiscordPresenceRuntime } from './main/runtime/discord-presence-runtime';
import { createCharacterDictionaryRuntimeService } from './main/character-dictionary-runtime';
import { createCharacterDictionaryAutoSyncRuntimeService } from './main/runtime/character-dictionary-auto-sync';
import { createCharacterDictionaryImageLookup } from './main/character-dictionary-runtime/image-lookup';
import {
createCharacterDictionaryAutoSyncRuntimeService,
getCharacterDictionaryManagerSnapshot,
moveCharacterDictionaryManagedEntry,
removeCharacterDictionaryManagedEntry,
replaceCharacterDictionaryManagedEntry,
} from './main/runtime/character-dictionary-auto-sync';
import { handleCharacterDictionaryAutoSyncComplete } from './main/runtime/character-dictionary-auto-sync-completion';
import { notifyCharacterDictionaryAutoSyncStatus } from './main/runtime/character-dictionary-auto-sync-notifications';
import { createCurrentMediaTokenizationGate } from './main/runtime/current-media-tokenization-gate';
@@ -563,6 +575,7 @@ import {
createCreateJellyfinSetupWindowHandler,
} from './main/runtime/setup-window-factory';
import { createConfigSettingsRuntime } from './main/runtime/config-settings-runtime';
import { shouldSuppressVisibleOverlayRaiseForSeparateWindow } from './main/runtime/settings-window-z-order';
import {
isSameYoutubeMediaPath,
isYoutubeMediaPath,
@@ -834,7 +847,15 @@ const bootServices = createMainBootServices({
createSubtitleWebSocket: (payloadMode) => new SubtitleWebSocket(payloadMode),
createLogger,
createMainRuntimeRegistry,
createOverlayManager,
createOverlayManager: () =>
createOverlayManager({
shouldPromoteWindowOnBoundsUpdate: (window) =>
!shouldSuppressVisibleOverlayRaiseForSeparateWindow({
window,
mainWindow: overlayManager.getMainWindow(),
separateWindows: [appState.configSettingsWindow, appState.yomitanSettingsWindow],
}),
}),
createOverlayModalInputState,
createOverlayContentMeasurementStore: ({ logger }) => {
const buildHandler = createBuildOverlayContentMeasurementStoreMainDepsHandler({
@@ -1895,6 +1916,9 @@ const overlayShortcutsRuntime = createOverlayShortcutsRuntimeService(
openCharacterDictionary: () => {
openCharacterDictionaryOverlay();
},
openCharacterDictionaryManager: () => {
openCharacterDictionaryManagerOverlay();
},
openJimaku: () => {
openJimakuOverlay();
},
@@ -2032,6 +2056,8 @@ const configSettingsRuntime = createConfigSettingsRuntime({
preloadPath: path.join(__dirname, 'preload-settings.js'),
}),
settingsHtmlPath: path.join(__dirname, 'settings', 'index.html'),
promoteSettingsWindowAboveOverlay: (window) =>
promoteSettingsWindowAboveOverlay(window as BrowserWindow),
openPath: (targetPath) => shell.openPath(targetPath),
ipcMain,
ipcChannels: IPC_CHANNELS.request,
@@ -2177,6 +2203,7 @@ const characterDictionaryRuntime = createCharacterDictionaryRuntimeService({
getCurrentMediaTitle: () => appState.currentMediaTitle,
resolveMediaPathForJimaku: (mediaPath) => mediaRuntime.resolveMediaPathForJimaku(mediaPath),
guessAnilistMediaInfo: (mediaPath, mediaTitle) => guessAnilistMediaInfo(mediaPath, mediaTitle),
getNameMatchImagesEnabled: () => getResolvedConfig().subtitleStyle.nameMatchImagesEnabled,
getCollapsibleSectionOpenState: (section) =>
getResolvedConfig().anilist.characterDictionary.collapsibleSections[section],
now: () => Date.now(),
@@ -2297,6 +2324,11 @@ const characterDictionaryAutoSyncRuntime = createCharacterDictionaryAutoSyncRunt
},
});
const characterDictionaryImageLookup = createCharacterDictionaryImageLookup({
userDataPath: USER_DATA_PATH,
getCurrentMediaId: () => characterDictionaryAutoSyncRuntime.getCurrentMediaId(),
});
const overlayVisibilityRuntime = createOverlayVisibilityRuntimeService(
createBuildOverlayVisibilityRuntimeMainDepsHandler({
getMainWindow: () => overlayManager.getMainWindow(),
@@ -2460,6 +2492,7 @@ function resolveWindowsOverlayBindTargetHandle(targetMpvSocketPath?: string | nu
if (typeof trackedHandle === 'number' && Number.isFinite(trackedHandle)) {
return trackedHandle;
}
return null;
}
return findWindowsMpvTargetWindowHandle();
} catch {
@@ -2467,6 +2500,104 @@ function resolveWindowsOverlayBindTargetHandle(targetMpvSocketPath?: string | nu
}
}
function createOverlayWindowTracker(override?: string | null, targetMpvSocketPath?: string | null) {
if (appState.initialArgs && isHeadlessInitialCommand(appState.initialArgs)) {
return null;
}
return createWindowTrackerCore(override, targetMpvSocketPath);
}
function bindVisibleOverlayOwner(): void {
const mainWindow = overlayManager.getMainWindow();
if (process.platform !== 'win32' || !mainWindow || mainWindow.isDestroyed()) return;
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
const targetSocketPath = appState.mpvSocketPath;
const targetWindowHwnd = resolveWindowsOverlayBindTargetHandle(targetSocketPath);
if (targetWindowHwnd !== null && bindWindowsOverlayAboveMpv(overlayHwnd, targetWindowHwnd)) {
return;
}
if (targetSocketPath) {
return;
}
const tracker = appState.windowTracker;
const mpvResult = tracker
? (() => {
try {
const win32 =
require('./window-trackers/win32') as typeof import('./window-trackers/win32');
const poll = win32.findMpvWindows();
const focused = poll.matches.find((m) => m.isForeground);
return focused ?? [...poll.matches].sort((a, b) => b.area - a.area)[0] ?? null;
} catch {
return null;
}
})()
: null;
if (!mpvResult) return;
if (!setWindowsOverlayOwner(overlayHwnd, mpvResult.hwnd)) {
logger.warn('Failed to set overlay owner via koffi');
}
}
function releaseVisibleOverlayOwner(): void {
const mainWindow = overlayManager.getMainWindow();
if (process.platform !== 'win32' || !mainWindow || mainWindow.isDestroyed()) return;
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
if (!clearWindowsOverlayOwner(overlayHwnd)) {
logger.warn('Failed to clear overlay owner via koffi');
}
}
function startOverlayWindowTrackerForCurrentSocket(): void {
startOverlayWindowTrackerCore({
backendOverride: appState.backendOverride,
getMpvSocketPath: () => appState.mpvSocketPath,
createWindowTracker: createOverlayWindowTracker,
setWindowTracker: (tracker) => {
appState.windowTracker = tracker;
},
updateVisibleOverlayBounds: (geometry: WindowGeometry) => updateVisibleOverlayBounds(geometry),
isVisibleOverlayVisible: () => overlayManager.getVisibleOverlayVisible(),
updateVisibleOverlayVisibility: () => overlayVisibilityRuntime.updateVisibleOverlayVisibility(),
refreshCurrentSubtitle: () => {
subtitleProcessingController.refreshCurrentSubtitle(appState.currentSubText);
},
getOverlayWindows: () => getOverlayWindows(),
syncOverlayShortcuts: () => overlayShortcutsRuntime.syncOverlayShortcuts(),
bindOverlayOwner: () => bindVisibleOverlayOwner(),
releaseOverlayOwner: () => releaseVisibleOverlayOwner(),
});
}
function retargetOverlayWindowTrackerForMpvSocket(
nextSocketPath: string,
previousSocketPath: string,
): void {
if (nextSocketPath === previousSocketPath || !appState.overlayRuntimeInitialized) {
return;
}
const previousTracker = appState.windowTracker;
if (previousTracker) {
try {
previousTracker.stop();
} catch (error) {
logger.warn('Failed to stop previous overlay window tracker before retargeting', error);
}
}
releaseVisibleOverlayOwner();
appState.windowTracker = null;
appState.trackerNotReadyWarningShown = false;
lastOverlayWindowGeometry = null;
startOverlayWindowTrackerForCurrentSocket();
overlayVisibilityRuntime.updateVisibleOverlayVisibility();
overlayShortcutsRuntime.syncOverlayShortcuts();
logger.info(
`Retargeted overlay window tracker for MPV socket: ${previousSocketPath} -> ${nextSocketPath}`,
);
}
async function syncWindowsVisibleOverlayToMpvZOrder(): Promise<boolean> {
if (process.platform !== 'win32') {
return false;
@@ -2808,6 +2939,14 @@ function openCharacterDictionaryOverlay(): void {
);
}
function openCharacterDictionaryManagerOverlay(): void {
openOverlayHostedModalWithOsd(
openCharacterDictionaryManagerModalRuntime,
'Character dictionary manager unavailable.',
'Failed to open character dictionary manager.',
);
}
function openControllerSelectOverlay(): void {
openOverlayHostedModalWithOsd(
openControllerSelectModalRuntime,
@@ -4628,6 +4767,10 @@ const {
yomitanProfilePolicy.isCharacterDictionaryEnabled() &&
!isYoutubePlaybackActiveNow(),
getNameMatchEnabled: () => getResolvedConfig().subtitleStyle.nameMatchEnabled,
getNameMatchImagesEnabled: () => getResolvedConfig().subtitleStyle.nameMatchImagesEnabled,
getCharacterNameImage: (term) => characterDictionaryImageLookup.get(term),
getCurrentCharacterDictionaryMediaId: () =>
characterDictionaryAutoSyncRuntime.getCurrentMediaId(),
getFrequencyDictionaryEnabled: () =>
getRuntimeBooleanOption(
'subtitle.annotation.frequency',
@@ -4819,8 +4962,17 @@ const updateVisibleOverlayBounds = createUpdateVisibleOverlayBoundsHandler(
const buildEnsureOverlayWindowLevelMainDepsHandler =
createBuildEnsureOverlayWindowLevelMainDepsHandler({
shouldSuppressOverlayWindowLevel: (window) =>
appState.statsOverlayVisible && window === overlayManager.getMainWindow(),
shouldSuppressOverlayWindowLevel: (window) => {
const mainWindow = overlayManager.getMainWindow();
return (
(appState.statsOverlayVisible && window === mainWindow) ||
shouldSuppressVisibleOverlayRaiseForSeparateWindow({
window,
mainWindow,
separateWindows: [appState.configSettingsWindow, appState.yomitanSettingsWindow],
})
);
},
ensureOverlayWindowLevelCore: (window) => ensureOverlayWindowLevelCore(window as BrowserWindow),
afterEnsureOverlayWindowLevel: () => {
promoteStatsOverlayAbovePlayback();
@@ -5227,8 +5379,8 @@ function getUpdateService() {
readState: () => updateStateStore.readState(),
writeState: (state) => updateStateStore.writeState(state),
checkAppUpdate: (channel) => appUpdater.checkForUpdates(channel),
shouldFetchReleaseMetadata: ({ appUpdate }) =>
shouldFetchReleaseMetadataForPlatform(process.platform, appUpdate),
shouldFetchReleaseMetadata: ({ request, appUpdate }) =>
shouldFetchReleaseMetadataForPlatform(process.platform, appUpdate, request),
fetchLatestStableRelease: (channel) =>
fetchLatestStableRelease({ fetch: getFetchForUpdater(), channel }),
updateLauncher: (launcherPath, channel, release) =>
@@ -5247,7 +5399,9 @@ function getUpdateService() {
{ notificationType: getResolvedConfig().updates.notificationType, version },
{
showSystemNotification: (title, body) => showDesktopNotification(title, { body }),
showOsdNotification: (message) => showMpvOsd(message),
showOsdNotification: (message) => {
showMpvOsd(message);
},
log: (message) => logger.warn(message),
},
),
@@ -5604,6 +5758,7 @@ async function dispatchSessionAction(request: SessionActionDispatchRequest): Pro
openJimaku: () => openJimakuOverlay(),
openSessionHelp: () => openSessionHelpOverlay(),
openCharacterDictionary: () => openCharacterDictionaryOverlay(),
openCharacterDictionaryManager: () => openCharacterDictionaryManagerOverlay(),
openControllerSelect: () => openControllerSelectOverlay(),
openControllerDebug: () => openControllerDebugOverlay(),
openYoutubeTrackPicker: () => openYoutubeTrackPickerFromPlayback(),
@@ -5865,10 +6020,33 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
getAnilistQueueStatus: () => anilistStateRuntime.getQueueStatusSnapshot(),
retryAnilistQueueNow: () => processNextAnilistRetryUpdate(),
runAnilistPostWatchUpdateOnManualMark: () => maybeRunAnilistPostWatchUpdate({ force: true }),
getCharacterDictionarySelection: () =>
characterDictionaryRuntime.getManualSelectionSnapshot(),
setCharacterDictionarySelection: async (mediaId: number) =>
applyCharacterDictionarySelection(
getCharacterDictionarySelection: (searchTitle?: string) =>
characterDictionaryRuntime.getManualSelectionSnapshot(undefined, searchTitle),
setCharacterDictionarySelection: async (
mediaId: number,
replaceManagedMediaId?: number,
mediaTitle?: string,
) => {
if (replaceManagedMediaId !== undefined && mediaTitle) {
const result = replaceCharacterDictionaryManagedEntry(
USER_DATA_PATH,
replaceManagedMediaId,
{
mediaId,
mediaTitle,
},
);
if (result.ok && result.rebuildRequired) {
try {
await characterDictionaryAutoSyncRuntime.runSyncNow();
characterDictionaryImageLookup.invalidate();
} catch (error) {
logger.warn('Failed to rebuild character dictionary after manager override:', error);
}
}
return result;
}
return await applyCharacterDictionarySelection(
{ mediaId },
{
setManualSelection: (request) => characterDictionaryRuntime.setManualSelection(request),
@@ -5876,7 +6054,46 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
runSyncNow: () => characterDictionaryAutoSyncRuntime.runSyncNow(),
warn: (message, error) => logger.warn(message, error),
},
);
},
getCharacterDictionaryManagerSnapshot: async () =>
getCharacterDictionaryManagerSnapshot(
USER_DATA_PATH,
characterDictionaryAutoSyncRuntime.getCurrentMediaId(),
),
removeCharacterDictionaryManagedEntry: async (mediaId: number) => {
const result = removeCharacterDictionaryManagedEntry(
USER_DATA_PATH,
mediaId,
characterDictionaryAutoSyncRuntime.getCurrentMediaId(),
);
if (result.ok && result.rebuildRequired) {
try {
await characterDictionaryAutoSyncRuntime.runSyncNow();
characterDictionaryImageLookup.invalidate();
} catch (error) {
logger.warn('Failed to rebuild character dictionary after manager removal:', error);
}
}
return result;
},
moveCharacterDictionaryManagedEntry: async (mediaId: number, direction: 1 | -1) => {
const result = moveCharacterDictionaryManagedEntry(
USER_DATA_PATH,
mediaId,
direction,
characterDictionaryAutoSyncRuntime.getCurrentMediaId(),
);
if (result.ok && result.rebuildRequired) {
try {
await characterDictionaryAutoSyncRuntime.runSyncNow();
characterDictionaryImageLookup.invalidate();
} catch (error) {
logger.warn('Failed to rebuild character dictionary after manager reorder:', error);
}
}
return result;
},
appendClipboardVideoToQueue: () => appendClipboardVideoToQueue(),
...playlistBrowserMainDeps,
getImmersionTracker: () => appState.immersionTracker,
@@ -5925,6 +6142,8 @@ const { handleCliCommand, handleInitialArgs } = composeCliStartupHandlers({
cliCommandContextMainDeps: {
appState,
setLogLevel: (level) => setLogLevel(level, 'cli'),
onMpvSocketPathChanged: (nextSocketPath, previousSocketPath) =>
retargetOverlayWindowTrackerForMpvSocket(nextSocketPath, previousSocketPath),
texthookerService,
getResolvedConfig: () => getResolvedConfig(),
defaultWebsocketPort: DEFAULT_CONFIG.websocket.port,
@@ -6213,7 +6432,7 @@ const { ensureTray: ensureTrayHandler, destroyTray: destroyTrayHandler } =
handleCliCommand(parseArgs(['--texthooker', '--open-browser'])),
showTexthookerPage: () => shouldShowTexthookerTrayEntry(getResolvedConfig()),
showFirstRunSetup: () => !firstRunSetupService.isSetupCompleted(),
openFirstRunSetupWindow: () => openFirstRunSetupWindow(),
openFirstRunSetupWindow: (force?: boolean) => openFirstRunSetupWindow(force),
showWindowsMpvLauncherSetup: () => process.platform === 'win32',
openYomitanSettings: () => openYomitanSettings(),
openConfigSettingsWindow: () => openConfigSettingsWindow(),
@@ -6323,52 +6542,12 @@ const { initializeOverlayRuntime: initializeOverlayRuntimeHandler } =
}
registerGlobalShortcuts();
},
createWindowTracker: (override, targetMpvSocketPath) => {
if (appState.initialArgs && isHeadlessInitialCommand(appState.initialArgs)) {
return null;
}
return createWindowTrackerCore(override, targetMpvSocketPath);
},
createWindowTracker: (override, targetMpvSocketPath) =>
createOverlayWindowTracker(override, targetMpvSocketPath),
updateVisibleOverlayBounds: (geometry: WindowGeometry) =>
updateVisibleOverlayBounds(geometry),
bindOverlayOwner: () => {
const mainWindow = overlayManager.getMainWindow();
if (process.platform !== 'win32' || !mainWindow || mainWindow.isDestroyed()) return;
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
const targetWindowHwnd = resolveWindowsOverlayBindTargetHandle(appState.mpvSocketPath);
if (
targetWindowHwnd !== null &&
bindWindowsOverlayAboveMpv(overlayHwnd, targetWindowHwnd)
) {
return;
}
const tracker = appState.windowTracker;
const mpvResult = tracker
? (() => {
try {
const win32 =
require('./window-trackers/win32') as typeof import('./window-trackers/win32');
const poll = win32.findMpvWindows();
const focused = poll.matches.find((m) => m.isForeground);
return focused ?? [...poll.matches].sort((a, b) => b.area - a.area)[0] ?? null;
} catch {
return null;
}
})()
: null;
if (!mpvResult) return;
if (!setWindowsOverlayOwner(overlayHwnd, mpvResult.hwnd)) {
logger.warn('Failed to set overlay owner via koffi');
}
},
releaseOverlayOwner: () => {
const mainWindow = overlayManager.getMainWindow();
if (process.platform !== 'win32' || !mainWindow || mainWindow.isDestroyed()) return;
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
if (!clearWindowsOverlayOwner(overlayHwnd)) {
logger.warn('Failed to clear overlay owner via koffi');
}
},
bindOverlayOwner: () => bindVisibleOverlayOwner(),
releaseOverlayOwner: () => releaseVisibleOverlayOwner(),
getOverlayWindows: () => getOverlayWindows(),
getResolvedConfig: () => getResolvedConfig(),
showDesktopNotification,
+31 -8
View File
@@ -195,22 +195,45 @@ test('generateForCurrentMedia emits structured-content glossary so image stays w
assert.equal(nameDiv.tag, 'div');
assert.equal(nameDiv.content, 'アレクシア・ミドガル');
const secondaryNameDiv = children[1] as { tag: string; content: string };
assert.equal(secondaryNameDiv.tag, 'div');
assert.equal(secondaryNameDiv.content, 'Alexia Midgar');
assert.equal(
children.some((child) => (child as { content?: unknown }).content === 'Alexia Midgar'),
false,
);
const imageWrap = children[2] as { tag: string; content: Record<string, unknown> };
const imageWrap = children.find((child) => {
const content = (child as { content?: unknown }).content;
return (
content &&
typeof content === 'object' &&
!Array.isArray(content) &&
(content as { path?: unknown }).path === 'img/m130298-c123.png'
);
}) as { tag: string; content: Record<string, unknown> } | undefined;
assert.ok(imageWrap);
assert.equal(imageWrap.tag, 'div');
const image = imageWrap.content as Record<string, unknown>;
assert.equal(image.tag, 'img');
assert.equal(image.path, 'img/m130298-c123.png');
assert.equal(image.sizeUnits, 'em');
const sourceDiv = children[3] as { tag: string; content: string };
const sourceDiv = children.find((child) => {
const content = (child as { content?: unknown }).content;
return typeof content === 'string' && content.includes('The Eminence in Shadow');
}) as { tag: string; content: string } | undefined;
assert.ok(sourceDiv);
assert.equal(sourceDiv.tag, 'div');
assert.ok(sourceDiv.content.includes('The Eminence in Shadow'));
const roleBadgeDiv = children[4] as { tag: string; content: Record<string, unknown> };
const roleBadgeDiv = children.find((child) => {
const content = (child as { content?: unknown }).content;
return (
content &&
typeof content === 'object' &&
!Array.isArray(content) &&
(content as { content?: unknown }).content === 'Main Character'
);
}) as { tag: string; content: Record<string, unknown> } | undefined;
assert.ok(roleBadgeDiv);
assert.equal(roleBadgeDiv.tag, 'div');
const badge = roleBadgeDiv.content as { tag: string; content: string };
assert.equal(badge.tag, 'span');
@@ -1882,9 +1905,9 @@ test('generateForCurrentMedia logs progress while resolving and rebuilding snaps
'[dictionary] snapshot miss for AniList 130298, fetching characters',
'[dictionary] downloaded AniList character page 1 for AniList 130298',
'[dictionary] downloading 1 images for AniList 130298',
'[dictionary] stored snapshot for AniList 130298: 32 terms',
'[dictionary] stored snapshot for AniList 130298: 16 terms',
'[dictionary] building ZIP for AniList 130298',
'[dictionary] generated AniList 130298: 32 terms -> ' +
'[dictionary] generated AniList 130298: 16 terms -> ' +
path.join(userDataPath, 'character-dictionaries', 'anilist-130298.zip'),
]);
} finally {
+53 -17
View File
@@ -37,6 +37,7 @@ import {
buildCharacterDictionarySeriesKey,
createCharacterDictionaryManualSelectionStore,
} from './character-dictionary-runtime/manual-selection';
import { snapshotHasCharacterNameImages } from './character-dictionary-runtime/image-lookup';
import type {
AniListMediaCandidate,
CharacterDictionaryBuildResult,
@@ -151,6 +152,7 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
buildMergedDictionary: (mediaIds: number[]) => Promise<MergedCharacterDictionaryBuildResult>;
getManualSelectionSnapshot: (
targetPath?: string,
searchTitle?: string,
) => Promise<CharacterDictionaryManualSelectionSnapshot>;
setManualSelection: (request: {
targetPath?: string;
@@ -168,6 +170,13 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
userDataPath: deps.userDataPath,
});
const shouldRefreshCachedSnapshot = (snapshot: CharacterDictionarySnapshot): boolean => {
if (deps.getNameMatchImagesEnabled?.() !== true) {
return false;
}
return !snapshotHasCharacterNameImages(snapshot);
};
const createAniListRequestSlot = (): (() => Promise<void>) => {
let hasAniListRequest = false;
return async (): Promise<void> => {
@@ -205,12 +214,19 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
mediaTitle: guessInput.mediaTitle,
guess: guessed,
}),
unscopedSeriesKey: buildCharacterDictionarySeriesKey({
mediaPath: null,
mediaTitle: guessInput.mediaTitle,
guess: guessed,
}),
};
};
const findCachedSnapshotForSeriesKey = (
seriesKey: string,
fallbackSeriesKey?: string,
): CharacterDictionarySnapshot | null => {
const acceptedKeys = new Set([seriesKey, fallbackSeriesKey].filter(Boolean));
return (
readCachedSnapshots(outputDir).find((snapshot) => {
const snapshotSeriesKey = buildCharacterDictionarySeriesKey({
@@ -223,7 +239,7 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
source: 'fallback',
},
});
return snapshotSeriesKey === seriesKey;
return acceptedKeys.has(snapshotSeriesKey);
}) ?? null
);
};
@@ -233,7 +249,7 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
beforeRequest?: () => Promise<void>,
): Promise<ResolvedAniListMedia> => {
deps.logInfo?.('[dictionary] resolving current anime for character dictionary generation');
const { guessed, seriesKey } = await guessCurrentMedia(targetPath);
const { guessed, seriesKey, unscopedSeriesKey } = await guessCurrentMedia(targetPath);
deps.logInfo?.(
`[dictionary] current anime guess: ${guessed.title.trim()}${
typeof guessed.episode === 'number' && guessed.episode > 0
@@ -267,7 +283,7 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
}
}
const cachedSnapshot = findCachedSnapshotForSeriesKey(seriesKey);
const cachedSnapshot = findCachedSnapshotForSeriesKey(seriesKey, unscopedSeriesKey);
if (cachedSnapshot) {
writeCachedMediaResolution(outputDir, {
seriesKey,
@@ -301,7 +317,7 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
): Promise<CharacterDictionarySnapshotResult> => {
const snapshotPath = getSnapshotPath(outputDir, mediaId);
const cachedSnapshot = readSnapshot(snapshotPath);
if (cachedSnapshot) {
if (cachedSnapshot && !shouldRefreshCachedSnapshot(cachedSnapshot)) {
deps.logInfo?.(`[dictionary] snapshot hit for AniList ${mediaId}`);
return {
mediaId: cachedSnapshot.mediaId,
@@ -311,6 +327,11 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
updatedAt: cachedSnapshot.updatedAt,
};
}
if (cachedSnapshot) {
deps.logInfo?.(
`[dictionary] snapshot stale for AniList ${mediaId}: missing cached character images`,
);
}
progress?.onGenerating?.({
mediaId,
@@ -455,28 +476,43 @@ export function createCharacterDictionaryRuntimeService(deps: CharacterDictionar
entryCount,
};
},
getManualSelectionSnapshot: async (targetPath?: string) => {
getManualSelectionSnapshot: async (targetPath?: string, searchTitle?: string) => {
const waitForAniListRequestSlot = createAniListRequestSlot();
const { guessed, seriesKey } = await guessCurrentMedia(targetPath);
const [candidates, override] = await Promise.all([
searchAniListMediaCandidates(guessed.title, waitForAniListRequestSlot),
const normalizedSearchTitle = searchTitle?.trim();
const shouldUseExplicitSearch = searchTitle !== undefined;
const candidateSearchTitle = shouldUseExplicitSearch ? normalizedSearchTitle : guessed.title;
const candidates = candidateSearchTitle
? await searchAniListMediaCandidates(candidateSearchTitle, waitForAniListRequestSlot)
: [];
const [override, current] = await Promise.all([
manualSelectionStore.getOverride(seriesKey),
shouldUseExplicitSearch
? Promise.resolve(null)
: resolveAniListMediaIdFromGuess(guessed, waitForAniListRequestSlot)
.then(
(entry): AniListMediaCandidate => ({
id: entry.id,
title: entry.title,
episodes:
candidates.find((candidate) => candidate.id === entry.id)?.episodes ?? null,
}),
)
.catch(() => null),
]);
const current = await resolveAniListMediaIdFromGuess(guessed, waitForAniListRequestSlot)
.then(
(entry): AniListMediaCandidate => ({
id: entry.id,
title: entry.title,
episodes: candidates.find((candidate) => candidate.id === entry.id)?.episodes ?? null,
}),
)
.catch(() => null);
const overrideCandidate = override
? candidates.find((candidate) => candidate.id === override.mediaId)
: null;
return {
seriesKey,
guessTitle: guessed.title,
current,
override: override
? { id: override.mediaId, title: override.mediaTitle, episodes: null }
? {
id: override.mediaId,
title: override.mediaTitle,
episodes: overrideCandidate?.episodes ?? null,
}
: null,
candidates,
};
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applyCollapsibleOpenStatesToTermEntries } from './build';
import type { CharacterDictionaryTermEntry } from './types';
import { applyCollapsibleOpenStatesToTermEntries, buildSnapshotFromCharacters } from './build';
import type { CharacterDictionaryTermEntry, CharacterRecord } from './types';
test('applyCollapsibleOpenStatesToTermEntries reapplies configured details open states', () => {
const termEntries: CharacterDictionaryTermEntry[] = [
@@ -56,3 +56,111 @@ test('applyCollapsibleOpenStatesToTermEntries reapplies configured details open
assert.equal(glossaryEntry.content.content[0]?.open, true);
assert.equal(glossaryEntry.content.content[1]?.open, false);
});
test('buildSnapshotFromCharacters shows Japanese aliases without adding romanized names as lookup entries', () => {
const character: CharacterRecord = {
id: 1,
role: 'main',
firstNameHint: '',
fullName: 'Aqua',
lastNameHint: '',
nativeName: 'アクア',
alternativeNames: ['阿久亜'],
bloodType: '',
birthday: null,
description: '',
imageUrl: null,
age: '',
sex: '',
voiceActors: [],
};
const snapshot = buildSnapshotFromCharacters(
100,
'KonoSuba',
[character],
new Map(),
new Map(),
1_700_000_000_000,
() => false,
);
const aquaEntry = snapshot.termEntries.find(([term]) => term === 'アクア');
assert.ok(aquaEntry);
const glossaryEntry = aquaEntry[5][0] as {
content: {
content: Array<{ content?: unknown }>;
};
};
const wholeGlossary = JSON.stringify(glossaryEntry);
const knownNames = glossaryEntry.content.content.find((node) => {
const content = node.content;
return (
Array.isArray(content) &&
content.some(
(child) =>
child &&
typeof child === 'object' &&
(child as { content?: unknown }).content === 'Known names',
)
);
}) as { content: Array<{ content?: unknown }> } | undefined;
assert.ok(knownNames, 'expected a Known names block in the character glossary');
const knownNameItems = JSON.stringify(knownNames.content);
const terms = snapshot.termEntries.map(([term]) => term);
assert.match(knownNameItems, /アクア/);
assert.match(knownNameItems, /阿久亜/);
assert.doesNotMatch(wholeGlossary, /Aqua/);
assert.doesNotMatch(knownNameItems, /Aqua/);
assert.doesNotMatch(knownNameItems, /アクア様/);
assert.equal(terms.includes('Aqua'), false);
assert.equal(terms.includes('アクア'), true);
assert.equal(terms.includes('阿久亜'), true);
});
test('buildSnapshotFromCharacters stores media id in Yomitan structured-content data', () => {
const character: CharacterRecord = {
id: 1,
role: 'main',
firstNameHint: '',
fullName: 'Aqua',
lastNameHint: '',
nativeName: 'アクア',
alternativeNames: [],
bloodType: '',
birthday: null,
description: '',
imageUrl: null,
age: '',
sex: '',
voiceActors: [],
};
const snapshot = buildSnapshotFromCharacters(
21699,
"KONOSUBA -God's blessing on this wonderful world! 2",
[character],
new Map(),
new Map(),
1_700_000_000_000,
() => false,
);
const aquaEntry = snapshot.termEntries.find(([term]) => term === 'アクア');
assert.ok(aquaEntry);
const glossaryEntry = aquaEntry[5][0] as {
content: {
data?: Record<string, string>;
content: Array<Record<string, unknown>>;
};
};
assert.equal(glossaryEntry.content.data?.subminerMediaId, '21699');
assert.equal(
glossaryEntry.content.content.some((node) =>
Object.prototype.hasOwnProperty.call(node, 'subminerMediaId'),
),
false,
);
});
@@ -52,3 +52,18 @@ test('readSnapshot ignores snapshots written with an older format version', () =
assert.equal(readSnapshot(snapshotPath), null);
});
test('readSnapshot ignores v15 snapshots with stale romanized character-name entries', () => {
const outputDir = makeTempDir();
const snapshotPath = getSnapshotPath(outputDir, 130298);
const staleSnapshot = {
...createSnapshot(),
formatVersion: 15,
termEntries: [['Vanir', 'ばにる', 'name primary', '', 75, ['Vanir'], 0, '']],
};
fs.mkdirSync(path.dirname(snapshotPath), { recursive: true });
fs.writeFileSync(snapshotPath, JSON.stringify(staleSnapshot), 'utf8');
assert.equal(readSnapshot(snapshotPath), null);
});
@@ -1,7 +1,7 @@
export const ANILIST_GRAPHQL_URL = 'https://graphql.anilist.co';
export const ANILIST_REQUEST_DELAY_MS = 2000;
export const CHARACTER_IMAGE_DOWNLOAD_DELAY_MS = 250;
export const CHARACTER_DICTIONARY_FORMAT_VERSION = 15;
export const CHARACTER_DICTIONARY_FORMAT_VERSION = 18;
export const CHARACTER_DICTIONARY_MERGED_TITLE = 'SubMiner Character Dictionary';
export const HONORIFIC_SUFFIXES = [
+42 -2
View File
@@ -191,11 +191,51 @@ function mapRole(input: string | null | undefined): CharacterDictionaryRole {
return 'side';
}
function inferImageExt(contentType: string | null): string {
function inferImageExtFromBytes(bytes: Buffer): string | null {
if (
bytes.length >= 8 &&
bytes[0] === 0x89 &&
bytes[1] === 0x50 &&
bytes[2] === 0x4e &&
bytes[3] === 0x47
) {
return 'png';
}
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
return 'jpg';
}
if (
bytes.length >= 12 &&
bytes.subarray(0, 4).toString('ascii') === 'RIFF' &&
bytes.subarray(8, 12).toString('ascii') === 'WEBP'
) {
return 'webp';
}
if (bytes.length >= 6 && bytes.subarray(0, 6).toString('ascii') === 'GIF89a') {
return 'gif';
}
if (bytes.length >= 6 && bytes.subarray(0, 6).toString('ascii') === 'GIF87a') {
return 'gif';
}
if (
bytes.length >= 12 &&
bytes.subarray(4, 8).toString('ascii') === 'ftyp' &&
bytes.subarray(8, 12).toString('ascii') === 'avif'
) {
return 'avif';
}
return null;
}
function inferImageExt(contentType: string | null, bytes: Buffer): string {
const extFromBytes = inferImageExtFromBytes(bytes);
if (extFromBytes) return extFromBytes;
const normalized = (contentType || '').toLowerCase();
if (normalized.includes('png')) return 'png';
if (normalized.includes('gif')) return 'gif';
if (normalized.includes('webp')) return 'webp';
if (normalized.includes('avif')) return 'avif';
return 'jpg';
}
@@ -462,7 +502,7 @@ export async function downloadCharacterImage(
if (!response.ok) return null;
const bytes = Buffer.from(await response.arrayBuffer());
if (bytes.length === 0) return null;
const ext = inferImageExt(response.headers.get('content-type'));
const ext = inferImageExt(response.headers.get('content-type'), bytes);
return {
filename: `c${charId}.${ext}`,
ext,
@@ -117,20 +117,45 @@ function buildVoicedByContent(
return { tag: 'ul', style: { marginTop: '0.15em' }, content: items };
}
function buildKnownNamesBlock(nameTerms: string[]): Record<string, unknown> | null {
const visibleTerms = [...new Set(nameTerms.map((term) => term.trim()).filter(Boolean))];
if (visibleTerms.length <= 1) {
return null;
}
return {
tag: 'div',
style: { fontSize: '0.85em', marginBottom: '0.25em' },
content: [
{
tag: 'div',
style: { fontWeight: 'bold', color: '#d0d0d0', marginBottom: '0.1em' },
content: 'Known names',
},
{
tag: 'ul',
style: { marginTop: '0', marginBottom: '0', paddingLeft: '1.2em' },
content: visibleTerms.map((term) => ({
tag: 'li',
content: term,
})),
},
],
};
}
export function createDefinitionGlossary(
character: CharacterRecord,
mediaId: number,
mediaTitle: string,
imagePath: string | null,
vaImagePaths: Map<number, string>,
nameTerms: string[],
getCollapsibleSectionOpenState: (
section: AnilistCharacterDictionaryCollapsibleSectionKey,
) => boolean,
): CharacterDictionaryGlossaryEntry[] {
const displayName = character.nativeName || character.fullName || `Character ${character.id}`;
const secondaryName =
character.nativeName && character.fullName && character.fullName !== character.nativeName
? character.fullName
: null;
const { fields, text: descriptionText } = parseCharacterDescription(character.description);
const content: Array<string | Record<string, unknown>> = [
@@ -141,12 +166,9 @@ export function createDefinitionGlossary(
},
];
if (secondaryName) {
content.push({
tag: 'div',
style: { fontSize: '0.85em', fontStyle: 'italic', color: '#b0b0b0', marginBottom: '0.2em' },
content: secondaryName,
});
const knownNamesBlock = buildKnownNamesBlock(nameTerms);
if (knownNamesBlock) {
content.push(knownNamesBlock);
}
if (imagePath) {
@@ -237,7 +259,7 @@ export function createDefinitionGlossary(
return [
{
type: 'structured-content',
content: { tag: 'div', content },
content: { tag: 'div', data: { subminerMediaId: String(mediaId) }, content },
},
];
}
@@ -0,0 +1,217 @@
import assert from 'node:assert/strict';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import test from 'node:test';
import { getSnapshotPath, writeSnapshot } from './cache';
import { CHARACTER_DICTIONARY_FORMAT_VERSION } from './constants';
import {
buildCharacterNameImageIndexFromSnapshots,
createCharacterDictionaryImageLookup,
} from './image-lookup';
import type { CharacterDictionarySnapshot } from './types';
const PNG_1X1_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+nmX8AAAAASUVORK5CYII=';
function makeTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-character-image-lookup-'));
}
test('buildCharacterNameImageIndexFromSnapshots maps name terms to character portrait data URLs', () => {
const outputDir = makeTempDir();
const snapshot: CharacterDictionarySnapshot = {
formatVersion: CHARACTER_DICTIONARY_FORMAT_VERSION,
mediaId: 130298,
mediaTitle: 'The Eminence in Shadow',
entryCount: 1,
updatedAt: 1_700_000_000_000,
termEntries: [
[
'アレクシア',
'あれくしあ',
'name primary',
'',
75,
[
{
type: 'structured-content',
content: {
tag: 'div',
content: [
{ tag: 'div', content: 'アレクシア・ミドガル' },
{
tag: 'div',
content: {
tag: 'img',
path: 'img/m130298-c123.png',
alt: 'アレクシア・ミドガル',
},
},
{
tag: 'details',
content: [
{ tag: 'summary', content: 'Voiced by' },
{
tag: 'div',
content: {
tag: 'img',
path: 'img/m130298-va456.png',
alt: 'VA',
},
},
],
},
],
},
},
],
0,
'',
],
],
images: [
{ path: 'img/m130298-c123.png', dataBase64: 'AAAA' },
{ path: 'img/m130298-va456.png', dataBase64: 'BBBB' },
],
};
writeSnapshot(getSnapshotPath(outputDir, snapshot.mediaId), snapshot);
const index = buildCharacterNameImageIndexFromSnapshots(outputDir);
assert.deepEqual(index.get('アレクシア'), {
src: 'data:image/png;base64,AAAA',
alt: 'アレクシア・ミドガル',
});
});
test('buildCharacterNameImageIndexFromSnapshots sniffs image MIME from bytes before path extension', () => {
const outputDir = makeTempDir();
const snapshot: CharacterDictionarySnapshot = {
formatVersion: CHARACTER_DICTIONARY_FORMAT_VERSION,
mediaId: 130298,
mediaTitle: 'The Eminence in Shadow',
entryCount: 1,
updatedAt: 1_700_000_000_000,
termEntries: [
[
'アレクシア',
'あれくしあ',
'name primary',
'',
75,
[
{
type: 'structured-content',
content: {
tag: 'img',
path: 'img/m130298-c123.jpg',
alt: 'アレクシア・ミドガル',
},
},
],
0,
'',
],
],
images: [{ path: 'img/m130298-c123.jpg', dataBase64: PNG_1X1_BASE64 }],
};
writeSnapshot(getSnapshotPath(outputDir, snapshot.mediaId), snapshot);
const index = buildCharacterNameImageIndexFromSnapshots(outputDir);
assert.equal(index.get('アレクシア')?.src, `data:image/png;base64,${PNG_1X1_BASE64}`);
});
test('createCharacterDictionaryImageLookup can scope duplicate names to the current media', () => {
const outputDir = makeTempDir();
const towerSnapshot: CharacterDictionarySnapshot = {
formatVersion: CHARACTER_DICTIONARY_FORMAT_VERSION,
mediaId: 115230,
mediaTitle: 'Tower of God',
entryCount: 1,
updatedAt: 1_700_000_000_000,
termEntries: [
[
'カズ',
'かず',
'name primary',
'',
75,
[
{
type: 'structured-content',
content: { tag: 'img', path: 'img/m115230-c1.png', alt: 'Kaz' },
},
],
0,
'',
],
],
images: [{ path: 'img/m115230-c1.png', dataBase64: 'TOWER' }],
};
const konosubaSnapshot: CharacterDictionarySnapshot = {
...towerSnapshot,
mediaId: 21202,
mediaTitle: 'KonoSuba',
termEntries: [
[
'カズ',
'かず',
'name primary',
'',
75,
[
{
type: 'structured-content',
content: { tag: 'img', path: 'img/m21202-c2.png', alt: 'Kazuma' },
},
],
0,
'',
],
],
images: [{ path: 'img/m21202-c2.png', dataBase64: 'KONOSUBA' }],
};
writeSnapshot(getSnapshotPath(outputDir, towerSnapshot.mediaId), towerSnapshot);
writeSnapshot(getSnapshotPath(outputDir, konosubaSnapshot.mediaId), konosubaSnapshot);
const lookup = createCharacterDictionaryImageLookup({ outputDir });
assert.equal(lookup.get('カズ', 21202)?.alt, 'Kazuma');
});
test('createCharacterDictionaryImageLookup does not fall back globally on scoped miss', () => {
const outputDir = makeTempDir();
const snapshot: CharacterDictionarySnapshot = {
formatVersion: CHARACTER_DICTIONARY_FORMAT_VERSION,
mediaId: 115230,
mediaTitle: 'Tower of God',
entryCount: 1,
updatedAt: 1_700_000_000_000,
termEntries: [
[
'カズ',
'かず',
'name primary',
'',
75,
[
{
type: 'structured-content',
content: { tag: 'img', path: 'img/m115230-c1.png', alt: 'Kaz' },
},
],
0,
'',
],
],
images: [{ path: 'img/m115230-c1.png', dataBase64: 'TOWER' }],
};
writeSnapshot(getSnapshotPath(outputDir, snapshot.mediaId), snapshot);
const lookup = createCharacterDictionaryImageLookup({ outputDir });
assert.equal(lookup.get('カズ', 21202), null);
assert.equal(lookup.get('カズ')?.alt, 'Kaz');
});
@@ -0,0 +1,273 @@
import * as fs from 'fs';
import * as path from 'path';
import type { CharacterNameImage } from '../../types';
import { readCachedSnapshots } from './cache';
import type {
CharacterDictionaryGlossaryEntry,
CharacterDictionarySnapshot,
CharacterDictionarySnapshotImage,
CharacterDictionaryTermEntry,
} from './types';
const CHARACTER_IMAGE_PATH_PATTERN = /^img\/m\d+-c\d+\.[a-z0-9]+$/i;
type StructuredContentNode = {
tag?: unknown;
path?: unknown;
alt?: unknown;
title?: unknown;
content?: unknown;
};
function normalizeLookupTerm(term: string): string {
return term.trim();
}
function normalizeLookupMediaId(mediaId: unknown): number | null {
if (typeof mediaId !== 'number' || !Number.isFinite(mediaId)) {
return null;
}
const normalized = Math.floor(mediaId);
return normalized > 0 ? normalized : null;
}
function getSnapshotsDir(outputDir: string): string {
return path.join(outputDir, 'snapshots');
}
function getImageMimeType(imagePath: string, dataBase64: string): string {
const signature = Buffer.from(dataBase64.slice(0, 64), 'base64');
if (
signature.length >= 8 &&
signature[0] === 0x89 &&
signature[1] === 0x50 &&
signature[2] === 0x4e &&
signature[3] === 0x47
) {
return 'image/png';
}
if (
signature.length >= 12 &&
signature.subarray(0, 4).toString('ascii') === 'RIFF' &&
signature.subarray(8, 12).toString('ascii') === 'WEBP'
) {
return 'image/webp';
}
if (
signature.length >= 6 &&
(signature.subarray(0, 6).toString('ascii') === 'GIF89a' ||
signature.subarray(0, 6).toString('ascii') === 'GIF87a')
) {
return 'image/gif';
}
if (signature.length >= 3 && signature[0] === 0xff && signature[1] === 0xd8) {
return 'image/jpeg';
}
if (
signature.length >= 12 &&
signature.subarray(4, 8).toString('ascii') === 'ftyp' &&
signature.subarray(8, 12).toString('ascii') === 'avif'
) {
return 'image/avif';
}
const ext = path.extname(imagePath).toLowerCase();
if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
if (ext === '.png') return 'image/png';
if (ext === '.webp') return 'image/webp';
if (ext === '.gif') return 'image/gif';
if (ext === '.avif') return 'image/avif';
return 'image/jpeg';
}
function buildImageByPath(
images: ReadonlyArray<CharacterDictionarySnapshotImage>,
): Map<string, CharacterDictionarySnapshotImage> {
const imageByPath = new Map<string, CharacterDictionarySnapshotImage>();
for (const image of images) {
if (image.path && image.dataBase64) {
imageByPath.set(image.path, image);
}
}
return imageByPath;
}
function findCharacterImageNode(value: unknown): StructuredContentNode | null {
if (Array.isArray(value)) {
for (const item of value) {
const found = findCharacterImageNode(item);
if (found) return found;
}
return null;
}
if (!value || typeof value !== 'object') {
return null;
}
const node = value as StructuredContentNode;
if (
node.tag === 'img' &&
typeof node.path === 'string' &&
CHARACTER_IMAGE_PATH_PATTERN.test(node.path)
) {
return node;
}
return findCharacterImageNode(node.content);
}
function findCharacterImageNodeInGlossary(
glossary: ReadonlyArray<CharacterDictionaryGlossaryEntry>,
): StructuredContentNode | null {
for (const entry of glossary) {
const found = findCharacterImageNode(entry);
if (found) return found;
}
return null;
}
function createCharacterNameImage(
entry: CharacterDictionaryTermEntry,
imageByPath: ReadonlyMap<string, CharacterDictionarySnapshotImage>,
): CharacterNameImage | null {
const term = normalizeLookupTerm(entry[0]);
if (!term) {
return null;
}
const imageNode = findCharacterImageNodeInGlossary(entry[5]);
const imagePath = typeof imageNode?.path === 'string' ? imageNode.path : '';
const image = imageByPath.get(imagePath);
if (!image) {
return null;
}
const rawAlt =
typeof imageNode?.alt === 'string'
? imageNode.alt
: typeof imageNode?.title === 'string'
? imageNode.title
: term;
const alt = rawAlt.trim() || term;
return {
src: `data:${getImageMimeType(image.path, image.dataBase64)};base64,${image.dataBase64}`,
alt,
};
}
function appendSnapshotImages(
index: Map<string, CharacterNameImage>,
snapshot: CharacterDictionarySnapshot,
): void {
const imageByPath = buildImageByPath(snapshot.images);
for (const entry of snapshot.termEntries) {
const term = normalizeLookupTerm(entry[0]);
if (!term || index.has(term)) {
continue;
}
const image = createCharacterNameImage(entry, imageByPath);
if (image) {
index.set(term, image);
}
}
}
export function snapshotHasCharacterNameImages(snapshot: CharacterDictionarySnapshot): boolean {
const imageByPath = buildImageByPath(snapshot.images);
return snapshot.termEntries.some(
(entry) => createCharacterNameImage(entry, imageByPath) !== null,
);
}
function getSnapshotDirectorySignature(outputDir: string): string {
let entries: fs.Dirent[] = [];
try {
entries = fs.readdirSync(getSnapshotsDir(outputDir), { withFileTypes: true });
} catch {
return '';
}
const parts: string[] = [];
for (const entry of entries) {
if (!entry.isFile() || !/^anilist-\d+\.json$/.test(entry.name)) {
continue;
}
const snapshotPath = path.join(getSnapshotsDir(outputDir), entry.name);
try {
const stat = fs.statSync(snapshotPath);
parts.push(`${entry.name}:${stat.mtimeMs}:${stat.size}`);
} catch {
// Ignore files that disappear during refresh; next lookup will rebuild.
}
}
return parts.sort().join('|');
}
export function buildCharacterNameImageIndexFromSnapshots(
outputDir: string,
): Map<string, CharacterNameImage> {
const index = new Map<string, CharacterNameImage>();
for (const snapshot of readCachedSnapshots(outputDir)) {
appendSnapshotImages(index, snapshot);
}
return index;
}
export function createCharacterDictionaryImageLookup(deps: {
userDataPath?: string;
outputDir?: string;
getCurrentMediaId?: () => number | null | undefined;
}): {
get: (term: string, mediaId?: number | null) => CharacterNameImage | null;
invalidate: () => void;
} {
const outputDir =
deps.outputDir ??
(deps.userDataPath ? path.join(deps.userDataPath, 'character-dictionaries') : '');
let signature: string | null = null;
let index = new Map<string, CharacterNameImage>();
let indexByMediaId = new Map<number, Map<string, CharacterNameImage>>();
function refreshIfNeeded(): void {
if (!outputDir) {
index = new Map<string, CharacterNameImage>();
indexByMediaId = new Map<number, Map<string, CharacterNameImage>>();
signature = '';
return;
}
const nextSignature = getSnapshotDirectorySignature(outputDir);
if (nextSignature === signature) {
return;
}
signature = nextSignature;
index = new Map<string, CharacterNameImage>();
indexByMediaId = new Map<number, Map<string, CharacterNameImage>>();
for (const snapshot of readCachedSnapshots(outputDir)) {
appendSnapshotImages(index, snapshot);
const mediaIndex = new Map<string, CharacterNameImage>();
appendSnapshotImages(mediaIndex, snapshot);
if (mediaIndex.size > 0) {
indexByMediaId.set(snapshot.mediaId, mediaIndex);
}
}
}
return {
get(term: string, mediaId?: number | null): CharacterNameImage | null {
const normalizedTerm = normalizeLookupTerm(term);
if (!normalizedTerm) {
return null;
}
refreshIfNeeded();
const scopedMediaId = normalizeLookupMediaId(mediaId ?? deps.getCurrentMediaId?.() ?? null);
if (scopedMediaId !== null) {
return indexByMediaId.get(scopedMediaId)?.get(normalizedTerm) ?? null;
}
return index.get(normalizedTerm) ?? null;
},
invalidate(): void {
signature = null;
},
};
}
@@ -0,0 +1,162 @@
import assert from 'node:assert/strict';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import test from 'node:test';
import { createCharacterDictionaryRuntimeService } from '../character-dictionary-runtime';
import { buildCharacterDictionarySeriesKey } from './manual-selection';
function makeTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-character-dictionary-'));
}
test('getManualSelectionSnapshot waits for explicit search text before fetching candidates', async () => {
const userDataPath = makeTempDir();
const originalFetch = globalThis.fetch;
const searchTerms: string[] = [];
globalThis.fetch = (async (_input: string | URL | Request, init?: RequestInit) => {
const body = JSON.parse(String(init?.body ?? '{}')) as {
variables?: { search?: string };
};
searchTerms.push(String(body.variables?.search ?? ''));
return new Response(
JSON.stringify({
data: {
Page: {
media: [
{
id: 154587,
episodes: 28,
title: {
romaji: 'Sousou no Frieren',
english: 'Frieren: Beyond Journeys End',
native: '葬送のフリーレン',
},
},
],
},
},
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
},
);
}) as typeof globalThis.fetch;
try {
const runtime = createCharacterDictionaryRuntimeService({
userDataPath,
getCurrentMediaPath: () => '/tmp/[SubsPlease] Kage no Jitsuryokusha - 05.mkv',
getCurrentMediaTitle: () => '[SubsPlease] Kage no Jitsuryokusha - 05.mkv',
resolveMediaPathForJimaku: (mediaPath) => mediaPath,
guessAnilistMediaInfo: async () => ({
title: 'Kage no Jitsuryokusha ni Naritakute!',
season: null,
episode: 5,
source: 'guessit',
}),
now: () => 1_700_000_000_000,
});
const initial = await runtime.getManualSelectionSnapshot(undefined, '');
assert.equal(initial.guessTitle, 'Kage no Jitsuryokusha ni Naritakute!');
assert.deepEqual(initial.candidates, []);
assert.deepEqual(searchTerms, []);
const searched = await runtime.getManualSelectionSnapshot(undefined, 'Frieren');
assert.deepEqual(searchTerms, ['Frieren']);
assert.deepEqual(searched.candidates, [
{ id: 154587, title: 'Frieren: Beyond Journeys End', episodes: 28 },
]);
} finally {
globalThis.fetch = originalFetch;
}
});
test('getManualSelectionSnapshot hydrates override episode count from searched candidates', async () => {
const userDataPath = makeTempDir();
const overrideSeriesKey = buildCharacterDictionarySeriesKey({
mediaPath: '/tmp/KonoSuba - 01.mkv',
mediaTitle: 'KonoSuba - 01.mkv',
guess: {
title: "KonoSuba - God's blessing on this wonderful world!",
year: 2016,
season: null,
episode: 1,
source: 'guessit',
},
});
const overrideDir = path.join(userDataPath, 'character-dictionaries');
fs.mkdirSync(overrideDir, { recursive: true });
fs.writeFileSync(
path.join(overrideDir, 'anilist-overrides.json'),
JSON.stringify({
overrides: [
{
seriesKey: overrideSeriesKey,
mediaId: 21202,
mediaTitle: "KONOSUBA -God's blessing on this wonderful world!",
staleMediaIds: [],
},
],
}),
'utf8',
);
const originalFetch = globalThis.fetch;
globalThis.fetch = (async (_input: string | URL | Request) => {
return new Response(
JSON.stringify({
data: {
Page: {
media: [
{
id: 21202,
episodes: 10,
title: {
romaji: 'Kono Subarashii Sekai ni Shukufuku wo!',
english: "KONOSUBA -God's blessing on this wonderful world!",
native: 'この素晴らしい世界に祝福を!',
},
},
],
},
},
}),
{
status: 200,
headers: { 'content-type': 'application/json' },
},
);
}) as typeof globalThis.fetch;
try {
const runtime = createCharacterDictionaryRuntimeService({
userDataPath,
getCurrentMediaPath: () => '/tmp/KonoSuba - 01.mkv',
getCurrentMediaTitle: () => 'KonoSuba - 01.mkv',
resolveMediaPathForJimaku: (mediaPath) => mediaPath,
guessAnilistMediaInfo: async () => ({
title: "KonoSuba - God's blessing on this wonderful world!",
year: 2016,
season: null,
episode: 1,
source: 'guessit',
}),
now: () => 1_700_000_000_000,
});
const snapshot = await runtime.getManualSelectionSnapshot(undefined, 'KonoSuba');
assert.deepEqual(snapshot.override, {
id: 21202,
title: "KONOSUBA -God's blessing on this wonderful world!",
episodes: 10,
});
} finally {
globalThis.fetch = originalFetch;
}
});
@@ -10,15 +10,17 @@ import {
} from './manual-selection';
const REZERO_EP1 =
'/anime/Re - ZERO, Starting Life in Another World (2016) - S01E01 - - The End of the Beginning and the Beginning of the End [v2 Bluray-1080p Proper][10bit][x265][FLAC 2.0][EN+JA]-SCY.mkv';
'/anime/ReZERO/Season 1/Re - ZERO, Starting Life in Another World (2016) - S01E01 - - The End of the Beginning and the Beginning of the End [v2 Bluray-1080p Proper][10bit][x265][FLAC 2.0][EN+JA]-SCY.mkv';
const REZERO_EP2 =
'/anime/Re - ZERO, Starting Life in Another World (2016) - S01E02 - Reunion with the Witch [Bluray-1080p][x265][JA]-SCY.mkv';
'/anime/ReZERO/Season 1/Re - ZERO, Starting Life in Another World (2016) - S01E02 - Reunion with the Witch [Bluray-1080p][x265][JA]-SCY.mkv';
const REZERO_S2_EP1 =
'/anime/ReZERO/Season 2/Re - ZERO, Starting Life in Another World (2016) - S02E01 - Each Ones Promise [Bluray-1080p][x265][JA]-SCY.mkv';
function makeTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-manual-selection-'));
}
test('buildCharacterDictionarySeriesKey uses guessit title, alternative title, and year for Re ZERO series scope', () => {
test('buildCharacterDictionarySeriesKey scopes guessit title and year by media directory', () => {
const key = buildCharacterDictionarySeriesKey({
mediaPath: REZERO_EP1,
mediaTitle: null,
@@ -32,10 +34,10 @@ test('buildCharacterDictionarySeriesKey uses guessit title, alternative title, a
},
});
assert.equal(key, 're-zero-starting-life-in-another-world-2016');
assert.equal(key, 'anime-rezero-season-1--re-zero-starting-life-in-another-world-2016');
});
test('manual selection store persists overrides and matches later episodes in the same series', async () => {
test('manual selection store persists overrides and matches later episodes in the same directory', async () => {
const userDataPath = makeTempDir();
const store = createCharacterDictionaryManualSelectionStore({ userDataPath });
const firstKey = buildCharacterDictionarySeriesKey({
@@ -79,3 +81,131 @@ test('manual selection store persists overrides and matches later episodes in th
staleMediaIds: [10607],
});
});
test('manual selection store resolves legacy unscoped override keys', async () => {
const userDataPath = makeTempDir();
const overrideDir = path.join(userDataPath, 'character-dictionaries');
fs.mkdirSync(overrideDir, { recursive: true });
fs.writeFileSync(
path.join(overrideDir, 'anilist-overrides.json'),
JSON.stringify({
overrides: [
{
seriesKey: 're-zero-starting-life-in-another-world-2016',
mediaId: 21355,
mediaTitle: 'Re:ZERO -Starting Life in Another World-',
staleMediaIds: [10607],
},
],
}),
'utf8',
);
const scopedKey = buildCharacterDictionarySeriesKey({
mediaPath: REZERO_EP1,
mediaTitle: null,
guess: {
title: 'Re ZERO, Starting Life in Another World',
alternativeTitle: 'ZERO, Starting Life in Another World',
year: 2016,
season: 1,
episode: 1,
source: 'guessit',
},
});
const store = createCharacterDictionaryManualSelectionStore({ userDataPath });
assert.deepEqual(await store.getOverride(scopedKey), {
seriesKey: 're-zero-starting-life-in-another-world-2016',
mediaId: 21355,
mediaTitle: 'Re:ZERO -Starting Life in Another World-',
staleMediaIds: [10607],
});
});
test('manual selection store prefers exact scoped override over legacy fallback', async () => {
const userDataPath = makeTempDir();
const overrideDir = path.join(userDataPath, 'character-dictionaries');
fs.mkdirSync(overrideDir, { recursive: true });
const scopedKey = buildCharacterDictionarySeriesKey({
mediaPath: REZERO_EP1,
mediaTitle: null,
guess: {
title: 'Re ZERO, Starting Life in Another World',
alternativeTitle: 'ZERO, Starting Life in Another World',
year: 2016,
season: 1,
episode: 1,
source: 'guessit',
},
});
fs.writeFileSync(
path.join(overrideDir, 'anilist-overrides.json'),
JSON.stringify({
overrides: [
{
seriesKey: 're-zero-starting-life-in-another-world-2016',
mediaId: 10607,
mediaTitle: 'Legacy Re:ZERO',
staleMediaIds: [],
},
{
seriesKey: scopedKey,
mediaId: 21355,
mediaTitle: 'Re:ZERO -Starting Life in Another World-',
staleMediaIds: [10607],
},
],
}),
'utf8',
);
const store = createCharacterDictionaryManualSelectionStore({ userDataPath });
assert.deepEqual(await store.getOverride(scopedKey), {
seriesKey: scopedKey,
mediaId: 21355,
mediaTitle: 'Re:ZERO -Starting Life in Another World-',
staleMediaIds: [10607],
});
});
test('manual selection store keeps overrides separate for different season directories', async () => {
const userDataPath = makeTempDir();
const store = createCharacterDictionaryManualSelectionStore({ userDataPath });
const firstSeasonKey = buildCharacterDictionarySeriesKey({
mediaPath: REZERO_EP1,
mediaTitle: null,
guess: {
title: 'Re ZERO, Starting Life in Another World',
alternativeTitle: 'ZERO, Starting Life in Another World',
year: 2016,
season: 1,
episode: 1,
source: 'guessit',
},
});
await store.setOverride({
seriesKey: firstSeasonKey,
mediaId: 21355,
mediaTitle: 'Re:ZERO -Starting Life in Another World-',
staleMediaIds: [],
});
const secondSeasonKey = buildCharacterDictionarySeriesKey({
mediaPath: REZERO_S2_EP1,
mediaTitle: null,
guess: {
title: 'Re ZERO, Starting Life in Another World',
alternativeTitle: 'ZERO, Starting Life in Another World',
year: 2016,
season: 2,
episode: 1,
source: 'guessit',
},
});
assert.notEqual(secondSeasonKey, firstSeasonKey);
assert.equal(await store.getOverride(secondSeasonKey), null);
});
@@ -31,6 +31,29 @@ function normalizeSeriesKeyPart(value: string): string {
.toLowerCase();
}
function getMediaDirectoryKey(mediaPath: string | null): string {
const rawPath = mediaPath?.trim();
if (!rawPath) return '';
if (/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//.test(rawPath) || rawPath.startsWith('file:')) {
try {
const url = new URL(rawPath);
const directoryPath = path.posix.dirname(
decodeURIComponent(url.pathname).replace(/\\/g, '/'),
);
const scopedPath = `${url.hostname}${directoryPath === '/' ? '' : directoryPath}`;
return normalizeSeriesKeyPart(scopedPath);
} catch {
return '';
}
}
const normalizedPath = rawPath.replace(/\\/g, '/');
const directoryPath = path.posix.dirname(normalizedPath);
if (!directoryPath || directoryPath === '.') return '';
return normalizeSeriesKeyPart(directoryPath);
}
function dedupeNumbers(values: number[]): number[] {
const seen = new Set<number>();
const result: number[] = [];
@@ -78,6 +101,12 @@ function writeOverrides(filePath: string, overrides: CharacterDictionaryManualSe
fs.writeFileSync(filePath, JSON.stringify({ overrides }, null, 2), 'utf8');
}
function getLegacySeriesKeyCandidates(seriesKey: string): string[] {
const scopedSeparatorIndex = seriesKey.indexOf('--');
if (scopedSeparatorIndex < 0) return [seriesKey];
return [seriesKey, seriesKey.slice(scopedSeparatorIndex + 2)];
}
export function buildCharacterDictionarySeriesKey(input: {
mediaPath: string | null;
mediaTitle: string | null;
@@ -94,7 +123,9 @@ export function buildCharacterDictionarySeriesKey(input: {
.replace(/\bepisode\s+\d+\b/gi, ' ')
.trim();
const base = normalizeSeriesKeyPart(withoutEpisode) || 'unknown';
return input.guess?.year ? `${base}-${input.guess.year}` : base;
const directoryKey = getMediaDirectoryKey(input.mediaPath);
const scopedBase = directoryKey ? `${directoryKey}--${base}` : base;
return input.guess?.year ? `${scopedBase}-${input.guess.year}` : scopedBase;
}
export function createCharacterDictionaryManualSelectionStore(deps: { userDataPath: string }) {
@@ -102,7 +133,13 @@ export function createCharacterDictionaryManualSelectionStore(deps: { userDataPa
return {
getOverride: async (seriesKey: string): Promise<CharacterDictionaryManualSelection | null> => {
return readOverrides(filePath).find((entry) => entry.seriesKey === seriesKey) ?? null;
const candidates = getLegacySeriesKeyCandidates(seriesKey);
const overrides = readOverrides(filePath);
for (const candidate of candidates) {
const match = overrides.find((entry) => entry.seriesKey === candidate);
if (match) return match;
}
return null;
},
setOverride: async (selection: CharacterDictionaryManualSelection): Promise<void> => {
const normalized = normalizeOverride(selection);
@@ -0,0 +1,157 @@
import assert from 'node:assert/strict';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import test from 'node:test';
import { createCharacterDictionaryRuntimeService } from '../character-dictionary-runtime';
import { getSnapshotPath, writeSnapshot } from './cache';
import { CHARACTER_DICTIONARY_FORMAT_VERSION } from './constants';
import type { CharacterDictionarySnapshot } from './types';
const GRAPHQL_URL = 'https://graphql.anilist.co';
const PNG_1X1 = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+nmX8AAAAASUVORK5CYII=',
'base64',
);
function makeTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-character-dictionary-'));
}
function createSnapshotWithoutImages(): CharacterDictionarySnapshot {
return {
formatVersion: CHARACTER_DICTIONARY_FORMAT_VERSION,
mediaId: 130298,
mediaTitle: 'The Eminence in Shadow',
entryCount: 1,
updatedAt: 1_700_000_000_000,
termEntries: [['アレクシア', 'あれくしあ', 'name primary', '', 75, ['Alexia'], 0, '']],
images: [],
};
}
test('generateForCurrentMedia refreshes same-version snapshots missing images when inline images are enabled', async () => {
const userDataPath = makeTempDir();
const outputDir = path.join(userDataPath, 'character-dictionaries');
writeSnapshot(getSnapshotPath(outputDir, 130298), createSnapshotWithoutImages());
const originalFetch = globalThis.fetch;
const fetchUrls: string[] = [];
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
fetchUrls.push(url);
if (url === GRAPHQL_URL) {
const body = JSON.parse(String(init?.body ?? '{}')) as {
query?: string;
};
if (body.query?.includes('characters(page: $page')) {
return new Response(
JSON.stringify({
data: {
Media: {
title: {
english: 'The Eminence in Shadow',
},
characters: {
pageInfo: { hasNextPage: false },
edges: [
{
role: 'SUPPORTING',
node: {
id: 123,
description: 'Alexia Midgar.',
image: {
large: 'https://cdn.example.com/character-123.png',
medium: null,
},
name: {
full: 'Alexia Midgar',
native: 'アレクシア・ミドガル',
},
},
},
],
},
},
},
}),
{ status: 200, headers: { 'content-type': 'application/json' } },
);
}
}
if (url === 'https://cdn.example.com/character-123.png') {
return new Response(PNG_1X1, {
status: 200,
headers: { 'content-type': 'image/png' },
});
}
throw new Error(`Unexpected fetch URL: ${url}`);
}) as typeof globalThis.fetch;
try {
const runtime = createCharacterDictionaryRuntimeService({
userDataPath,
getCurrentMediaPath: () => '/tmp/eminence-s01e05.mkv',
getCurrentMediaTitle: () => 'The Eminence in Shadow - S01E05',
resolveMediaPathForJimaku: (mediaPath) => mediaPath,
guessAnilistMediaInfo: async () => ({
title: 'The Eminence in Shadow',
season: null,
episode: 5,
source: 'fallback',
}),
getNameMatchImagesEnabled: () => true,
now: () => 1_700_000_000_500,
});
const result = await runtime.generateForCurrentMedia();
const refreshedSnapshot = JSON.parse(
fs.readFileSync(getSnapshotPath(outputDir, 130298), 'utf8'),
) as CharacterDictionarySnapshot;
assert.equal(result.fromCache, false);
assert.ok(fetchUrls.includes(GRAPHQL_URL));
assert.ok(refreshedSnapshot.images.some((image) => image.path === 'img/m130298-c123.png'));
} finally {
globalThis.fetch = originalFetch;
}
});
test('generateForCurrentMedia keeps same-version snapshots without images when inline images are disabled', async () => {
const userDataPath = makeTempDir();
const outputDir = path.join(userDataPath, 'character-dictionaries');
writeSnapshot(getSnapshotPath(outputDir, 130298), createSnapshotWithoutImages());
const originalFetch = globalThis.fetch;
globalThis.fetch = (async (input: string | URL | Request) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
throw new Error(`Unexpected fetch URL: ${url}`);
}) as typeof globalThis.fetch;
try {
const runtime = createCharacterDictionaryRuntimeService({
userDataPath,
getCurrentMediaPath: () => '/tmp/eminence-s01e05.mkv',
getCurrentMediaTitle: () => 'The Eminence in Shadow - S01E05',
resolveMediaPathForJimaku: (mediaPath) => mediaPath,
guessAnilistMediaInfo: async () => ({
title: 'The Eminence in Shadow',
season: null,
episode: 5,
source: 'fallback',
}),
getNameMatchImagesEnabled: () => false,
now: () => 1_700_000_000_500,
});
const result = await runtime.generateForCurrentMedia();
assert.equal(result.fromCache, true);
} finally {
globalThis.fetch = originalFetch;
}
});
@@ -2,7 +2,12 @@ import type { AnilistCharacterDictionaryCollapsibleSectionKey } from '../../type
import { CHARACTER_DICTIONARY_FORMAT_VERSION } from './constants';
import { createDefinitionGlossary } from './glossary';
import { generateNameReadings, splitJapaneseName } from './name-reading';
import { buildNameTerms, buildReadingForTerm, buildTermEntry } from './term-building';
import {
buildNameTerms,
buildReadingForTerm,
buildTermEntry,
buildVisibleNameTerms,
} from './term-building';
import type {
CharacterDictionaryGlossaryEntry,
CharacterDictionarySnapshot,
@@ -40,14 +45,16 @@ export function buildSnapshotFromCharacters(
const vaImg = imagesByVaId.get(va.id);
if (vaImg) vaImagePaths.set(va.id, vaImg.path);
}
const candidateTerms = buildNameTerms(character);
const glossary = createDefinitionGlossary(
character,
mediaId,
mediaTitle,
imagePath,
vaImagePaths,
buildVisibleNameTerms(candidateTerms),
getCollapsibleSectionOpenState,
);
const candidateTerms = buildNameTerms(character);
const nameParts = splitJapaneseName(
character.nativeName,
character.firstNameHint,
@@ -0,0 +1,38 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildNameTerms } from './term-building';
import type { CharacterRecord } from './types';
function characterRecord(overrides: Partial<CharacterRecord>): CharacterRecord {
return {
id: 136073,
role: 'primary',
firstNameHint: 'Chi-Yul',
fullName: 'Chi-Yul Song',
lastNameHint: 'Song',
nativeName: '송치율',
alternativeNames: [],
bloodType: '',
birthday: null,
description: '',
imageUrl: null,
age: '',
sex: '',
voiceActors: [],
...overrides,
};
}
test('buildNameTerms adds surname honorifics from Japanese localized aliases', () => {
const terms = buildNameTerms(
characterRecord({
alternativeNames: ['Isao Mabuchi (馬渕勲)', 'Chi-Yeol (송치열)'],
}),
);
assert.ok(terms.includes('馬渕勲'));
assert.ok(terms.includes('馬渕勲さん'));
assert.ok(terms.includes('馬渕'));
assert.ok(terms.includes('馬渕さん'));
assert.ok(!terms.includes('송치'));
});
@@ -3,6 +3,7 @@ import {
addRomanizedKanaAliases,
buildReading,
buildReadingFromRomanized,
containsKanji,
hasKanaOnly,
isRomanizedName,
splitJapaneseName,
@@ -39,27 +40,48 @@ function expandRawNameVariants(rawName: string): string[] {
return [...variants];
}
function isJapaneseNameSplitCandidate(name: string): boolean {
const compact = name.replace(/[\s\u3000・・·•]/g, '');
return (
containsKanji(compact) && /^[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff々〆ヵヶー]+$/.test(compact)
);
}
function addJapaneseNameParts(character: CharacterRecord, name: string, terms: Set<string>): void {
if (!isJapaneseNameSplitCandidate(name)) return;
const nameParts = splitJapaneseName(name, character.firstNameHint, character.lastNameHint);
if (nameParts.family) {
terms.add(nameParts.family);
}
if (nameParts.given) {
terms.add(nameParts.given);
}
}
export function buildNameTerms(character: CharacterRecord): string[] {
const base = new Set<string>();
const romanizedBase = new Set<string>();
const rawNames = [character.nativeName, character.fullName, ...character.alternativeNames];
for (const rawName of rawNames) {
for (const name of expandRawNameVariants(rawName)) {
base.add(name);
const target = isRomanizedName(name) ? romanizedBase : base;
target.add(name);
const compact = name.replace(/[\s\u3000]+/g, '');
if (compact && compact !== name) {
base.add(compact);
target.add(compact);
}
const noMiddleDots = compact.replace(/[・・·•]/g, '');
if (noMiddleDots && noMiddleDots !== compact) {
base.add(noMiddleDots);
target.add(noMiddleDots);
}
const split = name.split(/[\s\u3000]+/).filter((part) => part.trim().length > 0);
if (split.length === 2) {
base.add(split[0]!);
base.add(split[1]!);
target.add(split[0]!);
target.add(split[1]!);
}
const splitByMiddleDot = name
@@ -68,12 +90,20 @@ export function buildNameTerms(character: CharacterRecord): string[] {
.filter((part) => part.length > 0);
if (splitByMiddleDot.length >= 2) {
for (const part of splitByMiddleDot) {
base.add(part);
target.add(part);
}
}
if (target === base) {
addJapaneseNameParts(character, name, base);
}
}
}
for (const alias of addRomanizedKanaAliases(romanizedBase)) {
base.add(alias);
}
const nativeParts = splitJapaneseName(
character.nativeName,
character.firstNameHint,
@@ -94,16 +124,24 @@ export function buildNameTerms(character: CharacterRecord): string[] {
}
}
for (const alias of addRomanizedKanaAliases(withHonorifics)) {
withHonorifics.add(alias);
for (const suffix of HONORIFIC_SUFFIXES) {
withHonorifics.add(`${alias}${suffix.term}`);
}
}
return [...withHonorifics].filter((entry) => entry.trim().length > 0);
}
export function buildVisibleNameTerms(nameTerms: string[]): string[] {
const allTerms = new Set(nameTerms);
return nameTerms.filter((term) => {
for (const suffix of HONORIFIC_SUFFIXES) {
if (!term.endsWith(suffix.term) || term.length <= suffix.term.length) {
continue;
}
if (allTerms.has(term.slice(0, -suffix.term.length))) {
return false;
}
}
return true;
});
}
export function buildReadingForTerm(
term: string,
character: CharacterRecord,

Some files were not shown because too many files have changed in this diff Show More