mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-22 16:46:10 -08:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b6e589ab3
|
||
|
|
11da02e4e9
|
||
|
|
593c7cbc30
|
||
|
|
b7b9400aae
|
||
|
|
0ae70b4ab2 | ||
|
|
0c1865f4a6
|
||
|
|
6fd55053d4 | ||
|
|
0360270e81
|
||
|
|
a8e929eb26
|
||
|
|
b31ddce627 | ||
|
|
79e5535823
|
||
|
|
5140b5e9be
|
||
|
|
c2dac537da
|
No files matched your search
@@ -32,6 +32,9 @@ jobs:
|
||||
- name: Verify native mpv process launch
|
||||
run: bun test src/main/runtime/mpv-process.test.ts
|
||||
|
||||
- name: Verify mpv PID lookup and Windows tracker
|
||||
run: bun test src/window-trackers/mpv-process-id.test.ts src/window-trackers/windows-tracker.test.ts
|
||||
|
||||
- name: Verify POSIX launcher bootstrap
|
||||
run: bun test src/main/runtime/posix-launcher-bootstrap.test.ts
|
||||
|
||||
|
||||
@@ -1,5 +1,55 @@
|
||||
# Changelog
|
||||
|
||||
## v0.22.0 (2026-11-06)
|
||||
|
||||
### Added
|
||||
- **Plugins**:
|
||||
- JavaScript plugins load at startup from `<config dir>/plugins/<id>/` and are enabled under `plugins` in the config.
|
||||
- Plugins can react to playback and mined cards, add bindable actions, run programs, and show results in overlay panels or their own windows.
|
||||
- Example plugins cover AI line explanations (`ai-explain`), AnkiWeb sync (`anki-sync`), and show and episode tags on mined cards (`episode-tags`).
|
||||
- Plugin authors get a versioned API with standalone types.
|
||||
- **Subtitle Filters**: Remove text in parentheses, sound descriptions, speaker names, music notes, or custom regex matches from primary subtitles. Configure them in Settings under Behavior → Subtitle Filters.
|
||||
- **Controller Combos**: Controller actions can now be combos, such as holding `L1` and pressing D-pad right. Click **Learn** in `Alt+C`, then hold one button and press another.
|
||||
- **Controller Actions**: New bindings cover previous, next, replay, and play-next subtitle, hold-to-show secondary subtitle, and previous or next Yomitan entry. All are unbound by default and can be assigned in `Alt+C`.
|
||||
- **Controller Dialog Layouts**: The media timing review and duplicate card dialogs can now be used with a controller and show button hints while one is connected. Remap both layouts per controller in `Alt+C`.
|
||||
- **Controller Button Style**: Choose Xbox, Nintendo, or PlayStation button names per controller in `Alt+C`, or set a default with `controller.faceButtonLabels`.
|
||||
- **Controller Clash Warnings**: `Alt+C` now warns when two actions share the same input.
|
||||
- **Keyboard-Only Mode**:
|
||||
- Press `C` or use the new controller binding to move by character, reaching words split by the subtitle parser.
|
||||
- The new **Pause Video In Keyboard-Only Mode** setting pauses on entry and resumes on exit.
|
||||
- **Jimaku Auto-Open**: Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to pause and open Jimaku when a local video has no Japanese subtitle track. Reopening Jimaku after the video changes now refreshes the title and episode.
|
||||
|
||||
### Changed
|
||||
- **Stats Trends and Vocabulary**:
|
||||
- Trends adds a learning section, heatmap, title timeline, custom date ranges, and a page-wide title filter.
|
||||
- Vocabulary now has one searchable word table, known words by frequency band, a growth chart, and a full kanji view.
|
||||
- New word counts now count dictionary words, so a word's conjugations count once and totals are lower than before.
|
||||
- Stats now explains when streamed words or lines can't be mined.
|
||||
- **Bundled Hachidori**: Updated to upstream 0.4.0, adding every pitch accent in popup entries, per-kanji headword furigana, and Yomitan-style definition tags.
|
||||
- **Controller Behavior**: **Toggle MPV Pause** now works outside keyboard-only mode. Connected and disabled messages now follow your `ankiConnect.behavior.notificationType` setting.
|
||||
- **Dictionary Popup**: Turning keyboard-only mode off now also closes the popup.
|
||||
|
||||
### Fixed
|
||||
- **Controller Settings (`Alt+C`)**:
|
||||
- Remaps now apply right away, and Learn works on **(D-pad)** rows.
|
||||
- Clicking a row shows **Learn**, **Clear**, and **Reset** again.
|
||||
- The window previews your bindings until a press, then selects the pressed controller.
|
||||
- Button names are now correct on standard-layout controllers.
|
||||
- **Controller Input on macOS and Windows**: One press no longer runs its action twice. On macOS, buttons now work while mpv is in front.
|
||||
- **Dictionary Popup**: Keyboard and controller lookups now pause and resume playback reliably. Moving between words right after closing a popup no longer reopens it.
|
||||
- **Playback**: Reloading the current file no longer leaves playback paused. The "Overlay loading" message no longer sticks or turns into a false error when a playlist advances.
|
||||
- **Stats**:
|
||||
- The dashboard, Vocabulary tab, and sentence search load much faster on large databases, and Trends downloads far less data.
|
||||
- Trends now counts each finished episode once, and its Library totals match the selected range.
|
||||
- Word totals, readings, Hide Names, and rate charts are now accurate.
|
||||
- Date handling is now correct in time zones ahead of UTC.
|
||||
- **AniList**: Progress sync now adds a missing show to Watching, or Completed on the final episode, when the title matches exactly or is pinned. Entries marked Completed, Paused, Dropped, or Rewatching are still never changed.
|
||||
- **Anki Sentence Audio**: Generated sentence audio no longer overwrites Yomitan's word audio on default configs. If you relied on the old default, set `ankiConnect.fields.audio` to `ExpressionAudio`.
|
||||
- **AppImage**: Fixed "Service Crash" notifications on quit on Ubuntu 26.04 and newer.
|
||||
|
||||
### Docs
|
||||
- **Keyboard and Controller Reference**: Keyboard shortcuts now list the keyboard-only `C` key, and the configuration reference points to Controller support for default button actions.
|
||||
|
||||
## v0.21.1 (2026-10-26)
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -104,7 +104,7 @@ A stats dashboard tracks watch time, vocabulary growth, mining throughput, sessi
|
||||
</tr>
|
||||
<tr>
|
||||
<td><b>Plugins</b></td>
|
||||
<td>Load your own JavaScript at startup to react to playback, run timers, add key-bound actions, and show results in an overlay panel. The bundled example explains the current line with Codex. <a href="https://docs.subminer.moe/plugins">Plugin guide</a></td>
|
||||
<td>Load your own JavaScript at startup to react to playback, run timers, add key-bound actions, and show results in an overlay panel. Bundled examples explain the current line with Codex, sync Anki to AnkiWeb, and tag mined cards by episode. <a href="https://docs.subminer.moe/plugins">Plugin guide</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- The controller settings window (`Alt+C`) no longer edits a controller it cannot see. A newly opened window cannot see any controller until you press one of its buttons (browsers hide a pad from a new window until then); it used to show and edit the global defaults meanwhile, and its status could stay stuck on "No controllers detected". Now it shows the bindings of the controller the overlay is using (or the saved one), labelled as a preview, and Learn, Clear, Reset and the button style are locked until the press.
|
||||
- With several controllers connected, `Alt+C` now selects the one you just pressed, and Learn listens to that controller.
|
||||
@@ -1,5 +0,0 @@
|
||||
type: fixed
|
||||
area: anilist
|
||||
|
||||
- AniList progress sync now adds a show to your Watching list (or Completed on the final episode) when it is not on your list yet, instead of failing with "AniList update not possible". This only happens when the file title exactly matches an AniList title or the entry is pinned with the character dictionary override; loose matches still require adding the show yourself.
|
||||
- Entries marked Completed, Paused, Dropped, or Rewatching are still never changed.
|
||||
@@ -0,0 +1,7 @@
|
||||
type: fixed
|
||||
area: anilist
|
||||
|
||||
- Later seasons now resolve to the right AniList entry when the sequel chain contains split-season halves ("Part 2", "Cour 2"), specials, or movies. Mushoku Tensei S3, Re:ZERO S4, Dr. STONE S3, KonoSuba S3, and Attack on Titan S4 used to land one season short or on a movie.
|
||||
- An entry whose title names the season ("Season 3", "III", "第3期") is preferred over counting sequels.
|
||||
- Episodes past the first half of a split season update the second half's AniList entry at the right episode (episode 15 of an 11 + 12 season updates the second entry to episode 4).
|
||||
- Character dictionary AniList matches cached by older versions are re-resolved once.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: anki
|
||||
|
||||
- `ankiConnect.fields.audio` now defaults to `SentenceAudio` instead of `ExpressionAudio`, so generated sentence audio no longer overwrites Yomitan's word audio on default configs. `fields.wordAudio` still defaults to `ExpressionAudio`. If you relied on the old default, set `fields.audio` to `ExpressionAudio` explicitly.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: linux
|
||||
|
||||
- Fixed AppImage builds on Ubuntu 26.04+ (uutils coreutils) releasing their mount before Chromium child processes finished shutting down, which brought back "Service Crash" notifications on quit.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- Controller remaps made in `Alt+C` now apply right away; before, the overlay kept the old bindings until SubMiner restarted.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- `Alt+C` now warns when two controller actions share an input, as the dialog layouts already did. Both rows show "⚠ Same as …", including a button on the D-pad while a **(D-pad)** row under **Navigation** is still on, and a stick direction used by a stick action.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- `Alt+C` has a **Button Style** choice (Xbox, Nintendo or PlayStation), saved per controller. PlayStation is new: buttons and the review and duplicate card shortcuts show ╳ ○ □ △. `controller.faceButtonLabels` accepts `playstation` and stays the default for controllers without their own style.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: changed
|
||||
area: overlay
|
||||
|
||||
- Controller connected and controller-disabled messages are now regular notifications that follow `ankiConnect.behavior.notificationType` (overlay, system, both or none) instead of a separate pill in the corner of the overlay. Connected notices only appear when `controller.enabled` is on.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- Clicking a row in `Alt+C` shows its **Learn**, **Clear** and **Reset** buttons again. The panel opened but was squeezed to nothing once the list was taller than the window, so **Clear** (set a binding to None) could not be reached.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- The duplicate card (field grouping) dialog has a controller layout: the D-pad picks the original or new card, `A` continues and confirms the merge, `B` cancels or goes back from the preview, `X` turns "Delete duplicate" on or off, `Y` switches Compact / Full, and the D-pad scrolls the preview. Each control shows its shortcut, and the layout can be changed per controller in the new **Duplicate card (field grouping)** group of `Alt+C`.
|
||||
@@ -1,5 +0,0 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- Added a controller layout for the media timing review dialog covering every button, with L1 / R1 + D-pad combos for the clip start and end, and D-pad actions that repeat while held. Each button shows its controller shortcut while controller support is on, and the first press in a newly opened dialog already counts. The controller's usual actions pause while the dialog is open, including in the hidden subtitle overlay behind it.
|
||||
- Added `controller.faceButtonLabels` (`xbox` or `nintendo`) so fixed controller layouts and the `Alt+C` button names follow the letters printed on the pad. Use `nintendo` for controllers with A on the right and B at the bottom.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: changed
|
||||
area: overlay
|
||||
|
||||
- The controller's **Toggle MPV Pause** button now works without keyboard-only mode, so you can pause while just watching.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- The media timing review controller layout can now be changed in the new **Review media timing** group of `Alt+C`. Learn records a single button or a combo (hold one button, press another), any button can be a hold button, changes are saved per controller, rows warn about clashing inputs, and **Reset all** restores the default layout. The review's button hints follow your bindings.
|
||||
@@ -1,5 +0,0 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- Added a controller binding that shows the secondary subtitle only while a button is held (`controller.bindings.holdSecondarySub`). It is unbound by default; assign it with Learn in the `Alt+C` controller modal. It works with or without keyboard-only mode and does not change the saved secondary subtitle mode.
|
||||
- Added controller bindings to select the previous or next word entry in the open Yomitan popup (`controller.bindings.previousEntry` / `nextEntry`). Mine Card mines the selected entry. Both are unbound by default; assign them with Learn in the `Alt+C` controller modal.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- The `Alt+C` controller screen now shows the right button names for controllers that report the W3C standard layout (most Xbox, PlayStation, Switch and 8BitDo pads). Previously Select and Start showed as `L3` and `R3`, and the triggers as `Back` and `Start`. Bindings themselves were unaffected.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- New controller actions for subtitle lines, in the **Subtitles** group of `Alt+C`: **Previous Subtitle**, **Next Subtitle**, **Replay Subtitle** and **Play Next Subtitle**, matching `Shift+H`, `Shift+L`, `Ctrl+Shift+H` and `Ctrl+Shift+L`. They are unbound by default and work with or without keyboard-only mode.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: changed
|
||||
area: overlay
|
||||
|
||||
- With the Xbox **Button Style**, `Alt+C` names the face buttons `A`, `B`, `X` and `Y` instead of `A / Cross`, `B / Circle`, `X / Square` and `Y / Triangle`; PlayStation and Nintendo already showed their own names.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: docs
|
||||
area: overlay
|
||||
|
||||
- Listed the keyboard-only `C` key in Keyboard shortcuts, and pointed the configuration reference to Controller support for default button actions.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: changed
|
||||
area: dictionary
|
||||
|
||||
- Updated the bundled Hachidori to upstream 0.4.0 (d959a09), including every pitch accent in every popup entry, pitch drawn on the headword's reading, headword furigana split per kanji, and Yomitan-style definition tags.
|
||||
@@ -1,5 +0,0 @@
|
||||
type: added
|
||||
area: jimaku
|
||||
|
||||
- Added `jimaku.autoOpenWhenPrimarySubtitleMissing` (off by default). When a local video loads without a Japanese (primary-language) subtitle track, SubMiner pauses playback and opens the Jimaku modal; playback resumes when the modal closes.
|
||||
- Opening Jimaku while it is already open now reloads the title and episode if the video changed, instead of keeping the previous episode's search.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- Keyboard-only mode can move by character instead of by word: press `C`, or the new **Toggle Character Navigation** controller binding (unbound by default). The cursor box turns orange and covers one character, and a lookup searches from it, which reaches words the subtitle split cuts in two.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: added
|
||||
area: overlay
|
||||
|
||||
- New **Pause Video In Keyboard-Only Mode** setting (`subtitleStyle.autoPauseVideoOnKeyboardMode`, off by default): turning keyboard-only mode on, from the keyboard or a controller, pauses the video, and turning it off resumes it. A video that was already paused, or that you played or paused yourself in the meantime, is left as it is.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: changed
|
||||
area: overlay
|
||||
|
||||
- Turning keyboard-only mode off, from the keyboard or a controller, now also closes the dictionary popup.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- On macOS, controller buttons now work while mpv is in front: a press brings the overlay forward and runs that button's action, instead of doing nothing until you click the overlay.
|
||||
@@ -1,5 +0,0 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- On macOS and Windows, one controller press no longer runs its action twice, which cancelled out toggles like mpv pause.
|
||||
- On macOS, the press that brings the overlay forward from mpv no longer runs its action a second time.
|
||||
@@ -0,0 +1,6 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- mpv keys from `input.conf` (for example arrow keys bound to `sub-seek`) are no longer sent to a Yomitan popup that has already closed. The overlay decided whether the popup was open from a cached flag that could lag behind a close.
|
||||
- mpv keys no longer get dropped while the overlay reloads mpv's bindings after it regains focus.
|
||||
- With `--log-level debug`, the log names why the overlay kept an mpv-bound key instead of forwarding it.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: mpv-plugin
|
||||
|
||||
- Fixed the "Overlay loading" message staying on screen when mpv moves to the next file in a playlist, then turning into "Overlay did not become ready; check SubMiner logs" after 30 seconds even though the overlay was working. The overlay window is reused between files, so the plugin no longer restarts the loading message once the overlay has reported ready.
|
||||
@@ -1,9 +0,0 @@
|
||||
type: added
|
||||
area: plugins
|
||||
|
||||
- Added JavaScript plugins loaded at startup from `<config dir>/plugins/<id>/` and enabled under `plugins` in the config. Plugins can listen to mpv events, run timers, register actions bound with `__plugin-action:<id>/<action>` keybindings or run with `--plugin-action`, run built-in actions, react to mined Anki cards and call AnkiConnect, start mpv, run programs, keep state in a per-plugin data folder, and show results in an overlay panel or their own window.
|
||||
- Added an example `ai-explain` plugin that sends the current line and its neighbors to `codex exec` and shows a translation or grammar explanation.
|
||||
- Added an example `anki-sync` plugin that syncs Anki to AnkiWeb after you mine cards, once mining goes quiet or playback ends.
|
||||
- Added an example `episode-tags` plugin that tags mined cards with the show and episode, such as `show::Frieren::S01E07`.
|
||||
- Added a versioned plugin API with standalone authoring types, cached playback snapshots, lifecycle cancellation and cleanup, and awaitable mpv commands. Async activation is bounded and actions wait only for their own plugin. Shutdown skips pending loads, runs each deactivation once, and blocks calls from disposed plugins.
|
||||
- Mining events preserve original and kept note ids with the media and subtitle captured when mining starts, so delayed enrichment and merges into older notes keep the source episode. Stats-dashboard cards do not trigger plugin events. Plugin subtitle lookups and mining provenance account for subtitle delay and return timing on the subtitle file's timeline.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- Fixed controller and keyboard lookups sometimes pausing playback without a popup, leaving playback paused after the popup closed until the mouse moved, or not pausing when the popup opened.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- Moving between words with the keyboard or a controller right after closing the dictionary popup no longer reopens it. A popup that closed under the mouse pointer was still treated as open.
|
||||
@@ -1,4 +0,0 @@
|
||||
type: fixed
|
||||
area: playback
|
||||
|
||||
- Reloading the same file in mpv (`loadfile <current path> replace`) could intermittently leave playback paused forever. SubMiner now treats that reload like any other newly loaded file, so it resets the subtitle state and resumes once the file is ready.
|
||||
@@ -1,8 +0,0 @@
|
||||
type: fixed
|
||||
area: stats
|
||||
|
||||
- The stats dashboard loads much faster on large databases. Overview, media and library detail, and trends no longer re-count every recorded word in the whole database on each request, so these views only cost as much as the sessions they show. On a ~1 GB database the overview went from ~1.4 s to ~0.14 s, media detail from ~1.5 s to ~0.08 s, the 30-day trends from ~1.5 s to ~0.06 s, and all-time trends from ~1.6 s to ~0.2 s.
|
||||
- The Vocabulary tab's summary and word list load several times faster (summary ~2 s to ~0.2 s, word list ~0.6 s to ~0.2 s).
|
||||
- The Trends tab downloads far less data: the per-title library charts now arrive as daily values and are totalled in the dashboard, so the all-time response shrank from ~3.9 MB to ~0.2 MB.
|
||||
- Sentence search with headword matching returns several times faster (~0.3 s to ~0.08 s per query).
|
||||
- Vocabulary totals and new-word charts stay correct after running vocabulary cleanup. Words it repaired could be counted or hidden by mistake; the first launch after updating corrects them in the background.
|
||||
@@ -1,15 +0,0 @@
|
||||
type: changed
|
||||
area: stats
|
||||
|
||||
- Rebuilt the Trends tab: summary totals with period comparison, a Learning section (new words per 1,000 seen, new words by frequency rank), a day and hour heatmap, a title timeline, and a single running-total chart with a metric switcher that climbs from zero. These replace the seven cumulative charts, the Sessions chart, the day-of-week and hour charts, the four overlapping per-title charts, and the top titles chart.
|
||||
- Added week grouping, custom date ranges, a title filter for the whole page, and click-through from charts to sessions and from titles to their library page. Range and grouping are remembered, and changing them no longer blanks the page or loses your scroll position.
|
||||
- Fixed the Library section including days outside the selected range, so its totals now match Activity.
|
||||
- Fixed episode counts: Trends now counts finished episodes, each once, instead of counting a video again for every day it was opened.
|
||||
- New word counts across Trends and Vocabulary now count dictionary words, so a word's conjugations count once. Totals are lower than before.
|
||||
- Rate charts no longer plot idle days as zero or spike on very short days: they show gaps when there is too little data, and daily views use a rolling 7 days.
|
||||
- Fixed clipped chart axis labels and month labels that read like dates, and the All range ignoring Show empty days.
|
||||
- Rebuilt the Vocabulary tab: one word table with Worth mining, All words, Across titles, and Newest views, search across every word, form, and reading, sortable columns, and inline Hide. It replaces three lists that could only see your 500 most seen word forms. Also added known words by frequency band, a vocabulary growth chart, and a kanji view covering every kanji, with a filter for kanji outside your known words.
|
||||
- Fixed word counts and readings: lists and the word detail panel now total every form of a word and show the dictionary form's reading, so 見る no longer shows みてる. The detail panel loads example lines straight away and lists a word's forms.
|
||||
- Fixed names slipping past Hide Names and the Trends new-word counts when tagged with more than one part of speech.
|
||||
- Stats now says when a word or line can't be mined because it came from a stream, in Search and the word panel, instead of showing Unavailable buttons. Lines you can mine are listed first. The word panel counts affected lines, and the word table marks words with only streamed lines as Stream only.
|
||||
- Fixed stats treating the day as one earlier in time zones ahead of UTC, which affected today's totals, the custom date picker, and first-seen dates.
|
||||
@@ -1,5 +0,0 @@
|
||||
type: added
|
||||
area: subtitles
|
||||
|
||||
- Added subtitle filters (`subtitleFilter`) that remove unwanted text from primary subtitles before it reaches the overlay, sidebar, mined sentences and stats. Built-in presets cover text in parentheses (speaker names, readings, notes; whole-line inner thoughts are kept), square-bracket sound descriptions, speaker names before a colon, and music notes. Custom regex rules with a replacement can be added after the presets. Lines left with no words are hidden.
|
||||
- Configure them in the settings window under Behavior → Subtitle Filters; changes apply live to the current subtitle file.
|
||||
@@ -0,0 +1,4 @@
|
||||
type: docs
|
||||
area: overlay
|
||||
|
||||
- Explain how to collect and interpret Windows overlay attachment and readiness warnings without enabling debug logging.
|
||||
@@ -0,0 +1,6 @@
|
||||
type: fixed
|
||||
area: overlay
|
||||
|
||||
- Windows overlay attachment now identifies mpv through its IPC process ID, removing the dependency on PowerShell command-line lookups and allowing the IPC socket to be configured in `mpv.conf`.
|
||||
- Revalidate cached Windows mpv process IDs and expire them after sustained IPC failures so PID reuse cannot keep the overlay attached to an unrelated window.
|
||||
- Diagnose stalled Windows overlays at the default warn log level, including tracking/PID state, renderer readiness, opacity, native binding errors, and recovery, with repeated warnings rate limited.
|
||||
+17
-22
@@ -128,62 +128,62 @@
|
||||
"toggleLookup": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 0 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"closeLookup": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 1 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"toggleKeyboardOnlyMode": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 3 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"mineCard": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 2 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"quitMpv": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 6 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"previousAudio": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"nextAudio": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 5 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"playCurrentAudio": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 4 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"toggleMpvPause": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 9 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"holdSecondarySub": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"previousEntry": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"nextEntry": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"toggleCharacterNavigation": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"previousSubtitle": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"nextSubtitle": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"replaySubtitle": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"playNextSubtitle": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"leftStickHorizontal": {
|
||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||
"axisIndex": 0, // Raw axis index captured for this analog controller action.
|
||||
@@ -194,11 +194,6 @@
|
||||
"axisIndex": 1, // Raw axis index captured for this analog controller action.
|
||||
"dpadFallback": "vertical" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
||||
}, // Axis binding descriptor used for primary popup scrolling. Use Alt+C learn mode or set a raw axis descriptor manually.
|
||||
"rightStickHorizontal": {
|
||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||
"axisIndex": 3, // Raw axis index captured for this analog controller action.
|
||||
"dpadFallback": "none" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
||||
}, // Axis binding descriptor reserved for alternate right-stick mappings. Use Alt+C learn mode or set a raw axis descriptor manually.
|
||||
"rightStickVertical": {
|
||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||
"axisIndex": 4, // Raw axis index captured for this analog controller action.
|
||||
|
||||
@@ -26,8 +26,8 @@ On Linux, the token is stored with `gnome-libsecret` by default. If your keyring
|
||||
An episode counts as watched after 85% of its length and at least 10 minutes of playback. SubMiner then:
|
||||
|
||||
1. Reads the title, season, and episode from the file name and folder. Install [guessit](https://github.com/guessit-io/guessit) for better parsing. A folder named `Season 2` is a strong season hint.
|
||||
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels.
|
||||
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode.
|
||||
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels. Specials, movies, and the second half of a split season ("Part 2", "Cour 2") do not count as seasons, and an entry whose title names the season ("Season 3", "III") wins.
|
||||
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode. AniList lists the second half of a split season as its own entry, so an episode past the first half goes there: episode 15 of a season split 11 + 12 is episode 4 of the second entry.
|
||||
|
||||
If the show is not on your list yet, SubMiner adds it as Watching, but only when the file title exactly matches an AniList title or you pinned the entry with the character dictionary's AniList override. For a looser match, add the show to Planning or Watching yourself. SubMiner never changes entries marked Completed, Paused, Dropped, or Rewatching, and it never lowers your progress.
|
||||
|
||||
@@ -37,7 +37,9 @@ Failed updates are saved and retried in the background, up to 8 times with growi
|
||||
|
||||
If a cover or title in the stats Library is wrong, open the title and use **Change AniList Entry**.
|
||||
|
||||
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary).
|
||||
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary). The override is also the fix when AniList splits a season without marking the second half in any title.
|
||||
|
||||
Library entries matched by older versions keep their match after an update. If one points at the wrong season, use **Change AniList Entry**.
|
||||
|
||||
## Commands
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@ When you cancel, you can go back to editing, keep the original timing, create th
|
||||
|
||||
#### With a controller
|
||||
|
||||
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each button shows its controller shortcut. It works with or without keyboard-only mode, and the controller's usual actions pause until the dialog closes. Buttons that were already held when the dialog opened, such as the mine button, wait for a fresh press.
|
||||
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each button shows its controller shortcut once SubMiner has seen a controller, which takes one button press after connecting it. It works with or without keyboard-only mode, and the controller's usual actions pause until the dialog closes. Buttons that were already held when the dialog opened, such as the mine button, wait for a fresh press.
|
||||
|
||||
`A`, `B`, `X` and `Y` mean the letters printed on your controller. Pick your controller's **Button Style** in `Alt+C`: choose Nintendo if A is on the right and B at the bottom (Switch-style and many 8BitDo pads). On PlayStation, `A` is ╳, `B` ○, `X` □ and `Y` △, and the shortcuts on screen show those symbols.
|
||||
|
||||
@@ -267,7 +267,7 @@ The manual dialog cancels itself after 90 seconds. Identical entries are not ded
|
||||
|
||||
### With a controller {#field-grouping-with-a-controller}
|
||||
|
||||
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each control shows its controller shortcut. Like the [media timing review](#with-a-controller), it works with or without keyboard-only mode, `A`/`B`/`X`/`Y` are the printed letters (set by **Button Style** in `Alt+C`), and a button already held when the dialog opens waits for a fresh press.
|
||||
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each control shows its controller shortcut once SubMiner has seen a controller. Like the [media timing review](#with-a-controller), it works with or without keyboard-only mode, `A`/`B`/`X`/`Y` are the printed letters (set by **Button Style** in `Alt+C`), and a button already held when the dialog opens waits for a fresh press.
|
||||
|
||||
| Controller | Choosing the card | Merge preview |
|
||||
| ------------------ | --------------------------------- | ----------------------- |
|
||||
|
||||
+58
-3
@@ -1,6 +1,61 @@
|
||||
# Changelog
|
||||
|
||||
## v0.21.1 (2026-10-26)
|
||||
## v0.22.0 (2026-11-06)
|
||||
|
||||
**Added**
|
||||
- **Plugins**:
|
||||
- JavaScript plugins load at startup from `<config dir>/plugins/<id>/` and are enabled under `plugins` in the config.
|
||||
- Plugins can react to playback and mined cards, add bindable actions, run programs, and show results in overlay panels or their own windows.
|
||||
- Example plugins cover AI line explanations (`ai-explain`), AnkiWeb sync (`anki-sync`), and show and episode tags on mined cards (`episode-tags`).
|
||||
- Plugin authors get a versioned API with standalone types.
|
||||
- **Subtitle Filters**: Remove text in parentheses, sound descriptions, speaker names, music notes, or custom regex matches from primary subtitles. Configure them in Settings under Behavior → Subtitle Filters.
|
||||
- **Controller Combos**: Controller actions can now be combos, such as holding `L1` and pressing D-pad right. Click **Learn** in `Alt+C`, then hold one button and press another.
|
||||
- **Controller Actions**: New bindings cover previous, next, replay, and play-next subtitle, hold-to-show secondary subtitle, and previous or next Yomitan entry. All are unbound by default and can be assigned in `Alt+C`.
|
||||
- **Controller Dialog Layouts**: The media timing review and duplicate card dialogs can now be used with a controller and show button hints while one is connected. Remap both layouts per controller in `Alt+C`.
|
||||
- **Controller Button Style**: Choose Xbox, Nintendo, or PlayStation button names per controller in `Alt+C`, or set a default with `controller.faceButtonLabels`.
|
||||
- **Controller Clash Warnings**: `Alt+C` now warns when two actions share the same input.
|
||||
- **Keyboard-Only Mode**:
|
||||
- Press `C` or use the new controller binding to move by character, reaching words split by the subtitle parser.
|
||||
- The new **Pause Video In Keyboard-Only Mode** setting pauses on entry and resumes on exit.
|
||||
- **Jimaku Auto-Open**: Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to pause and open Jimaku when a local video has no Japanese subtitle track. Reopening Jimaku after the video changes now refreshes the title and episode.
|
||||
|
||||
**Changed**
|
||||
- **Stats Trends and Vocabulary**:
|
||||
- Trends adds a learning section, heatmap, title timeline, custom date ranges, and a page-wide title filter.
|
||||
- Vocabulary now has one searchable word table, known words by frequency band, a growth chart, and a full kanji view.
|
||||
- New word counts now count dictionary words, so a word's conjugations count once and totals are lower than before.
|
||||
- Stats now explains when streamed words or lines can't be mined.
|
||||
- **Bundled Hachidori**: Updated to upstream 0.4.0, adding every pitch accent in popup entries, per-kanji headword furigana, and Yomitan-style definition tags.
|
||||
- **Controller Behavior**: **Toggle MPV Pause** now works outside keyboard-only mode. Connected and disabled messages now follow your `ankiConnect.behavior.notificationType` setting.
|
||||
- **Dictionary Popup**: Turning keyboard-only mode off now also closes the popup.
|
||||
|
||||
**Fixed**
|
||||
- **Controller Settings (`Alt+C`)**:
|
||||
- Remaps now apply right away, and Learn works on **(D-pad)** rows.
|
||||
- Clicking a row shows **Learn**, **Clear**, and **Reset** again.
|
||||
- The window previews your bindings until a press, then selects the pressed controller.
|
||||
- Button names are now correct on standard-layout controllers.
|
||||
- **Controller Input on macOS and Windows**: One press no longer runs its action twice. On macOS, buttons now work while mpv is in front.
|
||||
- **Dictionary Popup**: Keyboard and controller lookups now pause and resume playback reliably. Moving between words right after closing a popup no longer reopens it.
|
||||
- **Playback**: Reloading the current file no longer leaves playback paused. The "Overlay loading" message no longer sticks or turns into a false error when a playlist advances.
|
||||
- **Stats**:
|
||||
- The dashboard, Vocabulary tab, and sentence search load much faster on large databases, and Trends downloads far less data.
|
||||
- Trends now counts each finished episode once, and its Library totals match the selected range.
|
||||
- Word totals, readings, Hide Names, and rate charts are now accurate.
|
||||
- Date handling is now correct in time zones ahead of UTC.
|
||||
- **AniList**: Progress sync now adds a missing show to Watching, or Completed on the final episode, when the title matches exactly or is pinned. Entries marked Completed, Paused, Dropped, or Rewatching are still never changed.
|
||||
- **Anki Sentence Audio**: Generated sentence audio no longer overwrites Yomitan's word audio on default configs. If you relied on the old default, set `ankiConnect.fields.audio` to `ExpressionAudio`.
|
||||
- **AppImage**: Fixed "Service Crash" notifications on quit on Ubuntu 26.04 and newer.
|
||||
|
||||
**Docs**
|
||||
- **Keyboard and Controller Reference**: Keyboard shortcuts now list the keyboard-only `C` key, and the configuration reference points to Controller support for default button actions.
|
||||
|
||||
## Previous Versions
|
||||
|
||||
<details>
|
||||
<summary>v0.21.x</summary>
|
||||
|
||||
<h2>v0.21.1 (2026-10-26)</h2>
|
||||
|
||||
**Changed**
|
||||
- **Stats Session View**: Redesigned the expanded session view in the stats dashboard.
|
||||
@@ -23,7 +78,7 @@
|
||||
|
||||
</details>
|
||||
|
||||
## v0.21.0 (2026-10-24)
|
||||
<h2>v0.21.0 (2026-10-24)</h2>
|
||||
|
||||
**Added**
|
||||
- **Hachidori Dictionary Backend**:
|
||||
@@ -68,7 +123,7 @@
|
||||
|
||||
</details>
|
||||
|
||||
## Previous Versions
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>v0.20.x</summary>
|
||||
|
||||
@@ -329,7 +329,11 @@ Gamepad input for the overlay, through the browser Gamepad API. Most actions onl
|
||||
| `controller.repeatDelayMs` | `320` | Delay before a held button repeats |
|
||||
| `controller.repeatIntervalMs` | `120` | Repeat interval for held buttons |
|
||||
|
||||
Bindings, including the media timing review and duplicate card dialog layouts, are set with `Alt+C` learn mode, which saves them per controller.
|
||||
Bindings, including the media timing review and duplicate card dialog layouts, are set with `Alt+C` learn mode, which saves them per controller. Learn can also record a [combo](/usage#controller-support), saved on the binding as an optional `hold` input in the same form:
|
||||
|
||||
```jsonc
|
||||
"nextAudio": { "kind": "button", "buttonIndex": 15, "hold": { "kind": "button", "buttonIndex": 4 } }
|
||||
```
|
||||
|
||||
## Anki integration
|
||||
|
||||
|
||||
@@ -128,62 +128,62 @@
|
||||
"toggleLookup": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 0 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"closeLookup": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 1 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"toggleKeyboardOnlyMode": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 3 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"mineCard": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 2 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"quitMpv": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 6 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"previousAudio": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"nextAudio": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 5 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"playCurrentAudio": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 4 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"toggleMpvPause": {
|
||||
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
"buttonIndex": 9 // Raw button index captured for this discrete controller action.
|
||||
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"holdSecondarySub": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"previousEntry": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"nextEntry": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"toggleCharacterNavigation": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"previousSubtitle": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"nextSubtitle": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"replaySubtitle": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"playNextSubtitle": {
|
||||
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
|
||||
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
|
||||
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
|
||||
"leftStickHorizontal": {
|
||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||
"axisIndex": 0, // Raw axis index captured for this analog controller action.
|
||||
@@ -194,11 +194,6 @@
|
||||
"axisIndex": 1, // Raw axis index captured for this analog controller action.
|
||||
"dpadFallback": "vertical" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
||||
}, // Axis binding descriptor used for primary popup scrolling. Use Alt+C learn mode or set a raw axis descriptor manually.
|
||||
"rightStickHorizontal": {
|
||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||
"axisIndex": 3, // Raw axis index captured for this analog controller action.
|
||||
"dpadFallback": "none" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
|
||||
}, // Axis binding descriptor reserved for alternate right-stick mappings. Use Alt+C learn mode or set a raw axis descriptor manually.
|
||||
"rightStickVertical": {
|
||||
"kind": "axis", // Analog binding input source kind. Values: none | axis
|
||||
"axisIndex": 4, // Raw axis index captured for this analog controller action.
|
||||
|
||||
@@ -51,6 +51,17 @@ When `connect ENOENT /tmp/subminer-socket` follows a cast in the app log, SubMin
|
||||
- Confirm SubMiner is running (`SubMiner.AppImage --start`, or check for the process).
|
||||
- Linux: Hyprland and Sway work natively. Any other compositor needs mpv and SubMiner under X11 or Xwayland, with `xdotool`, `xprop`, and `xwininfo` installed. See [KDE Plasma and other Wayland compositors](#kde-plasma-and-other-wayland-compositors).
|
||||
- macOS: grant Accessibility permission. See [macOS](#macos).
|
||||
- Windows: leave the affected mpv window open for at least five seconds, then collect the daily
|
||||
app log from the directory above. No debug setting is required: a stalled overlay logs
|
||||
`Windows overlay is not visible after startup or tracking loss` with its PID, native window
|
||||
handle, tracking state, geometry, opacity, and renderer readiness. The `reason` distinguishes
|
||||
a missing mpv window, an unready renderer, a hidden window, and a transparent window.
|
||||
This warning waits until mpv has answered on its IPC socket, so a requested overlay with no
|
||||
mpv running stays quiet. PID lookup failures and native ownership or transparency errors also
|
||||
appear at `warn`, and a PID lookup failure is the only trace if mpv never answers.
|
||||
Repeated visibility/native-operation warnings are limited to one every 30 seconds; recovery
|
||||
is recorded too. These logs diagnose attachment and readiness, but cannot prove that pixels
|
||||
were drawn correctly by the graphics driver.
|
||||
|
||||
## Overlay is on the wrong monitor or position
|
||||
|
||||
@@ -179,6 +190,10 @@ Another app or your desktop already uses `Alt+Shift+Y` (Yomitan settings). Free
|
||||
|
||||
Overlay shortcuts only work while the overlay has focus. Click the overlay, or press `Alt+Shift+O` with mpv or the overlay focused.
|
||||
|
||||
## An mpv key does nothing over the overlay
|
||||
|
||||
Keys from `input.conf` reach mpv through the overlay only in some cases (see [automatic mpv bindings](/shortcuts#automatic-mpv-bindings)). Run with `--log-level debug` and press the key: an `Overlay kept an mpv-bound key` line names the reason. To make a key work everywhere, add it to [`keybindings`](/configuration#keybindings) instead.
|
||||
|
||||
## Update checks
|
||||
|
||||
**"Update check failed"**: GitHub could not be reached. Check your connection and retry from the tray menu or with `subminer -u`.
|
||||
|
||||
+3
-1
@@ -164,7 +164,9 @@ You can drive the overlay with a gamepad.
|
||||
3. Press `Y` on the controller to turn on keyboard-only mode. Most controller actions only work in this mode.
|
||||
4. Move between words with the left stick, press `A` to look one up, and `X` to mine it.
|
||||
|
||||
Press `Alt+C` to choose a controller and remap buttons. Click an action's **Learn** button, then press the button you want. Set **Button Style** to Xbox, Nintendo or PlayStation so buttons are named as printed on your controller; it is saved per controller. Changes apply right away. When two actions share an input, both fire, so their rows show a ⚠ warning naming the other action; this includes a button on the D-pad while a **(D-pad)** row under **Navigation** is still on, and a stick direction used by a stick action. The window only sees a controller after you press one of its buttons; until then it shows the bindings of the controller in use as a preview, and editing stays locked. With several controllers connected, it selects the one you pressed last. `Alt+Shift+C` shows raw input values for unusual pads.
|
||||
Press `Alt+C` to choose a controller and remap buttons. Click an action's **Learn** button, then press the button you want, or hold one button and press another to make a combo such as `L1` + D-pad right. Set **Button Style** to Xbox, Nintendo or PlayStation so buttons are named as printed on your controller; it is saved per controller. Changes apply right away. When two actions share an input, both fire, so their rows show a ⚠ warning naming the other action; this includes a button on the D-pad while a **(D-pad)** row under **Navigation** is still on, and a stick direction used by a stick action. The window only sees a controller after you press one of its buttons; until then it shows the bindings of the controller in use as a preview, and editing stays locked. With several controllers connected, it selects the one you pressed last. `Alt+Shift+C` shows raw input values for unusual pads.
|
||||
|
||||
A combo fires each time you press its second button while the first is down, so holding `L1` and pressing right twice runs it twice. While a combo's hold button is down, other buttons only run combos that use it, and its press no longer drives a **(D-pad)** or stick row. A hold button can keep its own action: that action then runs when you let go, unless you pressed another bound button during the hold. The exception is **Show Secondary Subtitle (Hold)**, which can't wait for release, so its row warns if it shares a hold button.
|
||||
|
||||
| Button | Action |
|
||||
| --------------------- | -------------------------------------- |
|
||||
|
||||
@@ -27,6 +27,16 @@ Read when: you need to find the owner module for a behavior or test surface
|
||||
subtitle suppression while the overlay shows, and the overlay-window IPC handlers (modal
|
||||
open/close, pointer interaction, content measurement): `src/main/assemblies/overlay.ts`
|
||||
Overlay-hosted modal openers: `src/main/assemblies/overlay-modals.ts`
|
||||
Windows window tracking: `src/window-trackers/windows-tracker.ts` queries the target mpv IPC
|
||||
socket for its PID through `mpv-process-id.ts`, then `win32.ts` matches native windows by PID.
|
||||
Visible matches are revalidated every 10 seconds; a PID expires after 30 seconds without a
|
||||
successful IPC response. Missing windows retry at one-second intervals. Custom executable
|
||||
names remain supported because matching uses the IPC PID.
|
||||
`src/core/services/overlay-visibility-diagnostics.ts` watches requested Windows overlays:
|
||||
after five seconds hidden or transparent it logs a warn-level snapshot, repeating at most
|
||||
every 30 seconds. Intentional hiding, minimization and having no mpv answer on the socket
|
||||
yet suppress these warnings; an identified mpv whose window never matches does not. PID lookup
|
||||
failures and native ownership/transparency failures also log at warn, including recovery.
|
||||
- MPV runtime and protocol: `src/core/services/mpv*.ts`
|
||||
mpv client creation, mpv event wiring, AniSkip, the autoplay-ready gate that releases mpv's
|
||||
startup pause, managed local subtitle selection, subtitle prefetch, and subtitle sidebar state:
|
||||
@@ -57,7 +67,7 @@ Read when: you need to find the owner module for a behavior or test surface
|
||||
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
|
||||
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
|
||||
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
|
||||
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`
|
||||
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`. Every consumer maps a parsed title + season to an AniList entry through `anilist/season-resolver.ts` (sequel-chain walk; see its header for what counts as a season). Changing what it returns needs a `MEDIA_RESOLUTION_CACHE_VERSION` bump in `character-dictionary-runtime/cache.ts`, or old matches keep being served from `anilist-resolution-cache.json`.
|
||||
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
|
||||
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
|
||||
assembled by `src/main/assemblies/jellyfin.ts`
|
||||
|
||||
@@ -114,6 +114,45 @@ test(
|
||||
},
|
||||
);
|
||||
|
||||
// The other tests read the renderer over CDP, which works even if the window never appears.
|
||||
// Windows keeps the overlay hidden until the tracker identifies mpv's window.
|
||||
// Bun's node:test ignores the `skip` option, so this picks `test.skip` instead.
|
||||
const testOnWindows = process.platform === 'win32' ? test : test.skip;
|
||||
testOnWindows('visible overlay window appears over mpv', { timeout: TEST_TIMEOUT_MS }, async () => {
|
||||
const { session } = await useSession();
|
||||
await session.runAppCommand('--show-visible-overlay');
|
||||
const mpvPid = await session.mpv.command('get_property', 'pid');
|
||||
assert.equal(typeof mpvPid, 'number');
|
||||
const main = await session.mainProcess();
|
||||
await waitUntil(
|
||||
() =>
|
||||
main.evaluate<boolean>(
|
||||
`(() => {
|
||||
const electron = process.mainModule.require('electron');
|
||||
const overlay = electron.BrowserWindow.getAllWindows().find(
|
||||
(w) => w.webContents.getURL().includes(${JSON.stringify(OVERLAY_PAGE)}));
|
||||
if (!overlay?.isVisible() || overlay.getOpacity() !== 1 ||
|
||||
overlay.__subminerOverlayContentReady !== true) return false;
|
||||
// The inspector's mainModule can be Electron's bootstrap module. Resolve app
|
||||
// dependencies from the repository instead of that module's search paths.
|
||||
const appRequire = process.mainModule.require('node:module').createRequire(
|
||||
process.mainModule.require('node:path').resolve('package.json'));
|
||||
const koffi = appRequire('koffi');
|
||||
const getWindow = koffi.load('user32.dll').func(
|
||||
'intptr __stdcall GetWindow(intptr hwnd, uint uCmd)');
|
||||
const handle = overlay.getNativeWindowHandle();
|
||||
const hwnd = handle.length >= 8 ? Number(handle.readBigUInt64LE(0)) : handle.readUInt32LE(0);
|
||||
const owner = getWindow(hwnd, 4); // GW_OWNER
|
||||
const win32 = appRequire(
|
||||
process.mainModule.require('node:path').resolve('dist/window-trackers/win32.js'));
|
||||
return win32.findMpvWindows(${JSON.stringify(mpvPid)}).matches.some(
|
||||
(match) => match.hwnd === owner);
|
||||
})()`,
|
||||
),
|
||||
{ description: 'the visible overlay to be fully revealed and owned by the target mpv window' },
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'seeking to another cue replaces the line and deinflects verbs to their headword',
|
||||
{ timeout: TEST_TIMEOUT_MS },
|
||||
@@ -331,6 +370,35 @@ testOutsideLinux(
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'controller combos survive the real save path and can be rebound to one button',
|
||||
{ timeout: TEST_TIMEOUT_MS },
|
||||
async () => {
|
||||
const { overlay } = await useSession();
|
||||
const L1 = { kind: 'button', buttonIndex: 4 };
|
||||
const DPAD_LEFT = { kind: 'button', buttonIndex: 14 };
|
||||
const DPAD_RIGHT = { kind: 'button', buttonIndex: 15 };
|
||||
const save = (bindings: Record<string, unknown>) =>
|
||||
overlay.evaluate<Record<string, unknown>>(
|
||||
`(async () => {
|
||||
await window.electronAPI.saveControllerConfig(${JSON.stringify({ bindings })});
|
||||
return (await window.electronAPI.getControllerConfig()).bindings;
|
||||
})()`,
|
||||
);
|
||||
|
||||
await save({ previousEntry: { ...DPAD_LEFT, hold: L1 } });
|
||||
const bothCombos = await save({ nextEntry: { ...DPAD_RIGHT, hold: L1 } });
|
||||
assert.deepEqual(bothCombos.previousEntry, { ...DPAD_LEFT, hold: L1 });
|
||||
assert.deepEqual(bothCombos.nextEntry, { ...DPAD_RIGHT, hold: L1 });
|
||||
|
||||
const rebound = await save({ previousEntry: DPAD_LEFT, nextEntry: { kind: 'none' } });
|
||||
assert.deepEqual(rebound.previousEntry, DPAD_LEFT);
|
||||
assert.deepEqual(rebound.nextEntry, { kind: 'none' });
|
||||
|
||||
await save({ previousEntry: { kind: 'none' } });
|
||||
},
|
||||
);
|
||||
|
||||
// Runs last: it leaves the lookup popup open over the overlay.
|
||||
test(
|
||||
'holding Shift over a word opens the Yomitan popup with its dictionary entry',
|
||||
|
||||
@@ -543,8 +543,10 @@ test('launchAppBackgroundDetached starts background child directly', async () =>
|
||||
|
||||
launchAppBackgroundDetached(appPath, 'info');
|
||||
|
||||
// The shell creates each file before writing to it, so wait for content, not existence.
|
||||
const hasContent = (file: string) => fs.existsSync(file) && fs.statSync(file).size > 0;
|
||||
const deadline = Date.now() + 1000;
|
||||
while ((!fs.existsSync(argsPath) || !fs.existsSync(envPath)) && Date.now() < deadline) {
|
||||
while ((!hasContent(argsPath) || !hasContent(envPath)) && Date.now() < deadline) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "subminer",
|
||||
"productName": "SubMiner",
|
||||
"desktopName": "SubMiner.desktop",
|
||||
"version": "0.21.1",
|
||||
"version": "0.22.1-beta.1",
|
||||
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
|
||||
"packageManager": "bun@1.3.5",
|
||||
"main": "dist/main-entry.js",
|
||||
|
||||
@@ -1,88 +1,21 @@
|
||||
> This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release.
|
||||
|
||||
<!-- prerelease-version: 0.20.1-beta.2; since: v0.20.1-beta.1 -->
|
||||
|
||||
## Changes since v0.20.1-beta.1
|
||||
|
||||
- Upgraded the desktop runtime to Electron 43.7.7.
|
||||
- SubMiner now refuses to start on an unsupported Electron runtime, or after an Electron major or minor downgrade, so your Yomitan profile data stays safe; patch downgrades are still allowed.
|
||||
- Automatic character-dictionary updates now stop if a Yomitan profile that had dictionaries suddenly reports none.
|
||||
- Development launches now use a separate `SubMiner-dev` profile unless you explicitly ask for the production profile.
|
||||
- Sentence mining (single and multi-line) no longer counts each card twice in session and lifetime stats.
|
||||
- Deleting sessions now updates word and kanji "first seen" and "last seen" dates correctly, and retention pruning keeps historical discovery dates and counts.
|
||||
- Words hidden by the vocabulary filter are no longer counted in the new-words charts, so the charts now match the vocabulary summary.
|
||||
- A one-time background repair on next launch fixes stale "last seen" dates and existing chart mismatches.
|
||||
- Overview totals, charts, the activity calendar, and the vocabulary summary now refresh after you delete sessions, and a failed refresh keeps the dashboard visible with a retry option.
|
||||
- Subtitle generation now works during Windows YouTube playback and loads the generated subtitles into the playing video.
|
||||
- On Windows, moving on to a video queued from the YouTube browser window no longer drops the rest of mpv's queue.
|
||||
- The stats docs now cover the automatic Overview refresh after deletions and how discovery dates are kept through retention pruning.
|
||||
<!-- prerelease-version: 0.22.1-beta.1 -->
|
||||
|
||||
## Highlights
|
||||
### Added
|
||||
|
||||
- **YouTube Browser Window**:
|
||||
- Open it with `subminer youtube` (or `subminer yt`), or pick **Browse YouTube** from the tray. It stays logged in across restarts.
|
||||
- Clicking a video plays it in mpv. Middle-click, Shift-click, Ctrl-click, or the right-click menu adds it to mpv's playlist.
|
||||
- Queued videos get the same Japanese subtitle setup when they start.
|
||||
- Closing the window quits SubMiner if you started it with `subminer youtube`. If a video is still playing, SubMiner waits until mpv closes.
|
||||
- **Whisper Subtitles for YouTube**:
|
||||
- Set `youtube.subtitleSource` to `whisper` to make subtitles with Whisper instead of downloading YouTube's captions.
|
||||
- The video stays paused while Whisper works, and progress shows in the subtitle generation modal. You can close the modal to keep watching, or cancel.
|
||||
- The subtitle generation modal (`Ctrl+Shift+G`) now works on YouTube videos, including on Windows.
|
||||
- **Mouse and Scroll Wheel Bindings**:
|
||||
- You can now use scroll wheel keys (`WHEEL_UP`, `WHEEL_DOWN`, `WHEEL_LEFT`, `WHEEL_RIGHT`) in `keybindings` and record them in the settings key editor.
|
||||
- mpv's mouse button and wheel bindings now work while the cursor is over the overlay. This matters most on Hyprland, where these bindings did nothing before.
|
||||
- When a binding conflicts, SubMiner's own bindings and right-click pause take priority over mpv's.
|
||||
- **Session Help Commands**: During playback, press `Enter` or double-click a row in session help to run that command. Hovering over a row makes it the target for `Enter`.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Release Assets**: Releases no longer include package-size JSON reports.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Jellyfin Subtitles**:
|
||||
- The Japanese track is selected, and annotations start, as soon as it downloads. SubMiner no longer waits for the other tracks.
|
||||
- Japanese and English tracks are now picked automatically on episodes with image-based subtitles (PGS, DVD, DVB).
|
||||
- If one track fails to download, the other tracks are still selected.
|
||||
- **Jellyfin Audio Track**: On direct-play streams, timing review previews and mined card audio now use the audio track you're playing.
|
||||
- **Media Timing Review**:
|
||||
- Trim handles are now thin lines centered on the clip edges.
|
||||
- Original subtitle boundaries are now plain orange bars with no labels.
|
||||
- The preview cursor no longer stutters on macOS with Bluetooth headphones such as AirPods.
|
||||
- **Hyprland Fullscreen**: The overlay stays visible when mpv enters or leaves fullscreen. With `mpv.backend: x11`, subtitles and the sidebar stay clickable after going fullscreen.
|
||||
- **mpv Key Bindings in the Overlay**: mpv key bindings, such as `9`/`0` for volume, now work while the overlay has focus, even when the overlay loaded before mpv connected.
|
||||
- **YouTube Japanese Subtitles**: Some videos also list a machine-translated Japanese track. On those, Japanese subtitles no longer fail with "HTTP 429". If YouTube refuses a direct download, SubMiner retries with yt-dlp.
|
||||
- **Stats Accuracy**:
|
||||
- Sentence mining no longer counts each card twice in session and lifetime stats.
|
||||
- Overview totals, charts, the activity calendar, and the vocabulary summary now update after you delete sessions.
|
||||
- Word and kanji dates stay correct after deleting sessions. New-word charts now match the vocabulary summary.
|
||||
- **Dictionary Safety**: Automatic character dictionary changes now stop if a Yomitan profile that had dictionaries suddenly reports none. SubMiner also refuses to load Yomitan data after a downgrade to an older Electron version.
|
||||
- **AppImage in Sandboxes**: The AppImage now opens its window in sandboxes that mount the image themselves, such as `firejail --appimage`.
|
||||
- **Ctrl+C Crash**: Stopping the terminal command that started SubMiner with Ctrl+C no longer crashes it with a "write EPIPE" error.
|
||||
- **Security Updates**: Electron is updated to 43.7.7 and undici to 7.29.1, which fixes known security advisories.
|
||||
- **Windows Overlay**:
|
||||
- The overlay now finds mpv more reliably, without relying on PowerShell lookups.
|
||||
- You can now configure the IPC socket in `mpv.conf`.
|
||||
- The overlay no longer stays attached to an unrelated window after mpv's process ID is reused.
|
||||
- Stalled overlays now log diagnostic warnings without debug logging enabled.
|
||||
|
||||
### Docs
|
||||
|
||||
- **Docs Site Rewrite**: Pages are shorter and easier to scan. The configuration reference now has a short explanation and a table of keys and defaults for each config block. Pages that no longer matched current behavior are fixed.
|
||||
- **Arch Linux Install**: The MeCab install command now uses the AUR package `mecab-git`. The README now matches the installation guide.
|
||||
- **Stats**: The docs now cover the Overview refreshing after you delete sessions, and how first-seen dates are kept when old sessions are cleaned up.
|
||||
- **Windows Overlay Troubleshooting**: Added a guide to collecting and interpreting overlay attachment and readiness warnings without debug logging.
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix(storage): protect Yomitan profiles across Electron runtime changes by @ksyasuda in #211
|
||||
- fix(jellyfin): select subtitles faster and survive failed track downloads by @ksyasuda in #270
|
||||
- fix(jellyfin): use the current audio track for media generation by @ksyasuda in #271
|
||||
- feat(youtube): add YouTube browser window and Whisper subtitle source by @ksyasuda in #273
|
||||
- fix(overlay): thin centered trim handles and label-free subtitle boundaries in timing review by @ksyasuda in #274
|
||||
- feat(overlay): run session help commands with Enter or double-click by @ksyasuda in #275
|
||||
- fix(overlay): keep overlay mapped during Hyprland/Sway fullscreen by @ksyasuda in #276
|
||||
- fix(linux): skip AppImage mount keepalive on sandbox squashfs mounts by @ksyasuda in #277
|
||||
- fix(overlay): reload imported mpv keys after mpv connects by @ksyasuda in #278
|
||||
- feat(overlay): forward mpv mouse button and wheel bindings by @ksyasuda in #279
|
||||
- fix(stats): count mined cards once and keep lexical stats exact after deletes by @ksyasuda in #280
|
||||
- fix(youtube): keep mpv queue when advancing to a queued video on Windows by @ksyasuda in #281
|
||||
- fix(subtitles): allow Whisper generation during Windows YouTube stream playback by @ksyasuda in #282
|
||||
- fix(overlay): identify Windows mpv windows through IPC PID by @ksyasuda in #330
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
@@ -1,19 +1,73 @@
|
||||
## Highlights
|
||||
### Added
|
||||
- **Plugins**:
|
||||
- JavaScript plugins load from `<config dir>/plugins/<id>/` and are enabled under `plugins` in the config.
|
||||
- Plugins can react to mpv events and mined cards, call AnkiConnect, run programs, and show results in an overlay panel or window.
|
||||
- Three examples are included: `ai-explain` for line explanations, `anki-sync` for AnkiWeb syncing, and `episode-tags` for tagging cards by show and episode.
|
||||
- **Subtitle Filters**: Remove parenthesized text, sound descriptions, speaker names, music notes, or custom regex matches from primary subtitles. Configure them in Settings under Behavior → Subtitle Filters.
|
||||
- **Controller Dialog Layouts**: The media timing review and duplicate card dialogs can now be fully operated by controller and show button hints. Remap both layouts per controller in `Alt+C`.
|
||||
- **Controller Customization**:
|
||||
- `Alt+C` actions can be combos: click **Learn**, hold one button, and press another.
|
||||
- New unbound actions cover subtitle navigation, holding to show the secondary subtitle, Yomitan entry selection, and character navigation.
|
||||
- **Button Style** offers Xbox, Nintendo, or PlayStation names and symbols, saved per controller.
|
||||
- `Alt+C` now warns when two actions share an input.
|
||||
- **Keyboard-Only Mode**: Press `C` to move and look up by character, reaching words split by subtitle tokenization. **Pause Video In Keyboard-Only Mode** can also pause when the mode turns on and resume when it turns off.
|
||||
- **Jimaku Auto-Open**: Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to pause and open Jimaku when a local video has no Japanese subtitle track. Playback resumes when the modal closes.
|
||||
|
||||
### Changed
|
||||
- **Stats Session View**: The expanded session view in the stats dashboard has been redesigned. It shows stat tiles for pace, lines, known-word rate, lookups, and paused time, plus a reading density chart of known and unknown words with lookup and card-mined markers.
|
||||
- **Stats Trends**: Rebuilt with period comparisons, Learning charts, a heatmap, a title timeline, and a single running-total chart. Week grouping, custom ranges, a page-wide title filter, and click-through to sessions and library pages are also new.
|
||||
- **Stats Vocabulary**:
|
||||
- Rebuilt around one searchable, sortable word table with Worth mining, All words, Across titles, and Newest views.
|
||||
- Added known words by frequency band, a vocabulary growth chart, and a full kanji view.
|
||||
- New word counts now count dictionary words, so a word's conjugations count once and totals are lower than before.
|
||||
- Words and lines from streams now say they can't be mined, instead of showing Unavailable buttons.
|
||||
- **Controller Behavior**: **Toggle MPV Pause** now works outside keyboard-only mode. Controller connected and disabled messages now follow your regular notification setting instead of using a separate overlay pill.
|
||||
- **Keyboard-Only Mode Exit**: Turning the mode off now also closes the dictionary popup.
|
||||
- **Hachidori**: The bundled dictionary reader is updated to 0.4.0, adding every pitch accent in each popup entry, pitch drawn on the headword reading, per-kanji furigana, and Yomitan-style definition tags.
|
||||
|
||||
### Fixed
|
||||
- **Subtitle Delay**: Retiming subtitles in mpv (z/x or sub-step) now carries through SubMiner. Mined card audio, images, and timestamps match the retimed line, and so do the subtitle sidebar, subtitle navigation, and replay.
|
||||
- **Subtitle Sidebar**: mpv keys and mouse buttons, such as volume keys and double-click fullscreen, work again while the sidebar is open.
|
||||
- **Controller Settings (`Alt+C`)**:
|
||||
- Remaps now apply right away, without restarting SubMiner.
|
||||
- Editing stays locked until you press a button, so the window can't edit a controller it can't see.
|
||||
- With several controllers connected, it selects and listens to the one you just pressed.
|
||||
- **Learn**, **Clear**, and **Reset** are reachable again, D-pad **Learn** no longer errors, and button names are correct on standard-layout pads.
|
||||
- **Controller Input**: One press no longer runs its action twice on macOS and Windows. On macOS, buttons now work while mpv is in front.
|
||||
- **Dictionary Popup**: Controller and keyboard lookups pause and resume playback reliably, and moving between words right after closing the popup no longer reopens it.
|
||||
- **Anki Sentence Audio**: `ankiConnect.fields.audio` now defaults to `SentenceAudio`, so generated audio no longer overwrites Yomitan's word audio. If you relied on the old default, set it to `ExpressionAudio`.
|
||||
- **AniList**: Progress sync now adds an exactly matched or pinned show to your Watching or Completed list when it isn't on your list yet. Completed, Paused, Dropped, and Rewatching entries are never changed.
|
||||
- **Stats Dashboard**:
|
||||
- Overview, media, library, trends, vocabulary, and sentence search load several times faster on large databases.
|
||||
- Trends totals, episode counts, rate charts, axis labels, and date handling in time zones ahead of UTC are corrected.
|
||||
- Word lists now total every form of a word and show the dictionary form's reading.
|
||||
- Names no longer slip past Hide Names, and totals stay correct after vocabulary cleanup.
|
||||
- **Playback**: Reloading the current file in mpv no longer leaves playback paused, and the "Overlay loading" message no longer gets stuck when moving to the next playlist file.
|
||||
- **AppImage**: "Service Crash" notifications on quit no longer appear on Ubuntu 26.04 and newer.
|
||||
|
||||
### Docs
|
||||
- **README**: Refreshed the anime screenshots using the current build.
|
||||
- **Keyboard and Controller Reference**: Keyboard shortcuts now list the keyboard-only `C` key, and the configuration reference points to Controller support for default button actions.
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix(overlay): forward mpv input while subtitle sidebar is open by @ksyasuda in #300
|
||||
- fix(subtitles): follow mpv sub-delay in mining, sidebar, and navigation by @ksyasuda in #302
|
||||
- feat(stats): redesign expanded session view with density chart by @ksyasuda in #304
|
||||
- feat(plugins): add JavaScript plugin system with overlay panel by @ksyasuda in #303
|
||||
- fix(anilist): add missing list entry on confident match by @dandascan in #305
|
||||
- Controller: hold to show the secondary subtitle, dictionary entry navigation, standard button names by @YashaNoos in #312
|
||||
- Controller: layouts for the media timing review and duplicate card dialogs by @YashaNoos in #313
|
||||
- Controller: subtitle line actions, Button Style, keyboard-only mode pause, Alt+C fixes by @YashaNoos in #316
|
||||
- fix(plugin): keep loading OSD off on warm playlist advance by @ksyasuda in #317
|
||||
- feat(subtitles): add regex subtitle filters with built-in presets by @ksyasuda in #318
|
||||
- feat(jimaku): auto-open modal when a video has no Japanese subtitle by @dandascan in #319
|
||||
- fix(controller): pick up macOS presses while mpv is in front by @ksyasuda in #321
|
||||
- perf(stats): speed up dashboard queries on large databases by @ksyasuda in #322
|
||||
- fix(mpv): resume playback after a same-file reload that skips the path clear by @ksyasuda in #323
|
||||
- fix(controller): keep popup pause and press handling reliable by @ksyasuda in #324
|
||||
- feat(stats): overhaul the Trends tab by @ksyasuda in #325
|
||||
- Controller: character navigation in keyboard-only mode, plain Xbox face names by @YashaNoos in #326
|
||||
- feat(controller): add hold + press combos to main bindings by @ksyasuda in #328
|
||||
|
||||
## New Contributors
|
||||
|
||||
- @dandascan made their first contribution in #305
|
||||
- @YashaNoos made their first contribution in #312
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@ const http = require('node:http');
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const parser = require(path.join(root, 'dist/core/services/tokenizer/yomitan-parser-runtime.js'));
|
||||
const { writeStoredZip } = require(path.join(root, 'dist/shared/stored-zip.js'));
|
||||
const { HACHIDORI_POPUP_OPEN_SELECTOR } = require(
|
||||
path.join(root, 'dist/renderer/yomitan-popup.js'),
|
||||
);
|
||||
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-hachidori-parser-'));
|
||||
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
@@ -43,6 +46,58 @@ function fixture(name, title, bankName, entries, frequencyMode = 'rank-based') {
|
||||
return zipPath;
|
||||
}
|
||||
|
||||
// The renderer's popup auto-pause and key routing read this marker because the
|
||||
// reader's shadow root is closed. Drives the real reader with real input, since
|
||||
// stubbed DOM tests cannot notice an upstream merge that changes what it exposes.
|
||||
async function assertPopupOpenMarkerFollowsPane(targetSession) {
|
||||
const server = http.createServer((_request, response) => {
|
||||
response.setHeader('Content-Type', 'text/html; charset=utf-8');
|
||||
response.end(
|
||||
'<!doctype html><p id="word" style="font-size:48px;margin:300px 0 0 100px">食べた</p>',
|
||||
);
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const page = new BrowserWindow({
|
||||
width: 900,
|
||||
height: 600,
|
||||
show: true,
|
||||
webPreferences: { session: targetSession, contextIsolation: true, nodeIntegration: false },
|
||||
});
|
||||
try {
|
||||
await page.loadURL(`http://127.0.0.1:${server.address().port}/`);
|
||||
const { webContents } = page;
|
||||
const word = await webContents.executeJavaScript(
|
||||
`(() => { const { x, y, height } = document.getElementById('word').getBoundingClientRect(); return { x, y, height }; })()`,
|
||||
);
|
||||
const repeatUntilMarker = async (expected, act) => {
|
||||
const query = `document.querySelector(${JSON.stringify(HACHIDORI_POPUP_OPEN_SELECTOR)}) !== null`;
|
||||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||
// Content scripts load asynchronously, so keep acting until the reader reacts.
|
||||
act(attempt);
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
if ((await webContents.executeJavaScript(query)) === expected) return;
|
||||
}
|
||||
assert.fail(`Hachidori popup-open marker never became ${expected}`);
|
||||
};
|
||||
page.focus();
|
||||
webContents.focus();
|
||||
await repeatUntilMarker(true, (attempt) =>
|
||||
webContents.sendInputEvent({
|
||||
type: 'mouseMove',
|
||||
x: Math.round(word.x + 24) + (attempt % 2),
|
||||
y: Math.round(word.y + word.height / 2),
|
||||
}),
|
||||
);
|
||||
await repeatUntilMarker(false, () => {
|
||||
webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
|
||||
webContents.sendInputEvent({ type: 'keyUp', keyCode: 'Escape' });
|
||||
});
|
||||
} finally {
|
||||
page.destroy();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
}
|
||||
|
||||
app
|
||||
.whenReady()
|
||||
.then(async () => {
|
||||
@@ -211,6 +266,7 @@ app
|
||||
assert.deepEqual(unmatched, []);
|
||||
assert.equal(await parser.getYomitanCurrentAnkiDeckName(deps, logger), 'Test Mining');
|
||||
assert.equal((await targetSession.extensions.getAllExtensions()).length, 1);
|
||||
await assertPopupOpenMarkerFollowsPane(targetSession);
|
||||
assert.equal(
|
||||
await parser.syncYomitanDefaultAnkiServer('http://127.0.0.1:8765', deps, logger),
|
||||
true,
|
||||
|
||||
@@ -1297,7 +1297,6 @@ test('parses controller settings with logical bindings and tuning knobs', () =>
|
||||
"toggleMpvPause": "leftStickPress",
|
||||
"leftStickHorizontal": "rightStickX",
|
||||
"leftStickVertical": "rightStickY",
|
||||
"rightStickHorizontal": "leftStickX",
|
||||
"rightStickVertical": "leftStickY"
|
||||
}
|
||||
}
|
||||
@@ -1383,6 +1382,59 @@ test('parses descriptor-based controller bindings', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('parses a hold input on discrete controller bindings and rejects an invalid one', () => {
|
||||
const dir = makeTempDir();
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'config.jsonc'),
|
||||
`{
|
||||
"controller": {
|
||||
"bindings": {
|
||||
"nextAudio": {
|
||||
"kind": "button",
|
||||
"buttonIndex": 15,
|
||||
"hold": { "kind": "button", "buttonIndex": 4 }
|
||||
},
|
||||
"nextEntry": {
|
||||
"kind": "axis",
|
||||
"axisIndex": 0,
|
||||
"direction": "positive",
|
||||
"hold": { "kind": "axis", "axisIndex": 2, "direction": "positive" }
|
||||
},
|
||||
"mineCard": {
|
||||
"kind": "button",
|
||||
"buttonIndex": 12,
|
||||
"hold": { "kind": "button" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
const service = new ConfigService(dir);
|
||||
const config = service.getConfig();
|
||||
|
||||
assert.deepEqual(config.controller.bindings.nextAudio, {
|
||||
kind: 'button',
|
||||
buttonIndex: 15,
|
||||
hold: { kind: 'button', buttonIndex: 4 },
|
||||
});
|
||||
assert.deepEqual(config.controller.bindings.nextEntry, {
|
||||
kind: 'axis',
|
||||
axisIndex: 0,
|
||||
direction: 'positive',
|
||||
hold: { kind: 'axis', axisIndex: 2, direction: 'positive' },
|
||||
});
|
||||
// A broken hold must not silently become a plain press of button 12.
|
||||
assert.deepEqual(
|
||||
config.controller.bindings.mineCard,
|
||||
DEFAULT_CONFIG.controller.bindings.mineCard,
|
||||
);
|
||||
assert.ok(
|
||||
service.getWarnings().some((warning) => warning.path === 'controller.bindings.mineCard'),
|
||||
);
|
||||
});
|
||||
|
||||
test('parses controller profiles as per-gamepad binding overrides', () => {
|
||||
const dir = makeTempDir();
|
||||
fs.writeFileSync(
|
||||
|
||||
@@ -92,7 +92,6 @@ export const CORE_DEFAULT_CONFIG: Pick<
|
||||
playNextSubtitle: { kind: 'none' },
|
||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
||||
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
||||
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
||||
},
|
||||
reviewBindings: getDefaultControllerReviewBindings(),
|
||||
|
||||
@@ -125,11 +125,6 @@ export function buildCoreConfigOptionRegistry(
|
||||
defaultValue: defaultConfig.controller.bindings.leftStickVertical,
|
||||
description: 'Axis binding descriptor used for primary popup scrolling.',
|
||||
},
|
||||
{
|
||||
id: 'rightStickHorizontal',
|
||||
defaultValue: defaultConfig.controller.bindings.rightStickHorizontal,
|
||||
description: 'Axis binding descriptor reserved for alternate right-stick mappings.',
|
||||
},
|
||||
{
|
||||
id: 'rightStickVertical',
|
||||
defaultValue: defaultConfig.controller.bindings.rightStickVertical,
|
||||
@@ -472,7 +467,7 @@ export function buildCoreConfigOptionRegistry(
|
||||
path: `controller.bindings.${binding.id}`,
|
||||
kind: 'object' as const,
|
||||
defaultValue: binding.defaultValue,
|
||||
description: `${binding.description} Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.`,
|
||||
description: `${binding.description} Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.`,
|
||||
},
|
||||
{
|
||||
path: `controller.bindings.${binding.id}.kind`,
|
||||
@@ -505,6 +500,13 @@ export function buildCoreConfigOptionRegistry(
|
||||
description:
|
||||
'Axis direction captured for this discrete controller action. Required when kind is "axis".',
|
||||
},
|
||||
{
|
||||
path: `controller.bindings.${binding.id}.hold`,
|
||||
kind: 'object' as const,
|
||||
defaultValue: undefined,
|
||||
description:
|
||||
'Optional button or axis input, in the same form, that must be held down while pressing this one.',
|
||||
},
|
||||
]),
|
||||
...axisBindings.flatMap((binding) => [
|
||||
{
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type {
|
||||
ControllerAxisBinding,
|
||||
ControllerAxisDirection,
|
||||
ControllerButtonBinding,
|
||||
ControllerButtonIndicesConfig,
|
||||
ControllerDpadFallback,
|
||||
@@ -11,6 +10,7 @@ import type {
|
||||
import {
|
||||
isControllerFaceButtonLabels,
|
||||
isControllerScreenAction,
|
||||
parseControllerDiscreteBinding,
|
||||
parseControllerReviewBinding,
|
||||
type ControllerScreenBindings,
|
||||
type ControllerScreenDefinition,
|
||||
@@ -70,7 +70,6 @@ const CONTROLLER_BUTTON_INDEX_KEY_BY_BINDING: Record<
|
||||
const CONTROLLER_AXIS_FALLBACK_BY_SLOT = {
|
||||
leftStickHorizontal: 'horizontal',
|
||||
leftStickVertical: 'vertical',
|
||||
rightStickHorizontal: 'none',
|
||||
rightStickVertical: 'none',
|
||||
} as const satisfies Record<string, ControllerDpadFallback>;
|
||||
|
||||
@@ -111,7 +110,6 @@ const CONTROLLER_DISCRETE_BINDING_KEYS = [
|
||||
const CONTROLLER_AXIS_BINDING_KEYS = [
|
||||
'leftStickHorizontal',
|
||||
'leftStickVertical',
|
||||
'rightStickHorizontal',
|
||||
'rightStickVertical',
|
||||
] as const;
|
||||
|
||||
@@ -120,10 +118,6 @@ const RESERVED_CONTROLLER_PROFILE_IDS = new Set(['__proto__', 'constructor', 'pr
|
||||
type ControllerBindingsTarget = Required<ResolvedControllerBindingsConfig>;
|
||||
type ControllerButtonIndicesTarget = Required<ControllerButtonIndicesConfig>;
|
||||
|
||||
function isControllerAxisDirection(value: unknown): value is ControllerAxisDirection {
|
||||
return value === 'negative' || value === 'positive';
|
||||
}
|
||||
|
||||
function isControllerDpadFallback(value: unknown): value is ControllerDpadFallback {
|
||||
return value === 'none' || value === 'horizontal' || value === 'vertical';
|
||||
}
|
||||
@@ -152,29 +146,6 @@ function resolveLegacyAxisBinding(
|
||||
};
|
||||
}
|
||||
|
||||
function parseDiscreteBindingObject(value: unknown): ResolvedControllerDiscreteBinding | null {
|
||||
if (!isObject(value) || typeof value.kind !== 'string') return null;
|
||||
if (value.kind === 'none') {
|
||||
return { kind: 'none' };
|
||||
}
|
||||
if (value.kind === 'button') {
|
||||
return typeof value.buttonIndex === 'number' &&
|
||||
Number.isInteger(value.buttonIndex) &&
|
||||
value.buttonIndex >= 0
|
||||
? { kind: 'button', buttonIndex: value.buttonIndex }
|
||||
: null;
|
||||
}
|
||||
if (value.kind === 'axis') {
|
||||
return typeof value.axisIndex === 'number' &&
|
||||
Number.isInteger(value.axisIndex) &&
|
||||
value.axisIndex >= 0 &&
|
||||
isControllerAxisDirection(value.direction)
|
||||
? { kind: 'axis', axisIndex: value.axisIndex, direction: value.direction }
|
||||
: null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseAxisBindingObject(
|
||||
value: unknown,
|
||||
slot: keyof typeof CONTROLLER_AXIS_FALLBACK_BY_SLOT,
|
||||
@@ -242,7 +213,7 @@ function applyControllerBindings(
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const parsedObject = parseDiscreteBindingObject(bindingValue);
|
||||
const parsedObject = parseControllerDiscreteBinding(bindingValue);
|
||||
if (parsedObject) {
|
||||
target[key] = parsedObject;
|
||||
} else if (bindingValue !== undefined) {
|
||||
@@ -250,7 +221,7 @@ function applyControllerBindings(
|
||||
`${pathPrefix}.${key}`,
|
||||
bindingValue,
|
||||
target[key],
|
||||
"Expected legacy controller button name or binding object with kind 'none', 'button', or 'axis'.",
|
||||
"Expected legacy controller button name or binding object with kind 'none', 'button', or 'axis', and an optional button or axis 'hold'.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,651 @@
|
||||
// Captured from live AniList responses on 2026-11-22, trimmed to the fields the resolver reads.
|
||||
// Each chain is in SEQUEL order: entry i's only SEQUEL is entry i + 1.
|
||||
import type { AnilistSeasonMedia } from '../season-resolver';
|
||||
|
||||
/** Mushoku Tensei: S1 -> "Cour 2" -> S2 -> "Season 2 Part 2" -> S3 -> S3 Part 2. */
|
||||
export const MUSHOKU_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 108465,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'Jobless Reincarnation: I Will Seriously Try If I Go To Another World',
|
||||
'无职转生 ~到了异世界就拿出真本事~',
|
||||
'เกิดชาตินี้พี่ต้องเทพ',
|
||||
'Thất nghiệp chuyển sinh',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
native: '無職転生 ~異世界行ったら本気だす~',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 127720,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: ['Mushoku Tensei: Jobless Reincarnation Part 2', 'เกิดชาตินี้พี่ต้องเทพ พาร์ท 2'],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei: Isekai Ittara Honki Dasu Part 2',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Cour 2',
|
||||
native: '無職転生 ~異世界行ったら本気だす~ 第2クール',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 146065,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2',
|
||||
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season',
|
||||
'Mushoku Tensei II: Jobless Reincarnation',
|
||||
'Mushoku Tensei II: Reencarnación desde cero',
|
||||
'无职转生~到了异世界就拿出真本事~第2季',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Season 2',
|
||||
native: '無職転生Ⅱ ~異世界行ったら本気だす~',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 166873,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2024,
|
||||
synonyms: [
|
||||
'Mushoku Tensei: Jobless Reincarnation Season 2 Cour 2',
|
||||
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 2 ครึ่งหลัง',
|
||||
'Mushoku Tensei: Isekai Ittara Honki Dasu 2nd Season Part 2',
|
||||
'Mushoku Tensei II: Jobless Reincarnation Part 2',
|
||||
'Mushoku Tensei II: Reencarnación desde cero',
|
||||
'无职转生~到了异世界就拿出真本事~第2季',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei II: Isekai Ittara Honki Dasu Part 2',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Season 2 Part 2',
|
||||
native: '無職転生Ⅱ ~異世界行ったら本気だす~ 第2クール',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 178789,
|
||||
episodes: 14,
|
||||
format: 'TV',
|
||||
seasonYear: 2026,
|
||||
synonyms: [
|
||||
'無職転生 ~異世界行ったら本気だす~ 第3期',
|
||||
'Mushoku Tensei: Isekai Ittara Honki Dasu 3rd Season',
|
||||
'เกิดชาตินี้พี่ต้องเทพ ซีซั่น 3',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu',
|
||||
english: 'Mushoku Tensei: Jobless Reincarnation Season 3',
|
||||
native: '無職転生Ⅲ ~異世界行ったら本気だす~',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 217434,
|
||||
episodes: null,
|
||||
format: 'TV',
|
||||
seasonYear: 2027,
|
||||
synonyms: ['Mushoku Tensei: Jobless Reincarnation Season 3 Part 2'],
|
||||
title: {
|
||||
romaji: 'Mushoku Tensei III: Isekai Ittara Honki Dasu Part 2',
|
||||
english: null,
|
||||
native: '無職転生Ⅲ ~異世界行ったら本気だす~ 第2クール',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Re:ZERO: S1 -> S2 -> "Season 2 Part 2" -> S3 -> S4 -> S5 (unaired). */
|
||||
export const REZERO_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 21355,
|
||||
episodes: 25,
|
||||
format: 'TV',
|
||||
seasonYear: 2016,
|
||||
synonyms: [
|
||||
'Re: Life in a different world from zero',
|
||||
'ReZero',
|
||||
'Re Zero',
|
||||
'Re:从零开始的异世界生活',
|
||||
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก',
|
||||
'Re:Zero — жизнь с нуля в другом мире',
|
||||
'Re:Zero Empezar de cero en un mundo diferente',
|
||||
'Re:Zero – Bắt đầu lại ở thế giới khác',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu',
|
||||
english: 'Re:ZERO -Starting Life in Another World-',
|
||||
native: 'Re:ゼロから始める異世界生活',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 108632,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
synonyms: [
|
||||
'Re:Zero kara Hajimeru Isekai Seikatsu (2020)',
|
||||
'Re: 제로부터 시작하는 이세계 생활 2기',
|
||||
'Re:从零开始的异世界生活第二季(上半)',
|
||||
'Re:从零开始的异世界生活 2 上半',
|
||||
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2',
|
||||
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 2',
|
||||
native: 'Re:ゼロから始める異世界生活 2nd Season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 119661,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'Re:Zero kara Hajimeru Isekai Seikatsu (2021)',
|
||||
'Re: 제로부터 시작하는 이세계 생활 2기 파트 2',
|
||||
'Re:从零开始的异世界生活第二季(下半)',
|
||||
'Re:从零开始的异世界生活 2 下半',
|
||||
'Re:Zero รีเซทชีวิต ฝ่าวิกฤตต่างโลก ภาค 2 พาร์ท 2',
|
||||
'Re:Zero — жизнь с нуля в другом мире. Второй сезон',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season Part 2',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 2 Part 2',
|
||||
native: 'Re:ゼロから始める異世界生活 2nd Season Part 2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 163134,
|
||||
episodes: 16,
|
||||
format: 'TV',
|
||||
seasonYear: 2024,
|
||||
synonyms: ['Re:ZERO – Жизнь с нуля в альтернативном мире 3'],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 3rd Season',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 3',
|
||||
native: 'Re:ゼロから始める異世界生活 3rd season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 189046,
|
||||
episodes: 19,
|
||||
format: 'TV',
|
||||
seasonYear: 2026,
|
||||
synonyms: [
|
||||
'Re:ZERO รีเซทชีวิต ฝ่าวิกฤตต่างโลก ซีซั่น 4',
|
||||
'Re:ZERO – Жизнь с нуля в альтернативном мире 4',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 4th Season',
|
||||
english: 'Re:ZERO -Starting Life in Another World- Season 4',
|
||||
native: 'Re:ゼロから始める異世界生活 4th season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 219904,
|
||||
episodes: null,
|
||||
format: 'TV',
|
||||
seasonYear: null,
|
||||
synonyms: ['Re:ZERO -Starting Life in Another World- Season 5'],
|
||||
title: {
|
||||
romaji: 'Re:Zero kara Hajimeru Isekai Seikatsu 5th Season',
|
||||
english: null,
|
||||
native: 'Re:ゼロから始める異世界生活 5th season',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Dr. STONE: STONE WARS reaches NEW WORLD through a one-episode SPECIAL. */
|
||||
export const DR_STONE_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 105333,
|
||||
episodes: 24,
|
||||
format: 'TV',
|
||||
seasonYear: 2019,
|
||||
synonyms: [
|
||||
'Dcst',
|
||||
'石纪元',
|
||||
'ドクターストーン',
|
||||
'ดร.สโตน เจ้าแห่งวิทยาศาสตร์กู้คืนอารยธรรมโลก',
|
||||
'Доктор Стоун',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE',
|
||||
english: 'Dr. STONE',
|
||||
native: 'Dr.STONE',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 113936,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'ドクターストーン STONE WARS',
|
||||
'Dr.STONE第2期',
|
||||
'Dr. STONE 2',
|
||||
'닥터 스톤 STONE WARS',
|
||||
'石纪元第二季',
|
||||
'DR.STONE ภาค 2',
|
||||
'Доктор Стоун: Каменные войны',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: STONE WARS',
|
||||
english: 'Dr. STONE: STONE WARS',
|
||||
native: 'Dr.STONE STONE WARS',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 142876,
|
||||
episodes: 1,
|
||||
format: 'SPECIAL',
|
||||
seasonYear: 2022,
|
||||
synonyms: ['Dr. STONE: Ryusui', 'Доктор Стоун: Рюсуй'],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: Ryuusui',
|
||||
english: 'Dr. STONE Special Episode – RYUSUI',
|
||||
native: 'Dr.STONE 龍水',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 131518,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'石纪元第三季',
|
||||
'Dr.STONE Season 3',
|
||||
'DR.STONE ภาค 3',
|
||||
'Dr.STONE 第3期',
|
||||
'Dr. STONE 新石紀(第三季)',
|
||||
'Доктор Стоун: Новый Свет',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: NEW WORLD',
|
||||
english: 'Dr. STONE New World',
|
||||
native: 'Dr.STONE NEW WORLD',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 162670,
|
||||
episodes: 11,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'石纪元第三季',
|
||||
'Dr.STONE Season 3 Part 2',
|
||||
'DR.STONE ภาค 3',
|
||||
'Dr.STONE 第3期 第2クール',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: NEW WORLD Part 2',
|
||||
english: 'Dr. STONE New World Part 2',
|
||||
native: 'Dr.STONE NEW WORLD 第2クール',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 172019,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2025,
|
||||
synonyms: ['Dr.STONE Season 4', 'Dr.STONE 第4期', 'ドクターストーン'],
|
||||
title: {
|
||||
romaji: 'Dr. STONE: SCIENCE FUTURE',
|
||||
english: 'Dr. STONE SCIENCE FUTURE',
|
||||
native: 'Dr.STONE SCIENCE FUTURE',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Bleach TYBW: cours named after arcs; "Part N" only in synonyms, spelled "Thousand Year". */
|
||||
export const BLEACH_TYBW_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 116674,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
synonyms: [
|
||||
'بليتش: حرب الألف سنة الدموية',
|
||||
'Bleach: La guerre sanglante de mille ans',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen',
|
||||
english: 'BLEACH: Thousand-Year Blood War',
|
||||
native: 'BLEACH 千年血戦篇',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 159322,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'BLEACH: Thousand Year Blood War Part 2',
|
||||
'BLEACH 千年血戦篇 第2クール',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen - Ketsubetsu-tan',
|
||||
english: 'BLEACH: Thousand-Year Blood War - The Separation',
|
||||
native: 'BLEACH 千年血戦篇-訣別譚-',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 169755,
|
||||
episodes: 14,
|
||||
format: 'TV',
|
||||
seasonYear: 2024,
|
||||
synonyms: [
|
||||
'BLEACH: Thousand Year Blood War Part 3',
|
||||
'BLEACH 千年血戦篇 第3クール',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen - Soukoku-tan',
|
||||
english: 'BLEACH: Thousand-Year Blood War - The Conflict',
|
||||
native: 'BLEACH 千年血戦篇-相剋譚-',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 185874,
|
||||
episodes: 10,
|
||||
format: 'TV',
|
||||
seasonYear: 2026,
|
||||
synonyms: [
|
||||
'BLEACH: Thousand-Year Blood War Part 4',
|
||||
'BLEACH 千年血戦篇 第4クール',
|
||||
'BLEACH: Thousand-Year Blood War The Final Season',
|
||||
'BLEACH TYBW',
|
||||
],
|
||||
title: {
|
||||
romaji: 'BLEACH: Sennen Kessen-hen - Kashin-tan',
|
||||
english: 'BLEACH: Thousand-Year Blood War - The Calamity',
|
||||
native: 'BLEACH 千年血戦篇-禍進譚-',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Attack on Titan: season 3 carries the Thai synonym "... ภาค 3 Part 1"; the chain ends in SPECIALs. */
|
||||
export const AOT_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 16498,
|
||||
episodes: 25,
|
||||
format: 'TV',
|
||||
seasonYear: 2013,
|
||||
synonyms: [
|
||||
'SnK',
|
||||
'AoT',
|
||||
'Ataque a los Titanes',
|
||||
'Ataque dos Titãs',
|
||||
"L'Attacco dei Giganti",
|
||||
'מתקפת הטיטאנים',
|
||||
'进击的巨人',
|
||||
'L’Attaque des Titans',
|
||||
'الهجوم على العمالقة',
|
||||
'ผ่าพิภพไททัน',
|
||||
'حمله به تایتان',
|
||||
'Ataque de Titãs',
|
||||
'Atak Tytanów',
|
||||
'Атака титанов',
|
||||
'Đại Chiến Titan',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin',
|
||||
english: 'Attack on Titan',
|
||||
native: '進撃の巨人',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 20958,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2017,
|
||||
synonyms: [
|
||||
'SnK 2',
|
||||
'AoT 2',
|
||||
'+מתקפת הטיטאנים עונה 2',
|
||||
"L'Attacco dei Giganti 2",
|
||||
"L'Attacco dei Giganti - Seconda Stagione",
|
||||
'ผ่าพิภพไททัน ภาค 2',
|
||||
'حمله به تایتان فصل 2',
|
||||
'Атака титанов 2',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin Season 2',
|
||||
english: 'Attack on Titan Season 2',
|
||||
native: '進撃の巨人 Season2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 99147,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: [
|
||||
'SnK 3',
|
||||
'AoT 3',
|
||||
'מתקפת הטיטאנים עונה 3',
|
||||
"L'Attacco dei Giganti 3",
|
||||
"L'Attacco dei Giganti - Terza Stagione",
|
||||
'ผ่าพิภพไททัน ภาค 3',
|
||||
'حمله به تایتان فصل 3',
|
||||
'ผ่าพิภพไททัน ภาค 3 Part 1',
|
||||
'Атака титанов 3',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin Season 3',
|
||||
english: 'Attack on Titan Season 3',
|
||||
native: '進撃の巨人 Season3',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 104578,
|
||||
episodes: 10,
|
||||
format: 'TV',
|
||||
seasonYear: 2019,
|
||||
synonyms: [
|
||||
'SnK 3',
|
||||
'AoT 3',
|
||||
'Shingeki no Kyojin Season 3 (2019)',
|
||||
"L'Attaco dei Giganti 3 Parte 2",
|
||||
"L'Attacco dei Giganti - Terza Stagione Parte 2",
|
||||
'מתקפת הטיטאנים עונה 3 חלק 2',
|
||||
"L'Attaque des Titans Saison 3 Partie 2 ",
|
||||
'ผ่าพิภพไททัน ภาค 3 Part 2',
|
||||
'ผ่าพิภพไททัน ภาค 3 พาร์ท 2',
|
||||
'حمله به تایتان فصل 3',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin Season 3 Part 2',
|
||||
english: 'Attack on Titan Season 3 Part 2',
|
||||
native: '進撃の巨人 Season3 Part.2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 110277,
|
||||
episodes: 16,
|
||||
format: 'TV',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
'SnK 4',
|
||||
'AoT 4',
|
||||
'Shingeki no Kyojin 4',
|
||||
'進撃の巨人4',
|
||||
'Attack on Titan Season 4',
|
||||
'진격의 거인 더 파이널 시즌',
|
||||
'מתקפת הטיטאנים העונה האחרונה',
|
||||
"L'Attaque des Titans Saison Finale",
|
||||
"L'Attacco dei Giganti 4",
|
||||
"L'Attacco dei Giganti - La Stagione Finale",
|
||||
'حمله به تایتان فصل 4 ',
|
||||
' ผ่าพิภพไททัน ไฟนอล ซีซั่น',
|
||||
'ผ่าพิภพไททัน Final Season',
|
||||
'ผ่าพิภพไททัน ภาค 4',
|
||||
'هجوم العملاقة الجزء الأخير',
|
||||
'Атака Титанов: Финал',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin: The Final Season',
|
||||
english: 'Attack on Titan Final Season',
|
||||
native: '進撃の巨人 The Final Season',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 131681,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
synonyms: [
|
||||
'SnK 4',
|
||||
'AoT 4',
|
||||
"L'attaque des titans Saison Finale Partie 2",
|
||||
'Shingeki no Kyojin: The Final Season (2022)',
|
||||
'اتک عن تایتان',
|
||||
'حمله به غول ها',
|
||||
'حمله به تایتان فصل 4 ',
|
||||
' ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 2',
|
||||
'ผ่าพิภพไททัน ภาค 4',
|
||||
"L'Attacco dei Giganti 4 Parte 2",
|
||||
'Атака титанов: Финал. Часть 2',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin: The Final Season Part 2',
|
||||
english: 'Attack on Titan Final Season Part 2',
|
||||
native: '進撃の巨人 The Final Season Part 2',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 146984,
|
||||
episodes: 1,
|
||||
format: 'SPECIAL',
|
||||
seasonYear: 2023,
|
||||
synonyms: [
|
||||
'Shingeki no Kyojin: The Final Season Final Edition',
|
||||
'Shingeki no Kyojin: The Final Season Part 3',
|
||||
'ผ่าพิภพไททัน ภาค 4',
|
||||
'ผ่าพิภพไททัน ไฟนอล ซีซั่น Part 3',
|
||||
'Attack on Titan Final Season Part 3 Final Arc Part 1',
|
||||
'Attack on Titan The Final Season The Final Part Special',
|
||||
'Attack on Titan The Final Season The Final Part Part 1',
|
||||
'حمله به تایتان فصل آخر قسمت ویژه 1 ',
|
||||
'SnK 4',
|
||||
'AoT 4',
|
||||
],
|
||||
title: {
|
||||
romaji: 'Shingeki no Kyojin: The Final Season - Kanketsu-hen Zenpen',
|
||||
english: 'Attack on Titan Final Season THE FINAL CHAPTERS Special 1',
|
||||
native: '進撃の巨人 The Final Season完結編 前編',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Overlord: seasons named only by a trailing roman numeral. */
|
||||
export const OVERLORD_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 20832,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2015,
|
||||
synonyms: ['Over Lord', 'โอเวอร์ลอร์ด', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก'],
|
||||
title: {
|
||||
romaji: 'Overlord',
|
||||
english: 'Overlord',
|
||||
native: 'オーバーロード',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 98437,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: ['Over Lord 2', 'โอเวอร์ลอร์ด ภาค 2', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 2'],
|
||||
title: {
|
||||
romaji: 'Overlord II',
|
||||
english: 'Overlord II',
|
||||
native: 'オーバーロードⅡ',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 101474,
|
||||
episodes: 13,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: ['Over Lord 3', 'โอเวอร์ลอร์ด ภาค 3', 'โอเวอร์ ลอร์ด จอมมารพิชิตโลก ภาค 3'],
|
||||
title: {
|
||||
romaji: 'Overlord III',
|
||||
english: 'Overlord III',
|
||||
native: 'オーバーロードⅢ',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** JoJo: Golden Wind ends in the synonym "Part 5", Stone Ocean in "Part 6"; both are new seasons. */
|
||||
export const JOJO_CHAIN: AnilistSeasonMedia[] = [
|
||||
{
|
||||
id: 21450,
|
||||
episodes: 39,
|
||||
format: 'TV',
|
||||
seasonYear: 2016,
|
||||
synonyms: [
|
||||
'JoJo no Kimyou na Bouken Part 4: Diamond wa Kudakenai',
|
||||
"JoJo's Bizarre Adventure Part 4: Diamond is Unbreakable",
|
||||
'مغامرات جوجو العجيبة: الألماس غير قابل للكسر',
|
||||
'Le bizzarre avventure di JoJo: Diamond is Unbreakable',
|
||||
'Невероятные приключения ДжоДжо: Diamond is Unbreakable',
|
||||
],
|
||||
title: {
|
||||
romaji: 'JoJo no Kimyou na Bouken: Diamond wa Kudakenai',
|
||||
english: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
|
||||
native: 'ジョジョの奇妙な冒険 ダイヤモンドは砕けない',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 102883,
|
||||
episodes: 39,
|
||||
format: 'TV',
|
||||
seasonYear: 2018,
|
||||
synonyms: [
|
||||
"JoJo's Bizarre Adventure Part 5",
|
||||
"JoJo's Bizarre Adventure: Vento Aureo",
|
||||
'Le Bizzarre Avventure Di GioGio: Vento Aureo',
|
||||
'مغامرات جوجو العجيبة: الرياح الذهبية',
|
||||
'Невероятные приключения ДжоДжо: Золотой ветер',
|
||||
],
|
||||
title: {
|
||||
romaji: 'JoJo no Kimyou na Bouken: Ougon no Kaze',
|
||||
english: "JoJo's Bizarre Adventure: Golden Wind",
|
||||
native: 'ジョジョの奇妙な冒険 黄金の風',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 131942,
|
||||
episodes: 12,
|
||||
format: 'ONA',
|
||||
seasonYear: 2021,
|
||||
synonyms: [
|
||||
"JoJo's Bizarre Adventure: Stone Ocean",
|
||||
"JoJo's Bizarre Adventure Part 6",
|
||||
'JoJo no Kimyou na Bouken Part 6',
|
||||
'Le bizzarre avventure di JoJo: Stone Ocean',
|
||||
'โจโจ้ ล่าข้ามศตวรรษ: สโตนโอเชียน ',
|
||||
'โจโจ้ ล่าข้ามศตวรรษ ภาค 6',
|
||||
'مغامرات جوجو العجيبة: محيط الأحجار',
|
||||
"ההרפתקה המוזרה של ג'וג'ו: אוקיינוס האבן",
|
||||
'Невероятные приключения ДжоДжо: Каменный океан ',
|
||||
"Химерні пригоди ДжоДжо: Кам'яний океан",
|
||||
],
|
||||
title: {
|
||||
romaji: 'JoJo no Kimyou na Bouken: Stone Ocean',
|
||||
english: "JoJo's Bizarre Adventure: STONE OCEAN",
|
||||
native: 'ジョジョの奇妙な冒険 ストーンオーシャン',
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -585,6 +585,11 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
|
||||
});
|
||||
}
|
||||
if (call === 3) {
|
||||
// Looks one season past the count for an entry naming season 2; there is none.
|
||||
assert.equal(body.variables?.id, 202);
|
||||
return createJsonResponse({ data: { Media: { relations: { edges: [] } } } });
|
||||
}
|
||||
if (call === 4) {
|
||||
assert.equal(body.variables?.mediaId, 202);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
@@ -608,7 +613,68 @@ test('updateAnilistPostWatchProgress resolves later seasons through the sequel c
|
||||
assert.deepEqual(searchTerms, ['Demo Show']);
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.match(result.message, /Demo Show Sequel/);
|
||||
assert.equal(call, 4);
|
||||
assert.equal(call, 5);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('updateAnilistPostWatchProgress writes a split-cour episode to the part that airs it', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const saved: Array<Record<string, unknown> | undefined> = [];
|
||||
globalThis.fetch = (async (_input, init) => {
|
||||
const body = JSON.parse(String(init?.body)) as {
|
||||
query: string;
|
||||
variables?: Record<string, unknown>;
|
||||
};
|
||||
if (body.query.includes('Page(')) {
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Page: {
|
||||
media: [{ id: 101, episodes: 11, format: 'TV', title: { english: 'Demo Show' } }],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (body.query.includes('relations')) {
|
||||
assert.equal(body.variables?.id, 101);
|
||||
return createJsonResponse({
|
||||
data: {
|
||||
Media: {
|
||||
relations: {
|
||||
edges: [
|
||||
{
|
||||
relationType: 'SEQUEL',
|
||||
node: {
|
||||
id: 202,
|
||||
type: 'ANIME',
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
title: { english: 'Demo Show Cour 2' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (body.query.includes('SaveMediaListEntry')) {
|
||||
saved.push(body.variables);
|
||||
return createJsonResponse({ data: { SaveMediaListEntry: { progress: 4 } } });
|
||||
}
|
||||
assert.equal(body.variables?.mediaId, 202);
|
||||
return createJsonResponse({
|
||||
data: { Media: { id: 202, mediaListEntry: { progress: 3, status: 'CURRENT' } } },
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
// Episode 15 of an 11 + 12 season is episode 4 of the second cour's entry.
|
||||
const result = await updateAnilistPostWatchProgress('token', 'Demo Show', 15, { season: 1 });
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.match(result.message, /Demo Show Cour 2.*episode 4/);
|
||||
assert.deepEqual(saved, [{ mediaId: 202, progress: 4, status: 'CURRENT' }]);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
|
||||
@@ -273,6 +273,9 @@ export async function updateAnilistPostWatchProgress(
|
||||
let mediaId = pinnedMediaId;
|
||||
let resolvedTitle: string | null = null;
|
||||
let resolvedEpisodes: number | null = null;
|
||||
// Episode number within the entry being updated; differs from `episode` only for a
|
||||
// split-cour back half.
|
||||
let progress = episode;
|
||||
// A missing list entry is only created when we trust the match; otherwise a fuzzy
|
||||
// search hit would add an unrelated show to the user's list.
|
||||
let confidentMatch = pinnedMediaId !== null;
|
||||
@@ -312,14 +315,18 @@ export async function updateAnilistPostWatchProgress(
|
||||
};
|
||||
}
|
||||
|
||||
mediaId = resolution.id;
|
||||
resolvedTitle = resolution.title;
|
||||
resolvedEpisodes = resolution.episodes;
|
||||
// A split-cour back half is its own AniList entry with its own episode numbering:
|
||||
// "S1E15" of an 11 + 12 season is progress 4 on the second entry.
|
||||
const target = resolution.episodeEntry ?? resolution;
|
||||
mediaId = target.id;
|
||||
resolvedTitle = target.title;
|
||||
resolvedEpisodes = target.episodes;
|
||||
progress = resolution.episodeEntry?.episode ?? episode;
|
||||
// With no parsed season, an exact match on a season-stripped title ("Show S2" ->
|
||||
// "Show") only certifies the season 1 anchor, not the entry being watched.
|
||||
const seasonMarkerStripped = stripSeasonSuffix(title).trim() !== title.trim();
|
||||
confidentMatch =
|
||||
resolution.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
|
||||
target.exactTitleMatch && (resolution.requestedSeason !== null || !seasonMarkerStripped);
|
||||
}
|
||||
|
||||
const entryResponse = await anilistGraphQl<AnilistMediaEntryData>(
|
||||
@@ -376,8 +383,8 @@ export async function updateAnilistPostWatchProgress(
|
||||
}
|
||||
|
||||
const currentProgress = entry?.progress ?? 0;
|
||||
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, episode);
|
||||
if (typeof currentProgress === 'number' && currentProgress >= episode && !shouldMarkCompleted) {
|
||||
const shouldMarkCompleted = isKnownFinalEpisode(pickedEpisodes, progress);
|
||||
if (typeof currentProgress === 'number' && currentProgress >= progress && !shouldMarkCompleted) {
|
||||
return {
|
||||
status: 'skipped',
|
||||
message: `AniList already at episode ${currentProgress} (${pickedTitle}).`,
|
||||
@@ -396,7 +403,7 @@ export async function updateAnilistPostWatchProgress(
|
||||
`,
|
||||
{
|
||||
mediaId,
|
||||
progress: episode,
|
||||
progress,
|
||||
status: shouldMarkCompleted ? 'COMPLETED' : 'CURRENT',
|
||||
},
|
||||
options,
|
||||
@@ -410,15 +417,15 @@ export async function updateAnilistPostWatchProgress(
|
||||
return {
|
||||
status: 'updated',
|
||||
message: shouldMarkCompleted
|
||||
? `AniList added "${pickedTitle}" at episode ${episode} and marked it completed.`
|
||||
: `AniList added "${pickedTitle}" to Watching at episode ${episode}.`,
|
||||
? `AniList added "${pickedTitle}" at episode ${progress} and marked it completed.`
|
||||
: `AniList added "${pickedTitle}" to Watching at episode ${progress}.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'updated',
|
||||
message: shouldMarkCompleted
|
||||
? `AniList updated "${pickedTitle}" to episode ${episode} and marked it completed.`
|
||||
: `AniList updated "${pickedTitle}" to episode ${episode}.`,
|
||||
? `AniList updated "${pickedTitle}" to episode ${progress} and marked it completed.`
|
||||
: `AniList updated "${pickedTitle}" to episode ${progress}.`,
|
||||
};
|
||||
}
|
||||
@@ -4,11 +4,22 @@ import assert from 'node:assert/strict';
|
||||
import {
|
||||
ANILIST_SEASON_RELATIONS_QUERY,
|
||||
ANILIST_SEASON_SEARCH_QUERY,
|
||||
namedSeasons,
|
||||
pickByAirOrder,
|
||||
resolveAnilistSeasonMedia,
|
||||
splitPartMarker,
|
||||
stripSeasonSuffix,
|
||||
type AnilistSeasonMedia,
|
||||
} from './season-resolver';
|
||||
import {
|
||||
AOT_CHAIN,
|
||||
BLEACH_TYBW_CHAIN,
|
||||
DR_STONE_CHAIN,
|
||||
JOJO_CHAIN,
|
||||
MUSHOKU_CHAIN,
|
||||
OVERLORD_CHAIN,
|
||||
REZERO_CHAIN,
|
||||
} from './__fixtures__/anilist-season-chains';
|
||||
|
||||
/** Real AniList payloads for "My Teen Romantic Comedy SNAFU", trimmed to used fields. */
|
||||
const OREGAIRU_SEARCH: AnilistSeasonMedia[] = [
|
||||
@@ -161,7 +172,8 @@ test('resolves season 3 by walking sequel relations', async () => {
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
// Searches the bare title only; "Season 3" returns nothing on AniList.
|
||||
assert.deepEqual(searches, ['My Teen Romantic Comedy SNAFU']);
|
||||
assert.deepEqual(relationLookups, [14813, 20698]);
|
||||
// The last lookup checks one season past the count for an entry naming season 3.
|
||||
assert.deepEqual(relationLookups, [14813, 20698, 108489]);
|
||||
});
|
||||
|
||||
test('season 1 resolves to the anchor without relation lookups', async () => {
|
||||
@@ -215,7 +227,7 @@ test('a sequel resolution whose own title matches the parsed title stays exact',
|
||||
);
|
||||
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
assert.equal(result?.via, 'named-season');
|
||||
assert.equal(result?.exactTitleMatch, true);
|
||||
});
|
||||
|
||||
@@ -325,7 +337,7 @@ test('prefers the TV sequel when a franchise branches into other formats', async
|
||||
const result = await resolveAnilistSeasonMedia({ title: 'Show', season: 2 }, { execute });
|
||||
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
assert.equal(result?.via, 'named-season');
|
||||
});
|
||||
|
||||
test('air-order fallback refuses when the anchor is not the earliest entry', () => {
|
||||
@@ -399,3 +411,288 @@ test('air-order fallback declines when a franchise entry has no air year', async
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
assert.equal(result?.via, 'anchor');
|
||||
});
|
||||
|
||||
/** Executor over a fixture chain: search returns the whole chain, entry i's SEQUEL is i + 1. */
|
||||
function createChainExecutor(chain: AnilistSeasonMedia[]) {
|
||||
const relations: Record<number, Array<{ relationType: string; node: AnilistSeasonMedia }>> = {};
|
||||
chain.forEach((entry, index) => {
|
||||
const next = chain[index + 1];
|
||||
relations[entry.id] = next ? [{ relationType: 'SEQUEL', node: next }] : [];
|
||||
});
|
||||
return createExecutor(chain, relations);
|
||||
}
|
||||
|
||||
async function resolveInChain(
|
||||
chain: AnilistSeasonMedia[],
|
||||
input: { title: string; season?: number | null; episode?: number | null },
|
||||
) {
|
||||
const executor = createChainExecutor(chain);
|
||||
const result = await resolveAnilistSeasonMedia(input, { execute: executor.execute });
|
||||
return { result, relationLookups: executor.relationLookups };
|
||||
}
|
||||
|
||||
test('split-cour back halves do not count as seasons', async () => {
|
||||
const title = 'Mushoku Tensei: Jobless Reincarnation';
|
||||
const s2 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 2, episode: 1 });
|
||||
assert.equal(s2.result?.id, 146065);
|
||||
assert.equal(s2.result?.seasonResolved, true);
|
||||
|
||||
const s3 = await resolveInChain(MUSHOKU_CHAIN, { title, season: 3, episode: 1 });
|
||||
assert.equal(s3.result?.id, 178789);
|
||||
// Four hops for two seasons: "Cour 2" and "Season 2 Part 2" were walked through.
|
||||
assert.deepEqual(s3.relationLookups, [108465, 127720, 146065, 166873]);
|
||||
|
||||
const reZeroS3 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 3 });
|
||||
assert.equal(reZeroS3.result?.id, 163134);
|
||||
const reZeroS4 = await resolveInChain(REZERO_CHAIN, { title: 'Re:ZERO', season: 4 });
|
||||
assert.equal(reZeroS4.result?.id, 189046);
|
||||
});
|
||||
|
||||
test('a special in the sequel chain is walked through without counting', async () => {
|
||||
const s3 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 3 });
|
||||
assert.equal(s3.result?.id, 131518);
|
||||
const s4 = await resolveInChain(DR_STONE_CHAIN, { title: 'Dr. STONE', season: 4 });
|
||||
assert.equal(s4.result?.id, 172019);
|
||||
});
|
||||
|
||||
test('season names ignore part and cour numbers, including localized ones', () => {
|
||||
// "Cour 2" carries the Thai synonym "... พาร์ท 2" ("part 2").
|
||||
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[1]!)], []);
|
||||
assert.deepEqual([...namedSeasons(MUSHOKU_CHAIN[3]!)], [2]);
|
||||
assert.deepEqual([...namedSeasons(OVERLORD_CHAIN[1]!)], [2]);
|
||||
assert.deepEqual([...namedSeasons(DR_STONE_CHAIN[1]!)], [2]);
|
||||
assert.deepEqual([...namedSeasons(AOT_CHAIN[4]!)], [4]);
|
||||
});
|
||||
|
||||
test('an entry naming the requested season beats the hop count', async () => {
|
||||
// The second cour has no marker anywhere, so counting alone would call it season 2.
|
||||
const chain: AnilistSeasonMedia[] = [
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show: Arc Two' } },
|
||||
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
|
||||
];
|
||||
const { result } = await resolveInChain(chain, { title: 'Show', season: 2 });
|
||||
assert.equal(result?.id, 3);
|
||||
assert.equal(result?.via, 'named-season');
|
||||
|
||||
const overlord = await resolveInChain(OVERLORD_CHAIN, { title: 'Overlord', season: 2 });
|
||||
assert.equal(overlord.result?.id, 98437);
|
||||
assert.equal(overlord.result?.via, 'named-season');
|
||||
});
|
||||
|
||||
test('a counted entry whose title names another season is not accepted', async () => {
|
||||
const chain: AnilistSeasonMedia[] = [
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2021, title: { english: 'Show: Arc Two' } },
|
||||
{ id: 3, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Show Season 2' } },
|
||||
];
|
||||
// Counting lands on id 3 for season 3, but it says it is season 2.
|
||||
const { result } = await resolveInChain(chain, { title: 'Show', season: 3 });
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
});
|
||||
|
||||
test('JoJo parts are seasons, not split-cour continuations', async () => {
|
||||
assert.equal(splitPartMarker('JoJo no Kimyou na Bouken Part 5: Ougon no Kaze'), null);
|
||||
assert.deepEqual(splitPartMarker("JoJo's Bizarre Adventure Part 5"), {
|
||||
base: 'jojo s bizarre adventure',
|
||||
part: 5,
|
||||
});
|
||||
// Golden Wind ends in "Part 5" and Stone Ocean in "Part 6": same base, different
|
||||
// parts, so Stone Ocean must still count as the next season.
|
||||
const { result } = await resolveInChain(JOJO_CHAIN, {
|
||||
title: "JoJo's Bizarre Adventure: Diamond is Unbreakable",
|
||||
season: 3,
|
||||
});
|
||||
assert.equal(result?.id, 131942);
|
||||
assert.equal(result?.via, 'sequel-chain');
|
||||
});
|
||||
|
||||
test('Attack on Titan resolves its final season past the season 3 back half', async () => {
|
||||
const { result } = await resolveInChain(AOT_CHAIN, { title: 'Attack on Titan', season: 4 });
|
||||
assert.equal(result?.id, 110277);
|
||||
});
|
||||
|
||||
test('air-order fallback drops back halves but keeps a season spelled "Part 1"', () => {
|
||||
// AoT season 3 carries the synonym "ผ่าพิภพไททัน ภาค 3 Part 1".
|
||||
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 3, AOT_CHAIN)?.id, 99147);
|
||||
assert.equal(pickByAirOrder(AOT_CHAIN[0]!, 4, AOT_CHAIN)?.id, 110277);
|
||||
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 3, MUSHOKU_CHAIN)?.id, 178789);
|
||||
// Only three real seasons have aired, so a fourth must not fall out of the list.
|
||||
assert.equal(pickByAirOrder(MUSHOKU_CHAIN[0]!, 4, MUSHOKU_CHAIN.slice(0, 5)), null);
|
||||
});
|
||||
|
||||
test('a TYBW cour marked only in a differently spelled synonym is not season 2', async () => {
|
||||
const { result } = await resolveInChain(BLEACH_TYBW_CHAIN, {
|
||||
title: 'BLEACH: Thousand-Year Blood War',
|
||||
season: 2,
|
||||
});
|
||||
// Every sequel is a later cour of the same season, so there is no season 2 to find.
|
||||
assert.equal(result?.seasonResolved, false);
|
||||
assert.equal(result?.id, 116674);
|
||||
});
|
||||
|
||||
test('an episode past the season entry lands on the split-cour part that airs it', async () => {
|
||||
const mushoku = await resolveInChain(MUSHOKU_CHAIN, {
|
||||
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
season: 1,
|
||||
episode: 15,
|
||||
});
|
||||
assert.equal(mushoku.result?.id, 108465);
|
||||
assert.equal(mushoku.result?.episodeEntry?.id, 127720);
|
||||
assert.equal(mushoku.result?.episodeEntry?.episode, 4);
|
||||
|
||||
const mushokuS2 = await resolveInChain(MUSHOKU_CHAIN, {
|
||||
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
season: 2,
|
||||
episode: 20,
|
||||
});
|
||||
assert.equal(mushokuS2.result?.id, 146065);
|
||||
assert.equal(mushokuS2.result?.episodeEntry?.id, 166873);
|
||||
assert.equal(mushokuS2.result?.episodeEntry?.episode, 7);
|
||||
|
||||
// Three cours of 13 + 13 + 14: episode 28 is the third cour's second.
|
||||
const bleach = await resolveInChain(BLEACH_TYBW_CHAIN, {
|
||||
title: 'BLEACH: Thousand-Year Blood War',
|
||||
episode: 28,
|
||||
});
|
||||
assert.equal(bleach.result?.id, 116674);
|
||||
assert.equal(bleach.result?.episodeEntry?.id, 169755);
|
||||
assert.equal(bleach.result?.episodeEntry?.episode, 2);
|
||||
});
|
||||
|
||||
test('an episode inside the season entry needs no remap or relation lookup', async () => {
|
||||
const { result, relationLookups } = await resolveInChain(MUSHOKU_CHAIN, {
|
||||
title: 'Mushoku Tensei: Jobless Reincarnation',
|
||||
season: 1,
|
||||
episode: 5,
|
||||
});
|
||||
assert.equal(result?.id, 108465);
|
||||
assert.equal(result?.episodeEntry, null);
|
||||
assert.deepEqual(relationLookups, []);
|
||||
});
|
||||
|
||||
test('an episode past a season with no continuation is not moved into the next season', async () => {
|
||||
const { result } = await resolveInChain(OVERLORD_CHAIN, {
|
||||
title: 'Overlord',
|
||||
season: 1,
|
||||
episode: 20,
|
||||
});
|
||||
assert.equal(result?.id, 20832);
|
||||
assert.equal(result?.episodeEntry, null);
|
||||
});
|
||||
|
||||
test('a sequel naming its own season is not a back half, even with a part synonym', async () => {
|
||||
const sequel: AnilistSeasonMedia = {
|
||||
id: 2,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
title: { english: 'Part Synonym Show Season 2' },
|
||||
synonyms: ['Part Synonym Show Part 2'],
|
||||
};
|
||||
// The anchor names season 1 itself...
|
||||
const named = await resolveInChain(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Part Synonym Show' },
|
||||
synonyms: ['Part Synonym Show Season 1'],
|
||||
},
|
||||
sequel,
|
||||
],
|
||||
{ title: 'Part Synonym Show', season: 2 },
|
||||
);
|
||||
assert.equal(named.result?.id, 2);
|
||||
// ...or is season 1 because the walk starts there.
|
||||
const unnamed = await resolveInChain(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Part Synonym Show' },
|
||||
},
|
||||
sequel,
|
||||
],
|
||||
{ title: 'Part Synonym Show', season: 2 },
|
||||
);
|
||||
assert.equal(unnamed.result?.id, 2);
|
||||
});
|
||||
|
||||
test('air order keeps a sequel naming its own season despite a part synonym', () => {
|
||||
const anchor: AnilistSeasonMedia = {
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Air Order Show' },
|
||||
};
|
||||
const sequel: AnilistSeasonMedia = {
|
||||
id: 2,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
title: { english: 'Air Order Show Season 2' },
|
||||
synonyms: ['Air Order Show Part 2'],
|
||||
};
|
||||
assert.equal(pickByAirOrder(anchor, 2, [anchor, sequel])?.id, 2);
|
||||
});
|
||||
|
||||
test('a season 1 episode past its length does not move to a longer later season', async () => {
|
||||
const { result } = await resolveInChain(
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
episodes: 12,
|
||||
format: 'TV',
|
||||
seasonYear: 2020,
|
||||
title: { english: 'Long Later Show' },
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
episodes: 24,
|
||||
format: 'TV',
|
||||
seasonYear: 2022,
|
||||
title: { english: 'Long Later Show Season 2' },
|
||||
},
|
||||
],
|
||||
{ title: 'Long Later Show', season: 1, episode: 20 },
|
||||
);
|
||||
assert.equal(result?.id, 1);
|
||||
assert.equal(result?.episodeEntry, null);
|
||||
});
|
||||
|
||||
test('a sequel that repeats its predecessor name is still a new season', async () => {
|
||||
// No part marker, so the identical title must not be read as a continuation.
|
||||
const chain: AnilistSeasonMedia[] = [
|
||||
{ id: 1, episodes: 12, format: 'TV', seasonYear: 2020, title: { english: 'Same Name Show' } },
|
||||
{ id: 2, episodes: 12, format: 'TV', seasonYear: 2022, title: { english: 'Same Name Show' } },
|
||||
];
|
||||
const { result } = await resolveInChain(chain, { title: 'Same Name Show', season: 2 });
|
||||
assert.equal(result?.id, 2);
|
||||
assert.equal(result?.seasonResolved, true);
|
||||
});
|
||||
|
||||
test('a rate limit mid-walk is surfaced instead of answered from air order', async () => {
|
||||
const { execute } = createChainExecutor(MUSHOKU_CHAIN);
|
||||
let relationCalls = 0;
|
||||
const failing = async <T>(query: string, variables: Record<string, unknown>): Promise<T> => {
|
||||
if (query === ANILIST_SEASON_RELATIONS_QUERY && ++relationCalls === 2) {
|
||||
throw new Error('AniList rate limited (429)');
|
||||
}
|
||||
return execute<T>(query, variables);
|
||||
};
|
||||
// Air order alone would answer season 3 correctly from this search result, but it must
|
||||
// not answer from a franchise picture the failed walk never confirmed.
|
||||
await assert.rejects(
|
||||
resolveAnilistSeasonMedia(
|
||||
{ title: 'Mushoku Tensei: Jobless Reincarnation', season: 3 },
|
||||
{ execute: failing },
|
||||
),
|
||||
/429/,
|
||||
);
|
||||
});
|
||||
@@ -9,6 +9,14 @@ import { sanitizeMediaTitle } from '../../../shared/media-identity';
|
||||
* season 1 anchor and then walking AniList SEQUEL relations, with an air-order fallback
|
||||
* when the relation chain is incomplete. When the seasonal entry cannot be located it
|
||||
* reports `seasonResolved: false` so callers can refuse to act instead of guessing.
|
||||
*
|
||||
* Not every SEQUEL hop is a new season. Along the chain:
|
||||
* - the back half of a split cour ("Part 2", "Cour 2", "第2クール") is its own entry,
|
||||
* - movies, specials and OVAs sit between seasons,
|
||||
* so the walk only counts entries that start a new TV season, and prefers an entry whose
|
||||
* title names the requested season ("Season 3", "3rd Season", "III", "第3期") over the
|
||||
* count. A continuation with no marker anywhere is indistinguishable from a new season;
|
||||
* the manual AniList override covers those.
|
||||
*/
|
||||
|
||||
import { normalizeTitleIdentity } from '../../utils/title-normalization';
|
||||
@@ -35,9 +43,29 @@ export type AnilistQueryExecutor = <T>(
|
||||
variables: Record<string, unknown>,
|
||||
) => Promise<T>;
|
||||
|
||||
export type AnilistSeasonResolutionVia = 'anchor' | 'sequel-chain' | 'air-order';
|
||||
export type AnilistSeasonResolutionVia = 'anchor' | 'named-season' | 'sequel-chain' | 'air-order';
|
||||
|
||||
/**
|
||||
* The entry that actually airs the parsed episode when it runs past the season entry
|
||||
* into a later part of the same season ("S1E15" of an 11 + 12 split cour is episode 4
|
||||
* of the "Cour 2" entry).
|
||||
*/
|
||||
export interface AnilistEpisodeEntry {
|
||||
id: number;
|
||||
title: string;
|
||||
episodes: number | null;
|
||||
media: AnilistSeasonMedia;
|
||||
/** Episode number within this entry. */
|
||||
episode: number;
|
||||
exactTitleMatch: boolean;
|
||||
}
|
||||
|
||||
export interface AnilistSeasonResolution {
|
||||
/**
|
||||
* The season's own entry (its first part). Season-level consumers (cover art, the
|
||||
* anime row's AniList link, the character dictionary) use this so every episode of a
|
||||
* split-cour season agrees on one id.
|
||||
*/
|
||||
id: number;
|
||||
title: string;
|
||||
episodes: number | null;
|
||||
@@ -48,6 +76,8 @@ export interface AnilistSeasonResolution {
|
||||
via: AnilistSeasonResolutionVia;
|
||||
/** Exact normalized match against an AniList title or synonym. */
|
||||
exactTitleMatch: boolean;
|
||||
/** Set only when the parsed episode belongs to a later part of the season. */
|
||||
episodeEntry: AnilistEpisodeEntry | null;
|
||||
}
|
||||
|
||||
export interface ResolveAnilistSeasonMediaInput {
|
||||
@@ -119,8 +149,79 @@ interface AnilistSeasonRelationsResponse {
|
||||
/** Formats that can carry a numbered TV season, best first. */
|
||||
const SEASONAL_FORMAT_PRIORITY = ['TV', 'TV_SHORT', 'ONA'];
|
||||
|
||||
/** An ONA this short is a special released online, not a season. */
|
||||
const MIN_ONA_SEASON_EPISODES = 3;
|
||||
|
||||
/** Largest season the chain walk will count to. */
|
||||
const MAX_SEQUEL_HOPS = 12;
|
||||
|
||||
/**
|
||||
* Hops the walk may take in total. Continuations and specials add hops without adding
|
||||
* seasons, so this has to leave room beyond the season number.
|
||||
*/
|
||||
const MAX_SEQUEL_STEPS = 24;
|
||||
|
||||
/** Parts a single season can be split into before the episode remap gives up. */
|
||||
const MAX_SEASON_PARTS = 6;
|
||||
|
||||
/**
|
||||
* Markers AniList appends when one broadcast season is listed as several entries,
|
||||
* matched against normalized titles. Anchored to the end so a numbered *work*
|
||||
* ("JoJo no Kimyou na Bouken Part 5: Ougon no Kaze") is not read as a continuation:
|
||||
* those carry a subtitle after the number and really are separate seasons.
|
||||
*/
|
||||
const PART_MARKER_PATTERNS: RegExp[] = [
|
||||
/\bpart\s*(\d{1,2}|i{1,3}|iv|v)$/u,
|
||||
/\bcour\s*(\d{1,2})$/u,
|
||||
/\b(\d{1,2})(?:st|nd|rd|th)\s+(?:part|cour)$/u,
|
||||
/\b(second|final)\s+(?:part|cour)$/u,
|
||||
/第\s*(\d{1,2})\s*(?:部|クール)$/u,
|
||||
];
|
||||
|
||||
const NUMBER_WORDS: Record<string, number> = {
|
||||
i: 1,
|
||||
ii: 2,
|
||||
iii: 3,
|
||||
iv: 4,
|
||||
v: 5,
|
||||
vi: 6,
|
||||
second: 2,
|
||||
third: 3,
|
||||
fourth: 4,
|
||||
fifth: 5,
|
||||
sixth: 6,
|
||||
一: 1,
|
||||
二: 2,
|
||||
三: 3,
|
||||
四: 4,
|
||||
五: 5,
|
||||
六: 6,
|
||||
七: 7,
|
||||
八: 8,
|
||||
九: 9,
|
||||
};
|
||||
|
||||
/**
|
||||
* Patterns that state a season outright. Safe on any title or synonym, because none of
|
||||
* them can be confused with a part or cour number.
|
||||
*/
|
||||
const EXPLICIT_SEASON_PATTERNS: RegExp[] = [
|
||||
/\bseason\s*(\d{1,2})\b/u,
|
||||
/\b(\d{1,2})(?:st|nd|rd|th)\s+season\b/u,
|
||||
/\b(second|third|fourth|fifth|sixth)\s+season\b/u,
|
||||
/\bs(\d{1,2})\b/u,
|
||||
/第\s*(\d{1,2}|[二三四五六七八九])\s*[期季]/u,
|
||||
/(\d{1,2})\s*(?:期|기)/u,
|
||||
];
|
||||
|
||||
/** Words after which a trailing number counts parts, not seasons. */
|
||||
const PART_WORDS = new Set(['part', 'cour', 'parte', 'partie']);
|
||||
|
||||
function parseNumberToken(token: string): number | null {
|
||||
if (/^\d{1,2}$/.test(token)) return Number(token);
|
||||
return NUMBER_WORDS[token] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops season markers a release name carries but AniList titles never do,
|
||||
* so "Some Show Season 3" and "Some Show S3" both search as "Some Show".
|
||||
@@ -134,13 +235,65 @@ export function stripSeasonSuffix(title: string): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
function mediaTitles(media: AnilistSeasonMedia): string[] {
|
||||
const synonyms = Array.isArray(media.synonyms) ? media.synonyms : [];
|
||||
return [media.title?.english, media.title?.romaji, media.title?.native, ...synonyms]
|
||||
/**
|
||||
* Splits a trailing part/cour marker off a title, or returns null when it has none.
|
||||
*
|
||||
* "Mushoku Tensei: Jobless Reincarnation Season 2 Part 2" is the back half of season 2,
|
||||
* not season 3. `part` is null for an unnumbered marker ("Final Cour").
|
||||
*/
|
||||
export function splitPartMarker(title: string): { base: string; part: number | null } | null {
|
||||
const normalized = normalizeTitleIdentity(title);
|
||||
for (const pattern of PART_MARKER_PATTERNS) {
|
||||
const match = normalized.match(pattern);
|
||||
if (!match || match.index === undefined) continue;
|
||||
const base = normalized.slice(0, match.index).trim();
|
||||
if (!base) continue;
|
||||
const token = match[1] ?? '';
|
||||
return { base, part: token === 'final' ? null : parseNumberToken(token) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mainTitles(media: AnilistSeasonMedia): string[] {
|
||||
return [media.title?.english, media.title?.romaji, media.title?.native]
|
||||
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||
.map((value) => normalizeTitleIdentity(value));
|
||||
}
|
||||
|
||||
function mediaTitles(media: AnilistSeasonMedia): string[] {
|
||||
const synonyms = (Array.isArray(media.synonyms) ? media.synonyms : [])
|
||||
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||
.map((value) => normalizeTitleIdentity(value));
|
||||
return [...mainTitles(media), ...synonyms].filter((value) => value.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Season numbers an entry's titles name.
|
||||
*
|
||||
* A bare trailing number ("Overlord II", "Konosuba 2") is only trusted on the main
|
||||
* titles: localized synonyms end in part numbers spelled in other scripts (Mushoku
|
||||
* Tensei's "Cour 2" carries the Thai "... พาร์ท 2", "part 2").
|
||||
*/
|
||||
export function namedSeasons(media: AnilistSeasonMedia): Set<number> {
|
||||
const seasons = new Set<number>();
|
||||
for (const title of mediaTitles(media)) {
|
||||
for (const pattern of EXPLICIT_SEASON_PATTERNS) {
|
||||
const token = title.match(pattern)?.[1];
|
||||
const value = token ? parseNumberToken(token) : null;
|
||||
if (value !== null && value > 0) seasons.add(value);
|
||||
}
|
||||
}
|
||||
for (const title of mainTitles(media)) {
|
||||
const words = title.split(' ');
|
||||
const last = words.at(-1) ?? '';
|
||||
const before = words.at(-2) ?? '';
|
||||
if (PART_WORDS.has(before)) continue;
|
||||
const value = parseNumberToken(last);
|
||||
if (value !== null && value > 1) seasons.add(value);
|
||||
}
|
||||
return seasons;
|
||||
}
|
||||
|
||||
function displayTitle(media: AnilistSeasonMedia, fallback: string): string {
|
||||
return (
|
||||
media.title?.english?.trim() ||
|
||||
@@ -167,29 +320,64 @@ function isSeasonalFormat(media: AnilistSeasonMedia): boolean {
|
||||
return SEASONAL_FORMAT_PRIORITY.includes(format);
|
||||
}
|
||||
|
||||
function formatRank(media: AnilistSeasonMedia): number {
|
||||
const index = SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase());
|
||||
return index < 0 ? SEASONAL_FORMAT_PRIORITY.length : index;
|
||||
/** Whether an entry can be a season: a TV series, or an ONA long enough not to be a special. */
|
||||
function isSeasonEntry(media: AnilistSeasonMedia): boolean {
|
||||
if (!isSeasonalFormat(media)) return false;
|
||||
if ((media.format || '').toUpperCase() !== 'ONA') return true;
|
||||
const episodes = episodeCount(media);
|
||||
return episodes === null || episodes >= MIN_ONA_SEASON_EPISODES;
|
||||
}
|
||||
|
||||
function toResolution(
|
||||
media: AnilistSeasonMedia,
|
||||
fallbackTitle: string,
|
||||
season: number | null,
|
||||
via: AnilistSeasonResolutionVia,
|
||||
seasonResolved: boolean,
|
||||
exactTitleMatch: boolean,
|
||||
): AnilistSeasonResolution {
|
||||
return {
|
||||
id: media.id,
|
||||
title: displayTitle(media, fallbackTitle),
|
||||
episodes: episodeCount(media),
|
||||
media,
|
||||
seasonResolved,
|
||||
requestedSeason: season,
|
||||
via,
|
||||
exactTitleMatch,
|
||||
};
|
||||
function formatRank(media: AnilistSeasonMedia): number {
|
||||
if (!isSeasonEntry(media)) return SEASONAL_FORMAT_PRIORITY.length;
|
||||
return SEASONAL_FORMAT_PRIORITY.indexOf((media.format || '').toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `next` continues the season `seasonStart` began rather than starting a new one.
|
||||
*
|
||||
* Compared against the season's first entry, not the previous hop, so a special between
|
||||
* a season and its second cour cannot hide the link. The marker is required, not just a
|
||||
* matching base: a sequel that repeats its predecessor's name exactly is a new season
|
||||
* AniList did not number. "Part 1" never marks a back half, and a season's own marker is
|
||||
* only stripped when it is "Part 1" (AoT season 3 carries "... ภาค 3 Part 1"); stripping
|
||||
* any number would read JoJo's "Part 6" as a continuation of its "Part 5".
|
||||
*
|
||||
* An entry naming a season never continues a different one: "Show Season 2" with the
|
||||
* synonym "Show Part 2" is season 2, not a back half of "Show". The season `seasonStart`
|
||||
* stands for is taken from its own titles, else from `startSeason` when the caller
|
||||
* knows it (the chain walk counts it, the episode remap was asked for it).
|
||||
*/
|
||||
function isSeasonContinuation(
|
||||
seasonStart: AnilistSeasonMedia,
|
||||
next: AnilistSeasonMedia,
|
||||
startSeason: number | null = null,
|
||||
): boolean {
|
||||
const markers = mediaTitles(next)
|
||||
.map((title) => splitPartMarker(title))
|
||||
.filter((marker): marker is NonNullable<typeof marker> => marker !== null && marker.part !== 1);
|
||||
if (markers.length === 0) return false;
|
||||
|
||||
const nextSeasons = namedSeasons(next);
|
||||
if (nextSeasons.size > 0) {
|
||||
const startNamed = namedSeasons(seasonStart);
|
||||
const startSeasons =
|
||||
startNamed.size > 0 ? startNamed : startSeason !== null ? new Set([startSeason]) : null;
|
||||
if (startSeasons && ![...nextSeasons].some((value) => startSeasons.has(value))) return false;
|
||||
}
|
||||
|
||||
const seasonKeys = new Set<string>();
|
||||
for (const title of mediaTitles(seasonStart)) {
|
||||
seasonKeys.add(title);
|
||||
const own = splitPartMarker(title);
|
||||
if (own?.part === 1) seasonKeys.add(own.base);
|
||||
}
|
||||
return markers.some((marker) => seasonKeys.has(marker.base));
|
||||
}
|
||||
|
||||
function exactMatchFor(candidate: AnilistSeasonMedia, titles: string[]): boolean {
|
||||
const candidateTitles = mediaTitles(candidate);
|
||||
return titles.some((title) => candidateTitles.includes(normalizeTitleIdentity(title)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -250,49 +438,31 @@ export function pickAnchorMedia(
|
||||
return scored[0]?.entry ?? null;
|
||||
}
|
||||
|
||||
async function walkSequelChain(
|
||||
anchor: AnilistSeasonMedia,
|
||||
season: number,
|
||||
deps: ResolveAnilistSeasonMediaDeps,
|
||||
): Promise<AnilistSeasonMedia | null> {
|
||||
// Walking fewer hops than requested would land on the wrong season and report it as
|
||||
// resolved, so refuse instead and let the caller fall through to its guarded fallback.
|
||||
const hops = season - 1;
|
||||
if (hops > MAX_SEQUEL_HOPS) {
|
||||
return null;
|
||||
}
|
||||
const visited = new Set<number>([anchor.id]);
|
||||
let current = anchor;
|
||||
/** SEQUEL entries of a media id, minus those already visited, best continuation first. */
|
||||
type SequelLookup = (id: number, visited: Set<number>) => Promise<AnilistSeasonMedia[]>;
|
||||
|
||||
for (let hop = 0; hop < hops; hop += 1) {
|
||||
// Transport errors propagate: a failed hop must not be mistaken for "no sequel exists".
|
||||
/**
|
||||
* Relation lookups for one resolution, memoized so the episode remap does not refetch
|
||||
* what the chain walk already loaded. Sorted with a season over a special, then the TV
|
||||
* line over other formats, then the earliest. Transport errors propagate: a failed lookup
|
||||
* must not be mistaken for "no sequel exists".
|
||||
*/
|
||||
function createSequelLookup(deps: ResolveAnilistSeasonMediaDeps): SequelLookup {
|
||||
const cache = new Map<number, Promise<AnilistSeasonMedia[]>>();
|
||||
const load = async (id: number): Promise<AnilistSeasonMedia[]> => {
|
||||
const response = await deps.execute<AnilistSeasonRelationsResponse>(
|
||||
ANILIST_SEASON_RELATIONS_QUERY,
|
||||
{ id: current.id },
|
||||
{ id },
|
||||
);
|
||||
|
||||
const sequels = (response.Media?.relations?.edges ?? [])
|
||||
.map((edge) => edge ?? null)
|
||||
.filter(
|
||||
(
|
||||
edge,
|
||||
): edge is {
|
||||
relationType?: string | null;
|
||||
node: AnilistSeasonMedia & { type?: string | null };
|
||||
} =>
|
||||
Boolean(edge?.node) &&
|
||||
(edge?.relationType || '').toUpperCase() === 'SEQUEL' &&
|
||||
(edge?.node?.type || 'ANIME').toUpperCase() === 'ANIME',
|
||||
)
|
||||
.map((edge) => edge.node)
|
||||
.filter((node) => !visited.has(node.id));
|
||||
|
||||
if (sequels.length === 0) {
|
||||
return null;
|
||||
const sequels: AnilistSeasonMedia[] = [];
|
||||
for (const edge of response.Media?.relations?.edges ?? []) {
|
||||
const node = edge?.node;
|
||||
if (!node || typeof node.id !== 'number') continue;
|
||||
if ((edge.relationType || '').toUpperCase() !== 'SEQUEL') continue;
|
||||
if ((node.type || 'ANIME').toUpperCase() !== 'ANIME') continue;
|
||||
sequels.push(node);
|
||||
}
|
||||
|
||||
// A franchise can branch (a TV sequel plus an ONA spinoff); prefer the TV line.
|
||||
sequels.sort((a, b) => {
|
||||
return sequels.sort((a, b) => {
|
||||
const rankDelta = formatRank(a) - formatRank(b);
|
||||
if (rankDelta !== 0) return rankDelta;
|
||||
const yearDelta =
|
||||
@@ -300,12 +470,121 @@ async function walkSequelChain(
|
||||
if (yearDelta !== 0) return yearDelta;
|
||||
return a.id - b.id;
|
||||
});
|
||||
};
|
||||
return async (id, visited) => {
|
||||
let pending = cache.get(id);
|
||||
if (!pending) {
|
||||
pending = load(id);
|
||||
cache.set(id, pending);
|
||||
// A failed lookup is retried by the next caller rather than cached.
|
||||
pending.catch(() => cache.delete(id));
|
||||
}
|
||||
return (await pending).filter((node) => !visited.has(node.id));
|
||||
};
|
||||
}
|
||||
|
||||
current = sequels[0]!;
|
||||
visited.add(current.id);
|
||||
type ChainResult = { media: AnilistSeasonMedia; via: 'named-season' | 'sequel-chain' };
|
||||
|
||||
async function walkSequelChain(
|
||||
anchor: AnilistSeasonMedia,
|
||||
season: number,
|
||||
sequelsOf: SequelLookup,
|
||||
): Promise<ChainResult | null> {
|
||||
// Advancing fewer seasons than requested would land on the wrong one and report it as
|
||||
// resolved, so refuse instead and let the caller fall through to its guarded fallback.
|
||||
const targetAdvances = season - 1;
|
||||
if (targetAdvances > MAX_SEQUEL_HOPS) {
|
||||
return null;
|
||||
}
|
||||
const visited = new Set<number>([anchor.id]);
|
||||
let current = anchor;
|
||||
// The last entry that counted as a season.
|
||||
let seasonStart = anchor;
|
||||
let advances = 0;
|
||||
// The unnamed entry the count landed on. The walk looks one season further before
|
||||
// accepting it, because an entry naming the requested season outranks the count: the
|
||||
// counted entry may be a continuation with no marker.
|
||||
let counted: AnilistSeasonMedia | null = null;
|
||||
// Set once counting reached the requested season on an entry whose title names a
|
||||
// different one. Only a named match can answer after that.
|
||||
let countContradicted = false;
|
||||
|
||||
for (let step = 0; step < MAX_SEQUEL_STEPS; step += 1) {
|
||||
const next = (await sequelsOf(current.id, visited))[0];
|
||||
if (!next) break;
|
||||
current = next;
|
||||
visited.add(next.id);
|
||||
|
||||
// Specials, movies and OVAs are walked through, because the rest of the franchise
|
||||
// hangs off them, but never counted.
|
||||
if (!isSeasonEntry(next)) continue;
|
||||
|
||||
const named = namedSeasons(next);
|
||||
if (isSeasonContinuation(seasonStart, next, advances + 1)) {
|
||||
// A back half naming the requested season ("Season 3 Part 2") vouches for the
|
||||
// entry its season started on.
|
||||
if (named.has(season)) return { media: seasonStart, via: 'named-season' };
|
||||
continue;
|
||||
}
|
||||
if (named.has(season)) return { media: next, via: 'named-season' };
|
||||
// The season after the counted one does not claim the requested number either.
|
||||
if (counted) break;
|
||||
if (countContradicted) {
|
||||
// Past the requested season by name: it is not on this chain.
|
||||
if ([...named].some((value) => value > season)) return null;
|
||||
continue;
|
||||
}
|
||||
|
||||
advances += 1;
|
||||
seasonStart = next;
|
||||
if (advances === targetAdvances) {
|
||||
if (named.size === 0) counted = next;
|
||||
else countContradicted = true;
|
||||
}
|
||||
}
|
||||
|
||||
return current.id === anchor.id ? null : current;
|
||||
return counted ? { media: counted, via: 'sequel-chain' } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the parsed episode runs past `seasonEntry` into a later part of the same season,
|
||||
* and if so, which entry airs it and at what episode number. Null when the episode fits
|
||||
* the season entry, its length is unknown, or no continuation covers the episode (e.g.
|
||||
* absolute numbering across seasons).
|
||||
*/
|
||||
async function findEpisodeEntry(
|
||||
seasonEntry: AnilistSeasonMedia,
|
||||
season: number,
|
||||
episode: number,
|
||||
sequelsOf: SequelLookup,
|
||||
): Promise<{ media: AnilistSeasonMedia; episode: number } | null> {
|
||||
const seasonLength = episodeCount(seasonEntry);
|
||||
if (seasonLength === null || episode <= seasonLength) return null;
|
||||
|
||||
const visited = new Set<number>([seasonEntry.id]);
|
||||
let current = seasonEntry;
|
||||
// The last part whose episodes are still counted in `remaining`; its length is known.
|
||||
let lastPart = seasonEntry;
|
||||
let remaining = episode;
|
||||
let parts = 1;
|
||||
|
||||
for (let step = 0; step < MAX_SEQUEL_STEPS; step += 1) {
|
||||
const next = (await sequelsOf(current.id, visited))[0];
|
||||
if (!next) return null;
|
||||
visited.add(next.id);
|
||||
current = next;
|
||||
// A recap special between the two halves airs none of the season's episodes.
|
||||
if (!isSeasonEntry(next)) continue;
|
||||
if (!isSeasonContinuation(seasonEntry, next, season)) return null;
|
||||
|
||||
remaining -= episodeCount(lastPart) ?? 0;
|
||||
lastPart = next;
|
||||
parts += 1;
|
||||
const length = episodeCount(next);
|
||||
if (length === null || remaining <= length) return { media: next, episode: remaining };
|
||||
if (parts >= MAX_SEASON_PARTS) return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -317,24 +596,45 @@ export function pickByAirOrder(
|
||||
season: number,
|
||||
media: AnilistSeasonMedia[],
|
||||
): AnilistSeasonMedia | null {
|
||||
const anchorTitles = mediaTitles(anchor).map((value) => stripSeasonSuffix(value));
|
||||
const anchorBase = anchorTitles.sort((a, b) => a.length - b.length)[0];
|
||||
if (!anchorBase) return null;
|
||||
// Any of the anchor's main titles, matched on word boundaries. Synonyms are too short
|
||||
// and loose ("SnK", "ReZero") to define a franchise, and a single title misses entries
|
||||
// that only spell another one out (Mushoku Tensei II's native title adds "Ⅱ" to the
|
||||
// word the season 1 native title ends on).
|
||||
const anchorBases = mainTitles(anchor)
|
||||
.map((value) => stripSeasonSuffix(value))
|
||||
.filter((value) => value.length > 0);
|
||||
if (anchorBases.length === 0) return null;
|
||||
|
||||
const franchise = media.filter((entry) => {
|
||||
if (!isSeasonalFormat(entry)) return false;
|
||||
if (!isSeasonEntry(entry)) return false;
|
||||
if (entry.id === anchor.id) return true;
|
||||
return mediaTitles(entry).some((candidate) =>
|
||||
stripSeasonSuffix(candidate).includes(anchorBase),
|
||||
return mediaTitles(entry).some((candidate) => {
|
||||
const padded = ` ${stripSeasonSuffix(candidate)} `;
|
||||
return anchorBases.some((base) => padded.includes(` ${base} `));
|
||||
});
|
||||
});
|
||||
|
||||
// Drop the back halves of split-cour seasons, which are separate entries here but not
|
||||
// separate seasons: counting them shifts every later season index. An entry is only
|
||||
// compared against the *other* entries' titles, so a season whose own localized synonym
|
||||
// spells it "<season> Part 1" is kept.
|
||||
const seasons = franchise.filter((entry) => {
|
||||
if (entry.id === anchor.id) return true;
|
||||
// The anchor is season 1 here, which lets the continuation check reject an entry
|
||||
// naming another season even when the anchor's own titles name none.
|
||||
return !franchise.some(
|
||||
(other) =>
|
||||
other.id !== entry.id &&
|
||||
isSeasonContinuation(other, entry, other.id === anchor.id ? 1 : null),
|
||||
);
|
||||
});
|
||||
if (franchise.length < season) return null;
|
||||
if (seasons.length < season) return null;
|
||||
|
||||
// Ordering by air date is only meaningful when every entry has one: an unknown year
|
||||
// would sort last and shift the season index while still reporting a resolved match.
|
||||
if (franchise.some((entry) => airYear(entry) === null)) return null;
|
||||
if (seasons.some((entry) => airYear(entry) === null)) return null;
|
||||
|
||||
const ordered = [...franchise].sort((a, b) => {
|
||||
const ordered = [...seasons].sort((a, b) => {
|
||||
const yearDelta = (airYear(a) ?? 0) - (airYear(b) ?? 0);
|
||||
if (yearDelta !== 0) return yearDelta;
|
||||
return a.id - b.id;
|
||||
@@ -343,7 +643,12 @@ export function pickByAirOrder(
|
||||
// The anchor has to be the first entry, otherwise this ordering is not a season list.
|
||||
if (ordered[0]?.id !== anchor.id) return null;
|
||||
|
||||
return ordered[season - 1] ?? null;
|
||||
const picked = ordered[season - 1] ?? null;
|
||||
if (!picked) return null;
|
||||
// An entry that names some other season shows this ordering is off.
|
||||
const named = namedSeasons(picked);
|
||||
if (named.size > 0 && !named.has(season)) return null;
|
||||
return picked;
|
||||
}
|
||||
|
||||
export async function resolveAnilistSeasonMedia(
|
||||
@@ -359,6 +664,10 @@ export async function resolveAnilistSeasonMedia(
|
||||
typeof input.season === 'number' && Number.isInteger(input.season) && input.season > 0
|
||||
? input.season
|
||||
: null;
|
||||
const episode =
|
||||
typeof input.episode === 'number' && Number.isInteger(input.episode) && input.episode > 0
|
||||
? input.episode
|
||||
: null;
|
||||
|
||||
const response = await deps.execute<AnilistSeasonSearchResponse>(ANILIST_SEASON_SEARCH_QUERY, {
|
||||
search: searchTitle,
|
||||
@@ -368,72 +677,83 @@ export async function resolveAnilistSeasonMedia(
|
||||
);
|
||||
if (media.length === 0) return null;
|
||||
|
||||
// Season 1 (or unknown) resolves against the episode count; later seasons must not,
|
||||
// because the anchor is season 1 and may be shorter than the requested episode.
|
||||
const anchor = pickAnchorMedia(searchTitle, media, {
|
||||
episode: season === null || season <= 1 ? input.episode : null,
|
||||
});
|
||||
if (!anchor) return null;
|
||||
// Certifies the media actually returned, never the anchor on its behalf: a
|
||||
// sequel-chain hop can land one season short (split-cour entries) while the
|
||||
// anchor title still matches perfectly, and that certainty must not carry
|
||||
// over to the hopped-to entry.
|
||||
const exactMatchFor = (candidate: AnilistSeasonMedia): boolean => {
|
||||
const titles = mediaTitles(candidate);
|
||||
return (
|
||||
titles.includes(normalizeTitleIdentity(searchTitle)) ||
|
||||
titles.includes(normalizeTitleIdentity(input.title))
|
||||
);
|
||||
// Certifies the media actually returned, never the anchor on its behalf: a hop can land
|
||||
// on the wrong entry while the anchor title still matches perfectly, and that certainty
|
||||
// must not carry over to the hopped-to entry.
|
||||
const parsedTitles = [searchTitle, input.title];
|
||||
const sequelsOf = createSequelLookup(deps);
|
||||
|
||||
const finish = (
|
||||
seasonEntry: AnilistSeasonMedia,
|
||||
via: AnilistSeasonResolutionVia,
|
||||
split: { media: AnilistSeasonMedia; episode: number } | null = null,
|
||||
seasonResolved = true,
|
||||
): AnilistSeasonResolution => {
|
||||
if (split) {
|
||||
deps.logInfo?.(
|
||||
`[anilist] episode ${episode} of "${searchTitle}" is episode ${split.episode} of ${displayTitle(split.media, searchTitle)} (${split.media.id})`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
id: seasonEntry.id,
|
||||
title: displayTitle(seasonEntry, searchTitle),
|
||||
episodes: episodeCount(seasonEntry),
|
||||
media: seasonEntry,
|
||||
seasonResolved,
|
||||
requestedSeason: season,
|
||||
via,
|
||||
exactTitleMatch: exactMatchFor(seasonEntry, parsedTitles),
|
||||
episodeEntry: split
|
||||
? {
|
||||
id: split.media.id,
|
||||
title: displayTitle(split.media, searchTitle),
|
||||
episodes: episodeCount(split.media),
|
||||
media: split.media,
|
||||
episode: split.episode,
|
||||
exactTitleMatch: exactMatchFor(split.media, parsedTitles),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
};
|
||||
|
||||
if (season === null || season <= 1) {
|
||||
return toResolution(anchor, searchTitle, season, 'anchor', true, exactMatchFor(anchor));
|
||||
// The best title match first. If the episode runs past it, a split-cour continuation
|
||||
// may air it ("S1E15" of 11 + 12). Only when none does, and the title match is not a
|
||||
// season itself (a same-titled movie or special), is the episode count used to pick
|
||||
// a longer entry; it must not swap season 1 for a later, longer season.
|
||||
const titleAnchor = pickAnchorMedia(searchTitle, media);
|
||||
if (!titleAnchor) return null;
|
||||
if (episode === null) return finish(titleAnchor, 'anchor');
|
||||
const split = await findEpisodeEntry(titleAnchor, 1, episode, sequelsOf);
|
||||
if (split) return finish(titleAnchor, 'anchor', split);
|
||||
if (isSeasonEntry(titleAnchor)) return finish(titleAnchor, 'anchor');
|
||||
const fitted = pickAnchorMedia(searchTitle, media, { episode });
|
||||
const laterSeason = fitted !== null && [...namedSeasons(fitted)].some((value) => value > 1);
|
||||
return finish(fitted && !laterSeason ? fitted : titleAnchor, 'anchor');
|
||||
}
|
||||
|
||||
let chainError: unknown = null;
|
||||
let viaChain: AnilistSeasonMedia | null = null;
|
||||
try {
|
||||
viaChain = await walkSequelChain(anchor, season, deps);
|
||||
} catch (error) {
|
||||
chainError = error;
|
||||
}
|
||||
if (viaChain) {
|
||||
// Later seasons must not filter by episode, because the anchor is season 1 and may be
|
||||
// shorter than the requested episode.
|
||||
const anchor = pickAnchorMedia(searchTitle, media);
|
||||
if (!anchor) return null;
|
||||
|
||||
// Transport failures propagate from here: the air-order fallback is for a chain that
|
||||
// answered and had no edge to follow, and running it after a failed hop would turn a
|
||||
// rate limit into a confident wrong season.
|
||||
const viaChain = await walkSequelChain(anchor, season, sequelsOf);
|
||||
const seasonEntry = viaChain?.media ?? pickByAirOrder(anchor, season, media);
|
||||
if (seasonEntry) {
|
||||
const via = viaChain?.via ?? 'air-order';
|
||||
deps.logInfo?.(
|
||||
`[anilist] season ${season} of "${searchTitle}" resolved via sequel chain: ${displayTitle(viaChain, searchTitle)} (${viaChain.id})`,
|
||||
`[anilist] season ${season} of "${searchTitle}" resolved via ${via}: ${displayTitle(seasonEntry, searchTitle)} (${seasonEntry.id})`,
|
||||
);
|
||||
return toResolution(
|
||||
viaChain,
|
||||
searchTitle,
|
||||
season,
|
||||
'sequel-chain',
|
||||
true,
|
||||
exactMatchFor(viaChain),
|
||||
);
|
||||
}
|
||||
|
||||
const viaAirOrder = pickByAirOrder(anchor, season, media);
|
||||
if (viaAirOrder) {
|
||||
deps.logInfo?.(
|
||||
`[anilist] season ${season} of "${searchTitle}" resolved via air order: ${displayTitle(viaAirOrder, searchTitle)} (${viaAirOrder.id})`,
|
||||
);
|
||||
return toResolution(
|
||||
viaAirOrder,
|
||||
searchTitle,
|
||||
season,
|
||||
'air-order',
|
||||
true,
|
||||
exactMatchFor(viaAirOrder),
|
||||
);
|
||||
}
|
||||
|
||||
// The chain failed for transport reasons rather than because the season is absent;
|
||||
// surface that so callers retry instead of reporting an unresolvable season.
|
||||
if (chainError) {
|
||||
throw chainError;
|
||||
const split =
|
||||
episode === null ? null : await findEpisodeEntry(seasonEntry, season, episode, sequelsOf);
|
||||
return finish(seasonEntry, via, split);
|
||||
}
|
||||
|
||||
deps.logInfo?.(
|
||||
`[anilist] could not resolve season ${season} of "${searchTitle}"; falling back to ${displayTitle(anchor, searchTitle)} (${anchor.id})`,
|
||||
);
|
||||
return toResolution(anchor, searchTitle, season, 'anchor', false, exactMatchFor(anchor));
|
||||
return finish(anchor, 'anchor', null, false);
|
||||
}
|
||||
@@ -87,7 +87,6 @@ function createControllerConfigFixture() {
|
||||
dpadFallback: 'horizontal' as const,
|
||||
},
|
||||
leftStickVertical: { kind: 'axis' as const, axisIndex: 1, dpadFallback: 'vertical' as const },
|
||||
rightStickHorizontal: { kind: 'axis' as const, axisIndex: 3, dpadFallback: 'none' as const },
|
||||
rightStickVertical: { kind: 'axis' as const, axisIndex: 4, dpadFallback: 'none' as const },
|
||||
},
|
||||
reviewBindings: getDefaultControllerReviewBindings(),
|
||||
|
||||
@@ -40,10 +40,14 @@ import {
|
||||
parseSessionActionDispatchRequest,
|
||||
parseSubtitlePosition,
|
||||
parseSubsyncManualRunRequest,
|
||||
parseUnforwardedMpvKeyReport,
|
||||
parseYoutubePickerResolveRequest,
|
||||
} from '../../shared/ipc/validators';
|
||||
import { createLogger } from '../../logger';
|
||||
import { applyOverlayClickThrough } from './overlay-click-through';
|
||||
|
||||
const overlayInputLogger = createLogger('overlay:input');
|
||||
|
||||
const { ipcMain } = electron;
|
||||
|
||||
export interface IpcServiceDeps {
|
||||
@@ -640,6 +644,12 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
|
||||
},
|
||||
);
|
||||
|
||||
// Shows, at --log-level debug, why an mpv input.conf key never reached mpv.
|
||||
ipc.on(IPC_CHANNELS.command.reportUnforwardedMpvKey, (_event: unknown, payload: unknown) => {
|
||||
const report = parseUnforwardedMpvKeyReport(payload);
|
||||
if (report) overlayInputLogger.debug('Overlay kept an mpv-bound key', report);
|
||||
});
|
||||
|
||||
ipc.on(IPC_CHANNELS.command.recordYomitanLookup, (_event: unknown, payload: unknown) => {
|
||||
try {
|
||||
deps.recordSubtitleMiningContext?.(parseSubtitleMiningContext(payload));
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
createOverlayVisibilityDiagnostics,
|
||||
readOverlayVisibilitySnapshot,
|
||||
type OverlayVisibilitySnapshot,
|
||||
} from './overlay-visibility-diagnostics';
|
||||
|
||||
type SnapshotArgs = Parameters<typeof readOverlayVisibilitySnapshot>[0];
|
||||
|
||||
function snapshotFor(
|
||||
options: {
|
||||
tracking?: boolean;
|
||||
targetPid?: number | null;
|
||||
minimized?: boolean;
|
||||
window?: Record<string, unknown>;
|
||||
noTracker?: boolean;
|
||||
} & Pick<SnapshotArgs, 'modalActive' | 'suspendVisibleOverlay'> & {
|
||||
visibleOverlayVisible?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
const tracker = {
|
||||
isTracking: () => options.tracking ?? false,
|
||||
getGeometry: () => null,
|
||||
isTargetWindowFocused: () => false,
|
||||
isTargetWindowMinimized: () => options.minimized ?? false,
|
||||
getDiagnosticState: () => ({ targetPid: options.targetPid ?? null, socketPath: '/tmp/mpv' }),
|
||||
};
|
||||
return readOverlayVisibilitySnapshot({
|
||||
mainWindow: {
|
||||
isDestroyed: () => false,
|
||||
isVisible: () => false,
|
||||
getOpacity: () => 0,
|
||||
...options.window,
|
||||
} as unknown as SnapshotArgs['mainWindow'],
|
||||
windowTracker: options.noTracker ? null : (tracker as unknown as SnapshotArgs['windowTracker']),
|
||||
visibleOverlayVisible: options.visibleOverlayVisible ?? true,
|
||||
modalActive: options.modalActive,
|
||||
suspendVisibleOverlay: options.suspendVisibleOverlay,
|
||||
});
|
||||
}
|
||||
|
||||
function harness() {
|
||||
let now = 0;
|
||||
let callback: (() => void) | null = null;
|
||||
let delay = 0;
|
||||
const warnings: Array<{ message: string; details: Record<string, unknown> }> = [];
|
||||
let snapshot: OverlayVisibilitySnapshot | null = {
|
||||
expectedVisible: true,
|
||||
visible: false,
|
||||
opacity: 0,
|
||||
contentReady: false,
|
||||
tracking: false,
|
||||
targetPid: 4242,
|
||||
pidLookupPending: false,
|
||||
};
|
||||
const diagnostics = createOverlayVisibilityDiagnostics({
|
||||
now: () => now,
|
||||
warn: (message, details) => warnings.push({ message, details }),
|
||||
schedule: (fn, ms) => {
|
||||
callback = fn;
|
||||
delay = ms;
|
||||
return { unref() {} } as ReturnType<typeof setTimeout>;
|
||||
},
|
||||
cancel: () => {
|
||||
callback = null;
|
||||
},
|
||||
});
|
||||
const update = () => diagnostics.update(() => snapshot);
|
||||
return {
|
||||
warnings,
|
||||
update,
|
||||
setSnapshot: (value: typeof snapshot) => {
|
||||
snapshot = value;
|
||||
},
|
||||
tick: () => {
|
||||
assert.ok(callback, 'watchdog must be scheduled');
|
||||
now += delay;
|
||||
callback();
|
||||
},
|
||||
scheduled: () => callback !== null,
|
||||
};
|
||||
}
|
||||
|
||||
test('visibility watchdog warns without more events and rate limits repeated polls', () => {
|
||||
const h = harness();
|
||||
h.update();
|
||||
assert.equal(h.warnings.length, 0);
|
||||
for (let i = 0; i < 100; i += 1) h.update();
|
||||
h.tick();
|
||||
assert.equal(h.warnings.length, 1);
|
||||
assert.equal(h.warnings[0]?.details.reason, 'mpv-window-not-tracked');
|
||||
assert.equal(h.warnings[0]?.details.targetPid, 4242);
|
||||
assert.equal(h.warnings[0]?.details.elapsedMs, 5_000);
|
||||
for (let i = 0; i < 100; i += 1) h.update();
|
||||
assert.equal(h.warnings.length, 1);
|
||||
h.tick();
|
||||
assert.equal(h.warnings[1]?.details.elapsedMs, 35_000);
|
||||
});
|
||||
|
||||
test('visibility watchdog distinguishes renderer readiness, hidden windows and opacity', () => {
|
||||
for (const [contentReady, visible, opacity, reason] of [
|
||||
[false, false, 0, 'renderer-not-ready'],
|
||||
[true, false, 0, 'window-hidden'],
|
||||
[true, true, 0, 'window-transparent'],
|
||||
] as const) {
|
||||
const h = harness();
|
||||
h.setSnapshot({ expectedVisible: true, tracking: true, contentReady, visible, opacity });
|
||||
h.update();
|
||||
h.tick();
|
||||
assert.equal(h.warnings[0]?.details.reason, reason);
|
||||
}
|
||||
});
|
||||
|
||||
test('visibility watchdog reports recovery only after warning and stops', () => {
|
||||
const h = harness();
|
||||
h.update();
|
||||
h.tick();
|
||||
h.setSnapshot({
|
||||
expectedVisible: true,
|
||||
visible: true,
|
||||
opacity: 1,
|
||||
contentReady: true,
|
||||
tracking: true,
|
||||
});
|
||||
h.tick();
|
||||
assert.match(h.warnings[1]!.message, /recovered/);
|
||||
assert.equal(h.scheduled(), false);
|
||||
h.update();
|
||||
assert.equal(h.warnings.length, 2);
|
||||
});
|
||||
|
||||
test('visibility watchdog stays quiet after fast startup, intentional hide or window destruction', () => {
|
||||
for (const snapshot of [
|
||||
{ expectedVisible: true, visible: true, opacity: 1, contentReady: true, tracking: true },
|
||||
{ expectedVisible: false, visible: false, opacity: 0, contentReady: false, tracking: false },
|
||||
null,
|
||||
]) {
|
||||
const h = harness();
|
||||
h.update();
|
||||
h.setSnapshot(snapshot);
|
||||
h.tick();
|
||||
assert.deepEqual(h.warnings, []);
|
||||
assert.equal(h.scheduled(), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('overlay snapshot expects visibility only once an mpv has been identified', () => {
|
||||
// Requested before any mpv exists: auto_start_overlay, tray or --show-visible-overlay.
|
||||
assert.equal(snapshotFor()?.expectedVisible, false);
|
||||
assert.equal(snapshotFor({ noTracker: true })?.expectedVisible, false);
|
||||
// mpv answered on the socket but its window never matched, so tracking never started.
|
||||
assert.equal(snapshotFor({ targetPid: 4242 })?.expectedVisible, true);
|
||||
// A tracker with no target socket matches windows without ever learning a PID.
|
||||
assert.equal(snapshotFor({ tracking: true })?.expectedVisible, true);
|
||||
});
|
||||
|
||||
test('overlay snapshot does not expect an intentionally hidden overlay', () => {
|
||||
const identified = { targetPid: 4242, tracking: true };
|
||||
assert.equal(snapshotFor(identified)?.expectedVisible, true);
|
||||
assert.equal(snapshotFor({ ...identified, modalActive: true })?.expectedVisible, false);
|
||||
assert.equal(snapshotFor({ ...identified, suspendVisibleOverlay: true })?.expectedVisible, false);
|
||||
assert.equal(snapshotFor({ ...identified, minimized: true })?.expectedVisible, false);
|
||||
assert.equal(
|
||||
snapshotFor({ ...identified, visibleOverlayVisible: false })?.expectedVisible,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('overlay snapshot carries tracker state, defaults opacity and ends with the window', () => {
|
||||
const snapshot = snapshotFor({ targetPid: 4242, window: { getOpacity: undefined } });
|
||||
assert.equal(snapshot?.targetPid, 4242);
|
||||
assert.equal(snapshot?.socketPath, '/tmp/mpv');
|
||||
assert.equal(snapshot?.opacity, 1);
|
||||
assert.equal(snapshotFor({ window: { isDestroyed: () => true } }), null);
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import type { BaseWindowTracker } from '../../window-trackers';
|
||||
import { createLogger } from '../../logger';
|
||||
import {
|
||||
OVERLAY_WINDOW_CONTENT_READY_FLAG,
|
||||
OVERLAY_WINDOW_DOCUMENT_LOADED_FLAG,
|
||||
} from './overlay-window-flags';
|
||||
|
||||
const log = createLogger('overlay:visibility');
|
||||
|
||||
export type OverlayVisibilitySnapshot = {
|
||||
expectedVisible: boolean;
|
||||
visible: boolean;
|
||||
opacity: number;
|
||||
contentReady: boolean;
|
||||
tracking: boolean;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
// One watchdog per window, independent of further visibility events: a renderer
|
||||
// that never becomes ready must still leave evidence at the default warn level.
|
||||
export function createOverlayVisibilityDiagnostics(deps: {
|
||||
warn: (message: string, details: Record<string, unknown>) => void;
|
||||
now: () => number;
|
||||
schedule: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
|
||||
cancel: (timer: ReturnType<typeof setTimeout>) => void;
|
||||
}) {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let readSnapshot: () => OverlayVisibilitySnapshot | null = () => null;
|
||||
let stalledAtMs: number | null = null;
|
||||
let warned = false;
|
||||
let lastWarningAtMs = 0;
|
||||
|
||||
const check = () => {
|
||||
if (timer !== null) deps.cancel(timer);
|
||||
timer = null;
|
||||
const snapshot = readSnapshot();
|
||||
if (!snapshot?.expectedVisible) {
|
||||
stalledAtMs = null;
|
||||
warned = false;
|
||||
return;
|
||||
}
|
||||
if (snapshot.visible && snapshot.opacity > 0 && snapshot.contentReady) {
|
||||
if (warned) {
|
||||
deps.warn('Windows overlay visibility recovered', {
|
||||
...snapshot,
|
||||
elapsedMs: deps.now() - stalledAtMs!,
|
||||
});
|
||||
}
|
||||
stalledAtMs = null;
|
||||
warned = false;
|
||||
return;
|
||||
}
|
||||
stalledAtMs ??= deps.now();
|
||||
const elapsedMs = deps.now() - stalledAtMs;
|
||||
if (elapsedMs >= 5_000 && (!warned || deps.now() - lastWarningAtMs >= 30_000)) {
|
||||
const reason = !snapshot.tracking
|
||||
? 'mpv-window-not-tracked'
|
||||
: !snapshot.contentReady
|
||||
? 'renderer-not-ready'
|
||||
: !snapshot.visible
|
||||
? 'window-hidden'
|
||||
: 'window-transparent';
|
||||
deps.warn('Windows overlay is not visible after startup or tracking loss', {
|
||||
...snapshot,
|
||||
reason,
|
||||
elapsedMs,
|
||||
});
|
||||
warned = true;
|
||||
lastWarningAtMs = deps.now();
|
||||
}
|
||||
timer = deps.schedule(
|
||||
check,
|
||||
warned ? 30_000 - (deps.now() - lastWarningAtMs) : 5_000 - elapsedMs,
|
||||
);
|
||||
timer.unref?.();
|
||||
};
|
||||
|
||||
return {
|
||||
update(reader: () => OverlayVisibilitySnapshot | null) {
|
||||
readSnapshot = reader;
|
||||
// Frequent polls must not postpone a warning or bypass its rate limit.
|
||||
check();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const diagnosticsByWindow = new WeakMap<
|
||||
BrowserWindow,
|
||||
ReturnType<typeof createOverlayVisibilityDiagnostics>
|
||||
>();
|
||||
|
||||
type OverlayVisibilityWatchArgs = {
|
||||
mainWindow: BrowserWindow;
|
||||
windowTracker: BaseWindowTracker | null;
|
||||
visibleOverlayVisible: boolean;
|
||||
modalActive?: boolean;
|
||||
suspendVisibleOverlay?: boolean;
|
||||
};
|
||||
|
||||
export function readOverlayVisibilitySnapshot(
|
||||
args: OverlayVisibilityWatchArgs,
|
||||
): OverlayVisibilitySnapshot | null {
|
||||
const window = args.mainWindow;
|
||||
if (window.isDestroyed()) return null;
|
||||
const tracker = args.windowTracker as
|
||||
| (BaseWindowTracker & {
|
||||
getDiagnosticState?: () => { targetPid?: number | null } & Record<string, unknown>;
|
||||
})
|
||||
| null;
|
||||
const trackerState = tracker?.getDiagnosticState?.();
|
||||
const flags = window as unknown as Record<string, unknown>;
|
||||
const minimized = tracker?.isTargetWindowMinimized?.() ?? false;
|
||||
const tracking = tracker?.isTracking() ?? false;
|
||||
// The overlay may be requested with no mpv to attach to (auto_start_overlay, tray,
|
||||
// --show-visible-overlay), so it only counts as stalled once an mpv has answered on the
|
||||
// socket. That still covers an mpv whose window never matches, which never starts tracking.
|
||||
const mpvIdentified = tracking || (trackerState?.targetPid ?? null) !== null;
|
||||
return {
|
||||
...trackerState,
|
||||
expectedVisible:
|
||||
args.visibleOverlayVisible &&
|
||||
mpvIdentified &&
|
||||
!args.modalActive &&
|
||||
!args.suspendVisibleOverlay &&
|
||||
!minimized,
|
||||
visible: window.isVisible(),
|
||||
opacity: window.getOpacity?.() ?? 1,
|
||||
contentReady: flags[OVERLAY_WINDOW_CONTENT_READY_FLAG] === true,
|
||||
documentLoaded: flags[OVERLAY_WINDOW_DOCUMENT_LOADED_FLAG] === true,
|
||||
rendererLoading: window.webContents?.isLoading?.() ?? null,
|
||||
tracking,
|
||||
trackerInitialized: tracker !== null,
|
||||
geometry: tracker?.getGeometry() ?? null,
|
||||
focused: tracker?.isTargetWindowFocused?.() ?? false,
|
||||
minimized,
|
||||
};
|
||||
}
|
||||
|
||||
export function watchWindowsOverlayVisibility(args: OverlayVisibilityWatchArgs): void {
|
||||
const window = args.mainWindow;
|
||||
let diagnostics = diagnosticsByWindow.get(window);
|
||||
if (!diagnostics) {
|
||||
diagnostics = createOverlayVisibilityDiagnostics({
|
||||
warn: (message, details) => log.warn(message, details),
|
||||
now: Date.now,
|
||||
schedule: setTimeout,
|
||||
cancel: clearTimeout,
|
||||
});
|
||||
diagnosticsByWindow.set(window, diagnostics);
|
||||
}
|
||||
diagnostics.update(() => readOverlayVisibilitySnapshot(args));
|
||||
}
|
||||
@@ -589,6 +589,34 @@ runScenarios([
|
||||
},
|
||||
]);
|
||||
|
||||
test('only a live Windows overlay reads visibility diagnostics', () => {
|
||||
const diagnosticReads = (platform: Platform, overrides: Partial<VisibilityArgs> = {}): number => {
|
||||
let reads = 0;
|
||||
createHarness({ platform, tracker: tracked() }).run({
|
||||
windowTracker: {
|
||||
isTracking: () => true,
|
||||
getGeometry: () => GEOMETRY,
|
||||
getDiagnosticState: () => {
|
||||
reads += 1;
|
||||
return { targetPid: 4242 };
|
||||
},
|
||||
} as unknown as VisibilityArgs['windowTracker'],
|
||||
...overrides,
|
||||
});
|
||||
return reads;
|
||||
};
|
||||
|
||||
assert.equal(diagnosticReads('windows'), 1);
|
||||
assert.equal(diagnosticReads('linux'), 0);
|
||||
assert.equal(diagnosticReads('macos'), 0);
|
||||
assert.equal(
|
||||
diagnosticReads('windows', {
|
||||
mainWindow: { isDestroyed: () => true } as unknown as VisibilityArgs['mainWindow'],
|
||||
}),
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
test('Windows visible overlay restores opacity and rebinds after the deferred reveal delay', async () => {
|
||||
const h = createHarness({ platform: 'windows', tracker: tracked() });
|
||||
assertOutcome(h.run(), { opacity: 0, zOrderSyncs: 1 });
|
||||
|
||||
@@ -3,6 +3,7 @@ import { BaseWindowTracker } from '../../window-trackers';
|
||||
import { WindowGeometry } from '../../types';
|
||||
import { applyOverlayClickThrough } from './overlay-click-through';
|
||||
import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags';
|
||||
import { watchWindowsOverlayVisibility } from './overlay-visibility-diagnostics';
|
||||
|
||||
const WINDOWS_OVERLAY_REVEAL_DELAY_MS = 48;
|
||||
const pendingWindowsOverlayRevealTimeoutByWindow = new WeakMap<
|
||||
@@ -65,7 +66,7 @@ function isOverlayWindowContentReady(window: BrowserWindow): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export function updateVisibleOverlayVisibility(args: {
|
||||
function applyVisibleOverlayVisibility(args: {
|
||||
visibleOverlayVisible: boolean;
|
||||
modalActive?: boolean;
|
||||
forceMousePassthrough?: boolean;
|
||||
@@ -453,6 +454,15 @@ export function updateVisibleOverlayVisibility(args: {
|
||||
args.syncOverlayShortcuts();
|
||||
}
|
||||
|
||||
export function updateVisibleOverlayVisibility(
|
||||
args: Parameters<typeof applyVisibleOverlayVisibility>[0],
|
||||
): void {
|
||||
applyVisibleOverlayVisibility(args);
|
||||
if (args.isWindowsPlatform && args.mainWindow && !args.mainWindow.isDestroyed()) {
|
||||
watchWindowsOverlayVisibility({ ...args, mainWindow: args.mainWindow });
|
||||
}
|
||||
}
|
||||
|
||||
export function setVisibleOverlayVisible(options: {
|
||||
visible: boolean;
|
||||
setVisibleOverlayVisibleState: (visible: boolean) => void;
|
||||
|
||||
+2
-5
@@ -29,7 +29,7 @@ import {
|
||||
dialog,
|
||||
screen,
|
||||
} from 'electron';
|
||||
import { applyControllerConfigUpdate } from './main/controller-config-update.js';
|
||||
import { saveControllerConfigUpdate } from './main/controller-config-update.js';
|
||||
import { createHachidoriExtensionRuntime } from './core/services/hachidori-extension';
|
||||
import { createDiscordRpcClient } from './main/runtime/discord-rpc-client.js';
|
||||
import { startAppControlServer } from './main/runtime/app-control-server';
|
||||
@@ -1569,10 +1569,7 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
||||
});
|
||||
},
|
||||
saveControllerConfig: (update) => {
|
||||
const currentRawConfig = configService.getRawConfig();
|
||||
configService.patchRawConfig({
|
||||
controller: applyControllerConfigUpdate(currentRawConfig.controller, update),
|
||||
});
|
||||
saveControllerConfigUpdate(configService, update);
|
||||
// The overlay reads controller settings once at startup, and Alt+C runs in its own
|
||||
// window, so remaps would otherwise only apply after a restart.
|
||||
overlayManager.broadcastToOverlayWindows(IPC_CHANNELS.event.controllerConfigChanged);
|
||||
|
||||
@@ -157,6 +157,22 @@ function setup(t: TestContext, options: { platform?: NodeJS.Platform; visible?:
|
||||
Object.defineProperty(process, 'platform', { value: options.platform, configurable: true });
|
||||
t.after(() => Object.defineProperty(process, 'platform', { value: originalPlatform }));
|
||||
}
|
||||
if (options.platform === 'linux') {
|
||||
// Fullscreen recreation only runs outside Hyprland and Sway, so pin an X11
|
||||
// session rather than inheriting the compositor the tests happen to run under.
|
||||
for (const key of [
|
||||
'HYPRLAND_INSTANCE_SIGNATURE',
|
||||
'SWAYSOCK',
|
||||
'XDG_CURRENT_DESKTOP',
|
||||
'XDG_SESSION_DESKTOP',
|
||||
]) {
|
||||
const original = process.env[key];
|
||||
delete process.env[key];
|
||||
t.after(() => {
|
||||
if (original !== undefined) process.env[key] = original;
|
||||
});
|
||||
}
|
||||
}
|
||||
const recorder = createRecorder();
|
||||
const state: FixtureState = {
|
||||
visible: options.visible ?? false,
|
||||
|
||||
@@ -4,7 +4,13 @@ import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import test from 'node:test';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { getSnapshotPath, readSnapshot, writeSnapshot } from './cache';
|
||||
import {
|
||||
getSnapshotPath,
|
||||
readCachedMediaResolution,
|
||||
readSnapshot,
|
||||
writeCachedMediaResolution,
|
||||
writeSnapshot,
|
||||
} from './cache';
|
||||
import { CHARACTER_DICTIONARY_FORMAT_VERSION } from './constants';
|
||||
import type { CharacterDictionarySnapshot } from './types';
|
||||
|
||||
@@ -121,3 +127,20 @@ test('readSnapshot ignores snapshots written with an older format version', asyn
|
||||
|
||||
assert.equal(await readSnapshot(snapshotPath), null);
|
||||
});
|
||||
|
||||
test('media resolutions cached before the season resolver fix are re-resolved', () => {
|
||||
const outputDir = makeTempDir();
|
||||
const cachePath = path.join(outputDir, 'anilist-resolution-cache.json');
|
||||
// Written by the old resolver, which counted "Season 2 Part 2" as season 3.
|
||||
fs.writeFileSync(
|
||||
cachePath,
|
||||
JSON.stringify({
|
||||
entries: [{ seriesKey: 'mushoku-tensei-s3', mediaId: 166873, mediaTitle: 'Part 2' }],
|
||||
}),
|
||||
);
|
||||
assert.equal(readCachedMediaResolution(outputDir, 'mushoku-tensei-s3'), null);
|
||||
|
||||
const entry = { seriesKey: 'mushoku-tensei-s3', mediaId: 178789, mediaTitle: 'Season 3' };
|
||||
writeCachedMediaResolution(outputDir, entry);
|
||||
assert.deepEqual(readCachedMediaResolution(outputDir, 'mushoku-tensei-s3'), entry);
|
||||
});
|
||||
@@ -28,9 +28,17 @@ type MediaResolutionCacheEntry = {
|
||||
};
|
||||
|
||||
type MediaResolutionCacheFile = {
|
||||
version?: number;
|
||||
entries?: MediaResolutionCacheEntry[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Bump when the AniList season resolver changes what it returns, so matches it used to get
|
||||
* wrong are re-resolved instead of being served from here forever. Version 2: split-cour
|
||||
* continuations and specials no longer count as seasons.
|
||||
*/
|
||||
const MEDIA_RESOLUTION_CACHE_VERSION = 2;
|
||||
|
||||
function getMediaResolutionCachePath(outputDir: string): string {
|
||||
return path.join(outputDir, 'anilist-resolution-cache.json');
|
||||
}
|
||||
@@ -55,6 +63,7 @@ function readMediaResolutionEntries(outputDir: string): MediaResolutionCacheEntr
|
||||
const parsed = JSON.parse(
|
||||
fs.readFileSync(getMediaResolutionCachePath(outputDir), 'utf8'),
|
||||
) as MediaResolutionCacheFile;
|
||||
if (parsed.version !== MEDIA_RESOLUTION_CACHE_VERSION) return [];
|
||||
if (!Array.isArray(parsed.entries)) return [];
|
||||
const byKey = new Map<string, MediaResolutionCacheEntry>();
|
||||
for (const value of parsed.entries) {
|
||||
@@ -74,7 +83,11 @@ function writeMediaResolutionEntries(
|
||||
ensureDir(outputDir);
|
||||
fs.writeFileSync(
|
||||
getMediaResolutionCachePath(outputDir),
|
||||
JSON.stringify({ entries }, null, 2),
|
||||
JSON.stringify(
|
||||
{ version: MEDIA_RESOLUTION_CACHE_VERSION, entries } satisfies MediaResolutionCacheFile,
|
||||
null,
|
||||
2,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,79 @@
|
||||
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 { applyControllerConfigUpdate } from './controller-config-update.js';
|
||||
import { ConfigService } from '../config/service';
|
||||
import { parseControllerConfigUpdate } from '../shared/ipc/validators';
|
||||
import {
|
||||
applyControllerConfigUpdate,
|
||||
saveControllerConfigUpdate,
|
||||
} from './controller-config-update.js';
|
||||
|
||||
const L1 = { kind: 'button', buttonIndex: 4 } as const;
|
||||
const L2 = { kind: 'button', buttonIndex: 6 } as const;
|
||||
const DPAD_LEFT = { kind: 'button', buttonIndex: 14 } as const;
|
||||
const DPAD_RIGHT = { kind: 'button', buttonIndex: 15 } as const;
|
||||
|
||||
/** One Alt+C save for a profile, through the same validator and merge as the real IPC handler. */
|
||||
function createSaveHarness() {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-controller-save-'));
|
||||
const service = new ConfigService(dir);
|
||||
return {
|
||||
service,
|
||||
save: (action: string, binding: unknown) => {
|
||||
const update = parseControllerConfigUpdate({
|
||||
profiles: { 'pad-1': { bindings: { [action]: binding } } },
|
||||
});
|
||||
assert.ok(update, 'the validator accepts the update');
|
||||
saveControllerConfigUpdate(service, update);
|
||||
},
|
||||
savedBinding: (action: 'nextAudio' | 'previousAudio' | 'nextEntry') =>
|
||||
service.getConfig().controller.profiles['pad-1']?.bindings[action],
|
||||
cleanup: () => fs.rmSync(dir, { recursive: true, force: true }),
|
||||
};
|
||||
}
|
||||
|
||||
test('combos sharing a hold button or a press button all survive later saves', () => {
|
||||
const harness = createSaveHarness();
|
||||
try {
|
||||
harness.save('nextAudio', { ...DPAD_LEFT, hold: L1 });
|
||||
harness.save('previousAudio', { ...DPAD_RIGHT, hold: L1 });
|
||||
harness.save('nextEntry', { ...DPAD_LEFT, hold: L2 });
|
||||
|
||||
assert.deepEqual(harness.savedBinding('nextAudio'), { ...DPAD_LEFT, hold: L1 });
|
||||
assert.deepEqual(harness.savedBinding('previousAudio'), { ...DPAD_RIGHT, hold: L1 });
|
||||
assert.deepEqual(harness.savedBinding('nextEntry'), { ...DPAD_LEFT, hold: L2 });
|
||||
} finally {
|
||||
harness.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('rebinding a combo to one button drops its hold', () => {
|
||||
const harness = createSaveHarness();
|
||||
try {
|
||||
harness.save('nextAudio', { ...DPAD_LEFT, hold: L1 });
|
||||
harness.save('nextAudio', DPAD_RIGHT);
|
||||
|
||||
assert.deepEqual(harness.savedBinding('nextAudio'), DPAD_RIGHT);
|
||||
assert.deepEqual(
|
||||
harness.service.getRawConfig().controller?.profiles?.['pad-1']?.bindings?.nextAudio,
|
||||
DPAD_RIGHT,
|
||||
);
|
||||
} finally {
|
||||
harness.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('the validator rejects an invalid hold instead of saving a plain press', () => {
|
||||
assert.equal(
|
||||
parseControllerConfigUpdate({
|
||||
bindings: { nextAudio: { ...DPAD_LEFT, hold: { kind: 'face' } } },
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('applyControllerConfigUpdate replaces binding descriptors instead of deep-merging them', () => {
|
||||
const next = applyControllerConfigUpdate(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ConfigService } from '../config/service';
|
||||
import type { ControllerConfigUpdate, RawConfig } from '../types';
|
||||
|
||||
type RawControllerConfig = NonNullable<RawConfig['controller']>;
|
||||
@@ -96,6 +97,21 @@ function mergeControllerProfile(
|
||||
return nextProfile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves an Alt+C update to the config file. The controller section is replaced, not patched:
|
||||
* `patchRawConfig` deep-merges, so a combo rebound to one button would keep its old `hold`.
|
||||
*/
|
||||
export function saveControllerConfigUpdate(
|
||||
configService: Pick<ConfigService, 'getRawConfig' | 'saveRawConfig'>,
|
||||
update: ControllerConfigUpdate,
|
||||
): void {
|
||||
const rawConfig = configService.getRawConfig();
|
||||
configService.saveRawConfig({
|
||||
...rawConfig,
|
||||
controller: applyControllerConfigUpdate(rawConfig.controller, update),
|
||||
});
|
||||
}
|
||||
|
||||
export function applyControllerConfigUpdate(
|
||||
currentController: RawConfig['controller'] | undefined,
|
||||
update: ControllerConfigUpdate,
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
import { clipboard, contextBridge, ipcRenderer, IpcRendererEvent, webUtils } from 'electron';
|
||||
import { resolveOverlayLayerFromArgv } from './preload-args';
|
||||
import { createIpcListenerFactories } from './preload-ipc-listeners';
|
||||
import type { UnforwardedMpvKeyReport } from './types/session-bindings';
|
||||
import {
|
||||
DICTIONARY_EXTERNAL_LINK_CHANNEL,
|
||||
parseDictionaryExternalUrl,
|
||||
@@ -329,6 +330,10 @@ const electronAPI: ElectronAPI = {
|
||||
ipcRenderer.send(IPC_CHANNELS.command.recordYomitanLookup, context ?? null);
|
||||
},
|
||||
|
||||
reportUnforwardedMpvKey: (report: UnforwardedMpvKeyReport) => {
|
||||
ipcRenderer.send(IPC_CHANNELS.command.reportUnforwardedMpvKey, report);
|
||||
},
|
||||
|
||||
getSubtitlePosition: (): Promise<SubtitlePosition | null> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.request.getSubtitlePosition),
|
||||
saveSubtitlePosition: (position: SubtitlePosition) => {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { createControllerHintVisibility } from './controller-hint-visibility.js';
|
||||
|
||||
function createHarness(answers: Array<string | null | Error>) {
|
||||
const pending = [...answers];
|
||||
let requests = 0;
|
||||
const visibility = createControllerHintVisibility({
|
||||
getOverlayControllerId: async () => {
|
||||
requests += 1;
|
||||
const answer = pending.shift() ?? null;
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer;
|
||||
},
|
||||
});
|
||||
const frame = async (now: number, activeGamepadId: string | null = null) => {
|
||||
const visible = visibility.update({ enabled: true, dialogOpen: true, activeGamepadId, now });
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
return visible;
|
||||
};
|
||||
return { visibility, frame, getRequests: () => requests };
|
||||
}
|
||||
|
||||
test('hints stay hidden while no window can see a controller', async () => {
|
||||
const { frame } = createHarness([null, null]);
|
||||
|
||||
assert.equal(await frame(0), false);
|
||||
assert.equal(await frame(16), false);
|
||||
assert.equal(await frame(2_000), false);
|
||||
});
|
||||
|
||||
test('a controller the dialog window can see shows hints without asking the overlay', async () => {
|
||||
const { frame, getRequests } = createHarness([]);
|
||||
|
||||
assert.equal(await frame(0, 'pad-1'), true);
|
||||
assert.equal(getRequests(), 0);
|
||||
});
|
||||
|
||||
test('a fresh dialog window shows hints for the controller the overlay reports', async () => {
|
||||
const { frame } = createHarness(['pad-1']);
|
||||
|
||||
assert.equal(await frame(0), false);
|
||||
assert.equal(await frame(16), true);
|
||||
});
|
||||
|
||||
test('hints hide on the next refresh after the overlay loses the controller', async () => {
|
||||
const { frame, getRequests } = createHarness(['pad-1', null]);
|
||||
|
||||
await frame(0);
|
||||
assert.equal(await frame(500), true);
|
||||
assert.equal(getRequests(), 1);
|
||||
|
||||
await frame(1_000);
|
||||
assert.equal(getRequests(), 2);
|
||||
assert.equal(await frame(1_016), false);
|
||||
});
|
||||
|
||||
test('a failed request keeps the last answer and retries on the next refresh', async () => {
|
||||
const { frame, getRequests } = createHarness(['pad-1', new Error('ipc closed'), null]);
|
||||
|
||||
await frame(0);
|
||||
await frame(1_000);
|
||||
assert.equal(await frame(1_016), true);
|
||||
|
||||
await frame(2_000);
|
||||
assert.equal(getRequests(), 3);
|
||||
assert.equal(await frame(2_016), false);
|
||||
});
|
||||
|
||||
test('nothing is requested while controller support is off or no dialog is open', () => {
|
||||
const { visibility, getRequests } = createHarness([]);
|
||||
|
||||
assert.equal(
|
||||
visibility.update({ enabled: false, dialogOpen: true, activeGamepadId: 'pad-1', now: 0 }),
|
||||
false,
|
||||
);
|
||||
visibility.update({ enabled: true, dialogOpen: false, activeGamepadId: null, now: 0 });
|
||||
assert.equal(getRequests(), 0);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
const OVERLAY_CONTROLLER_REFRESH_MS = 1_000;
|
||||
|
||||
/**
|
||||
* Decides whether dialogs show their controller shortcut tags. A fresh dialog window cannot
|
||||
* see a pad until a button is pressed in it, so an open dialog also asks main which controller
|
||||
* the overlay is reading. Called every frame; requests are limited to one per refresh interval.
|
||||
*/
|
||||
export function createControllerHintVisibility(options: {
|
||||
getOverlayControllerId: () => Promise<string | null>;
|
||||
}) {
|
||||
let overlayHasController = false;
|
||||
let nextRefreshAt = Number.NEGATIVE_INFINITY;
|
||||
|
||||
function refreshOverlayController(now: number): void {
|
||||
if (now < nextRefreshAt) return;
|
||||
nextRefreshAt = now + OVERLAY_CONTROLLER_REFRESH_MS;
|
||||
options.getOverlayControllerId().then(
|
||||
(gamepadId) => {
|
||||
overlayHasController = gamepadId !== null;
|
||||
},
|
||||
() => {
|
||||
// Keep the last answer; the next refresh tries again.
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
update(state: {
|
||||
enabled: boolean;
|
||||
dialogOpen: boolean;
|
||||
activeGamepadId: string | null;
|
||||
now: number;
|
||||
}): boolean {
|
||||
if (!state.enabled) return false;
|
||||
if (state.activeGamepadId !== null) return true;
|
||||
if (state.dialogOpen) refreshOverlayController(state.now);
|
||||
return overlayHasController;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -21,45 +21,27 @@ function createSnapshot(
|
||||
};
|
||||
}
|
||||
|
||||
test('controller binding capture waits for neutral-to-active button edge', () => {
|
||||
test('controller binding capture waits for a neutral-to-active D-pad edge', () => {
|
||||
const capture = createControllerBindingCapture({
|
||||
triggerDeadzone: 0.5,
|
||||
stickDeadzone: 0.2,
|
||||
});
|
||||
|
||||
const heldButtons = createSnapshot({
|
||||
buttons: [{ value: 1, pressed: true, touched: true }],
|
||||
const buttons = Array.from({ length: 16 }, () => ({ value: 0, pressed: false, touched: false }));
|
||||
const heldDpad = createSnapshot({
|
||||
buttons: buttons.map((button, index) =>
|
||||
index === 15 ? { value: 1, pressed: true, touched: true } : button,
|
||||
),
|
||||
});
|
||||
|
||||
capture.arm({ actionId: 'toggleLookup', bindingType: 'discrete' }, heldButtons);
|
||||
capture.arm({ actionId: 'leftStickHorizontal', bindingType: 'dpad' }, heldDpad);
|
||||
|
||||
assert.equal(capture.poll(heldButtons), null);
|
||||
|
||||
const neutralButtons = createSnapshot();
|
||||
assert.equal(capture.poll(neutralButtons), null);
|
||||
|
||||
const freshPress = createSnapshot({
|
||||
buttons: [{ value: 1, pressed: true, touched: true }],
|
||||
});
|
||||
assert.deepEqual(capture.poll(freshPress), {
|
||||
actionId: 'toggleLookup',
|
||||
bindingType: 'discrete',
|
||||
binding: { kind: 'button', buttonIndex: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
test('controller binding capture records fresh axis direction for discrete learn mode', () => {
|
||||
const capture = createControllerBindingCapture({
|
||||
triggerDeadzone: 0.5,
|
||||
stickDeadzone: 0.2,
|
||||
});
|
||||
|
||||
capture.arm({ actionId: 'closeLookup', bindingType: 'discrete' }, createSnapshot());
|
||||
|
||||
assert.deepEqual(capture.poll(createSnapshot({ axes: [0, 0, 0, -0.8] })), {
|
||||
actionId: 'closeLookup',
|
||||
bindingType: 'discrete',
|
||||
binding: { kind: 'axis', axisIndex: 3, direction: 'negative' },
|
||||
assert.equal(capture.poll(heldDpad), null);
|
||||
assert.equal(capture.poll(createSnapshot({ buttons })), null);
|
||||
assert.deepEqual(capture.poll(heldDpad), {
|
||||
actionId: 'leftStickHorizontal',
|
||||
bindingType: 'dpad',
|
||||
dpadDirection: 'horizontal',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -69,7 +51,10 @@ test('controller binding capture ignores analog drift inside deadzone', () => {
|
||||
stickDeadzone: 0.3,
|
||||
});
|
||||
|
||||
capture.arm({ actionId: 'mineCard', bindingType: 'discrete' }, createSnapshot());
|
||||
capture.arm(
|
||||
{ actionId: 'leftStickHorizontal', bindingType: 'axis', dpadFallback: 'none' },
|
||||
createSnapshot(),
|
||||
);
|
||||
|
||||
assert.equal(capture.poll(createSnapshot({ axes: [0.2, 0, 0, 0] })), null);
|
||||
assert.equal(capture.isArmed(), true);
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import type {
|
||||
ControllerDpadFallback,
|
||||
ResolvedControllerAxisBinding,
|
||||
ResolvedControllerDiscreteBinding,
|
||||
} from '../../types';
|
||||
import type { ControllerDpadFallback, ResolvedControllerAxisBinding } from '../../types';
|
||||
|
||||
type ControllerButtonState = {
|
||||
value: number;
|
||||
@@ -15,11 +11,8 @@ type ControllerBindingCaptureSnapshot = {
|
||||
buttons: readonly ControllerButtonState[];
|
||||
};
|
||||
|
||||
/** Learn for stick rows and their D-pad rows; discrete rows use the combo capture. */
|
||||
type ControllerBindingCaptureTarget =
|
||||
| {
|
||||
actionId: string;
|
||||
bindingType: 'discrete';
|
||||
}
|
||||
| {
|
||||
actionId: string;
|
||||
bindingType: 'axis';
|
||||
@@ -31,11 +24,6 @@ type ControllerBindingCaptureTarget =
|
||||
};
|
||||
|
||||
type ControllerBindingCaptureResult =
|
||||
| {
|
||||
actionId: string;
|
||||
bindingType: 'discrete';
|
||||
binding: ResolvedControllerDiscreteBinding;
|
||||
}
|
||||
| {
|
||||
actionId: string;
|
||||
bindingType: 'axis';
|
||||
@@ -134,58 +122,24 @@ export function createControllerBindingCapture(options: {
|
||||
|
||||
const dpadDirection: ControllerDpadFallback =
|
||||
index === 12 || index === 13 ? 'vertical' : 'horizontal';
|
||||
const { actionId } = target;
|
||||
cancel();
|
||||
return {
|
||||
actionId: target.actionId,
|
||||
bindingType: 'dpad' as const,
|
||||
dpadDirection,
|
||||
};
|
||||
return { actionId, bindingType: 'dpad', dpadDirection };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// After dpad early-return, only 'discrete' | 'axis' remain
|
||||
const narrowedTarget: Extract<
|
||||
ControllerBindingCaptureTarget,
|
||||
{ bindingType: 'discrete' | 'axis' }
|
||||
> = target;
|
||||
|
||||
for (let index = 0; index < snapshot.buttons.length; index += 1) {
|
||||
if (!isActiveButton(snapshot.buttons[index], options.triggerDeadzone)) continue;
|
||||
if (blockedButtons.has(index)) continue;
|
||||
if (narrowedTarget.bindingType === 'axis') continue;
|
||||
|
||||
const result: ControllerBindingCaptureResult = {
|
||||
actionId: narrowedTarget.actionId,
|
||||
bindingType: 'discrete',
|
||||
binding: { kind: 'button', buttonIndex: index },
|
||||
};
|
||||
cancel();
|
||||
return result;
|
||||
}
|
||||
|
||||
for (let index = 0; index < snapshot.axes.length; index += 1) {
|
||||
const direction = getAxisDirection(snapshot.axes[index], activationThreshold);
|
||||
if (!direction) continue;
|
||||
const directionKey = `${index}:${direction}`;
|
||||
if (blockedAxisDirections.has(directionKey)) continue;
|
||||
|
||||
const result: ControllerBindingCaptureResult =
|
||||
narrowedTarget.bindingType === 'discrete'
|
||||
? {
|
||||
actionId: narrowedTarget.actionId,
|
||||
bindingType: 'discrete',
|
||||
binding: { kind: 'axis', axisIndex: index, direction },
|
||||
}
|
||||
: {
|
||||
actionId: narrowedTarget.actionId,
|
||||
bindingType: 'axis',
|
||||
binding: {
|
||||
kind: 'axis',
|
||||
axisIndex: index,
|
||||
dpadFallback: narrowedTarget.dpadFallback,
|
||||
},
|
||||
};
|
||||
const result: ControllerBindingCaptureResult = {
|
||||
actionId: target.actionId,
|
||||
bindingType: 'axis',
|
||||
binding: { kind: 'axis', axisIndex: index, dpadFallback: target.dpadFallback },
|
||||
};
|
||||
cancel();
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -73,3 +73,49 @@ test('combo capture never records a trigger axis resting position', () => {
|
||||
hold: { kind: 'axis', axisIndex: 2, direction: 'positive' },
|
||||
});
|
||||
});
|
||||
|
||||
test('combo capture records one axis from a diagonal push, not a hold and a press', () => {
|
||||
const capture = createCapture();
|
||||
capture.arm(snapshot());
|
||||
const diagonal = snapshot([], [0.9, 0.9, 0, 0]);
|
||||
|
||||
const hold = { kind: 'axis', axisIndex: 0, direction: 'positive' } as const;
|
||||
assert.deepEqual(capture.poll(diagonal), { status: 'holding', hold });
|
||||
assert.deepEqual(capture.poll(diagonal), { status: 'holding', hold });
|
||||
assert.deepEqual(capture.poll(snapshot()), {
|
||||
status: 'done',
|
||||
binding: { kind: 'combo', press: hold, hold: null },
|
||||
});
|
||||
});
|
||||
|
||||
test('combo capture still records a second axis pressed after the first', () => {
|
||||
const capture = createCapture();
|
||||
capture.arm(snapshot());
|
||||
|
||||
capture.poll(snapshot([], [0.9, 0, 0, 0]));
|
||||
assert.deepEqual(capture.poll(snapshot([], [0.9, 0.9, 0, 0])), {
|
||||
status: 'done',
|
||||
binding: {
|
||||
kind: 'combo',
|
||||
press: { kind: 'axis', axisIndex: 1, direction: 'positive' },
|
||||
hold: { kind: 'axis', axisIndex: 0, direction: 'positive' },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('combo capture records a button and an axis activated in the same poll as a combo', () => {
|
||||
const capture = createCapture();
|
||||
capture.arm(snapshot());
|
||||
const both = snapshot([4], [0.9, 0, 0, 0]);
|
||||
|
||||
const hold = { kind: 'button', buttonIndex: 4 } as const;
|
||||
assert.deepEqual(capture.poll(both), { status: 'holding', hold });
|
||||
assert.deepEqual(capture.poll(both), {
|
||||
status: 'done',
|
||||
binding: {
|
||||
kind: 'combo',
|
||||
press: { kind: 'axis', axisIndex: 0, direction: 'positive' },
|
||||
hold,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ControllerReviewInput, ResolvedControllerReviewBinding } from '../../types';
|
||||
import type { ControllerRawInput } from '../../types';
|
||||
|
||||
type ControllerButtonState = {
|
||||
value: number;
|
||||
@@ -13,19 +13,23 @@ type ControllerSnapshot = {
|
||||
|
||||
export type ControllerComboCaptureState =
|
||||
| { status: 'waiting' }
|
||||
| { status: 'holding'; hold: ControllerReviewInput }
|
||||
| { status: 'done'; binding: ResolvedControllerReviewBinding };
|
||||
| { status: 'holding'; hold: ControllerRawInput }
|
||||
| { status: 'done'; binding: ControllerCapturedCombo };
|
||||
|
||||
type RawInput = Extract<ControllerReviewInput, { kind: 'button' | 'axis' }>;
|
||||
export type ControllerCapturedCombo = {
|
||||
kind: 'combo';
|
||||
press: ControllerRawInput;
|
||||
hold: ControllerRawInput | null;
|
||||
};
|
||||
|
||||
function inputKey(input: RawInput): string {
|
||||
function inputKey(input: ControllerRawInput): string {
|
||||
return input.kind === 'button'
|
||||
? `button:${input.buttonIndex}`
|
||||
: `axis:${input.axisIndex}:${input.direction}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Learn for review bindings. Waits for a first input; letting go of it records it alone,
|
||||
* Learn for discrete and dialog bindings. Waits for a first input; letting go of it records it alone,
|
||||
* while pressing a second input during the hold records "hold first + press second".
|
||||
* Buttons already down when learning starts are ignored until released. Axis directions
|
||||
* active at the start stay ignored for the whole capture: some pads rest a trigger axis at
|
||||
@@ -37,10 +41,10 @@ export function createControllerComboCapture(options: {
|
||||
}) {
|
||||
const blocked = new Set<string>();
|
||||
const restingAxes = new Set<string>();
|
||||
let first: RawInput | null = null;
|
||||
let first: ControllerRawInput | null = null;
|
||||
|
||||
function activeInputs(snapshot: ControllerSnapshot): RawInput[] {
|
||||
const inputs: RawInput[] = [];
|
||||
function activeInputs(snapshot: ControllerSnapshot): ControllerRawInput[] {
|
||||
const inputs: ControllerRawInput[] = [];
|
||||
snapshot.buttons.forEach((button, buttonIndex) => {
|
||||
if (button && (Boolean(button.pressed) || button.value >= options.triggerDeadzone)) {
|
||||
inputs.push({ kind: 'button', buttonIndex });
|
||||
@@ -77,6 +81,11 @@ export function createControllerComboCapture(options: {
|
||||
const next = fresh[0];
|
||||
if (!next) return { status: 'waiting' };
|
||||
first = next;
|
||||
// Axes crossing the threshold in the same poll are one movement, such as a diagonal push.
|
||||
// Buttons sort first, so an axis here means every other fresh input is an axis too.
|
||||
if (next.kind === 'axis') {
|
||||
for (const input of fresh.slice(1)) blocked.add(inputKey(input));
|
||||
}
|
||||
return { status: 'holding', hold: first };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { controllerReviewInputSourceKey as inputKey } from '../../shared/controller-review';
|
||||
import type { ControllerRawInput, ResolvedControllerDiscreteBinding } from '../../types';
|
||||
import type { GamepadLike } from './gamepad-controller.js';
|
||||
|
||||
type BoundBinding = Exclude<ResolvedControllerDiscreteBinding, { kind: 'none' }>;
|
||||
|
||||
const isBound = (binding: ResolvedControllerDiscreteBinding): binding is BoundBinding =>
|
||||
binding.kind !== 'none';
|
||||
|
||||
/**
|
||||
* Per-poll view of hold + press combos in the main controller bindings. Dialog layouts have
|
||||
* their own matching in `controller-screen-layout.ts`; the rules for choosing a binding match.
|
||||
*
|
||||
* A press belongs to the binding that matches the hold buttons down when it starts, so
|
||||
* pressing the same input again during one hold fires the combo again, and letting go of the
|
||||
* hold first does not turn the press into its plain binding.
|
||||
*/
|
||||
export function createControllerComboTracker() {
|
||||
let pressedLastPoll: ReadonlySet<string> = new Set();
|
||||
let holdKeys: ReadonlySet<string> = new Set();
|
||||
let heldHoldKeys: string[] = [];
|
||||
let usedHolds: ReadonlySet<string> = new Set();
|
||||
/** Holds used during their press, kept for the poll that sees them released. */
|
||||
let cancelledTaps: ReadonlySet<string> = new Set();
|
||||
const claimedInputs = new Map<string, ControllerRawInput>();
|
||||
|
||||
function update(
|
||||
bindings: readonly ResolvedControllerDiscreteBinding[],
|
||||
isPressed: (input: ControllerRawInput) => boolean,
|
||||
): void {
|
||||
const bound = bindings.filter(isBound);
|
||||
const pressed = new Set<string>();
|
||||
for (const binding of bound) {
|
||||
for (const input of binding.hold ? [binding, binding.hold] : [binding]) {
|
||||
if (isPressed(input)) pressed.add(inputKey(input));
|
||||
}
|
||||
}
|
||||
|
||||
holdKeys = new Set(bound.flatMap((binding) => (binding.hold ? [inputKey(binding.hold)] : [])));
|
||||
heldHoldKeys = [...holdKeys].filter((key) => pressed.has(key));
|
||||
|
||||
const freshPresses = bound
|
||||
.map(inputKey)
|
||||
.filter((key) => pressed.has(key) && !pressedLastPoll.has(key));
|
||||
const nextUsedHolds = new Set(
|
||||
heldHoldKeys.filter(
|
||||
(holdKey) => usedHolds.has(holdKey) || freshPresses.some((key) => key !== holdKey),
|
||||
),
|
||||
);
|
||||
cancelledTaps = new Set([...usedHolds, ...nextUsedHolds]);
|
||||
usedHolds = nextUsedHolds;
|
||||
pressedLastPoll = pressed;
|
||||
|
||||
for (const key of claimedInputs.keys()) {
|
||||
if (!pressed.has(key)) claimedInputs.delete(key);
|
||||
}
|
||||
for (const binding of bound) {
|
||||
if (!binding.hold) continue;
|
||||
const pressKey = inputKey(binding);
|
||||
const holdKey = inputKey(binding.hold);
|
||||
if (pressKey !== holdKey && pressed.has(pressKey) && pressed.has(holdKey)) {
|
||||
claimedInputs.set(pressKey, binding);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
update,
|
||||
|
||||
reset(): void {
|
||||
pressedLastPoll = new Set();
|
||||
holdKeys = new Set();
|
||||
heldHoldKeys = [];
|
||||
usedHolds = new Set();
|
||||
cancelledTaps = new Set();
|
||||
claimedInputs.clear();
|
||||
},
|
||||
|
||||
/**
|
||||
* Whether a press of this binding counts right now: with one hold button down, only the
|
||||
* binding that uses it; with none, only a plain binding. Two holds down match nothing.
|
||||
*/
|
||||
matches(binding: ResolvedControllerDiscreteBinding): boolean {
|
||||
if (!isBound(binding)) return false;
|
||||
const pressKey = inputKey(binding);
|
||||
const others = heldHoldKeys.filter((key) => key !== pressKey);
|
||||
if (others.length > 1) return false;
|
||||
return others[0] === (binding.hold ? inputKey(binding.hold) : undefined);
|
||||
},
|
||||
|
||||
/** A plain binding on a hold button waits for release, when a tap can be told from a hold. */
|
||||
firesOnRelease(binding: ResolvedControllerDiscreteBinding): boolean {
|
||||
return isBound(binding) && !binding.hold && holdKeys.has(inputKey(binding));
|
||||
},
|
||||
|
||||
/** Another bound input was pressed during this hold, so its release is not a tap. */
|
||||
isTapCancelled(binding: ResolvedControllerDiscreteBinding): boolean {
|
||||
return isBound(binding) && cancelledTaps.has(inputKey(binding));
|
||||
},
|
||||
|
||||
/**
|
||||
* The pad with inputs claimed by a combo reading as released, for the stick actions and
|
||||
* their D-pad fallbacks. A claim lasts until the input is released, so letting go of the
|
||||
* hold first does not start moving the word selection.
|
||||
*/
|
||||
withoutClaimedInputs(gamepad: GamepadLike): GamepadLike {
|
||||
if (claimedInputs.size === 0) return gamepad;
|
||||
const axes = [...gamepad.axes];
|
||||
const buttons = [...gamepad.buttons];
|
||||
for (const input of claimedInputs.values()) {
|
||||
if (input.kind === 'button') {
|
||||
buttons[input.buttonIndex] = { value: 0, pressed: false, touched: false };
|
||||
} else if ((axes[input.axisIndex] ?? 0) > 0 === (input.direction === 'positive')) {
|
||||
axes[input.axisIndex] = 0;
|
||||
}
|
||||
}
|
||||
// Native Gamepad fields are prototype getters, so object spread would drop them.
|
||||
return {
|
||||
id: gamepad.id,
|
||||
index: gamepad.index,
|
||||
connected: gamepad.connected,
|
||||
mapping: gamepad.mapping,
|
||||
timestamp: gamepad.timestamp,
|
||||
axes,
|
||||
buttons,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -919,3 +919,261 @@ test('gamepad controller pauses mpv outside keyboard-only mode, but not under a
|
||||
|
||||
assert.deepEqual(harness.calls, ['toggleMpvPause']);
|
||||
});
|
||||
|
||||
/** Harness driven frame by frame: `pads(4, 15)` polls once with those buttons down. */
|
||||
function createComboHarness(
|
||||
bindings: Partial<Bindings>,
|
||||
deps: Partial<ControllerOptions> = {},
|
||||
extraConfig: Partial<ResolvedControllerConfig> = {},
|
||||
) {
|
||||
let pressed: number[] = [];
|
||||
let now = 0;
|
||||
const harness = createHarness({
|
||||
gamepads: () => [
|
||||
createGamepad('pad-1', {
|
||||
buttons: Object.fromEntries(pressed.map((index) => [index, PRESSED])),
|
||||
}),
|
||||
],
|
||||
config: createControllerConfig({ ...extraConfig, bindings }),
|
||||
deps: { getLookupWindowOpen: () => true, ...deps },
|
||||
});
|
||||
return {
|
||||
...harness,
|
||||
pads: (...buttons: number[]) => {
|
||||
pressed = buttons;
|
||||
now += 16;
|
||||
harness.poll(now);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const L1 = 4;
|
||||
const R1 = 5;
|
||||
const DPAD_UP = 12;
|
||||
const DPAD_RIGHT = 15;
|
||||
const L1_DPAD_RIGHT = {
|
||||
kind: 'button',
|
||||
buttonIndex: DPAD_RIGHT,
|
||||
hold: { kind: 'button', buttonIndex: L1 },
|
||||
} as const;
|
||||
|
||||
test('holding L1 and pressing D-pad right twice fires the combo twice and nothing else', () => {
|
||||
// L1 keeps its default Play Current Audio, and the D-pad keeps moving between words.
|
||||
const harness = createComboHarness({ nextAudio: L1_DPAD_RIGHT });
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
harness.pads(L1, DPAD_RIGHT);
|
||||
harness.pads(L1);
|
||||
harness.pads(L1, DPAD_RIGHT);
|
||||
harness.pads(L1);
|
||||
harness.pads();
|
||||
|
||||
assert.deepEqual(harness.calls, ['nextAudio', 'nextAudio']);
|
||||
});
|
||||
|
||||
test('a plain button that is also a hold button fires when tapped, on release', () => {
|
||||
const harness = createComboHarness({ nextAudio: L1_DPAD_RIGHT });
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
assert.deepEqual(harness.calls, []);
|
||||
harness.pads();
|
||||
assert.deepEqual(harness.calls, ['playCurrentAudio']);
|
||||
|
||||
// The next tap is unaffected by a combo used on an earlier hold.
|
||||
harness.pads(L1);
|
||||
harness.pads(L1, DPAD_RIGHT);
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
harness.pads();
|
||||
assert.deepEqual(harness.calls, ['playCurrentAudio', 'nextAudio', 'playCurrentAudio']);
|
||||
});
|
||||
|
||||
test('a plain button stays on press while no combo holds it', () => {
|
||||
const harness = createComboHarness({ nextAudio: { kind: 'button', buttonIndex: R1 } });
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
|
||||
assert.deepEqual(harness.calls, ['playCurrentAudio']);
|
||||
});
|
||||
|
||||
test('a tap on a hold button also fires outside keyboard-only mode', () => {
|
||||
const harness = createComboHarness(
|
||||
{
|
||||
previousSubtitle: { kind: 'button', buttonIndex: L1 },
|
||||
nextSubtitle: { kind: 'button', buttonIndex: R1, hold: { kind: 'button', buttonIndex: L1 } },
|
||||
},
|
||||
{ getKeyboardModeEnabled: () => false },
|
||||
);
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
harness.pads();
|
||||
|
||||
assert.deepEqual(harness.calls, ['previousSubtitle']);
|
||||
});
|
||||
|
||||
test('a tap on a hold button is dropped if its action stops applying before the release', () => {
|
||||
let lookupOpen = true;
|
||||
const harness = createComboHarness(
|
||||
{ nextAudio: L1_DPAD_RIGHT },
|
||||
{ getLookupWindowOpen: () => lookupOpen },
|
||||
);
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
lookupOpen = false;
|
||||
harness.pads(L1);
|
||||
lookupOpen = true;
|
||||
harness.pads(L1);
|
||||
harness.pads();
|
||||
|
||||
assert.deepEqual(harness.calls, []);
|
||||
});
|
||||
|
||||
test('pressing a plain binding during a hold does nothing and cancels the tap', () => {
|
||||
const harness = createComboHarness({ nextAudio: L1_DPAD_RIGHT });
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
harness.pads(L1, 2); // X is Mine Card; there is no L1 + X.
|
||||
harness.pads();
|
||||
|
||||
assert.deepEqual(harness.calls, []);
|
||||
});
|
||||
|
||||
test('letting go of the hold first does not fire the plain binding on the same input', () => {
|
||||
const harness = createComboHarness({
|
||||
playCurrentAudio: { kind: 'none' },
|
||||
nextAudio: L1_DPAD_RIGHT,
|
||||
nextEntry: { kind: 'button', buttonIndex: DPAD_RIGHT },
|
||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'none' },
|
||||
});
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
harness.pads(L1, DPAD_RIGHT);
|
||||
harness.pads(DPAD_RIGHT);
|
||||
harness.pads();
|
||||
assert.deepEqual(harness.calls, ['nextAudio']);
|
||||
|
||||
harness.pads(DPAD_RIGHT);
|
||||
assert.deepEqual(harness.calls, ['nextAudio', 'nextEntry']);
|
||||
});
|
||||
|
||||
test('a combo needs its hold down first, and two holds at once match nothing', () => {
|
||||
const harness = createComboHarness({
|
||||
playCurrentAudio: { kind: 'none' },
|
||||
nextAudio: L1_DPAD_RIGHT,
|
||||
previousAudio: {
|
||||
kind: 'button',
|
||||
buttonIndex: DPAD_RIGHT,
|
||||
hold: { kind: 'button', buttonIndex: R1 },
|
||||
},
|
||||
});
|
||||
|
||||
harness.pads();
|
||||
harness.pads(DPAD_RIGHT);
|
||||
harness.pads(L1, DPAD_RIGHT);
|
||||
harness.pads();
|
||||
harness.pads(L1, R1);
|
||||
harness.pads(L1, R1, DPAD_RIGHT);
|
||||
|
||||
// Only the first press of the D-pad moves a word; the combos never fire.
|
||||
assert.deepEqual(harness.calls, ['moveSelection:1']);
|
||||
});
|
||||
|
||||
test('a combo keeps the D-pad from driving its stick row until the D-pad is released', () => {
|
||||
const harness = createComboHarness({
|
||||
playCurrentAudio: { kind: 'none' },
|
||||
nextAudio: L1_DPAD_RIGHT,
|
||||
nextEntry: {
|
||||
kind: 'button',
|
||||
buttonIndex: DPAD_UP,
|
||||
hold: { kind: 'button', buttonIndex: L1 },
|
||||
},
|
||||
});
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
harness.pads(L1, DPAD_RIGHT);
|
||||
harness.pads(L1, DPAD_UP);
|
||||
harness.pads(DPAD_UP);
|
||||
harness.pads();
|
||||
assert.deepEqual(harness.calls, ['nextAudio', 'nextEntry']);
|
||||
|
||||
// L1 with a direction no combo uses still moves between words.
|
||||
harness.pads(L1);
|
||||
harness.pads(L1, 14);
|
||||
assert.deepEqual(harness.calls, ['nextAudio', 'nextEntry', 'moveSelection:-1']);
|
||||
});
|
||||
|
||||
test('L1 and L2 can each hold the same press for different actions', () => {
|
||||
const L2 = 6;
|
||||
const DPAD_LEFT = 14;
|
||||
const harness = createComboHarness({
|
||||
// L2 keeps its default Quit MPV, so this also pins that a combo never quits on release.
|
||||
playCurrentAudio: { kind: 'none' },
|
||||
nextAudio: {
|
||||
kind: 'button',
|
||||
buttonIndex: DPAD_LEFT,
|
||||
hold: { kind: 'button', buttonIndex: L1 },
|
||||
},
|
||||
nextEntry: {
|
||||
kind: 'button',
|
||||
buttonIndex: DPAD_LEFT,
|
||||
hold: { kind: 'button', buttonIndex: L2 },
|
||||
},
|
||||
});
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
harness.pads(L1, DPAD_LEFT);
|
||||
harness.pads();
|
||||
harness.pads(L2);
|
||||
harness.pads(L2, DPAD_LEFT);
|
||||
harness.pads();
|
||||
|
||||
assert.deepEqual(harness.calls, ['nextAudio', 'nextEntry']);
|
||||
});
|
||||
|
||||
test('the secondary subtitle hold can be a combo', () => {
|
||||
const harness = createComboHarness({
|
||||
playCurrentAudio: { kind: 'none' },
|
||||
holdSecondarySub: {
|
||||
kind: 'button',
|
||||
buttonIndex: R1,
|
||||
hold: { kind: 'button', buttonIndex: L1 },
|
||||
},
|
||||
nextAudio: { kind: 'none' },
|
||||
});
|
||||
|
||||
harness.pads();
|
||||
harness.pads(R1);
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
harness.pads(L1, R1);
|
||||
harness.pads(L1);
|
||||
|
||||
assert.deepEqual(harness.secondarySubHeld, [true, false]);
|
||||
});
|
||||
|
||||
test('a dialog owning the pad keeps combos from firing and from leaving a tap behind', () => {
|
||||
let suspended = false;
|
||||
const harness = createComboHarness(
|
||||
{ nextAudio: L1_DPAD_RIGHT },
|
||||
{ getSuspended: () => suspended },
|
||||
);
|
||||
|
||||
harness.pads();
|
||||
harness.pads(L1);
|
||||
suspended = true;
|
||||
harness.pads(L1, DPAD_RIGHT);
|
||||
suspended = false;
|
||||
harness.pads(L1, DPAD_RIGHT);
|
||||
harness.pads();
|
||||
|
||||
assert.deepEqual(harness.calls, []);
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
ResolvedControllerDiscreteBinding,
|
||||
} from '../../types';
|
||||
import { resolveControllerConfigForGamepad } from '../controller-profile-config.js';
|
||||
import { createControllerComboTracker } from './controller-combo-tracker.js';
|
||||
|
||||
type ControllerButtonState = {
|
||||
value: number;
|
||||
@@ -228,6 +229,7 @@ function syncHeldActionBlocked(
|
||||
state.initialFired = true;
|
||||
}
|
||||
|
||||
/** Whether the binding's press input is down. A combo's `hold` is checked by the combo tracker. */
|
||||
export function resolveDiscreteBindingPressed(
|
||||
gamepad: GamepadLike,
|
||||
binding: ResolvedControllerDiscreteBinding,
|
||||
@@ -295,8 +297,24 @@ const WATCHING_ACTIONS = [
|
||||
'playNextSubtitle',
|
||||
] as const;
|
||||
|
||||
/** Every action fired by a fresh press; `holdSecondarySub` follows the button instead. */
|
||||
const PRESS_ACTIONS = [
|
||||
'toggleKeyboardOnlyMode',
|
||||
'toggleLookup',
|
||||
'closeLookup',
|
||||
'mineCard',
|
||||
'quitMpv',
|
||||
'toggleCharacterNavigation',
|
||||
...POPUP_ONLY_ACTIONS,
|
||||
...WATCHING_ACTIONS,
|
||||
] as const;
|
||||
|
||||
export function createGamepadController(options: GamepadControllerOptions) {
|
||||
let previousActions = new Map<string, boolean>();
|
||||
const comboTracker = createControllerComboTracker();
|
||||
/** Plain actions on a hold button, pressed and waiting to see whether they were a tap. */
|
||||
const pendingTaps = new Set<string>();
|
||||
const handledThisPoll = new Set<string>();
|
||||
let selectionHold = createHoldState();
|
||||
let jumpHold = createHoldState();
|
||||
let activeGamepadId: string | null = null;
|
||||
@@ -361,14 +379,38 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
config: ResolvedControllerConfig,
|
||||
action: () => void,
|
||||
): void {
|
||||
handledThisPoll.add(actionKey);
|
||||
const isPressed = resolveDiscreteBindingPressed(activeGamepad, binding, config);
|
||||
const wasPressed = previousActions.get(actionKey) ?? false;
|
||||
previousActions.set(actionKey, isPressed);
|
||||
if (!wasPressed && isPressed) {
|
||||
if (isPressed === wasPressed) return;
|
||||
|
||||
if (!isPressed) {
|
||||
if (pendingTaps.delete(actionKey) && !comboTracker.isTapCancelled(binding)) action();
|
||||
return;
|
||||
}
|
||||
if (!comboTracker.matches(binding)) return;
|
||||
if (comboTracker.firesOnRelease(binding)) {
|
||||
pendingTaps.add(actionKey);
|
||||
} else {
|
||||
action();
|
||||
}
|
||||
}
|
||||
|
||||
// The action does not apply this poll. Its edge state keeps following the pad, so a release
|
||||
// is not missed and a held button waits for a fresh press, and a pending tap is dropped.
|
||||
function trackActionWithoutFiring(
|
||||
actionKey: (typeof PRESS_ACTIONS)[number],
|
||||
activeGamepad: GamepadLike,
|
||||
config: ResolvedControllerConfig,
|
||||
): void {
|
||||
previousActions.set(
|
||||
actionKey,
|
||||
resolveDiscreteBindingPressed(activeGamepad, config.bindings[actionKey], config),
|
||||
);
|
||||
if (!handledThisPoll.has(actionKey)) pendingTaps.delete(actionKey);
|
||||
}
|
||||
|
||||
function handleSelectionAxis(value: number, now: number, config: ResolvedControllerConfig): void {
|
||||
const activationThreshold = Math.max(config.stickDeadzone, 0.55);
|
||||
if (Math.abs(value) < activationThreshold) {
|
||||
@@ -410,28 +452,14 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
config: ResolvedControllerConfig,
|
||||
now: number,
|
||||
): void {
|
||||
const discreteActions = [
|
||||
['toggleKeyboardOnlyMode', config.bindings.toggleKeyboardOnlyMode],
|
||||
['toggleLookup', config.bindings.toggleLookup],
|
||||
['closeLookup', config.bindings.closeLookup],
|
||||
['mineCard', config.bindings.mineCard],
|
||||
['quitMpv', config.bindings.quitMpv],
|
||||
['previousAudio', config.bindings.previousAudio],
|
||||
['nextAudio', config.bindings.nextAudio],
|
||||
['playCurrentAudio', config.bindings.playCurrentAudio],
|
||||
['previousEntry', config.bindings.previousEntry],
|
||||
['nextEntry', config.bindings.nextEntry],
|
||||
['toggleCharacterNavigation', config.bindings.toggleCharacterNavigation],
|
||||
...WATCHING_ACTIONS.map((actionKey) => [actionKey, config.bindings[actionKey]] as const),
|
||||
] as const;
|
||||
|
||||
for (const [actionKey, binding] of discreteActions) {
|
||||
previousActions.set(actionKey, resolveDiscreteBindingPressed(activeGamepad, binding, config));
|
||||
for (const actionKey of PRESS_ACTIONS) {
|
||||
trackActionWithoutFiring(actionKey, activeGamepad, config);
|
||||
}
|
||||
|
||||
const axisGamepad = comboTracker.withoutClaimedInputs(activeGamepad);
|
||||
const activationThreshold = Math.max(config.stickDeadzone, 0.55);
|
||||
const selectionValue = resolveAxisBindingValue(
|
||||
activeGamepad,
|
||||
axisGamepad,
|
||||
config.bindings.leftStickHorizontal,
|
||||
config.triggerDeadzone,
|
||||
activationThreshold,
|
||||
@@ -442,7 +470,7 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
syncHeldActionBlocked(
|
||||
jumpHold,
|
||||
resolveAxisBindingValue(
|
||||
activeGamepad,
|
||||
axisGamepad,
|
||||
config.bindings.rightStickVertical,
|
||||
config.triggerDeadzone,
|
||||
activationThreshold,
|
||||
@@ -463,6 +491,7 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
const activeGamepad = resolveActiveGamepad(connectedGamepads, config);
|
||||
const previousActiveGamepadId = activeGamepadId;
|
||||
publishState(connectedGamepads, activeGamepad);
|
||||
handledThisPoll.clear();
|
||||
|
||||
if (!activeGamepad) {
|
||||
syncSecondarySubHold(false);
|
||||
@@ -472,6 +501,8 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
// the press that reveals it started after the screen opened, so it should count.
|
||||
screenLayoutWaitingForPad = config.enabled && (options.getScreenLayout?.() ?? null) !== null;
|
||||
previousActions = new Map();
|
||||
comboTracker.reset();
|
||||
pendingTaps.clear();
|
||||
resetHeldAction(selectionHold);
|
||||
resetHeldAction(jumpHold);
|
||||
lastPollAt = null;
|
||||
@@ -481,11 +512,17 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
if (activeGamepad.id !== previousActiveGamepadId) {
|
||||
activeScreenLayout = null;
|
||||
previousActions = new Map();
|
||||
comboTracker.reset();
|
||||
pendingTaps.clear();
|
||||
resetHeldAction(selectionHold);
|
||||
resetHeldAction(jumpHold);
|
||||
}
|
||||
|
||||
const activeConfig = resolveControllerConfigForGamepad(config, activeGamepad.id);
|
||||
comboTracker.update(
|
||||
[...PRESS_ACTIONS, 'holdSecondarySub' as const].map((key) => activeConfig.bindings[key]),
|
||||
(input) => resolveDiscreteBindingPressed(activeGamepad, input, activeConfig),
|
||||
);
|
||||
|
||||
// A screen layout or another window owning the controller pauses every normal action,
|
||||
// including the keyboard-mode toggle and the secondary subtitle hold. Their edge state
|
||||
@@ -521,7 +558,8 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
activeGamepad,
|
||||
activeConfig.bindings.holdSecondarySub,
|
||||
activeConfig,
|
||||
),
|
||||
) &&
|
||||
comboTracker.matches(activeConfig.bindings.holdSecondarySub),
|
||||
);
|
||||
|
||||
// Pause and subtitle navigation also work while simply watching; a blocking modal pauses them.
|
||||
@@ -592,6 +630,7 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
);
|
||||
|
||||
const activationThreshold = Math.max(activeConfig.stickDeadzone, 0.55);
|
||||
const axisGamepad = comboTracker.withoutClaimedInputs(activeGamepad);
|
||||
|
||||
if (options.getLookupWindowOpen()) {
|
||||
handleActionEdge(
|
||||
@@ -631,7 +670,7 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
);
|
||||
|
||||
const primaryScroll = resolveAxisBindingValue(
|
||||
activeGamepad,
|
||||
axisGamepad,
|
||||
activeConfig.bindings.leftStickVertical,
|
||||
activeConfig.triggerDeadzone,
|
||||
activeConfig.stickDeadzone,
|
||||
@@ -644,7 +683,7 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
|
||||
handleJumpAxis(
|
||||
resolveAxisBindingValue(
|
||||
activeGamepad,
|
||||
axisGamepad,
|
||||
activeConfig.bindings.rightStickVertical,
|
||||
activeConfig.triggerDeadzone,
|
||||
activationThreshold,
|
||||
@@ -654,24 +693,14 @@ export function createGamepadController(options: GamepadControllerOptions) {
|
||||
);
|
||||
} else {
|
||||
resetHeldAction(jumpHold);
|
||||
// Popup-only buttons keep tracking the pad while the popup is closed, like blocked
|
||||
// actions do: a release is not missed, and a button held as the popup opens waits for
|
||||
// a fresh press instead of firing at once.
|
||||
for (const actionKey of POPUP_ONLY_ACTIONS) {
|
||||
previousActions.set(
|
||||
actionKey,
|
||||
resolveDiscreteBindingPressed(
|
||||
activeGamepad,
|
||||
activeConfig.bindings[actionKey],
|
||||
activeConfig,
|
||||
),
|
||||
);
|
||||
trackActionWithoutFiring(actionKey, activeGamepad, activeConfig);
|
||||
}
|
||||
}
|
||||
|
||||
handleSelectionAxis(
|
||||
resolveAxisBindingValue(
|
||||
activeGamepad,
|
||||
axisGamepad,
|
||||
activeConfig.bindings.leftStickHorizontal,
|
||||
activeConfig.triggerDeadzone,
|
||||
activationThreshold,
|
||||
|
||||
@@ -3,7 +3,7 @@ import test from 'node:test';
|
||||
|
||||
import { createKeyboardHandlers } from './keyboard.js';
|
||||
import { createRendererState } from '../state.js';
|
||||
import { HACHIDORI_HOST_SELECTOR } from '../yomitan-popup.js';
|
||||
import { HACHIDORI_HOST_SELECTOR, HACHIDORI_POPUP_OPEN_SELECTOR } from '../yomitan-popup.js';
|
||||
import type { CompiledSessionBinding } from '../../types';
|
||||
import type { MpvInputBindingsSnapshot } from '../../types/session-bindings';
|
||||
import { DEFAULT_KEYBINDINGS, SPECIAL_COMMANDS } from '../../config/definitions';
|
||||
@@ -150,15 +150,13 @@ function installKeyboardTestGlobals() {
|
||||
let markActiveVideoWatchedCalls = 0;
|
||||
let statsToggleOverlayCalls = 0;
|
||||
const openedModalNotifications: string[] = [];
|
||||
const unforwardedMpvKeys: Array<{ key: string; reason: string }> = [];
|
||||
let selectionClearCount = 0;
|
||||
let selectionAddCount = 0;
|
||||
let mutationRecordsTaken = 0;
|
||||
|
||||
let popupVisible = false;
|
||||
let hachidoriPaneOpen = false;
|
||||
const hachidoriHost = {
|
||||
shadowRoot: { querySelectorAll: () => [{ hidden: false }] },
|
||||
};
|
||||
|
||||
const popupIframe = {
|
||||
tagName: 'IFRAME',
|
||||
@@ -255,6 +253,9 @@ function installKeyboardTestGlobals() {
|
||||
sendMpvCommand: (command: Array<string | number>) => {
|
||||
mpvCommands.push(command);
|
||||
},
|
||||
reportUnforwardedMpvKey: (report: { key: string; reason: string }) => {
|
||||
unforwardedMpvKeys.push(report);
|
||||
},
|
||||
dispatchSessionAction: async (actionId: string, payload?: unknown) => {
|
||||
sessionActions.push({ actionId, payload });
|
||||
},
|
||||
@@ -293,8 +294,8 @@ function installKeyboardTestGlobals() {
|
||||
documentListeners.set(type, listeners);
|
||||
},
|
||||
querySelectorAll: (selector: string) => {
|
||||
if (selector === HACHIDORI_HOST_SELECTOR) {
|
||||
return hachidoriPaneOpen ? [hachidoriHost] : [];
|
||||
if (selector === HACHIDORI_POPUP_OPEN_SELECTOR) {
|
||||
return hachidoriPaneOpen ? [{}] : [];
|
||||
}
|
||||
if (popupVisible) {
|
||||
return [popupIframe];
|
||||
@@ -521,6 +522,7 @@ function installKeyboardTestGlobals() {
|
||||
markActiveVideoWatchedCalls: () => markActiveVideoWatchedCalls,
|
||||
statsToggleOverlayCalls: () => statsToggleOverlayCalls,
|
||||
openedModalNotifications,
|
||||
unforwardedMpvKeys,
|
||||
getPlaybackPaused: async () => playbackPausedResponse,
|
||||
setPlaybackPausedResponse: (value: boolean | null) => {
|
||||
playbackPausedResponse = value;
|
||||
@@ -2573,6 +2575,27 @@ test('discovered mpv keys only run after SubMiner controls and stay out of sessi
|
||||
}
|
||||
});
|
||||
|
||||
test('imported mpv keys forward once the popup closes, even if the cached popup flag lags', async () => {
|
||||
const { handlers, testGlobals, ctx } = createKeyboardHandlerHarness();
|
||||
try {
|
||||
testGlobals.setGetMpvInputBindings(async () => ({ keys: ['r'], blockedKeys: [] }));
|
||||
await handlers.setupMpvInputForwarding();
|
||||
await wait(0);
|
||||
testGlobals.setPopupVisible(true);
|
||||
testGlobals.dispatchKeydown({ key: 'r', code: 'KeyR' });
|
||||
assert.deepEqual(testGlobals.mpvCommands, []);
|
||||
assert.deepEqual(testGlobals.unforwardedMpvKeys, [{ key: 'r', reason: 'lookup-popup' }]);
|
||||
|
||||
// #331: the popup closed, but a late popup event left the cached flag set.
|
||||
testGlobals.setPopupVisible(false);
|
||||
ctx.state.yomitanPopupVisible = true;
|
||||
testGlobals.dispatchKeydown({ key: 'r', code: 'KeyR' });
|
||||
assert.deepEqual(testGlobals.mpvCommands, [['keydown', 'r']]);
|
||||
} finally {
|
||||
testGlobals.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('stalled mpv discovery does not delay configured overlay controls', async () => {
|
||||
const { handlers, testGlobals } = createKeyboardHandlerHarness();
|
||||
try {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { CompiledSessionBinding, PrimarySubMode, ShortcutsConfig } from '../../types';
|
||||
import type { MpvKeyForwardBlock } from '../../types/session-bindings';
|
||||
import type { RendererContext } from '../context';
|
||||
import { createMpvInputForwarding } from './mpv-input-forwarding';
|
||||
import { MPV_MOUSE_BUTTON_BY_BUTTON, wheelEventToMpvWheel } from '../../shared/mpv-input-bindings';
|
||||
@@ -141,14 +142,24 @@ export function createKeyboardHandlers(
|
||||
// Imported mpv bindings only run when no SubMiner UI could be the input's target.
|
||||
// The subtitle sidebar is a side panel over playback, so only input inside it (a
|
||||
// `.modal` target) stays with SubMiner.
|
||||
// Why imported mpv input must stay in the overlay right now, or null when it may forward.
|
||||
// SubMiner's own keybindings never pass through here.
|
||||
function getMpvForwardBlock(target: EventTarget | null): MpvKeyForwardBlock | null {
|
||||
if (!keyboardConfigLoaded) return 'config-loading';
|
||||
if (ctx.state.playlistBrowserModalOpen || ctx.state.youtubePickerModalOpen) return 'modal';
|
||||
if (isLookupPopupOpen(ctx.state, document)) return 'lookup-popup';
|
||||
if (isInteractiveTarget(target)) return 'interactive-target';
|
||||
return null;
|
||||
}
|
||||
|
||||
function canForwardToMpv(target: EventTarget | null): boolean {
|
||||
return (
|
||||
keyboardConfigLoaded &&
|
||||
!ctx.state.playlistBrowserModalOpen &&
|
||||
!ctx.state.youtubePickerModalOpen &&
|
||||
!isLookupPopupOpen(ctx.state, document) &&
|
||||
!isInteractiveTarget(target)
|
||||
);
|
||||
return getMpvForwardBlock(target) === null;
|
||||
}
|
||||
|
||||
// Debug breadcrumb for "my mpv key does nothing": the main process logs it at debug level.
|
||||
function reportUnforwardedMpvKey(e: KeyboardEvent, reason: MpvKeyForwardBlock): void {
|
||||
const report = importedMpvBindings.unforwardedReport(e, reason);
|
||||
if (report) window.electronAPI.reportUnforwardedMpvKey(report);
|
||||
}
|
||||
|
||||
// Scrolling over subtitles still reaches mpv; only scrollable overlay UI keeps the wheel.
|
||||
@@ -1403,6 +1414,7 @@ export function createKeyboardHandlers(
|
||||
|
||||
if (isLookupPopupOpen(ctx.state, document)) {
|
||||
if (handleYomitanPopupKeybind(e)) {
|
||||
reportUnforwardedMpvKey(e, 'lookup-popup');
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
@@ -1469,7 +1481,13 @@ export function createKeyboardHandlers(
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (canForwardToMpv(e.target)) importedMpvBindings.keydown(e);
|
||||
const forwardBlock = getMpvForwardBlock(e.target);
|
||||
if (forwardBlock) {
|
||||
reportUnforwardedMpvKey(e, forwardBlock);
|
||||
} else if (!importedMpvBindings.keydown(e)) {
|
||||
// Reports only while nothing is imported; an unbound key is not worth a line.
|
||||
reportUnforwardedMpvKey(e, 'no-imported-bindings');
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('mousedown', (e: MouseEvent) => {
|
||||
|
||||
@@ -5,9 +5,8 @@ import { SUBTITLE_DEFAULT_CONFIG } from '../../config/definitions/defaults-subti
|
||||
import { createRendererState } from '../state';
|
||||
import { createMouseHandlers } from './mouse.js';
|
||||
import {
|
||||
HACHIDORI_HOST_SELECTOR,
|
||||
HACHIDORI_POPUP_HIDDEN_EVENT,
|
||||
HACHIDORI_POPUP_SELECTOR,
|
||||
HACHIDORI_POPUP_OPEN_SELECTOR,
|
||||
HACHIDORI_POPUP_SHOWN_EVENT,
|
||||
YOMITAN_LOOKUP_EVENT,
|
||||
YOMITAN_POPUP_HIDDEN_EVENT,
|
||||
@@ -110,23 +109,11 @@ function createMouseHarness(
|
||||
};
|
||||
const ignoreCalls: IgnoreCall[] = [];
|
||||
const mpvCommands: Array<(string | number)[]> = [];
|
||||
const popupPane = {
|
||||
get hidden() {
|
||||
return !harness.popupPaneOpen;
|
||||
},
|
||||
};
|
||||
const popupHost = {
|
||||
tagName: options.hachidori ? 'HACHIDORI-HOST' : 'DIV',
|
||||
getAttribute: (name: string) =>
|
||||
name === 'data-subminer-yomitan-popup-visible' ? String(harness.popupHostVisible) : null,
|
||||
shadowRoot: {
|
||||
querySelectorAll: (selector: string) =>
|
||||
selector === HACHIDORI_POPUP_SELECTOR ? [popupPane] : [],
|
||||
},
|
||||
};
|
||||
const hostSelectors = options.hachidori
|
||||
? [HACHIDORI_HOST_SELECTOR, YOMITAN_POPUP_HOST_SELECTOR]
|
||||
: [YOMITAN_POPUP_HOST_SELECTOR];
|
||||
|
||||
const harness = {
|
||||
ctx,
|
||||
@@ -183,7 +170,10 @@ function createMouseHarness(
|
||||
if (selector === YOMITAN_POPUP_VISIBLE_HOST_SELECTOR) {
|
||||
return harness.popupHostVisible ? [popupHost] : [];
|
||||
}
|
||||
return hostSelectors.includes(selector) &&
|
||||
if (selector === HACHIDORI_POPUP_OPEN_SELECTOR) {
|
||||
return harness.popupPaneOpen ? [popupHost] : [];
|
||||
}
|
||||
return selector === YOMITAN_POPUP_HOST_SELECTOR &&
|
||||
(harness.popupHostVisible || harness.popupHostAttached)
|
||||
? [popupHost]
|
||||
: [];
|
||||
@@ -529,6 +519,31 @@ test('Hachidori hover popup pauses when shown', async (t) => {
|
||||
assert.deepEqual(h.mpvCommands, [PAUSE]);
|
||||
});
|
||||
|
||||
test('leaving the subtitle keeps playback paused while a Hachidori popup is open', async (t) => {
|
||||
let paused = false;
|
||||
const h = createMouseHarness(t, {
|
||||
hoverPause: true,
|
||||
popupPause: true,
|
||||
hachidori: true,
|
||||
getPlaybackPaused: async () => paused,
|
||||
});
|
||||
h.handlers.setupYomitanObserver();
|
||||
|
||||
await h.handlers.handleMouseEnter();
|
||||
paused = true;
|
||||
h.popupPaneOpen = true;
|
||||
h.popupHostVisible = true;
|
||||
h.fire('window', HACHIDORI_POPUP_SHOWN_EVENT);
|
||||
await waitForNextTick();
|
||||
await h.handlers.handleMouseLeave();
|
||||
assert.deepEqual(h.mpvCommands, [PAUSE]);
|
||||
|
||||
h.popupPaneOpen = false;
|
||||
h.popupHostVisible = false;
|
||||
h.fire('window', HACHIDORI_POPUP_HIDDEN_EVENT);
|
||||
assert.deepEqual(h.mpvCommands, [PAUSE, RESUME]);
|
||||
});
|
||||
|
||||
test('popup shown reclaims overlay focus on macOS and captures click-away', (t) => {
|
||||
const h = createMouseHarness(t, { platform: 'macos' });
|
||||
h.handlers.setupYomitanObserver();
|
||||
|
||||
@@ -175,3 +175,50 @@ test('focus loss releases held keys and failed refresh clears stale bindings', a
|
||||
await forwarding.refresh();
|
||||
assert.equal(forwarding.keydown(keyEvent()), false);
|
||||
});
|
||||
|
||||
test('a reload keeps forwarding the current keys until it settles', async () => {
|
||||
let resolveReload: (snapshot: MpvInputBindingsSnapshot) => void = () => {};
|
||||
let loads = 0;
|
||||
const forwarding = createMpvInputForwarding({
|
||||
load: () => {
|
||||
loads += 1;
|
||||
if (loads === 1) return Promise.resolve({ keys: ['r'], blockedKeys: [] });
|
||||
return new Promise((resolve) => {
|
||||
resolveReload = resolve;
|
||||
});
|
||||
},
|
||||
send: () => {},
|
||||
});
|
||||
await forwarding.refresh();
|
||||
const reload = forwarding.refresh();
|
||||
assert.equal(forwarding.keydown(keyEvent()), true);
|
||||
forwarding.keyup(keyEvent());
|
||||
resolveReload({ keys: ['t'], blockedKeys: [] });
|
||||
await reload;
|
||||
assert.equal(forwarding.keydown(keyEvent()), false);
|
||||
assert.equal(forwarding.keydown(keyEvent({ key: 't', code: 'KeyT' })), true);
|
||||
});
|
||||
|
||||
test('unforwarded reports name keys mpv binds, or any key while nothing is imported', async () => {
|
||||
let snapshot: MpvInputBindingsSnapshot = { keys: [], blockedKeys: [] };
|
||||
const forwarding = createMpvInputForwarding({ load: async () => snapshot, send: () => {} });
|
||||
await forwarding.refresh();
|
||||
assert.deepEqual(forwarding.unforwardedReport(keyEvent(), 'lookup-popup'), {
|
||||
key: 'r',
|
||||
reason: 'no-imported-bindings',
|
||||
});
|
||||
assert.equal(
|
||||
forwarding.unforwardedReport(keyEvent({ key: 'Shift', code: 'ShiftLeft' }), 'lookup-popup'),
|
||||
null,
|
||||
);
|
||||
|
||||
snapshot = { keys: ['r', 't'], blockedKeys: [{ code: 'KeyT', modifiers: [] }] };
|
||||
await forwarding.refresh();
|
||||
assert.deepEqual(forwarding.unforwardedReport(keyEvent(), 'interactive-target'), {
|
||||
key: 'r',
|
||||
reason: 'interactive-target',
|
||||
});
|
||||
assert.equal(forwarding.unforwardedReport(keyEvent(), 'no-imported-bindings'), null);
|
||||
assert.equal(forwarding.unforwardedReport(keyEvent({ key: 't', code: 'KeyT' }), 'modal'), null);
|
||||
assert.equal(forwarding.unforwardedReport(keyEvent({ key: 'z', code: 'KeyZ' }), 'modal'), null);
|
||||
});
|
||||
@@ -4,7 +4,13 @@ import {
|
||||
normalizeMpvInputKey,
|
||||
wheelEventToMpvWheel,
|
||||
} from '../../shared/mpv-input-bindings';
|
||||
import type { MpvInputBindingsSnapshot } from '../../types/session-bindings';
|
||||
import type {
|
||||
MpvInputBindingsSnapshot,
|
||||
MpvKeyForwardBlock,
|
||||
UnforwardedMpvKeyReport,
|
||||
} from '../../types/session-bindings';
|
||||
|
||||
const MODIFIER_ONLY_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph']);
|
||||
|
||||
type ModifierState = Pick<KeyboardEvent, 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey'>;
|
||||
type ForwardedKeyEvent = Parameters<typeof keyboardEventToMpvKey>[0] &
|
||||
@@ -31,25 +37,26 @@ export function createMpvInputForwarding(deps: {
|
||||
heldKeys.clear();
|
||||
}
|
||||
|
||||
// Every window focus refreshes, so the current list keeps forwarding until the reload
|
||||
// settles; a key pressed mid-reload would otherwise be dropped.
|
||||
function refresh(): Promise<void> {
|
||||
if (disposed) return Promise.resolve();
|
||||
generation += 1;
|
||||
keys.clear();
|
||||
blockedKeys = [];
|
||||
releaseAll();
|
||||
if (pending) return pending;
|
||||
pending = (async () => {
|
||||
let requestedGeneration: number;
|
||||
do {
|
||||
requestedGeneration = generation;
|
||||
let snapshot: MpvInputBindingsSnapshot | null = null;
|
||||
try {
|
||||
const snapshot = await deps.load();
|
||||
if (!disposed && requestedGeneration === generation) {
|
||||
keys = new Set(snapshot.keys);
|
||||
blockedKeys = snapshot.blockedKeys;
|
||||
}
|
||||
snapshot = await deps.load();
|
||||
} catch {
|
||||
// Discovery is optional. Keep the existing overlay controls available.
|
||||
// Discovery is optional: SubMiner's own bindings keep working without it.
|
||||
}
|
||||
if (!disposed && requestedGeneration === generation) {
|
||||
keys = new Set(snapshot?.keys ?? []);
|
||||
blockedKeys = snapshot?.blockedKeys ?? [];
|
||||
}
|
||||
} while (!disposed && requestedGeneration !== generation);
|
||||
})().finally(() => {
|
||||
@@ -98,6 +105,23 @@ export function createMpvInputForwarding(deps: {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The debug report for a key the overlay kept from mpv, or null when mpv does not bind
|
||||
* it. With nothing imported yet, every nameable key is reported as such.
|
||||
*/
|
||||
function unforwardedReport(
|
||||
event: ForwardedKeyEvent,
|
||||
reason: MpvKeyForwardBlock,
|
||||
): UnforwardedMpvKeyReport | null {
|
||||
if (disposed || event.repeat || MODIFIER_ONLY_KEYS.has(event.key)) return null;
|
||||
const key = keyboardEventToMpvKey(event);
|
||||
if (!key) return null;
|
||||
if (keys.size === 0) return { key, reason: 'no-imported-bindings' };
|
||||
if (reason === 'no-imported-bindings') return null;
|
||||
if (isBlocked(event.code, event) || !keys.has(key)) return null;
|
||||
return { key, reason };
|
||||
}
|
||||
|
||||
function keyup(event: Pick<KeyboardEvent, 'code' | 'preventDefault'>): void {
|
||||
const key = heldKeys.get(event.code);
|
||||
if (!key) return;
|
||||
@@ -154,5 +178,15 @@ export function createMpvInputForwarding(deps: {
|
||||
releaseAll();
|
||||
}
|
||||
|
||||
return { refresh, keydown, keyup, wheel, mousedown, mouseup, releaseAll, dispose };
|
||||
return {
|
||||
refresh,
|
||||
keydown,
|
||||
keyup,
|
||||
wheel,
|
||||
mousedown,
|
||||
mouseup,
|
||||
releaseAll,
|
||||
dispose,
|
||||
unforwardedReport,
|
||||
};
|
||||
}
|
||||
@@ -39,6 +39,44 @@ test('a button on the D-pad clashes with a D-pad row that is still on', () => {
|
||||
);
|
||||
});
|
||||
|
||||
const L1_DPAD_RIGHT = {
|
||||
kind: 'button',
|
||||
buttonIndex: 15,
|
||||
hold: { kind: 'button', buttonIndex: 4 },
|
||||
} as const;
|
||||
|
||||
test('a combo does not clash with its hold or press used elsewhere on their own', () => {
|
||||
// L1 is Play Current Audio by default; the D-pad is still on Token Move.
|
||||
assert.deepEqual(issuesWith({ nextAudio: L1_DPAD_RIGHT }), {});
|
||||
});
|
||||
|
||||
test('two actions on the same combo both warn', () => {
|
||||
assert.deepEqual(issuesWith({ nextAudio: L1_DPAD_RIGHT, nextEntry: L1_DPAD_RIGHT }), {
|
||||
nextAudio: 'Same as Next Entry',
|
||||
nextEntry: 'Same as Next Audio',
|
||||
});
|
||||
});
|
||||
|
||||
test('a combo holding and pressing the same button warns', () => {
|
||||
assert.deepEqual(
|
||||
issuesWith({
|
||||
nextEntry: { kind: 'button', buttonIndex: 7, hold: { kind: 'button', buttonIndex: 7 } },
|
||||
}),
|
||||
{ nextEntry: 'Hold and press are the same button' },
|
||||
);
|
||||
});
|
||||
|
||||
test('the secondary subtitle hold warns on a hold button, since it cannot wait for release', () => {
|
||||
assert.deepEqual(
|
||||
issuesWith({
|
||||
playCurrentAudio: { kind: 'none' },
|
||||
nextAudio: L1_DPAD_RIGHT,
|
||||
holdSecondarySub: { kind: 'button', buttonIndex: 4 },
|
||||
}),
|
||||
{ holdSecondarySub: 'Also the hold button of Next Audio' },
|
||||
);
|
||||
});
|
||||
|
||||
test('a D-pad reported as a hat axis also counts as the D-pad', () => {
|
||||
assert.deepEqual(
|
||||
issuesWith({ previousEntry: { kind: 'axis', axisIndex: 7, direction: 'negative' } }),
|
||||
@@ -80,14 +118,6 @@ test('two stick actions on the same stick both warn', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('Alt Horizontal does nothing, so it never clashes', () => {
|
||||
// On standard pads the right stick's vertical axis is 3, the default of Alt Horizontal.
|
||||
assert.deepEqual(
|
||||
issuesWith({ rightStickVertical: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' } }),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
test('a row shared by several actions lists them all', () => {
|
||||
assert.equal(
|
||||
issuesWith({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { controllerReviewInputSourceKey } from '../../shared/controller-review';
|
||||
import { DPAD_AXIS_INDEX, DPAD_BUTTON_INDEX } from '../handlers/gamepad-controller.js';
|
||||
import type {
|
||||
ControllerDpadFallback,
|
||||
@@ -16,12 +17,6 @@ export type ControllerBindingIssueDefinition = {
|
||||
bindingType: 'discrete' | 'axis';
|
||||
};
|
||||
|
||||
/**
|
||||
* Rows that do nothing in SubMiner: no action reads `rightStickHorizontal`, so it cannot
|
||||
* clash with anything.
|
||||
*/
|
||||
const INACTIVE_BINDINGS: ReadonlySet<ControllerBindingActionId> = new Set(['rightStickHorizontal']);
|
||||
|
||||
/** Row key of a stick binding's D-pad row in Alt+C. */
|
||||
export function getControllerDpadRowKey(actionId: ControllerBindingActionId): string {
|
||||
return `${actionId}:dpad`;
|
||||
@@ -31,10 +26,14 @@ const buttonKey = (buttonIndex: number) => `button:${buttonIndex}`;
|
||||
const axisKey = (axisIndex: number, direction: 'negative' | 'positive') =>
|
||||
`axis:${axisIndex}:${direction}`;
|
||||
|
||||
/**
|
||||
* A combo counts as one input, apart from its hold and press alone: a plain action on the hold
|
||||
* button waits for release, and a combo keeps its press away from plain actions and stick rows.
|
||||
*/
|
||||
function discreteInputs(binding: ResolvedControllerDiscreteBinding): string[] {
|
||||
if (binding.kind === 'none') return [];
|
||||
if ('buttonIndex' in binding) return [buttonKey(binding.buttonIndex)];
|
||||
return [axisKey(binding.axisIndex, binding.direction)];
|
||||
const press = controllerReviewInputSourceKey(binding);
|
||||
return [binding.hold ? `${controllerReviewInputSourceKey(binding.hold)}+${press}` : press];
|
||||
}
|
||||
|
||||
function stickInputs(binding: ResolvedControllerAxisBinding): string[] {
|
||||
@@ -74,9 +73,10 @@ export function findControllerBindingIssues(
|
||||
definitions: readonly ControllerBindingIssueDefinition[],
|
||||
bindings: ControllerBindings,
|
||||
): Partial<Record<string, string>> {
|
||||
const issues: Partial<Record<string, string>> = {};
|
||||
const holdActions = new Map<string, string>();
|
||||
const rows: { key: string; label: string; inputs: string[] }[] = [];
|
||||
for (const definition of definitions) {
|
||||
if (INACTIVE_BINDINGS.has(definition.id)) continue;
|
||||
const binding = bindings[definition.id];
|
||||
if (!binding) continue;
|
||||
if (definition.bindingType === 'axis') {
|
||||
@@ -92,15 +92,30 @@ export function findControllerBindingIssues(
|
||||
inputs: dpadInputs(axisBinding.kind === 'none' ? 'none' : axisBinding.dpadFallback),
|
||||
});
|
||||
} else {
|
||||
const discreteBinding = binding as ResolvedControllerDiscreteBinding;
|
||||
rows.push({
|
||||
key: definition.id,
|
||||
label: definition.label,
|
||||
inputs: discreteInputs(binding as ResolvedControllerDiscreteBinding),
|
||||
inputs: discreteInputs(discreteBinding),
|
||||
});
|
||||
if (discreteBinding.kind !== 'none' && discreteBinding.hold) {
|
||||
const holdKey = controllerReviewInputSourceKey(discreteBinding.hold);
|
||||
if (holdKey === controllerReviewInputSourceKey(discreteBinding)) {
|
||||
issues[definition.id] = 'Hold and press are the same button';
|
||||
} else if (!holdActions.has(holdKey)) {
|
||||
holdActions.set(holdKey, definition.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const issues: Partial<Record<string, string>> = {};
|
||||
// Everything else on a hold button can wait for release. This one shows while held.
|
||||
const secondaryHold = bindings.holdSecondarySub;
|
||||
if (secondaryHold.kind !== 'none' && !secondaryHold.hold) {
|
||||
const comboLabel = holdActions.get(controllerReviewInputSourceKey(secondaryHold));
|
||||
if (comboLabel) issues.holdSecondarySub = `Also the hold button of ${comboLabel}`;
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
const inputs = new Set(row.inputs);
|
||||
const clashes = rows
|
||||
|
||||
@@ -31,7 +31,6 @@ const BINDINGS: ResolvedControllerConfig['bindings'] = {
|
||||
playNextSubtitle: { kind: 'none' },
|
||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
||||
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
||||
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
||||
};
|
||||
|
||||
@@ -188,15 +187,13 @@ test('controller config form renders grouped rows with friendly binding labels',
|
||||
['Token Move (D-pad)', 'D-pad ↔'],
|
||||
['Popup Scroll (Stick)', 'Left Stick Y'],
|
||||
['Popup Scroll (D-pad)', 'D-pad ↕'],
|
||||
['Alt Horizontal (Stick)', 'Right Stick X'],
|
||||
['Alt Horizontal (D-pad)', 'None'],
|
||||
['Popup Jump (Stick)', 'Right Stick Y'],
|
||||
['Popup Jump (D-pad)', 'None'],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
findAll(container, 'disabled').map((badge) => badge.textContent),
|
||||
['None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None'],
|
||||
['None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None'],
|
||||
);
|
||||
assert.deepEqual(findAll(container, 'expanded'), []);
|
||||
assert.deepEqual(findAll(container, 'controller-config-edit-panel'), []);
|
||||
@@ -216,7 +213,7 @@ test('controller config form expands the learning row with a listening edit pane
|
||||
assert.equal(panel.classList.contains('controller-config-edit-panel'), true);
|
||||
|
||||
const hint = findOne(panel, 'controller-config-edit-hint');
|
||||
assert.equal(hint.textContent, 'Press a button, trigger, or move a stick…');
|
||||
assert.equal(hint.textContent, 'Press a button, or hold one and press another for a combo…');
|
||||
assert.equal(hint.classList.contains('learning'), true);
|
||||
assert.equal(findOne(panel, 'btn-learn').textContent, 'Listening…');
|
||||
});
|
||||
|
||||
@@ -28,6 +28,7 @@ export type ControllerScreenLearning = {
|
||||
};
|
||||
import type {
|
||||
ControllerDpadFallback,
|
||||
ControllerRawInput,
|
||||
ResolvedControllerAxisBinding,
|
||||
ResolvedControllerConfig,
|
||||
ResolvedControllerDiscreteBinding,
|
||||
@@ -177,13 +178,6 @@ export const CONTROLLER_BINDING_DEFINITIONS: ControllerBindingDefinition[] = [
|
||||
bindingType: 'axis',
|
||||
defaultBinding: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||
},
|
||||
{
|
||||
id: 'rightStickHorizontal',
|
||||
label: 'Alt Horizontal',
|
||||
group: 'Navigation',
|
||||
bindingType: 'axis',
|
||||
defaultBinding: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
||||
},
|
||||
{
|
||||
id: 'rightStickVertical',
|
||||
label: 'Popup Jump',
|
||||
@@ -296,22 +290,25 @@ export function getFriendlyAxisName(axisIndex: number, mapping?: ControllerMappi
|
||||
return names[axisIndex] ?? `Axis ${axisIndex}`;
|
||||
}
|
||||
|
||||
function formatInputSummary(input: ControllerRawInput): string {
|
||||
return input.kind === 'button'
|
||||
? `Button ${input.buttonIndex}`
|
||||
: `Axis ${input.axisIndex} ${input.direction === 'positive' ? '+' : '-'}`;
|
||||
}
|
||||
|
||||
export function formatControllerBindingSummary(
|
||||
binding: ResolvedControllerDiscreteBinding | ResolvedControllerAxisBinding,
|
||||
): string {
|
||||
if (binding.kind === 'none') {
|
||||
return 'Disabled';
|
||||
}
|
||||
if ('direction' in binding) {
|
||||
return `Axis ${binding.axisIndex} ${binding.direction === 'positive' ? '+' : '-'}`;
|
||||
if ('dpadFallback' in binding) {
|
||||
return binding.dpadFallback === 'none'
|
||||
? `Axis ${binding.axisIndex}`
|
||||
: `Axis ${binding.axisIndex} + D-pad ${binding.dpadFallback}`;
|
||||
}
|
||||
if ('buttonIndex' in binding) {
|
||||
return `Button ${binding.buttonIndex}`;
|
||||
}
|
||||
if (binding.dpadFallback === 'none') {
|
||||
return `Axis ${binding.axisIndex}`;
|
||||
}
|
||||
return `Axis ${binding.axisIndex} + D-pad ${binding.dpadFallback}`;
|
||||
const press = formatInputSummary(binding);
|
||||
return binding.hold ? `${formatInputSummary(binding.hold)} + ${press}` : press;
|
||||
}
|
||||
|
||||
function formatFriendlyStickLabel(
|
||||
@@ -322,20 +319,36 @@ function formatFriendlyStickLabel(
|
||||
return getFriendlyAxisName(binding.axisIndex, mapping);
|
||||
}
|
||||
|
||||
export function formatFriendlyInputLabel(
|
||||
input: ControllerRawInput,
|
||||
mapping: ControllerMapping,
|
||||
faceButtonLabels: FaceButtonLabels,
|
||||
): string {
|
||||
if (input.kind === 'button') {
|
||||
return getFriendlyButtonName(input.buttonIndex, mapping, faceButtonLabels);
|
||||
}
|
||||
const name = getFriendlyAxisName(input.axisIndex, mapping);
|
||||
return `${name} ${input.direction === 'positive' ? '+' : '\u2212'}`;
|
||||
}
|
||||
|
||||
function formatFriendlyBindingLabel(
|
||||
binding: ResolvedControllerDiscreteBinding | ResolvedControllerAxisBinding,
|
||||
mapping: ControllerMapping,
|
||||
faceButtonLabels: FaceButtonLabels,
|
||||
): string {
|
||||
if (binding.kind === 'none') return 'None';
|
||||
if ('direction' in binding) {
|
||||
const name = getFriendlyAxisName(binding.axisIndex, mapping);
|
||||
return `${name} ${binding.direction === 'positive' ? '+' : '\u2212'}`;
|
||||
}
|
||||
if ('buttonIndex' in binding) {
|
||||
return getFriendlyButtonName(binding.buttonIndex, mapping, faceButtonLabels);
|
||||
}
|
||||
return getFriendlyAxisName(binding.axisIndex, mapping);
|
||||
if ('dpadFallback' in binding) return getFriendlyAxisName(binding.axisIndex, mapping);
|
||||
const press = formatFriendlyInputLabel(binding, mapping, faceButtonLabels);
|
||||
return binding.hold
|
||||
? `${formatFriendlyInputLabel(binding.hold, mapping, faceButtonLabels)} + ${press}`
|
||||
: press;
|
||||
}
|
||||
|
||||
/** What Alt+C asks for while learning a binding that can be a combo. */
|
||||
function formatComboLearnHint(holdLabel: string | null): string {
|
||||
return holdLabel
|
||||
? `Holding ${holdLabel}: press another button for a combo, or let go to use ${holdLabel} alone\u2026`
|
||||
: 'Press a button, or hold one and press another for a combo\u2026';
|
||||
}
|
||||
|
||||
/** Unique key for expanded rows. Stick rows use the action id, dpad rows append ':dpad'. */
|
||||
@@ -345,6 +358,8 @@ export function createControllerConfigForm(options: {
|
||||
container: HTMLElement;
|
||||
getBindings: () => ResolvedControllerConfig['bindings'];
|
||||
getLearningActionId: () => ControllerBindingActionId | null;
|
||||
/** The hold button pressed so far while learning a discrete action, if any. */
|
||||
getLearningHoldLabel?: () => string | null;
|
||||
getDpadLearningActionId: () => ControllerBindingActionId | null;
|
||||
onLearn: (actionId: ControllerBindingActionId, bindingType: 'discrete' | 'axis') => void;
|
||||
onClear: (actionId: ControllerBindingActionId) => void;
|
||||
@@ -539,11 +554,7 @@ export function createControllerConfigForm(options: {
|
||||
options.container.appendChild(row);
|
||||
|
||||
if (isExpanded) {
|
||||
const hint = !isLearning
|
||||
? `Currently: ${current}`
|
||||
: holdLabel
|
||||
? `Holding ${holdLabel}: press another button for a combo, or let go to use ${holdLabel} alone\u2026`
|
||||
: 'Press a button, or hold one and press another for a combo\u2026';
|
||||
const hint = isLearning ? formatComboLearnHint(holdLabel) : `Currently: ${current}`;
|
||||
const panel = createEditPanel(rowKey, hint, isLearning, {
|
||||
onLearn: learn,
|
||||
onClear: (e) => {
|
||||
@@ -565,14 +576,17 @@ export function createControllerConfigForm(options: {
|
||||
const rowKey = definition.id as string;
|
||||
const isExpanded = expandedRowKey === rowKey;
|
||||
const isLearning = learningActionId === definition.id;
|
||||
const holdLabel = isLearning ? (options.getLearningHoldLabel?.() ?? null) : null;
|
||||
|
||||
const row = createRow(
|
||||
definition.label,
|
||||
formatFriendlyBindingLabel(
|
||||
binding,
|
||||
options.getControllerMapping?.(),
|
||||
options.getFaceButtonLabels?.(),
|
||||
),
|
||||
holdLabel
|
||||
? `${holdLabel} + \u2026`
|
||||
: formatFriendlyBindingLabel(
|
||||
binding,
|
||||
options.getControllerMapping?.(),
|
||||
options.getFaceButtonLabels?.(),
|
||||
),
|
||||
binding.kind === 'none',
|
||||
isExpanded,
|
||||
`Learn ${definition.label}`,
|
||||
@@ -596,7 +610,7 @@ export function createControllerConfigForm(options: {
|
||||
|
||||
if (isExpanded) {
|
||||
const hint = isLearning
|
||||
? 'Press a button, trigger, or move a stick\u2026'
|
||||
? formatComboLearnHint(holdLabel)
|
||||
: `Currently: ${formatControllerBindingSummary(binding)}`;
|
||||
const panel = createEditPanel(rowKey, hint, isLearning, {
|
||||
onLearn: (e) => {
|
||||
|
||||
@@ -84,7 +84,6 @@ test('controller debug modal renders active controller axes, buttons, and config
|
||||
playNextSubtitle: { kind: 'none' },
|
||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
||||
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
||||
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
||||
},
|
||||
reviewBindings: getDefaultControllerReviewBindings(),
|
||||
@@ -210,7 +209,6 @@ test('controller debug modal copies buttonIndices config to clipboard', async ()
|
||||
playNextSubtitle: { kind: 'none' },
|
||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
||||
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
||||
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
||||
},
|
||||
reviewBindings: getDefaultControllerReviewBindings(),
|
||||
@@ -335,7 +333,6 @@ test('controller debug modal stays closed and notifies when controller support i
|
||||
playNextSubtitle: { kind: 'none' },
|
||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
||||
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
||||
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
||||
},
|
||||
reviewBindings: getDefaultControllerReviewBindings(),
|
||||
|
||||
@@ -170,7 +170,6 @@ function buildContext() {
|
||||
playNextSubtitle: { kind: 'none' },
|
||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
||||
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
||||
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
||||
},
|
||||
reviewBindings: getDefaultControllerReviewBindings(),
|
||||
@@ -294,6 +293,9 @@ test('controller select modal learn mode captures fresh button input and persist
|
||||
}));
|
||||
state.controllerRawButtons[11] = { value: 1, pressed: true, touched: true };
|
||||
modal.updateDevices();
|
||||
// A lone button is only final once released: it could still become a combo's hold.
|
||||
state.controllerRawButtons[11] = { value: 0, pressed: false, touched: false };
|
||||
modal.updateDevices();
|
||||
|
||||
await Promise.resolve();
|
||||
|
||||
@@ -423,6 +425,9 @@ test('controller select modal binding badge starts learn mode and persists bindi
|
||||
}));
|
||||
state.controllerRawButtons[11] = { value: 1, pressed: true, touched: true };
|
||||
modal.updateDevices();
|
||||
// A lone button is only final once released: it could still become a combo's hold.
|
||||
state.controllerRawButtons[11] = { value: 0, pressed: false, touched: false };
|
||||
modal.updateDevices();
|
||||
|
||||
await Promise.resolve();
|
||||
|
||||
@@ -543,6 +548,9 @@ test('controller select modal edit control starts learn mode and persists bindin
|
||||
}));
|
||||
state.controllerRawButtons[11] = { value: 1, pressed: true, touched: true };
|
||||
modal.updateDevices();
|
||||
// A lone button is only final once released: it could still become a combo's hold.
|
||||
state.controllerRawButtons[11] = { value: 0, pressed: false, touched: false };
|
||||
modal.updateDevices();
|
||||
|
||||
await Promise.resolve();
|
||||
|
||||
@@ -736,6 +744,68 @@ test('controller select modal learns a review combo and saves it to the controll
|
||||
}
|
||||
});
|
||||
|
||||
test('controller select modal learns a combo for a main action', async () => {
|
||||
const domHandle = installFakeDom();
|
||||
const saved: unknown[] = [];
|
||||
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: {
|
||||
focus: () => {},
|
||||
electronAPI: {
|
||||
saveControllerConfig: async (update: unknown) => {
|
||||
saved.push(update);
|
||||
},
|
||||
notifyOverlayModalClosed: () => {},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const { state, dom } = buildContext();
|
||||
const modal = createControllerSelectModal({ state, dom } as never, {
|
||||
modalStateReader: { isAnyModalOpen: () => false },
|
||||
syncSettingsModalSubtitleSuppression: () => {},
|
||||
notifyControllerDisabled: () => {},
|
||||
});
|
||||
modal.wireDomEvents();
|
||||
modal.openControllerSelectModal();
|
||||
|
||||
const firstBadge = () => dom.controllerConfigList.children[1].children[1].children[0];
|
||||
firstBadge().dispatch('click');
|
||||
|
||||
const buttons = (pressed: number[]) =>
|
||||
Array.from({ length: 17 }, (_, index) => ({
|
||||
value: pressed.includes(index) ? 1 : 0,
|
||||
pressed: pressed.includes(index),
|
||||
touched: pressed.includes(index),
|
||||
}));
|
||||
|
||||
// Hold L1, then press D-pad right.
|
||||
state.controllerRawButtons = buttons([4]);
|
||||
modal.updateDevices();
|
||||
assert.equal(firstBadge().textContent, 'LB / L1 + \u2026');
|
||||
state.controllerRawButtons = buttons([4, 15]);
|
||||
modal.updateDevices();
|
||||
|
||||
// Let the save finish so the row re-renders with the saved combo.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const binding = {
|
||||
kind: 'button',
|
||||
buttonIndex: 15,
|
||||
hold: { kind: 'button', buttonIndex: 4 },
|
||||
};
|
||||
assert.deepEqual(saved.at(-1), {
|
||||
profiles: { 'pad-1': { bindings: { toggleLookup: binding } } },
|
||||
});
|
||||
assert.deepEqual(state.controllerConfig?.profiles['pad-1']?.bindings.toggleLookup, binding);
|
||||
assert.equal(firstBadge().textContent, 'LB / L1 + D-pad Right');
|
||||
} finally {
|
||||
domHandle.restore();
|
||||
}
|
||||
});
|
||||
|
||||
function findAllByClass(root: any, className: string, found: any[] = []): any[] {
|
||||
for (const child of root.children ?? []) {
|
||||
if (
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { ModalStateReader, RendererContext } from '../context';
|
||||
import { resolveControllerConfigForGamepad } from '../controller-profile-config.js';
|
||||
import { createControllerBindingCapture } from '../handlers/controller-binding-capture.js';
|
||||
import { createControllerComboCapture } from '../handlers/controller-combo-capture.js';
|
||||
import {
|
||||
createControllerComboCapture,
|
||||
type ControllerCapturedCombo,
|
||||
} from '../handlers/controller-combo-capture.js';
|
||||
import {
|
||||
CONTROLLER_FACE_BUTTON_STYLES,
|
||||
formatControllerReviewInput,
|
||||
@@ -18,11 +21,14 @@ import {
|
||||
} from '../../shared/controller-screens';
|
||||
import {
|
||||
createControllerConfigForm,
|
||||
formatFriendlyInputLabel,
|
||||
getControllerBindingDefinition,
|
||||
getDefaultControllerBinding,
|
||||
getDefaultDpadFallback,
|
||||
} from './controller-config-form.js';
|
||||
|
||||
import type { ControllerDpadFallback, ControllerRawInput } from '../../types';
|
||||
|
||||
const PRESS_TO_EDIT_STATUS = 'Press any button on your controller to edit its bindings.';
|
||||
|
||||
/** `8BitDo Ultimate Wireless Controller (STANDARD GAMEPAD Vendor: …)` → the name part. */
|
||||
@@ -75,12 +81,15 @@ export function createControllerSelectModal(
|
||||
let learningActionId: ControllerBindingKey | null = null;
|
||||
let dpadLearningActionId: ControllerBindingKey | null = null;
|
||||
let bindingCapture: ReturnType<typeof createControllerBindingCapture> | null = null;
|
||||
let screenLearning: {
|
||||
screen: ControllerScreenDefinition;
|
||||
actionId: string;
|
||||
type ComboLearning = {
|
||||
capture: ReturnType<typeof createControllerComboCapture>;
|
||||
holdLabel: string | null;
|
||||
} | null = null;
|
||||
};
|
||||
/** Set with `learningActionId` while learning a discrete row. */
|
||||
let discreteLearning: ComboLearning | null = null;
|
||||
let screenLearning:
|
||||
| (ComboLearning & { screen: ControllerScreenDefinition; actionId: string })
|
||||
| null = null;
|
||||
|
||||
/** The controller the overlay reports in use, fetched when the window opens. */
|
||||
let overlayActiveControllerId: string | null = null;
|
||||
@@ -161,6 +170,36 @@ export function createControllerSelectModal(
|
||||
screenLearning = null;
|
||||
}
|
||||
|
||||
function startComboLearning(): ComboLearning {
|
||||
const config = ctx.state.controllerConfig;
|
||||
const capture = createControllerComboCapture({
|
||||
triggerDeadzone: config?.triggerDeadzone ?? 0.5,
|
||||
stickDeadzone: config?.stickDeadzone ?? 0.2,
|
||||
});
|
||||
capture.arm({ axes: ctx.state.controllerRawAxes, buttons: ctx.state.controllerRawButtons });
|
||||
return { capture, holdLabel: null };
|
||||
}
|
||||
|
||||
/** Advances a combo capture, showing the hold button so far; returns the finished combo. */
|
||||
function pollComboLearning(
|
||||
learning: ComboLearning,
|
||||
formatHold: (input: ControllerRawInput) => string,
|
||||
): ControllerCapturedCombo | null {
|
||||
const state = learning.capture.poll({
|
||||
axes: ctx.state.controllerRawAxes,
|
||||
buttons: ctx.state.controllerRawButtons,
|
||||
});
|
||||
if (state.status === 'done') return state.binding;
|
||||
if (state.status === 'holding') {
|
||||
const holdLabel = formatHold(state.hold);
|
||||
if (holdLabel !== learning.holdLabel) {
|
||||
learning.holdLabel = holdLabel;
|
||||
controllerConfigForm.render();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function actionLabel(screen: ControllerScreenDefinition, actionId: string): string {
|
||||
return getControllerScreenAction(screen, actionId).label;
|
||||
}
|
||||
@@ -191,7 +230,6 @@ export function createControllerSelectModal(
|
||||
playNextSubtitle: { kind: 'none' },
|
||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
||||
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
||||
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
||||
},
|
||||
getScreenGroups: () => {
|
||||
@@ -203,6 +241,7 @@ export function createControllerSelectModal(
|
||||
}));
|
||||
},
|
||||
getScreenInputContext,
|
||||
getLearningHoldLabel: () => discreteLearning?.holdLabel ?? null,
|
||||
getScreenLearning: () =>
|
||||
screenLearning
|
||||
? {
|
||||
@@ -216,14 +255,9 @@ export function createControllerSelectModal(
|
||||
learningActionId = null;
|
||||
dpadLearningActionId = null;
|
||||
bindingCapture = null;
|
||||
const config = ctx.state.controllerConfig;
|
||||
const capture = createControllerComboCapture({
|
||||
triggerDeadzone: config?.triggerDeadzone ?? 0.5,
|
||||
stickDeadzone: config?.stickDeadzone ?? 0.2,
|
||||
});
|
||||
capture.arm({ axes: ctx.state.controllerRawAxes, buttons: ctx.state.controllerRawButtons });
|
||||
discreteLearning = null;
|
||||
const screen = getControllerScreen(screenId);
|
||||
screenLearning = { screen, actionId, capture, holdLabel: null };
|
||||
screenLearning = { ...startComboLearning(), screen, actionId };
|
||||
controllerConfigForm.render();
|
||||
setStatus(
|
||||
`Press a button for ${actionLabel(screen, actionId)}, or hold one and press another for a combo.`,
|
||||
@@ -264,6 +298,17 @@ export function createControllerSelectModal(
|
||||
if (!definition) return;
|
||||
dpadLearningActionId = null;
|
||||
cancelScreenLearning();
|
||||
learningActionId = actionId;
|
||||
if (bindingType === 'discrete') {
|
||||
bindingCapture = null;
|
||||
discreteLearning = startComboLearning();
|
||||
controllerConfigForm.render();
|
||||
setStatus(
|
||||
`Press a button for ${definition.label}, or hold one and press another for a combo.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
discreteLearning = null;
|
||||
const config = ctx.state.controllerConfig;
|
||||
bindingCapture = createControllerBindingCapture({
|
||||
triggerDeadzone: config?.triggerDeadzone ?? 0.5,
|
||||
@@ -275,22 +320,12 @@ export function createControllerSelectModal(
|
||||
? currentBinding.dpadFallback
|
||||
: 'none';
|
||||
bindingCapture.arm(
|
||||
bindingType === 'axis'
|
||||
? {
|
||||
actionId,
|
||||
bindingType: 'axis',
|
||||
dpadFallback: currentDpadFallback,
|
||||
}
|
||||
: {
|
||||
actionId,
|
||||
bindingType: 'discrete',
|
||||
},
|
||||
{ actionId, bindingType: 'axis', dpadFallback: currentDpadFallback },
|
||||
{
|
||||
axes: ctx.state.controllerRawAxes,
|
||||
buttons: ctx.state.controllerRawButtons,
|
||||
},
|
||||
);
|
||||
learningActionId = actionId;
|
||||
controllerConfigForm.render();
|
||||
setStatus(`Waiting for input for ${definition.label}.`);
|
||||
},
|
||||
@@ -307,6 +342,7 @@ export function createControllerSelectModal(
|
||||
const definition = getControllerBindingDefinition(actionId);
|
||||
if (!definition) return;
|
||||
learningActionId = null;
|
||||
discreteLearning = null;
|
||||
cancelScreenLearning();
|
||||
const config = ctx.state.controllerConfig;
|
||||
bindingCapture = createControllerBindingCapture({
|
||||
@@ -564,6 +600,7 @@ export function createControllerSelectModal(
|
||||
learningActionId = null;
|
||||
dpadLearningActionId = null;
|
||||
bindingCapture = null;
|
||||
discreteLearning = null;
|
||||
controllerConfigForm.render();
|
||||
setStatus(`${definition?.label ?? actionId} updated.`);
|
||||
} catch (error) {
|
||||
@@ -592,7 +629,7 @@ export function createControllerSelectModal(
|
||||
|
||||
async function saveDpadFallback(
|
||||
actionId: ControllerBindingKey,
|
||||
dpadFallback: import('../../types').ControllerDpadFallback,
|
||||
dpadFallback: ControllerDpadFallback,
|
||||
): Promise<void> {
|
||||
const definition = getControllerBindingDefinition(actionId);
|
||||
const currentBinding = getSelectedControllerConfig()?.bindings[actionId];
|
||||
@@ -665,25 +702,31 @@ export function createControllerSelectModal(
|
||||
}
|
||||
}
|
||||
|
||||
if (discreteLearning && learningActionId) {
|
||||
const actionId = learningActionId;
|
||||
const combo = pollComboLearning(discreteLearning, (input) =>
|
||||
formatFriendlyInputLabel(
|
||||
input,
|
||||
getSelectedController()?.mapping,
|
||||
getSelectedControllerConfig()?.faceButtonLabels,
|
||||
),
|
||||
);
|
||||
if (combo) {
|
||||
discreteLearning = null;
|
||||
void saveBinding(actionId, combo.hold ? { ...combo.press, hold: combo.hold } : combo.press);
|
||||
}
|
||||
}
|
||||
|
||||
if (screenLearning) {
|
||||
const learning = screenLearning;
|
||||
const state = learning.capture.poll({
|
||||
axes: ctx.state.controllerRawAxes,
|
||||
buttons: ctx.state.controllerRawButtons,
|
||||
});
|
||||
if (state.status === 'holding') {
|
||||
const holdLabel = formatControllerReviewInput(state.hold, getScreenInputContext(), {
|
||||
dpadPrefix: true,
|
||||
});
|
||||
if (holdLabel !== learning.holdLabel) {
|
||||
learning.holdLabel = holdLabel;
|
||||
controllerConfigForm.render();
|
||||
}
|
||||
} else if (state.status === 'done') {
|
||||
const combo = pollComboLearning(learning, (input) =>
|
||||
formatControllerReviewInput(input, getScreenInputContext(), { dpadPrefix: true }),
|
||||
);
|
||||
if (combo) {
|
||||
screenLearning = null;
|
||||
void saveScreenBindings(
|
||||
learning.screen,
|
||||
{ [learning.actionId]: state.binding },
|
||||
{ [learning.actionId]: combo },
|
||||
`${actionLabel(learning.screen, learning.actionId)} updated.`,
|
||||
);
|
||||
}
|
||||
@@ -741,6 +784,7 @@ export function createControllerSelectModal(
|
||||
learningActionId = null;
|
||||
dpadLearningActionId = null;
|
||||
bindingCapture = null;
|
||||
discreteLearning = null;
|
||||
cancelScreenLearning();
|
||||
ctx.state.controllerSelectModalOpen = false;
|
||||
ctx.state.controllerSelectGamepadId = null;
|
||||
@@ -760,6 +804,7 @@ export function createControllerSelectModal(
|
||||
learningActionId = null;
|
||||
dpadLearningActionId = null;
|
||||
bindingCapture = null;
|
||||
discreteLearning = null;
|
||||
cancelScreenLearning();
|
||||
controllerConfigForm.render();
|
||||
setStatus('Controller learn mode cancelled.');
|
||||
|
||||
@@ -29,6 +29,7 @@ import type {
|
||||
import type { OverlayHostedModal } from '../shared/ipc/contracts';
|
||||
import { createKeyboardHandlers } from './handlers/keyboard.js';
|
||||
import { createGamepadController } from './handlers/gamepad-controller.js';
|
||||
import { createControllerHintVisibility } from './controller-hint-visibility.js';
|
||||
import { createControllerPressReplay } from './handlers/controller-press-replay.js';
|
||||
import { createMouseHandlers } from './handlers/mouse.js';
|
||||
import { createControllerStatusIndicator } from './controller-status-indicator.js';
|
||||
@@ -398,6 +399,9 @@ let lastSecondarySubtitlePreview = '';
|
||||
let overlayErrorToastTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
let controllerAnimationFrameId: number | null = null;
|
||||
const controllerPressReplay = createControllerPressReplay();
|
||||
const controllerHintVisibility = createControllerHintVisibility({
|
||||
getOverlayControllerId: () => window.electronAPI.getActiveControllerId(),
|
||||
});
|
||||
|
||||
function truncateForErrorLog(text: string): string {
|
||||
const normalized = text.replace(/\s+/g, ' ').trim();
|
||||
@@ -453,10 +457,13 @@ function applyControllerSnapshot(snapshot: {
|
||||
ctx.state.controllerRawButtons = snapshot.rawButtons;
|
||||
controllerSelectModal.updateDevices();
|
||||
controllerDebugModal.updateSnapshot();
|
||||
// Shown whenever controller support is on: a fresh dialog window cannot see the pad
|
||||
// until its first press, so "connected" would hide the hints exactly when needed.
|
||||
const controllerConfig = ctx.state.controllerConfig;
|
||||
const hintsVisible = controllerConfig?.enabled === true;
|
||||
const hintsVisible = controllerHintVisibility.update({
|
||||
enabled: controllerConfig?.enabled === true,
|
||||
dialogOpen: ctx.state.mediaTimingReviewModalOpen || ctx.state.kikuModalOpen,
|
||||
activeGamepadId: snapshot.activeGamepadId,
|
||||
now: performance.now(),
|
||||
});
|
||||
mediaTimingReviewModal.setControllerHintsVisible(hintsVisible);
|
||||
kikuModal.setControllerHintsVisible(hintsVisible);
|
||||
if (
|
||||
@@ -583,7 +590,6 @@ function startControllerPolling(): void {
|
||||
playNextSubtitle: { kind: 'none' },
|
||||
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
|
||||
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
|
||||
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
|
||||
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
|
||||
},
|
||||
reviewBindings: getDefaultControllerReviewBindings(),
|
||||
|
||||
@@ -2045,7 +2045,7 @@ body:focus-visible,
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Controller hints: shown beside each control while controller support is on. */
|
||||
/* Controller hints: shown beside each control while a controller is connected. */
|
||||
.media-timing-review-modal.controller-hints-visible button[data-controller-hint]::after,
|
||||
#kikuFieldGroupingModal.controller-hints-visible [data-controller-hint]::after {
|
||||
content: attr(data-controller-hint);
|
||||
|
||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user