mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-04-11 04:19:26 -07:00
Compare commits
3 Commits
windows-qo
...
v0.12.0-be
| Author | SHA1 | Date | |
|---|---|---|---|
| f79e6bde3b | |||
| bd5275fbf8 | |||
| 3281a7b39e |
@@ -1,4 +0,0 @@
|
|||||||
type: fixed
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- Addressed the latest CodeRabbit follow-ups on the Windows overlay flow, including exact mpv target resolution, lower-overlay helper arguments, Win32 failure detection, and overlay cleanup on tracker loss.
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
type: changed
|
|
||||||
area: overlay
|
|
||||||
|
|
||||||
- Added configurable overlay shortcuts for session help, controller select, and controller debug actions.
|
|
||||||
- Added mpv/plugin and CLI routing for session help, controller utilities, and subtitle sidebar toggling through the shared session-action path.
|
|
||||||
- Improved dedicated overlay modal retry and focus handling for runtime options, Jimaku, session help, controller tools, and the playlist browser.
|
|
||||||
@@ -173,11 +173,7 @@
|
|||||||
"toggleSecondarySub": "CommandOrControl+Shift+V", // Toggle secondary sub setting.
|
"toggleSecondarySub": "CommandOrControl+Shift+V", // Toggle secondary sub setting.
|
||||||
"markAudioCard": "CommandOrControl+Shift+A", // Mark audio card setting.
|
"markAudioCard": "CommandOrControl+Shift+A", // Mark audio card setting.
|
||||||
"openRuntimeOptions": "CommandOrControl+Shift+O", // Open runtime options setting.
|
"openRuntimeOptions": "CommandOrControl+Shift+O", // Open runtime options setting.
|
||||||
"openJimaku": "Ctrl+Shift+J", // Open jimaku setting.
|
"openJimaku": "Ctrl+Shift+J" // Open jimaku setting.
|
||||||
"openSessionHelp": "CommandOrControl+Shift+H", // Open session help setting.
|
|
||||||
"openControllerSelect": "Alt+C", // Open controller select setting.
|
|
||||||
"openControllerDebug": "Alt+Shift+C", // Open controller debug setting.
|
|
||||||
"toggleSubtitleSidebar": "\\" // Toggle subtitle sidebar setting.
|
|
||||||
}, // Overlay keyboard shortcuts. Set a shortcut to null to disable.
|
}, // Overlay keyboard shortcuts. Set a shortcut to null to disable.
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|||||||
@@ -536,11 +536,7 @@ See `config.example.jsonc` for detailed configuration options.
|
|||||||
"mineSentenceMultiple": "CommandOrControl+Shift+S",
|
"mineSentenceMultiple": "CommandOrControl+Shift+S",
|
||||||
"markAudioCard": "CommandOrControl+Shift+A",
|
"markAudioCard": "CommandOrControl+Shift+A",
|
||||||
"openRuntimeOptions": "CommandOrControl+Shift+O",
|
"openRuntimeOptions": "CommandOrControl+Shift+O",
|
||||||
"openSessionHelp": "CommandOrControl+Shift+H",
|
|
||||||
"openControllerSelect": "Alt+C",
|
|
||||||
"openControllerDebug": "Alt+Shift+C",
|
|
||||||
"openJimaku": "Ctrl+Shift+J",
|
"openJimaku": "Ctrl+Shift+J",
|
||||||
"toggleSubtitleSidebar": "\\",
|
|
||||||
"multiCopyTimeoutMs": 3000
|
"multiCopyTimeoutMs": 3000
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -560,11 +556,7 @@ See `config.example.jsonc` for detailed configuration options.
|
|||||||
| `toggleSecondarySub` | string \| `null` | Accelerator for cycling secondary subtitle mode (default: `"CommandOrControl+Shift+V"`) |
|
| `toggleSecondarySub` | string \| `null` | Accelerator for cycling secondary subtitle mode (default: `"CommandOrControl+Shift+V"`) |
|
||||||
| `markAudioCard` | string \| `null` | Accelerator for marking last card as audio card (default: `"CommandOrControl+Shift+A"`) |
|
| `markAudioCard` | string \| `null` | Accelerator for marking last card as audio card (default: `"CommandOrControl+Shift+A"`) |
|
||||||
| `openRuntimeOptions` | string \| `null` | Opens runtime options palette for live session-only toggles (default: `"CommandOrControl+Shift+O"`) |
|
| `openRuntimeOptions` | string \| `null` | Opens runtime options palette for live session-only toggles (default: `"CommandOrControl+Shift+O"`) |
|
||||||
| `openSessionHelp` | string \| `null` | Opens the in-overlay session help modal (default: `"CommandOrControl+Shift+H"`) |
|
|
||||||
| `openControllerSelect` | string \| `null` | Opens the controller config/remap modal (default: `"Alt+C"`) |
|
|
||||||
| `openControllerDebug` | string \| `null` | Opens the controller debug modal (default: `"Alt+Shift+C"`) |
|
|
||||||
| `openJimaku` | string \| `null` | Opens the Jimaku search modal (default: `"Ctrl+Shift+J"`) |
|
| `openJimaku` | string \| `null` | Opens the Jimaku search modal (default: `"Ctrl+Shift+J"`) |
|
||||||
| `toggleSubtitleSidebar` | string \| `null` | Dispatches the subtitle sidebar toggle action (default: `"\\"`). `subtitleSidebar.toggleKey` remains the primary bare-key setting. |
|
|
||||||
|
|
||||||
**See `config.example.jsonc`** for the complete list of shortcut configuration options.
|
**See `config.example.jsonc`** for the complete list of shortcut configuration options.
|
||||||
|
|
||||||
@@ -581,10 +573,9 @@ Important behavior:
|
|||||||
- Controller input is only active while keyboard-only mode is enabled.
|
- Controller input is only active while keyboard-only mode is enabled.
|
||||||
- Keyboard-only mode continues to work normally without a controller.
|
- Keyboard-only mode continues to work normally without a controller.
|
||||||
- By default SubMiner uses the first connected controller.
|
- By default SubMiner uses the first connected controller.
|
||||||
- `Alt+C` opens the controller config modal by default, and you can remap that shortcut through `shortcuts.openControllerSelect`.
|
- `Alt+C` opens the controller config modal, where you can save the selected controller and remap actions inline.
|
||||||
- Click `Learn`, then press the next fresh button, trigger, or stick direction you want to bind for that overlay action.
|
- Click `Learn`, then press the next fresh button, trigger, or stick direction you want to bind for that overlay action.
|
||||||
- `Alt+Shift+C` opens the debug modal by default, and you can remap that shortcut through `shortcuts.openControllerDebug`.
|
- `Alt+Shift+C` opens a live debug modal showing raw axes/button values plus a ready-to-copy `buttonIndices` config block.
|
||||||
- The debug modal shows raw axes/button values plus a ready-to-copy `buttonIndices` config block.
|
|
||||||
- `controller.buttonIndices` is a semantic reference/legacy mapping. Changing it does not rewrite the raw numeric descriptor values already stored under `controller.bindings`.
|
- `controller.buttonIndices` is a semantic reference/legacy mapping. Changing it does not rewrite the raw numeric descriptor values already stored under `controller.bindings`.
|
||||||
- Turning keyboard-only mode off clears the keyboard-only token highlight state.
|
- Turning keyboard-only mode off clears the keyboard-only token highlight state.
|
||||||
- Closing the Yomitan popup clears the temporary native text-selection fill, but keeps controller token selection active.
|
- Closing the Yomitan popup clears the temporary native text-selection fill, but keeps controller token selection active.
|
||||||
@@ -703,7 +694,7 @@ These shortcuts are only active when the overlay window is visible and automatic
|
|||||||
|
|
||||||
### Session Help Modal
|
### Session Help Modal
|
||||||
|
|
||||||
The session help modal opens from the overlay with `Ctrl/Cmd+Shift+H` by default. The mpv plugin also exposes it through the `Y-H` chord (falling back to `Y-K` if needed). It shows the current session keybindings and color legend.
|
The session help modal is opened with `Y-H` by default (falls back to `Y-K` if needed) and shows the current session keybindings and color legend.
|
||||||
|
|
||||||
You can filter the modal quickly with `/`:
|
You can filter the modal quickly with `/`:
|
||||||
|
|
||||||
|
|||||||
@@ -173,11 +173,7 @@
|
|||||||
"toggleSecondarySub": "CommandOrControl+Shift+V", // Toggle secondary sub setting.
|
"toggleSecondarySub": "CommandOrControl+Shift+V", // Toggle secondary sub setting.
|
||||||
"markAudioCard": "CommandOrControl+Shift+A", // Mark audio card setting.
|
"markAudioCard": "CommandOrControl+Shift+A", // Mark audio card setting.
|
||||||
"openRuntimeOptions": "CommandOrControl+Shift+O", // Open runtime options setting.
|
"openRuntimeOptions": "CommandOrControl+Shift+O", // Open runtime options setting.
|
||||||
"openJimaku": "Ctrl+Shift+J", // Open jimaku setting.
|
"openJimaku": "Ctrl+Shift+J" // Open jimaku setting.
|
||||||
"openSessionHelp": "CommandOrControl+Shift+H", // Open session help setting.
|
|
||||||
"openControllerSelect": "Alt+C", // Open controller select setting.
|
|
||||||
"openControllerDebug": "Alt+Shift+C", // Open controller debug setting.
|
|
||||||
"toggleSubtitleSidebar": "\\" // Toggle subtitle sidebar setting.
|
|
||||||
}, // Overlay keyboard shortcuts. Set a shortcut to null to disable.
|
}, // Overlay keyboard shortcuts. Set a shortcut to null to disable.
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|||||||
@@ -67,7 +67,6 @@ Mouse-hover playback behavior is configured separately from shortcuts: `subtitle
|
|||||||
| ------------------ | -------------------------------------------------------- | ------------------------------ |
|
| ------------------ | -------------------------------------------------------- | ------------------------------ |
|
||||||
| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle mode (hidden → visible → hover) | `shortcuts.toggleSecondarySub` |
|
| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle mode (hidden → visible → hover) | `shortcuts.toggleSecondarySub` |
|
||||||
| `Ctrl/Cmd+Shift+O` | Open runtime options palette | `shortcuts.openRuntimeOptions` |
|
| `Ctrl/Cmd+Shift+O` | Open runtime options palette | `shortcuts.openRuntimeOptions` |
|
||||||
| `Ctrl/Cmd+Shift+H` | Open session help modal | `shortcuts.openSessionHelp` |
|
|
||||||
| `Ctrl+Shift+J` | Open Jimaku subtitle search modal | `shortcuts.openJimaku` |
|
| `Ctrl+Shift+J` | Open Jimaku subtitle search modal | `shortcuts.openJimaku` |
|
||||||
| `Ctrl+Alt+C` | Open the manual YouTube subtitle picker | `keybindings` |
|
| `Ctrl+Alt+C` | Open the manual YouTube subtitle picker | `keybindings` |
|
||||||
| `Ctrl+Alt+S` | Open subtitle sync (subsync) modal | `shortcuts.triggerSubsync` |
|
| `Ctrl+Alt+S` | Open subtitle sync (subsync) modal | `shortcuts.triggerSubsync` |
|
||||||
@@ -80,12 +79,12 @@ The subtitle sidebar toggle is overlay-local and only opens when SubMiner has a
|
|||||||
|
|
||||||
## Controller Shortcuts
|
## Controller Shortcuts
|
||||||
|
|
||||||
These overlay-local shortcuts open controller utilities for the Chrome Gamepad API integration.
|
These overlay-local shortcuts are fixed and open controller utilities for the Chrome Gamepad API integration.
|
||||||
|
|
||||||
| Shortcut | Action | Configurable |
|
| Shortcut | Action | Configurable |
|
||||||
| ------------- | ------------------------------------ | -------------------------------- |
|
| ------------- | ------------------------------ | ------------ |
|
||||||
| `Alt+C` | Open controller config + remap modal | `shortcuts.openControllerSelect` |
|
| `Alt+C` | Open controller config + remap modal | Fixed |
|
||||||
| `Alt+Shift+C` | Open controller debug modal | `shortcuts.openControllerDebug` |
|
| `Alt+Shift+C` | Open controller debug modal | Fixed |
|
||||||
|
|
||||||
Controller input only drives the overlay while keyboard-only mode is enabled. The controller mapping and tuning live under the top-level `controller` config block; keyboard-only mode still works normally without a controller.
|
Controller input only drives the overlay while keyboard-only mode is enabled. The controller mapping and tuning live under the top-level `controller` config block; keyboard-only mode still works normally without a controller.
|
||||||
|
|
||||||
@@ -102,7 +101,6 @@ When the mpv plugin is installed, all commands use a `y` chord prefix — press
|
|||||||
| `y-o` | Open Yomitan settings |
|
| `y-o` | Open Yomitan settings |
|
||||||
| `y-r` | Restart overlay |
|
| `y-r` | Restart overlay |
|
||||||
| `y-c` | Check overlay status |
|
| `y-c` | Check overlay status |
|
||||||
| `y-h` | Open session help |
|
|
||||||
|
|
||||||
When the overlay has focus, press `y` then `d` to toggle DevTools (debugging helper).
|
When the overlay has focus, press `y` then `d` to toggle DevTools (debugging helper).
|
||||||
|
|
||||||
|
|||||||
@@ -272,12 +272,12 @@ SubMiner supports gamepad/controller input for couch-friendly usage via the Chro
|
|||||||
|
|
||||||
1. Connect a controller before or after launching SubMiner.
|
1. Connect a controller before or after launching SubMiner.
|
||||||
2. Enable keyboard-only mode — press `Y` on the controller (default binding) or use the overlay keybinding.
|
2. Enable keyboard-only mode — press `Y` on the controller (default binding) or use the overlay keybinding.
|
||||||
3. Press `Alt+C` in the overlay by default to pick the controller you want to save and remap any action inline.
|
3. Press `Alt+C` in the overlay to pick the controller you want to save and remap any action inline.
|
||||||
4. Click `Learn` on the overlay action you want, then press the matching button, trigger, or stick direction on the controller.
|
4. Click `Learn` on the overlay action you want, then press the matching button, trigger, or stick direction on the controller.
|
||||||
5. Use the left stick to navigate subtitle tokens and scroll the popup; use the right stick vertically for popup page jumps.
|
5. Use the left stick to navigate subtitle tokens and scroll the popup; use the right stick vertically for popup page jumps.
|
||||||
6. Press `A` to look up the selected word, `X` to mine a card, `B` to close the popup.
|
6. Press `A` to look up the selected word, `X` to mine a card, `B` to close the popup.
|
||||||
|
|
||||||
By default SubMiner uses the first connected controller. `Alt+C` opens the controller config modal, where you can save the preferred controller and remap bindings inline, and `Alt+Shift+C` opens the live debug modal with raw axes/button values for non-standard pads. Both shortcuts can be changed through `shortcuts.openControllerSelect` and `shortcuts.openControllerDebug`.
|
By default SubMiner uses the first connected controller. `Alt+C` opens the controller config modal, where you can save the preferred controller and remap bindings inline. `Alt+Shift+C` still opens the live debug modal with raw axes/button values for non-standard pads.
|
||||||
|
|
||||||
### Default Button Mapping
|
### Default Button Mapping
|
||||||
|
|
||||||
@@ -321,8 +321,6 @@ See [Keyboard Shortcuts](/shortcuts) for the full reference, including mining sh
|
|||||||
|
|
||||||
Useful overlay-local default keybinding: `Ctrl+Alt+P` opens the playlist browser for the current video's parent directory and the live mpv queue so you can append, reorder, remove, or jump between episodes without leaving playback.
|
Useful overlay-local default keybinding: `Ctrl+Alt+P` opens the playlist browser for the current video's parent directory and the live mpv queue so you can append, reorder, remove, or jump between episodes without leaving playback.
|
||||||
|
|
||||||
`Ctrl/Cmd+Shift+H` opens the session help modal with the current overlay and mpv keybindings. If you use the mpv plugin, the same help view is also available through the `y-h` chord.
|
|
||||||
|
|
||||||
Hovering over subtitle text pauses mpv by default; leaving resumes it. Yomitan popups also pause playback by default. Set `subtitleStyle.autoPauseVideoOnHover: false` or `subtitleStyle.autoPauseVideoOnYomitanPopup: false` to disable either behavior.
|
Hovering over subtitle text pauses mpv by default; leaving resumes it. Yomitan popups also pause playback by default. Set `subtitleStyle.autoPauseVideoOnHover: false` or `subtitleStyle.autoPauseVideoOnYomitanPopup: false` to disable either behavior.
|
||||||
|
|
||||||
### Drag-and-Drop
|
### Drag-and-Drop
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"name": "subminer",
|
"name": "subminer",
|
||||||
"productName": "SubMiner",
|
"productName": "SubMiner",
|
||||||
"desktopName": "SubMiner.desktop",
|
"desktopName": "SubMiner.desktop",
|
||||||
"version": "0.12.0-beta.3",
|
"version": "0.12.0-beta.2",
|
||||||
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
|
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
|
||||||
"packageManager": "bun@1.3.5",
|
"packageManager": "bun@1.3.5",
|
||||||
"main": "dist/main-entry.js",
|
"main": "dist/main-entry.js",
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ function M.init()
|
|||||||
local utils = require("mp.utils")
|
local utils = require("mp.utils")
|
||||||
|
|
||||||
local options_helper = require("options")
|
local options_helper = require("options")
|
||||||
local environment = require("environment").create({ mp = mp, utils = utils })
|
local environment = require("environment").create({ mp = mp })
|
||||||
local opts = options_helper.load(options_lib, environment.default_socket_path())
|
local opts = options_helper.load(options_lib, environment.default_socket_path())
|
||||||
local state = require("state").new()
|
local state = require("state").new()
|
||||||
|
|
||||||
@@ -61,9 +61,6 @@ function M.init()
|
|||||||
ctx.process = make_lazy_proxy("process", function()
|
ctx.process = make_lazy_proxy("process", function()
|
||||||
return require("process").create(ctx)
|
return require("process").create(ctx)
|
||||||
end)
|
end)
|
||||||
ctx.session_bindings = make_lazy_proxy("session_bindings", function()
|
|
||||||
return require("session_bindings").create(ctx)
|
|
||||||
end)
|
|
||||||
ctx.ui = make_lazy_proxy("ui", function()
|
ctx.ui = make_lazy_proxy("ui", function()
|
||||||
return require("ui").create(ctx)
|
return require("ui").create(ctx)
|
||||||
end)
|
end)
|
||||||
@@ -75,7 +72,6 @@ function M.init()
|
|||||||
end)
|
end)
|
||||||
|
|
||||||
ctx.ui.register_keybindings()
|
ctx.ui.register_keybindings()
|
||||||
ctx.session_bindings.register_bindings()
|
|
||||||
ctx.messages.register_script_messages()
|
ctx.messages.register_script_messages()
|
||||||
ctx.lifecycle.register_lifecycle_hooks()
|
ctx.lifecycle.register_lifecycle_hooks()
|
||||||
ctx.log.subminer_log("info", "lifecycle", "SubMiner plugin loaded")
|
ctx.log.subminer_log("info", "lifecycle", "SubMiner plugin loaded")
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
local M = {}
|
local M = {}
|
||||||
local unpack_fn = table.unpack or unpack
|
|
||||||
|
|
||||||
function M.create(ctx)
|
function M.create(ctx)
|
||||||
local mp = ctx.mp
|
local mp = ctx.mp
|
||||||
local utils = ctx.utils
|
|
||||||
|
|
||||||
local detected_backend = nil
|
local detected_backend = nil
|
||||||
local app_running_cache_value = nil
|
local app_running_cache_value = nil
|
||||||
@@ -32,57 +30,6 @@ function M.create(ctx)
|
|||||||
return "/tmp/subminer-socket"
|
return "/tmp/subminer-socket"
|
||||||
end
|
end
|
||||||
|
|
||||||
local function path_separator()
|
|
||||||
return is_windows() and "\\" or "/"
|
|
||||||
end
|
|
||||||
|
|
||||||
local function join_path(...)
|
|
||||||
local parts = { ... }
|
|
||||||
if utils and type(utils.join_path) == "function" then
|
|
||||||
return utils.join_path(unpack_fn(parts))
|
|
||||||
end
|
|
||||||
return table.concat(parts, path_separator())
|
|
||||||
end
|
|
||||||
|
|
||||||
local function file_exists(path)
|
|
||||||
if not utils or type(utils.file_info) ~= "function" then
|
|
||||||
return false
|
|
||||||
end
|
|
||||||
return utils.file_info(path) ~= nil
|
|
||||||
end
|
|
||||||
|
|
||||||
local function resolve_subminer_config_dir()
|
|
||||||
local home = os.getenv("HOME") or os.getenv("USERPROFILE") or ""
|
|
||||||
local candidates = {}
|
|
||||||
if is_windows() then
|
|
||||||
local app_data = os.getenv("APPDATA") or join_path(home, "AppData", "Roaming")
|
|
||||||
candidates = {
|
|
||||||
join_path(app_data, "SubMiner"),
|
|
||||||
}
|
|
||||||
else
|
|
||||||
local xdg_config_home = os.getenv("XDG_CONFIG_HOME")
|
|
||||||
local primary_base = (type(xdg_config_home) == "string" and xdg_config_home ~= "")
|
|
||||||
and xdg_config_home
|
|
||||||
or join_path(home, ".config")
|
|
||||||
candidates = {
|
|
||||||
join_path(primary_base, "SubMiner"),
|
|
||||||
join_path(home, ".config", "SubMiner"),
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
for _, dir in ipairs(candidates) do
|
|
||||||
if file_exists(join_path(dir, "config.jsonc")) or file_exists(join_path(dir, "config.json")) or file_exists(dir) then
|
|
||||||
return dir
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
return candidates[1]
|
|
||||||
end
|
|
||||||
|
|
||||||
local function resolve_session_bindings_artifact_path()
|
|
||||||
return join_path(resolve_subminer_config_dir(), "session-bindings.json")
|
|
||||||
end
|
|
||||||
|
|
||||||
local function is_linux()
|
local function is_linux()
|
||||||
return not is_windows() and not is_macos()
|
return not is_windows() and not is_macos()
|
||||||
end
|
end
|
||||||
@@ -251,10 +198,7 @@ function M.create(ctx)
|
|||||||
is_windows = is_windows,
|
is_windows = is_windows,
|
||||||
is_macos = is_macos,
|
is_macos = is_macos,
|
||||||
is_linux = is_linux,
|
is_linux = is_linux,
|
||||||
join_path = join_path,
|
|
||||||
default_socket_path = default_socket_path,
|
default_socket_path = default_socket_path,
|
||||||
resolve_subminer_config_dir = resolve_subminer_config_dir,
|
|
||||||
resolve_session_bindings_artifact_path = resolve_session_bindings_artifact_path,
|
|
||||||
is_subminer_process_running = is_subminer_process_running,
|
is_subminer_process_running = is_subminer_process_running,
|
||||||
is_subminer_app_running = is_subminer_app_running,
|
is_subminer_app_running = is_subminer_app_running,
|
||||||
is_subminer_app_running_async = is_subminer_app_running_async,
|
is_subminer_app_running_async = is_subminer_app_running_async,
|
||||||
|
|||||||
@@ -47,9 +47,6 @@ function M.create(ctx)
|
|||||||
mp.register_script_message("subminer-stats-toggle", function()
|
mp.register_script_message("subminer-stats-toggle", function()
|
||||||
mp.osd_message("Stats: press ` (backtick) in overlay", 3)
|
mp.osd_message("Stats: press ` (backtick) in overlay", 3)
|
||||||
end)
|
end)
|
||||||
mp.register_script_message("subminer-reload-session-bindings", function()
|
|
||||||
ctx.session_bindings.reload_bindings()
|
|
||||||
end)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -229,22 +229,6 @@ function M.create(ctx)
|
|||||||
end)
|
end)
|
||||||
end
|
end
|
||||||
|
|
||||||
local function run_binary_command_async(args, callback)
|
|
||||||
subminer_log("debug", "process", "Binary command: " .. table.concat(args, " "))
|
|
||||||
mp.command_native_async({
|
|
||||||
name = "subprocess",
|
|
||||||
args = args,
|
|
||||||
playback_only = false,
|
|
||||||
capture_stdout = true,
|
|
||||||
capture_stderr = true,
|
|
||||||
}, function(success, result, error)
|
|
||||||
local ok = success and (result == nil or result.status == 0)
|
|
||||||
if callback then
|
|
||||||
callback(ok, result, error)
|
|
||||||
end
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
local function parse_start_script_message_overrides(...)
|
local function parse_start_script_message_overrides(...)
|
||||||
local overrides = {}
|
local overrides = {}
|
||||||
for i = 1, select("#", ...) do
|
for i = 1, select("#", ...) do
|
||||||
@@ -544,7 +528,6 @@ function M.create(ctx)
|
|||||||
build_command_args = build_command_args,
|
build_command_args = build_command_args,
|
||||||
has_matching_mpv_ipc_socket = has_matching_mpv_ipc_socket,
|
has_matching_mpv_ipc_socket = has_matching_mpv_ipc_socket,
|
||||||
run_control_command_async = run_control_command_async,
|
run_control_command_async = run_control_command_async,
|
||||||
run_binary_command_async = run_binary_command_async,
|
|
||||||
parse_start_script_message_overrides = parse_start_script_message_overrides,
|
parse_start_script_message_overrides = parse_start_script_message_overrides,
|
||||||
ensure_texthooker_running = ensure_texthooker_running,
|
ensure_texthooker_running = ensure_texthooker_running,
|
||||||
start_overlay = start_overlay,
|
start_overlay = start_overlay,
|
||||||
|
|||||||
@@ -1,357 +0,0 @@
|
|||||||
local M = {}
|
|
||||||
|
|
||||||
local unpack_fn = table.unpack or unpack
|
|
||||||
|
|
||||||
local KEY_NAME_MAP = {
|
|
||||||
Space = "SPACE",
|
|
||||||
Tab = "TAB",
|
|
||||||
Enter = "ENTER",
|
|
||||||
Escape = "ESC",
|
|
||||||
Backspace = "BS",
|
|
||||||
Delete = "DEL",
|
|
||||||
ArrowUp = "UP",
|
|
||||||
ArrowDown = "DOWN",
|
|
||||||
ArrowLeft = "LEFT",
|
|
||||||
ArrowRight = "RIGHT",
|
|
||||||
Slash = "/",
|
|
||||||
Backslash = "\\",
|
|
||||||
Minus = "-",
|
|
||||||
Equal = "=",
|
|
||||||
Comma = ",",
|
|
||||||
Period = ".",
|
|
||||||
Quote = "'",
|
|
||||||
Semicolon = ";",
|
|
||||||
BracketLeft = "[",
|
|
||||||
BracketRight = "]",
|
|
||||||
Backquote = "`",
|
|
||||||
}
|
|
||||||
|
|
||||||
local MODIFIER_MAP = {
|
|
||||||
ctrl = "Ctrl",
|
|
||||||
alt = "Alt",
|
|
||||||
shift = "Shift",
|
|
||||||
meta = "Meta",
|
|
||||||
}
|
|
||||||
|
|
||||||
function M.create(ctx)
|
|
||||||
local mp = ctx.mp
|
|
||||||
local utils = ctx.utils
|
|
||||||
local state = ctx.state
|
|
||||||
local process = ctx.process
|
|
||||||
local environment = ctx.environment
|
|
||||||
local subminer_log = ctx.log.subminer_log
|
|
||||||
local show_osd = ctx.log.show_osd
|
|
||||||
|
|
||||||
local function read_file(path)
|
|
||||||
local handle = io.open(path, "r")
|
|
||||||
if not handle then
|
|
||||||
return nil
|
|
||||||
end
|
|
||||||
local content = handle:read("*a")
|
|
||||||
handle:close()
|
|
||||||
return content
|
|
||||||
end
|
|
||||||
|
|
||||||
local function remove_binding_names(names)
|
|
||||||
for _, name in ipairs(names) do
|
|
||||||
mp.remove_key_binding(name)
|
|
||||||
end
|
|
||||||
for index = #names, 1, -1 do
|
|
||||||
names[index] = nil
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
local function key_code_to_mpv_name(code)
|
|
||||||
if KEY_NAME_MAP[code] then
|
|
||||||
return KEY_NAME_MAP[code]
|
|
||||||
end
|
|
||||||
|
|
||||||
local letter = code:match("^Key([A-Z])$")
|
|
||||||
if letter then
|
|
||||||
return string.lower(letter)
|
|
||||||
end
|
|
||||||
|
|
||||||
local digit = code:match("^Digit([0-9])$")
|
|
||||||
if digit then
|
|
||||||
return digit
|
|
||||||
end
|
|
||||||
|
|
||||||
local function_key = code:match("^(F%d+)$")
|
|
||||||
if function_key then
|
|
||||||
return function_key
|
|
||||||
end
|
|
||||||
|
|
||||||
return nil
|
|
||||||
end
|
|
||||||
|
|
||||||
local function key_spec_to_mpv_binding(key)
|
|
||||||
if type(key) ~= "table" then
|
|
||||||
return nil
|
|
||||||
end
|
|
||||||
|
|
||||||
if type(key.code) ~= "string" then
|
|
||||||
return nil
|
|
||||||
end
|
|
||||||
if type(key.modifiers) ~= "table" then
|
|
||||||
return nil
|
|
||||||
end
|
|
||||||
|
|
||||||
local key_name = key_code_to_mpv_name(key.code)
|
|
||||||
if not key_name then
|
|
||||||
return nil
|
|
||||||
end
|
|
||||||
|
|
||||||
local parts = {}
|
|
||||||
for _, modifier in ipairs(key.modifiers) do
|
|
||||||
local mapped = MODIFIER_MAP[modifier]
|
|
||||||
if mapped then
|
|
||||||
parts[#parts + 1] = mapped
|
|
||||||
end
|
|
||||||
end
|
|
||||||
parts[#parts + 1] = key_name
|
|
||||||
return table.concat(parts, "+")
|
|
||||||
end
|
|
||||||
|
|
||||||
local function build_cli_args(action_id, payload)
|
|
||||||
if action_id == "toggleVisibleOverlay" then
|
|
||||||
return { "--toggle-visible-overlay" }
|
|
||||||
elseif action_id == "toggleStatsOverlay" then
|
|
||||||
return { "--toggle-stats-overlay" }
|
|
||||||
elseif action_id == "copySubtitle" then
|
|
||||||
return { "--copy-subtitle" }
|
|
||||||
elseif action_id == "copySubtitleMultiple" then
|
|
||||||
return { "--copy-subtitle-count", tostring(payload and payload.count or 1) }
|
|
||||||
elseif action_id == "updateLastCardFromClipboard" then
|
|
||||||
return { "--update-last-card-from-clipboard" }
|
|
||||||
elseif action_id == "triggerFieldGrouping" then
|
|
||||||
return { "--trigger-field-grouping" }
|
|
||||||
elseif action_id == "triggerSubsync" then
|
|
||||||
return { "--trigger-subsync" }
|
|
||||||
elseif action_id == "mineSentence" then
|
|
||||||
return { "--mine-sentence" }
|
|
||||||
elseif action_id == "mineSentenceMultiple" then
|
|
||||||
return { "--mine-sentence-count", tostring(payload and payload.count or 1) }
|
|
||||||
elseif action_id == "toggleSecondarySub" then
|
|
||||||
return { "--toggle-secondary-sub" }
|
|
||||||
elseif action_id == "toggleSubtitleSidebar" then
|
|
||||||
return { "--toggle-subtitle-sidebar" }
|
|
||||||
elseif action_id == "markAudioCard" then
|
|
||||||
return { "--mark-audio-card" }
|
|
||||||
elseif action_id == "openRuntimeOptions" then
|
|
||||||
return { "--open-runtime-options" }
|
|
||||||
elseif action_id == "openJimaku" then
|
|
||||||
return { "--open-jimaku" }
|
|
||||||
elseif action_id == "openYoutubePicker" then
|
|
||||||
return { "--open-youtube-picker" }
|
|
||||||
elseif action_id == "openSessionHelp" then
|
|
||||||
return { "--open-session-help" }
|
|
||||||
elseif action_id == "openControllerSelect" then
|
|
||||||
return { "--open-controller-select" }
|
|
||||||
elseif action_id == "openControllerDebug" then
|
|
||||||
return { "--open-controller-debug" }
|
|
||||||
elseif action_id == "openPlaylistBrowser" then
|
|
||||||
return { "--open-playlist-browser" }
|
|
||||||
elseif action_id == "replayCurrentSubtitle" then
|
|
||||||
return { "--replay-current-subtitle" }
|
|
||||||
elseif action_id == "playNextSubtitle" then
|
|
||||||
return { "--play-next-subtitle" }
|
|
||||||
elseif action_id == "shiftSubDelayPrevLine" then
|
|
||||||
return { "--shift-sub-delay-prev-line" }
|
|
||||||
elseif action_id == "shiftSubDelayNextLine" then
|
|
||||||
return { "--shift-sub-delay-next-line" }
|
|
||||||
elseif action_id == "cycleRuntimeOption" then
|
|
||||||
local runtime_option_id = payload and payload.runtimeOptionId or nil
|
|
||||||
if type(runtime_option_id) ~= "string" or runtime_option_id == "" then
|
|
||||||
return nil
|
|
||||||
end
|
|
||||||
local direction = payload and payload.direction == -1 and "prev" or "next"
|
|
||||||
return { "--cycle-runtime-option", runtime_option_id .. ":" .. direction }
|
|
||||||
end
|
|
||||||
|
|
||||||
return nil
|
|
||||||
end
|
|
||||||
|
|
||||||
local function invoke_cli_action(action_id, payload)
|
|
||||||
if not process.check_binary_available() then
|
|
||||||
show_osd("Error: binary not found")
|
|
||||||
return
|
|
||||||
end
|
|
||||||
|
|
||||||
local cli_args = build_cli_args(action_id, payload)
|
|
||||||
if not cli_args then
|
|
||||||
subminer_log("warn", "session-bindings", "No CLI mapping for action: " .. tostring(action_id))
|
|
||||||
return
|
|
||||||
end
|
|
||||||
|
|
||||||
local args = { state.binary_path }
|
|
||||||
for _, arg in ipairs(cli_args) do
|
|
||||||
args[#args + 1] = arg
|
|
||||||
end
|
|
||||||
local runner = process.run_binary_command_async
|
|
||||||
if type(runner) ~= "function" then
|
|
||||||
runner = function(binary_args, callback)
|
|
||||||
mp.command_native_async({
|
|
||||||
name = "subprocess",
|
|
||||||
args = binary_args,
|
|
||||||
playback_only = false,
|
|
||||||
capture_stdout = true,
|
|
||||||
capture_stderr = true,
|
|
||||||
}, function(success, result, error)
|
|
||||||
local ok = success and (result == nil or result.status == 0)
|
|
||||||
if callback then
|
|
||||||
callback(ok, result, error)
|
|
||||||
end
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
runner(args, function(ok, result, error)
|
|
||||||
if ok then
|
|
||||||
return
|
|
||||||
end
|
|
||||||
local reason = error or (result and result.stderr) or "unknown error"
|
|
||||||
subminer_log("warn", "session-bindings", "Session action failed: " .. tostring(reason))
|
|
||||||
show_osd("Session action failed")
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
local function clear_numeric_selection(show_cancelled)
|
|
||||||
if state.session_numeric_selection and state.session_numeric_selection.timeout then
|
|
||||||
state.session_numeric_selection.timeout:kill()
|
|
||||||
end
|
|
||||||
state.session_numeric_selection = nil
|
|
||||||
remove_binding_names(state.session_numeric_binding_names)
|
|
||||||
if show_cancelled then
|
|
||||||
show_osd("Cancelled")
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
local function start_numeric_selection(action_id, timeout_ms)
|
|
||||||
clear_numeric_selection(false)
|
|
||||||
for digit = 1, 9 do
|
|
||||||
local digit_string = tostring(digit)
|
|
||||||
local name = "subminer-session-digit-" .. digit_string
|
|
||||||
state.session_numeric_binding_names[#state.session_numeric_binding_names + 1] = name
|
|
||||||
mp.add_forced_key_binding(digit_string, name, function()
|
|
||||||
clear_numeric_selection(false)
|
|
||||||
invoke_cli_action(action_id, { count = digit })
|
|
||||||
end)
|
|
||||||
end
|
|
||||||
|
|
||||||
state.session_numeric_binding_names[#state.session_numeric_binding_names + 1] =
|
|
||||||
"subminer-session-digit-cancel"
|
|
||||||
mp.add_forced_key_binding("ESC", "subminer-session-digit-cancel", function()
|
|
||||||
clear_numeric_selection(true)
|
|
||||||
end)
|
|
||||||
|
|
||||||
state.session_numeric_selection = {
|
|
||||||
action_id = action_id,
|
|
||||||
timeout = mp.add_timeout((timeout_ms or 3000) / 1000, function()
|
|
||||||
clear_numeric_selection(false)
|
|
||||||
show_osd(action_id == "copySubtitleMultiple" and "Copy timeout" or "Mine timeout")
|
|
||||||
end),
|
|
||||||
}
|
|
||||||
|
|
||||||
show_osd(
|
|
||||||
action_id == "copySubtitleMultiple"
|
|
||||||
and "Copy how many lines? Press 1-9 (Esc to cancel)"
|
|
||||||
or "Mine how many lines? Press 1-9 (Esc to cancel)"
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
local function execute_mpv_command(command)
|
|
||||||
if type(command) ~= "table" or command[1] == nil then
|
|
||||||
return
|
|
||||||
end
|
|
||||||
mp.commandv(unpack_fn(command))
|
|
||||||
end
|
|
||||||
|
|
||||||
local function handle_binding(binding, numeric_selection_timeout_ms)
|
|
||||||
if binding.actionType == "mpv-command" then
|
|
||||||
execute_mpv_command(binding.command)
|
|
||||||
return
|
|
||||||
end
|
|
||||||
|
|
||||||
if binding.actionId == "copySubtitleMultiple" or binding.actionId == "mineSentenceMultiple" then
|
|
||||||
start_numeric_selection(binding.actionId, numeric_selection_timeout_ms)
|
|
||||||
return
|
|
||||||
end
|
|
||||||
|
|
||||||
invoke_cli_action(binding.actionId, binding.payload)
|
|
||||||
end
|
|
||||||
|
|
||||||
local function load_artifact()
|
|
||||||
local artifact_path = environment.resolve_session_bindings_artifact_path()
|
|
||||||
local raw = read_file(artifact_path)
|
|
||||||
if not raw or raw == "" then
|
|
||||||
return nil, "Missing session binding artifact: " .. tostring(artifact_path)
|
|
||||||
end
|
|
||||||
|
|
||||||
local parsed, parse_error = utils.parse_json(raw)
|
|
||||||
if not parsed then
|
|
||||||
return nil, "Failed to parse session binding artifact: " .. tostring(parse_error)
|
|
||||||
end
|
|
||||||
if type(parsed) ~= "table" or type(parsed.bindings) ~= "table" then
|
|
||||||
return nil, "Invalid session binding artifact"
|
|
||||||
end
|
|
||||||
|
|
||||||
return parsed, nil
|
|
||||||
end
|
|
||||||
|
|
||||||
local function clear_bindings()
|
|
||||||
clear_numeric_selection(false)
|
|
||||||
remove_binding_names(state.session_binding_names)
|
|
||||||
end
|
|
||||||
|
|
||||||
local function register_bindings()
|
|
||||||
local artifact, load_error = load_artifact()
|
|
||||||
if not artifact then
|
|
||||||
subminer_log("warn", "session-bindings", load_error)
|
|
||||||
return false
|
|
||||||
end
|
|
||||||
|
|
||||||
clear_numeric_selection(false)
|
|
||||||
|
|
||||||
local previous_binding_names = state.session_binding_names
|
|
||||||
local next_binding_names = {}
|
|
||||||
|
|
||||||
local timeout_ms = tonumber(artifact.numericSelectionTimeoutMs) or 3000
|
|
||||||
for index, binding in ipairs(artifact.bindings) do
|
|
||||||
local key_name = key_spec_to_mpv_binding(binding.key)
|
|
||||||
if key_name then
|
|
||||||
local name = "subminer-session-binding-" .. tostring(index)
|
|
||||||
next_binding_names[#next_binding_names + 1] = name
|
|
||||||
mp.add_forced_key_binding(key_name, name, function()
|
|
||||||
handle_binding(binding, timeout_ms)
|
|
||||||
end)
|
|
||||||
else
|
|
||||||
subminer_log(
|
|
||||||
"warn",
|
|
||||||
"session-bindings",
|
|
||||||
"Skipped unsupported key code from artifact: " .. tostring(binding.key and binding.key.code or "unknown")
|
|
||||||
)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
remove_binding_names(previous_binding_names)
|
|
||||||
state.session_binding_names = next_binding_names
|
|
||||||
|
|
||||||
subminer_log(
|
|
||||||
"info",
|
|
||||||
"session-bindings",
|
|
||||||
"Registered " .. tostring(#next_binding_names) .. " shared session bindings"
|
|
||||||
)
|
|
||||||
return true
|
|
||||||
end
|
|
||||||
|
|
||||||
local function reload_bindings()
|
|
||||||
return register_bindings()
|
|
||||||
end
|
|
||||||
|
|
||||||
return {
|
|
||||||
register_bindings = register_bindings,
|
|
||||||
reload_bindings = reload_bindings,
|
|
||||||
clear_bindings = clear_bindings,
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
return M
|
|
||||||
@@ -33,9 +33,6 @@ function M.new()
|
|||||||
auto_play_ready_timeout = nil,
|
auto_play_ready_timeout = nil,
|
||||||
auto_play_ready_osd_timer = nil,
|
auto_play_ready_osd_timer = nil,
|
||||||
suppress_ready_overlay_restore = false,
|
suppress_ready_overlay_restore = false,
|
||||||
session_binding_names = {},
|
|
||||||
session_numeric_binding_names = {},
|
|
||||||
session_numeric_selection = nil,
|
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -90,12 +90,6 @@ function M.create(ctx)
|
|||||||
mp.add_key_binding("y-c", "subminer-status", function()
|
mp.add_key_binding("y-c", "subminer-status", function()
|
||||||
process.check_status()
|
process.check_status()
|
||||||
end)
|
end)
|
||||||
mp.add_key_binding("y-h", "subminer-session-help", function()
|
|
||||||
if not ensure_binary_for_menu() then
|
|
||||||
return
|
|
||||||
end
|
|
||||||
process.run_control_command_async("open-session-help")
|
|
||||||
end)
|
|
||||||
if type(opts.aniskip_button_key) == "string" and opts.aniskip_button_key ~= "" then
|
if type(opts.aniskip_button_key) == "string" and opts.aniskip_button_key ~= "" then
|
||||||
mp.add_key_binding(opts.aniskip_button_key, "subminer-skip-intro", function()
|
mp.add_key_binding(opts.aniskip_button_key, "subminer-skip-intro", function()
|
||||||
aniskip.skip_intro_now()
|
aniskip.skip_intro_now()
|
||||||
|
|||||||
349
scripts/get-mpv-window-windows.ps1
Normal file
349
scripts/get-mpv-window-windows.ps1
Normal file
@@ -0,0 +1,349 @@
|
|||||||
|
param(
|
||||||
|
[ValidateSet('geometry', 'foreground-process', 'bind-overlay', 'lower-overlay', 'set-owner', 'clear-owner')]
|
||||||
|
[string]$Mode = 'geometry',
|
||||||
|
[string]$SocketPath,
|
||||||
|
[string]$OverlayWindowHandle
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
try {
|
||||||
|
Add-Type -TypeDefinition @"
|
||||||
|
using System;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
public static class SubMinerWindowsHelper {
|
||||||
|
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
public struct RECT {
|
||||||
|
public int Left;
|
||||||
|
public int Top;
|
||||||
|
public int Right;
|
||||||
|
public int Bottom;
|
||||||
|
}
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
public static extern bool IsWindowVisible(IntPtr hWnd);
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
public static extern bool IsIconic(IntPtr hWnd);
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
public static extern IntPtr GetForegroundWindow();
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
public static extern bool SetWindowPos(
|
||||||
|
IntPtr hWnd,
|
||||||
|
IntPtr hWndInsertAfter,
|
||||||
|
int X,
|
||||||
|
int Y,
|
||||||
|
int cx,
|
||||||
|
int cy,
|
||||||
|
uint uFlags
|
||||||
|
);
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
public static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
|
||||||
|
|
||||||
|
[DllImport("dwmapi.dll")]
|
||||||
|
public static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out RECT pvAttribute, int cbAttribute);
|
||||||
|
}
|
||||||
|
"@
|
||||||
|
|
||||||
|
$DWMWA_EXTENDED_FRAME_BOUNDS = 9
|
||||||
|
$SWP_NOSIZE = 0x0001
|
||||||
|
$SWP_NOMOVE = 0x0002
|
||||||
|
$SWP_NOACTIVATE = 0x0010
|
||||||
|
$SWP_NOOWNERZORDER = 0x0200
|
||||||
|
$SWP_FLAGS = $SWP_NOSIZE -bor $SWP_NOMOVE -bor $SWP_NOACTIVATE -bor $SWP_NOOWNERZORDER
|
||||||
|
$GWL_EXSTYLE = -20
|
||||||
|
$WS_EX_TOPMOST = 0x00000008
|
||||||
|
$GWLP_HWNDPARENT = -8
|
||||||
|
$HWND_TOP = [IntPtr]::Zero
|
||||||
|
$HWND_BOTTOM = [IntPtr]::One
|
||||||
|
$HWND_TOPMOST = [IntPtr](-1)
|
||||||
|
$HWND_NOTOPMOST = [IntPtr](-2)
|
||||||
|
|
||||||
|
if ($Mode -eq 'foreground-process') {
|
||||||
|
$foregroundWindow = [SubMinerWindowsHelper]::GetForegroundWindow()
|
||||||
|
if ($foregroundWindow -eq [IntPtr]::Zero) {
|
||||||
|
Write-Output 'not-found'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
[uint32]$foregroundProcessId = 0
|
||||||
|
[void][SubMinerWindowsHelper]::GetWindowThreadProcessId($foregroundWindow, [ref]$foregroundProcessId)
|
||||||
|
if ($foregroundProcessId -eq 0) {
|
||||||
|
Write-Output 'not-found'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$foregroundProcess = Get-Process -Id $foregroundProcessId -ErrorAction Stop
|
||||||
|
} catch {
|
||||||
|
Write-Output 'not-found'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Output "process=$($foregroundProcess.ProcessName)"
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($Mode -eq 'clear-owner') {
|
||||||
|
if ([string]::IsNullOrWhiteSpace($OverlayWindowHandle)) {
|
||||||
|
[Console]::Error.WriteLine('overlay-window-handle-required')
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
[IntPtr]$overlayWindow = [IntPtr]([int64]$OverlayWindowHandle)
|
||||||
|
[void][SubMinerWindowsHelper]::SetWindowLongPtr($overlayWindow, $GWLP_HWNDPARENT, [IntPtr]::Zero)
|
||||||
|
Write-Output 'ok'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-WindowBounds {
|
||||||
|
param([IntPtr]$hWnd)
|
||||||
|
|
||||||
|
$rect = New-Object SubMinerWindowsHelper+RECT
|
||||||
|
$size = [System.Runtime.InteropServices.Marshal]::SizeOf($rect)
|
||||||
|
$dwmResult = [SubMinerWindowsHelper]::DwmGetWindowAttribute(
|
||||||
|
$hWnd,
|
||||||
|
$DWMWA_EXTENDED_FRAME_BOUNDS,
|
||||||
|
[ref]$rect,
|
||||||
|
$size
|
||||||
|
)
|
||||||
|
|
||||||
|
if ($dwmResult -ne 0) {
|
||||||
|
if (-not [SubMinerWindowsHelper]::GetWindowRect($hWnd, [ref]$rect)) {
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$width = $rect.Right - $rect.Left
|
||||||
|
$height = $rect.Bottom - $rect.Top
|
||||||
|
if ($width -le 0 -or $height -le 0) {
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
|
||||||
|
return [PSCustomObject]@{
|
||||||
|
X = $rect.Left
|
||||||
|
Y = $rect.Top
|
||||||
|
Width = $width
|
||||||
|
Height = $height
|
||||||
|
Area = $width * $height
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$commandLineByPid = @{}
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($SocketPath)) {
|
||||||
|
foreach ($process in Get-CimInstance Win32_Process) {
|
||||||
|
$commandLineByPid[[uint32]$process.ProcessId] = $process.CommandLine
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$mpvMatches = New-Object System.Collections.Generic.List[object]
|
||||||
|
$targetWindowState = 'not-found'
|
||||||
|
$foregroundWindow = [SubMinerWindowsHelper]::GetForegroundWindow()
|
||||||
|
$callback = [SubMinerWindowsHelper+EnumWindowsProc]{
|
||||||
|
param([IntPtr]$hWnd, [IntPtr]$lParam)
|
||||||
|
|
||||||
|
if (-not [SubMinerWindowsHelper]::IsWindowVisible($hWnd)) {
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
|
||||||
|
[uint32]$windowProcessId = 0
|
||||||
|
[void][SubMinerWindowsHelper]::GetWindowThreadProcessId($hWnd, [ref]$windowProcessId)
|
||||||
|
if ($windowProcessId -eq 0) {
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$process = Get-Process -Id $windowProcessId -ErrorAction Stop
|
||||||
|
} catch {
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($process.ProcessName -ine 'mpv') {
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($SocketPath)) {
|
||||||
|
$commandLine = $commandLineByPid[[uint32]$windowProcessId]
|
||||||
|
if ([string]::IsNullOrWhiteSpace($commandLine)) {
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
($commandLine -notlike "*--input-ipc-server=$SocketPath*") -and
|
||||||
|
($commandLine -notlike "*--input-ipc-server $SocketPath*")
|
||||||
|
) {
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ([SubMinerWindowsHelper]::IsIconic($hWnd)) {
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($SocketPath) -and $targetWindowState -ne 'visible') {
|
||||||
|
$targetWindowState = 'minimized'
|
||||||
|
}
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
|
||||||
|
$bounds = Get-WindowBounds -hWnd $hWnd
|
||||||
|
if ($null -eq $bounds) {
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($SocketPath)) {
|
||||||
|
$targetWindowState = 'visible'
|
||||||
|
}
|
||||||
|
|
||||||
|
$mpvMatches.Add([PSCustomObject]@{
|
||||||
|
HWnd = $hWnd
|
||||||
|
X = $bounds.X
|
||||||
|
Y = $bounds.Y
|
||||||
|
Width = $bounds.Width
|
||||||
|
Height = $bounds.Height
|
||||||
|
Area = $bounds.Area
|
||||||
|
IsForeground = ($foregroundWindow -ne [IntPtr]::Zero -and $hWnd -eq $foregroundWindow)
|
||||||
|
})
|
||||||
|
|
||||||
|
return $true
|
||||||
|
}
|
||||||
|
|
||||||
|
[void][SubMinerWindowsHelper]::EnumWindows($callback, [IntPtr]::Zero)
|
||||||
|
|
||||||
|
if ($Mode -eq 'lower-overlay') {
|
||||||
|
if ([string]::IsNullOrWhiteSpace($OverlayWindowHandle)) {
|
||||||
|
[Console]::Error.WriteLine('overlay-window-handle-required')
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
[IntPtr]$overlayWindow = [IntPtr]([int64]$OverlayWindowHandle)
|
||||||
|
|
||||||
|
[void][SubMinerWindowsHelper]::SetWindowPos(
|
||||||
|
$overlayWindow,
|
||||||
|
$HWND_NOTOPMOST,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
$SWP_FLAGS
|
||||||
|
)
|
||||||
|
[void][SubMinerWindowsHelper]::SetWindowPos(
|
||||||
|
$overlayWindow,
|
||||||
|
$HWND_BOTTOM,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
$SWP_FLAGS
|
||||||
|
)
|
||||||
|
Write-Output 'ok'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
$focusedMatch = $mpvMatches | Where-Object { $_.IsForeground } | Select-Object -First 1
|
||||||
|
if ($null -ne $focusedMatch) {
|
||||||
|
[Console]::Error.WriteLine('focus=focused')
|
||||||
|
} else {
|
||||||
|
[Console]::Error.WriteLine('focus=not-focused')
|
||||||
|
}
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($SocketPath)) {
|
||||||
|
[Console]::Error.WriteLine("state=$targetWindowState")
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($mpvMatches.Count -eq 0) {
|
||||||
|
Write-Output 'not-found'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
$bestMatch = if ($null -ne $focusedMatch) {
|
||||||
|
$focusedMatch
|
||||||
|
} else {
|
||||||
|
$mpvMatches | Sort-Object -Property Area, Width, Height -Descending | Select-Object -First 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($Mode -eq 'set-owner') {
|
||||||
|
if ([string]::IsNullOrWhiteSpace($OverlayWindowHandle)) {
|
||||||
|
[Console]::Error.WriteLine('overlay-window-handle-required')
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
[IntPtr]$overlayWindow = [IntPtr]([int64]$OverlayWindowHandle)
|
||||||
|
$targetWindow = [IntPtr]$bestMatch.HWnd
|
||||||
|
[void][SubMinerWindowsHelper]::SetWindowLongPtr($overlayWindow, $GWLP_HWNDPARENT, $targetWindow)
|
||||||
|
Write-Output 'ok'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($Mode -eq 'bind-overlay') {
|
||||||
|
if ([string]::IsNullOrWhiteSpace($OverlayWindowHandle)) {
|
||||||
|
[Console]::Error.WriteLine('overlay-window-handle-required')
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
[IntPtr]$overlayWindow = [IntPtr]([int64]$OverlayWindowHandle)
|
||||||
|
$targetWindow = [IntPtr]$bestMatch.HWnd
|
||||||
|
[void][SubMinerWindowsHelper]::SetWindowLongPtr($overlayWindow, $GWLP_HWNDPARENT, $targetWindow)
|
||||||
|
$targetWindowExStyle = [SubMinerWindowsHelper]::GetWindowLong($targetWindow, $GWL_EXSTYLE)
|
||||||
|
$targetWindowIsTopmost = ($targetWindowExStyle -band $WS_EX_TOPMOST) -ne 0
|
||||||
|
|
||||||
|
$overlayExStyle = [SubMinerWindowsHelper]::GetWindowLong($overlayWindow, $GWL_EXSTYLE)
|
||||||
|
$overlayIsTopmost = ($overlayExStyle -band $WS_EX_TOPMOST) -ne 0
|
||||||
|
if ($targetWindowIsTopmost -and -not $overlayIsTopmost) {
|
||||||
|
[void][SubMinerWindowsHelper]::SetWindowPos(
|
||||||
|
$overlayWindow, $HWND_TOPMOST, 0, 0, 0, 0, $SWP_FLAGS
|
||||||
|
)
|
||||||
|
} elseif (-not $targetWindowIsTopmost -and $overlayIsTopmost) {
|
||||||
|
[void][SubMinerWindowsHelper]::SetWindowPos(
|
||||||
|
$overlayWindow, $HWND_NOTOPMOST, 0, 0, 0, 0, $SWP_FLAGS
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
$GW_HWNDPREV = 3
|
||||||
|
$windowAboveMpv = [SubMinerWindowsHelper]::GetWindow($targetWindow, $GW_HWNDPREV)
|
||||||
|
|
||||||
|
if ($windowAboveMpv -ne [IntPtr]::Zero -and $windowAboveMpv -eq $overlayWindow) {
|
||||||
|
Write-Output 'ok'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
$insertAfter = $HWND_TOP
|
||||||
|
if ($windowAboveMpv -ne [IntPtr]::Zero) {
|
||||||
|
$aboveExStyle = [SubMinerWindowsHelper]::GetWindowLong($windowAboveMpv, $GWL_EXSTYLE)
|
||||||
|
$aboveIsTopmost = ($aboveExStyle -band $WS_EX_TOPMOST) -ne 0
|
||||||
|
if ($aboveIsTopmost -eq $targetWindowIsTopmost) {
|
||||||
|
$insertAfter = $windowAboveMpv
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[void][SubMinerWindowsHelper]::SetWindowPos(
|
||||||
|
$overlayWindow, $insertAfter, 0, 0, 0, 0, $SWP_FLAGS
|
||||||
|
)
|
||||||
|
Write-Output 'ok'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Output "$($bestMatch.X),$($bestMatch.Y),$($bestMatch.Width),$($bestMatch.Height)"
|
||||||
|
} catch {
|
||||||
|
[Console]::Error.WriteLine($_.Exception.Message)
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
@@ -28,27 +28,6 @@ USAGE
|
|||||||
force=0
|
force=0
|
||||||
generate_webp=0
|
generate_webp=0
|
||||||
input=""
|
input=""
|
||||||
ffmpeg_bin="${FFMPEG_BIN:-ffmpeg}"
|
|
||||||
|
|
||||||
normalize_path() {
|
|
||||||
local value="$1"
|
|
||||||
if command -v cygpath > /dev/null 2>&1; then
|
|
||||||
case "$value" in
|
|
||||||
[A-Za-z]:\\* | [A-Za-z]:/*)
|
|
||||||
cygpath -u "$value"
|
|
||||||
return 0
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
fi
|
|
||||||
if [[ "$value" =~ ^([A-Za-z]):[\\/](.*)$ ]]; then
|
|
||||||
local drive="${BASH_REMATCH[1],,}"
|
|
||||||
local rest="${BASH_REMATCH[2]}"
|
|
||||||
rest="${rest//\\//}"
|
|
||||||
printf '/mnt/%s/%s\n' "$drive" "$rest"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
printf '%s\n' "$value"
|
|
||||||
}
|
|
||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
while [[ $# -gt 0 ]]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
@@ -84,20 +63,10 @@ if [[ -z "$input" ]]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
input="$(normalize_path "$input")"
|
if ! command -v ffmpeg > /dev/null 2>&1; then
|
||||||
ffmpeg_bin="$(normalize_path "$ffmpeg_bin")"
|
|
||||||
|
|
||||||
if [[ "$ffmpeg_bin" == */* ]]; then
|
|
||||||
if [[ ! -x "$ffmpeg_bin" ]]; then
|
|
||||||
echo "Error: ffmpeg binary is not executable: $ffmpeg_bin" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
if ! command -v "$ffmpeg_bin" > /dev/null 2>&1; then
|
|
||||||
echo "Error: ffmpeg is not installed or not in PATH." >&2
|
echo "Error: ffmpeg is not installed or not in PATH." >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! -f "$input" ]]; then
|
if [[ ! -f "$input" ]]; then
|
||||||
echo "Error: input file not found: $input" >&2
|
echo "Error: input file not found: $input" >&2
|
||||||
@@ -133,7 +102,7 @@ fi
|
|||||||
|
|
||||||
has_encoder() {
|
has_encoder() {
|
||||||
local encoder="$1"
|
local encoder="$1"
|
||||||
"$ffmpeg_bin" -hide_banner -encoders 2> /dev/null | awk -v encoder="$encoder" '$2 == encoder { found = 1 } END { exit(found ? 0 : 1) }'
|
ffmpeg -hide_banner -encoders 2> /dev/null | awk -v encoder="$encoder" '$2 == encoder { found = 1 } END { exit(found ? 0 : 1) }'
|
||||||
}
|
}
|
||||||
|
|
||||||
pick_webp_encoder() {
|
pick_webp_encoder() {
|
||||||
@@ -154,7 +123,7 @@ webm_vf="${crop_vf},fps=30"
|
|||||||
echo "Generating MP4: $mp4_out"
|
echo "Generating MP4: $mp4_out"
|
||||||
if has_encoder "h264_nvenc"; then
|
if has_encoder "h264_nvenc"; then
|
||||||
echo "Trying GPU encoder for MP4: h264_nvenc"
|
echo "Trying GPU encoder for MP4: h264_nvenc"
|
||||||
if "$ffmpeg_bin" "$overwrite_flag" -i "$input" \
|
if ffmpeg "$overwrite_flag" -i "$input" \
|
||||||
-vf "$crop_vf" \
|
-vf "$crop_vf" \
|
||||||
-c:v h264_nvenc -preset p6 -rc:v vbr -cq:v 20 -b:v 0 \
|
-c:v h264_nvenc -preset p6 -rc:v vbr -cq:v 20 -b:v 0 \
|
||||||
-pix_fmt yuv420p -movflags +faststart \
|
-pix_fmt yuv420p -movflags +faststart \
|
||||||
@@ -163,7 +132,7 @@ if has_encoder "h264_nvenc"; then
|
|||||||
:
|
:
|
||||||
else
|
else
|
||||||
echo "GPU MP4 encode failed; retrying with CPU encoder: libx264"
|
echo "GPU MP4 encode failed; retrying with CPU encoder: libx264"
|
||||||
"$ffmpeg_bin" "$overwrite_flag" -i "$input" \
|
ffmpeg "$overwrite_flag" -i "$input" \
|
||||||
-vf "$crop_vf" \
|
-vf "$crop_vf" \
|
||||||
-c:v libx264 -preset slow -crf 20 \
|
-c:v libx264 -preset slow -crf 20 \
|
||||||
-profile:v high -level 4.1 -pix_fmt yuv420p \
|
-profile:v high -level 4.1 -pix_fmt yuv420p \
|
||||||
@@ -173,7 +142,7 @@ if has_encoder "h264_nvenc"; then
|
|||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
echo "Using CPU encoder for MP4: libx264"
|
echo "Using CPU encoder for MP4: libx264"
|
||||||
"$ffmpeg_bin" "$overwrite_flag" -i "$input" \
|
ffmpeg "$overwrite_flag" -i "$input" \
|
||||||
-vf "$crop_vf" \
|
-vf "$crop_vf" \
|
||||||
-c:v libx264 -preset slow -crf 20 \
|
-c:v libx264 -preset slow -crf 20 \
|
||||||
-profile:v high -level 4.1 -pix_fmt yuv420p \
|
-profile:v high -level 4.1 -pix_fmt yuv420p \
|
||||||
@@ -185,7 +154,7 @@ fi
|
|||||||
echo "Generating WebM: $webm_out"
|
echo "Generating WebM: $webm_out"
|
||||||
if has_encoder "av1_nvenc"; then
|
if has_encoder "av1_nvenc"; then
|
||||||
echo "Trying GPU encoder for WebM: av1_nvenc"
|
echo "Trying GPU encoder for WebM: av1_nvenc"
|
||||||
if "$ffmpeg_bin" "$overwrite_flag" -i "$input" \
|
if ffmpeg "$overwrite_flag" -i "$input" \
|
||||||
-vf "$webm_vf" \
|
-vf "$webm_vf" \
|
||||||
-c:v av1_nvenc -preset p6 -cq:v 34 -b:v 0 \
|
-c:v av1_nvenc -preset p6 -cq:v 34 -b:v 0 \
|
||||||
-c:a libopus -b:a 96k \
|
-c:a libopus -b:a 96k \
|
||||||
@@ -193,7 +162,7 @@ if has_encoder "av1_nvenc"; then
|
|||||||
:
|
:
|
||||||
else
|
else
|
||||||
echo "GPU WebM encode failed; retrying with CPU encoder: libvpx-vp9"
|
echo "GPU WebM encode failed; retrying with CPU encoder: libvpx-vp9"
|
||||||
"$ffmpeg_bin" "$overwrite_flag" -i "$input" \
|
ffmpeg "$overwrite_flag" -i "$input" \
|
||||||
-vf "$webm_vf" \
|
-vf "$webm_vf" \
|
||||||
-c:v libvpx-vp9 -crf 34 -b:v 0 \
|
-c:v libvpx-vp9 -crf 34 -b:v 0 \
|
||||||
-row-mt 1 -threads 8 \
|
-row-mt 1 -threads 8 \
|
||||||
@@ -202,7 +171,7 @@ if has_encoder "av1_nvenc"; then
|
|||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
echo "Using CPU encoder for WebM: libvpx-vp9"
|
echo "Using CPU encoder for WebM: libvpx-vp9"
|
||||||
"$ffmpeg_bin" "$overwrite_flag" -i "$input" \
|
ffmpeg "$overwrite_flag" -i "$input" \
|
||||||
-vf "$webm_vf" \
|
-vf "$webm_vf" \
|
||||||
-c:v libvpx-vp9 -crf 34 -b:v 0 \
|
-c:v libvpx-vp9 -crf 34 -b:v 0 \
|
||||||
-row-mt 1 -threads 8 \
|
-row-mt 1 -threads 8 \
|
||||||
@@ -216,7 +185,7 @@ if [[ "$generate_webp" -eq 1 ]]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "Generating animated WebP with $webp_encoder: $webp_out"
|
echo "Generating animated WebP with $webp_encoder: $webp_out"
|
||||||
"$ffmpeg_bin" "$overwrite_flag" -i "$input" \
|
ffmpeg "$overwrite_flag" -i "$input" \
|
||||||
-vf "${crop_vf},fps=24,scale=960:-1:flags=lanczos" \
|
-vf "${crop_vf},fps=24,scale=960:-1:flags=lanczos" \
|
||||||
-c:v "$webp_encoder" \
|
-c:v "$webp_encoder" \
|
||||||
-q:v 80 \
|
-q:v 80 \
|
||||||
@@ -226,7 +195,7 @@ if [[ "$generate_webp" -eq 1 ]]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
echo "Generating poster: $poster_out"
|
echo "Generating poster: $poster_out"
|
||||||
"$ffmpeg_bin" "$overwrite_flag" -ss 00:00:05 -i "$input" \
|
ffmpeg "$overwrite_flag" -ss 00:00:05 -i "$input" \
|
||||||
-vf "$crop_vf" \
|
-vf "$crop_vf" \
|
||||||
-vframes 1 \
|
-vframes 1 \
|
||||||
-q:v 2 \
|
-q:v 2 \
|
||||||
|
|||||||
@@ -19,33 +19,11 @@ function writeExecutable(filePath: string, contents: string): void {
|
|||||||
fs.chmodSync(filePath, 0o755);
|
fs.chmodSync(filePath, 0o755);
|
||||||
}
|
}
|
||||||
|
|
||||||
function shellQuote(value: string): string {
|
|
||||||
return `'${value.replace(/'/g, `'\"'\"'`)}'`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function toBashPath(filePath: string): string {
|
|
||||||
if (process.platform !== 'win32') return filePath;
|
|
||||||
|
|
||||||
const normalized = filePath.replace(/\\/g, '/');
|
|
||||||
const match = normalized.match(/^([A-Za-z]):\/(.*)$/);
|
|
||||||
if (!match) return normalized;
|
|
||||||
|
|
||||||
const drive = match[1]!;
|
|
||||||
const rest = match[2]!;
|
|
||||||
const probe = spawnSync('bash', ['-c', 'uname -s'], { encoding: 'utf8' });
|
|
||||||
if (probe.status === 0 && /linux/i.test(probe.stdout)) {
|
|
||||||
return `/mnt/${drive.toLowerCase()}/${rest}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${drive.toUpperCase()}:/${rest}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
test('mkv-to-readme-video accepts libwebp_anim when libwebp is unavailable', () => {
|
test('mkv-to-readme-video accepts libwebp_anim when libwebp is unavailable', () => {
|
||||||
withTempDir((root) => {
|
withTempDir((root) => {
|
||||||
const binDir = path.join(root, 'bin');
|
const binDir = path.join(root, 'bin');
|
||||||
const inputPath = path.join(root, 'sample.mkv');
|
const inputPath = path.join(root, 'sample.mkv');
|
||||||
const ffmpegLogPath = path.join(root, 'ffmpeg-args.log');
|
const ffmpegLogPath = path.join(root, 'ffmpeg-args.log');
|
||||||
const ffmpegLogPathBash = toBashPath(ffmpegLogPath);
|
|
||||||
|
|
||||||
fs.mkdirSync(binDir, { recursive: true });
|
fs.mkdirSync(binDir, { recursive: true });
|
||||||
fs.writeFileSync(inputPath, 'fake-video', 'utf8');
|
fs.writeFileSync(inputPath, 'fake-video', 'utf8');
|
||||||
@@ -66,33 +44,22 @@ EOF
|
|||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "$#" -eq 0 ]]; then
|
printf '%s\\n' "$*" >> "${ffmpegLogPath}"
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
printf '%s\\n' "$*" >> "${ffmpegLogPathBash}"
|
|
||||||
output=""
|
output=""
|
||||||
for arg in "$@"; do
|
for arg in "$@"; do
|
||||||
output="$arg"
|
output="$arg"
|
||||||
done
|
done
|
||||||
if [[ -z "$output" ]]; then
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
mkdir -p "$(dirname "$output")"
|
mkdir -p "$(dirname "$output")"
|
||||||
touch "$output"
|
touch "$output"
|
||||||
`,
|
`,
|
||||||
);
|
);
|
||||||
|
|
||||||
const ffmpegShimPath = toBashPath(path.join(binDir, 'ffmpeg'));
|
const result = spawnSync('bash', ['scripts/mkv-to-readme-video.sh', '--webp', inputPath], {
|
||||||
const ffmpegShimDir = toBashPath(binDir);
|
|
||||||
const inputBashPath = toBashPath(inputPath);
|
|
||||||
const command = [
|
|
||||||
`chmod +x ${shellQuote(ffmpegShimPath)}`,
|
|
||||||
`PATH=${shellQuote(`${ffmpegShimDir}:`)}"$PATH"`,
|
|
||||||
`scripts/mkv-to-readme-video.sh --webp ${shellQuote(inputBashPath)}`,
|
|
||||||
].join('; ');
|
|
||||||
const result = spawnSync('bash', ['-lc', command], {
|
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
PATH: `${binDir}:${process.env.PATH || ''}`,
|
||||||
|
},
|
||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ const repoRoot = path.resolve(scriptDir, '..');
|
|||||||
const rendererSourceDir = path.join(repoRoot, 'src', 'renderer');
|
const rendererSourceDir = path.join(repoRoot, 'src', 'renderer');
|
||||||
const rendererOutputDir = path.join(repoRoot, 'dist', 'renderer');
|
const rendererOutputDir = path.join(repoRoot, 'dist', 'renderer');
|
||||||
const scriptsOutputDir = path.join(repoRoot, 'dist', 'scripts');
|
const scriptsOutputDir = path.join(repoRoot, 'dist', 'scripts');
|
||||||
|
const windowsHelperSourcePath = path.join(scriptDir, 'get-mpv-window-windows.ps1');
|
||||||
|
const windowsHelperOutputPath = path.join(scriptsOutputDir, 'get-mpv-window-windows.ps1');
|
||||||
const macosHelperSourcePath = path.join(scriptDir, 'get-mpv-window-macos.swift');
|
const macosHelperSourcePath = path.join(scriptDir, 'get-mpv-window-macos.swift');
|
||||||
const macosHelperBinaryPath = path.join(scriptsOutputDir, 'get-mpv-window-macos');
|
const macosHelperBinaryPath = path.join(scriptsOutputDir, 'get-mpv-window-macos');
|
||||||
const macosHelperSourceCopyPath = path.join(scriptsOutputDir, 'get-mpv-window-macos.swift');
|
const macosHelperSourceCopyPath = path.join(scriptsOutputDir, 'get-mpv-window-macos.swift');
|
||||||
@@ -31,6 +33,11 @@ function copyRendererAssets() {
|
|||||||
process.stdout.write(`Staged renderer assets in ${rendererOutputDir}\n`);
|
process.stdout.write(`Staged renderer assets in ${rendererOutputDir}\n`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function stageWindowsHelper() {
|
||||||
|
copyFile(windowsHelperSourcePath, windowsHelperOutputPath);
|
||||||
|
process.stdout.write(`Staged Windows helper: ${windowsHelperOutputPath}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
function fallbackToMacosSource() {
|
function fallbackToMacosSource() {
|
||||||
copyFile(macosHelperSourcePath, macosHelperSourceCopyPath);
|
copyFile(macosHelperSourcePath, macosHelperSourceCopyPath);
|
||||||
process.stdout.write(`Staged macOS helper source fallback: ${macosHelperSourceCopyPath}\n`);
|
process.stdout.write(`Staged macOS helper source fallback: ${macosHelperSourceCopyPath}\n`);
|
||||||
@@ -70,6 +77,7 @@ function buildMacosHelper() {
|
|||||||
|
|
||||||
function main() {
|
function main() {
|
||||||
copyRendererAssets();
|
copyRendererAssets();
|
||||||
|
stageWindowsHelper();
|
||||||
buildMacosHelper();
|
buildMacosHelper();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,26 +13,6 @@ appimage=
|
|||||||
wrapper=
|
wrapper=
|
||||||
assets=
|
assets=
|
||||||
|
|
||||||
normalize_path() {
|
|
||||||
local value="$1"
|
|
||||||
if command -v cygpath >/dev/null 2>&1; then
|
|
||||||
case "$value" in
|
|
||||||
[A-Za-z]:\\* | [A-Za-z]:/*)
|
|
||||||
cygpath -u "$value"
|
|
||||||
return 0
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
fi
|
|
||||||
if [[ "$value" =~ ^([A-Za-z]):[\\/](.*)$ ]]; then
|
|
||||||
local drive="${BASH_REMATCH[1],,}"
|
|
||||||
local rest="${BASH_REMATCH[2]}"
|
|
||||||
rest="${rest//\\//}"
|
|
||||||
printf '/mnt/%s/%s\n' "$drive" "$rest"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
printf '%s\n' "$value"
|
|
||||||
}
|
|
||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
while [[ $# -gt 0 ]]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
--pkg-dir)
|
--pkg-dir)
|
||||||
@@ -73,10 +53,6 @@ if [[ -z "$pkg_dir" || -z "$version" || -z "$appimage" || -z "$wrapper" || -z "$
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
version="${version#v}"
|
version="${version#v}"
|
||||||
pkg_dir="$(normalize_path "$pkg_dir")"
|
|
||||||
appimage="$(normalize_path "$appimage")"
|
|
||||||
wrapper="$(normalize_path "$wrapper")"
|
|
||||||
assets="$(normalize_path "$assets")"
|
|
||||||
pkgbuild="${pkg_dir}/PKGBUILD"
|
pkgbuild="${pkg_dir}/PKGBUILD"
|
||||||
srcinfo="${pkg_dir}/.SRCINFO"
|
srcinfo="${pkg_dir}/.SRCINFO"
|
||||||
|
|
||||||
@@ -106,9 +82,6 @@ awk \
|
|||||||
found_pkgver = 0
|
found_pkgver = 0
|
||||||
found_sha_block = 0
|
found_sha_block = 0
|
||||||
}
|
}
|
||||||
{
|
|
||||||
sub(/\r$/, "")
|
|
||||||
}
|
|
||||||
/^pkgver=/ {
|
/^pkgver=/ {
|
||||||
print "pkgver=" version
|
print "pkgver=" version
|
||||||
found_pkgver = 1
|
found_pkgver = 1
|
||||||
@@ -167,9 +140,6 @@ awk \
|
|||||||
found_source_wrapper = 0
|
found_source_wrapper = 0
|
||||||
found_source_assets = 0
|
found_source_assets = 0
|
||||||
}
|
}
|
||||||
{
|
|
||||||
sub(/\r$/, "")
|
|
||||||
}
|
|
||||||
/^\tpkgver = / {
|
/^\tpkgver = / {
|
||||||
print "\tpkgver = " version
|
print "\tpkgver = " version
|
||||||
found_pkgver = 1
|
found_pkgver = 1
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { execFileSync, spawnSync } from 'node:child_process';
|
import { execFileSync } from 'node:child_process';
|
||||||
import crypto from 'node:crypto';
|
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
@@ -10,23 +9,6 @@ function createWorkspace(name: string): string {
|
|||||||
return fs.mkdtempSync(path.join(os.tmpdir(), `${name}-`));
|
return fs.mkdtempSync(path.join(os.tmpdir(), `${name}-`));
|
||||||
}
|
}
|
||||||
|
|
||||||
function toBashPath(filePath: string): string {
|
|
||||||
if (process.platform !== 'win32') return filePath;
|
|
||||||
|
|
||||||
const normalized = filePath.replace(/\\/g, '/');
|
|
||||||
const match = normalized.match(/^([A-Za-z]):\/(.*)$/);
|
|
||||||
if (!match) return normalized;
|
|
||||||
|
|
||||||
const drive = match[1]!;
|
|
||||||
const rest = match[2]!;
|
|
||||||
const probe = spawnSync('bash', ['-c', 'uname -s'], { encoding: 'utf8' });
|
|
||||||
if (probe.status === 0 && /linux/i.test(probe.stdout)) {
|
|
||||||
return `/mnt/${drive.toLowerCase()}/${rest}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `${drive.toUpperCase()}:/${rest}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
test('update-aur-package updates PKGBUILD and .SRCINFO without makepkg', () => {
|
test('update-aur-package updates PKGBUILD and .SRCINFO without makepkg', () => {
|
||||||
const workspace = createWorkspace('subminer-aur-package');
|
const workspace = createWorkspace('subminer-aur-package');
|
||||||
const pkgDir = path.join(workspace, 'aur-subminer-bin');
|
const pkgDir = path.join(workspace, 'aur-subminer-bin');
|
||||||
@@ -47,15 +29,15 @@ test('update-aur-package updates PKGBUILD and .SRCINFO without makepkg', () => {
|
|||||||
[
|
[
|
||||||
'scripts/update-aur-package.sh',
|
'scripts/update-aur-package.sh',
|
||||||
'--pkg-dir',
|
'--pkg-dir',
|
||||||
toBashPath(pkgDir),
|
pkgDir,
|
||||||
'--version',
|
'--version',
|
||||||
'v0.6.3',
|
'v0.6.3',
|
||||||
'--appimage',
|
'--appimage',
|
||||||
toBashPath(appImagePath),
|
appImagePath,
|
||||||
'--wrapper',
|
'--wrapper',
|
||||||
toBashPath(wrapperPath),
|
wrapperPath,
|
||||||
'--assets',
|
'--assets',
|
||||||
toBashPath(assetsPath),
|
assetsPath,
|
||||||
],
|
],
|
||||||
{
|
{
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
@@ -65,8 +47,8 @@ test('update-aur-package updates PKGBUILD and .SRCINFO without makepkg', () => {
|
|||||||
|
|
||||||
const pkgbuild = fs.readFileSync(path.join(pkgDir, 'PKGBUILD'), 'utf8');
|
const pkgbuild = fs.readFileSync(path.join(pkgDir, 'PKGBUILD'), 'utf8');
|
||||||
const srcinfo = fs.readFileSync(path.join(pkgDir, '.SRCINFO'), 'utf8');
|
const srcinfo = fs.readFileSync(path.join(pkgDir, '.SRCINFO'), 'utf8');
|
||||||
const expectedSums = [appImagePath, wrapperPath, assetsPath].map((filePath) =>
|
const expectedSums = [appImagePath, wrapperPath, assetsPath].map(
|
||||||
crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex'),
|
(filePath) => execFileSync('sha256sum', [filePath], { encoding: 'utf8' }).split(/\s+/)[0],
|
||||||
);
|
);
|
||||||
|
|
||||||
assert.match(pkgbuild, /^pkgver=0\.6\.3$/m);
|
assert.match(pkgbuild, /^pkgver=0\.6\.3$/m);
|
||||||
|
|||||||
@@ -73,50 +73,6 @@ test('parseArgs captures youtube startup forwarding flags', () => {
|
|||||||
assert.equal(shouldStartApp(args), true);
|
assert.equal(shouldStartApp(args), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('parseArgs captures session action forwarding flags', () => {
|
|
||||||
const args = parseArgs([
|
|
||||||
'--toggle-stats-overlay',
|
|
||||||
'--open-jimaku',
|
|
||||||
'--open-youtube-picker',
|
|
||||||
'--open-playlist-browser',
|
|
||||||
'--replay-current-subtitle',
|
|
||||||
'--play-next-subtitle',
|
|
||||||
'--shift-sub-delay-prev-line',
|
|
||||||
'--shift-sub-delay-next-line',
|
|
||||||
'--cycle-runtime-option',
|
|
||||||
'anki.autoUpdateNewCards:prev',
|
|
||||||
'--copy-subtitle-count',
|
|
||||||
'3',
|
|
||||||
'--mine-sentence-count=2',
|
|
||||||
]);
|
|
||||||
|
|
||||||
assert.equal(args.toggleStatsOverlay, true);
|
|
||||||
assert.equal(args.openJimaku, true);
|
|
||||||
assert.equal(args.openYoutubePicker, true);
|
|
||||||
assert.equal(args.openPlaylistBrowser, true);
|
|
||||||
assert.equal(args.replayCurrentSubtitle, true);
|
|
||||||
assert.equal(args.playNextSubtitle, true);
|
|
||||||
assert.equal(args.shiftSubDelayPrevLine, true);
|
|
||||||
assert.equal(args.shiftSubDelayNextLine, true);
|
|
||||||
assert.equal(args.cycleRuntimeOptionId, 'anki.autoUpdateNewCards');
|
|
||||||
assert.equal(args.cycleRuntimeOptionDirection, -1);
|
|
||||||
assert.equal(args.copySubtitleCount, 3);
|
|
||||||
assert.equal(args.mineSentenceCount, 2);
|
|
||||||
assert.equal(hasExplicitCommand(args), true);
|
|
||||||
assert.equal(shouldStartApp(args), true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('parseArgs ignores non-positive numeric session action counts', () => {
|
|
||||||
const args = parseArgs([
|
|
||||||
'--copy-subtitle-count=0',
|
|
||||||
'--mine-sentence-count',
|
|
||||||
'-1',
|
|
||||||
]);
|
|
||||||
|
|
||||||
assert.equal(args.copySubtitleCount, undefined);
|
|
||||||
assert.equal(args.mineSentenceCount, undefined);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('youtube playback does not use generic overlay-runtime bootstrap classification', () => {
|
test('youtube playback does not use generic overlay-runtime bootstrap classification', () => {
|
||||||
const args = parseArgs(['--youtube-play', 'https://youtube.com/watch?v=abc']);
|
const args = parseArgs(['--youtube-play', 'https://youtube.com/watch?v=abc']);
|
||||||
|
|
||||||
@@ -216,21 +172,6 @@ test('hasExplicitCommand and shouldStartApp preserve command intent', () => {
|
|||||||
assert.equal(hasExplicitCommand(anilistRetryQueue), true);
|
assert.equal(hasExplicitCommand(anilistRetryQueue), true);
|
||||||
assert.equal(shouldStartApp(anilistRetryQueue), false);
|
assert.equal(shouldStartApp(anilistRetryQueue), false);
|
||||||
|
|
||||||
const toggleStatsOverlay = parseArgs(['--toggle-stats-overlay']);
|
|
||||||
assert.equal(toggleStatsOverlay.toggleStatsOverlay, true);
|
|
||||||
assert.equal(hasExplicitCommand(toggleStatsOverlay), true);
|
|
||||||
assert.equal(shouldStartApp(toggleStatsOverlay), true);
|
|
||||||
|
|
||||||
const cycleRuntimeOption = parseArgs([
|
|
||||||
'--cycle-runtime-option',
|
|
||||||
'anki.autoUpdateNewCards:next',
|
|
||||||
]);
|
|
||||||
assert.equal(cycleRuntimeOption.cycleRuntimeOptionId, 'anki.autoUpdateNewCards');
|
|
||||||
assert.equal(cycleRuntimeOption.cycleRuntimeOptionDirection, 1);
|
|
||||||
assert.equal(hasExplicitCommand(cycleRuntimeOption), true);
|
|
||||||
assert.equal(shouldStartApp(cycleRuntimeOption), true);
|
|
||||||
assert.equal(commandNeedsOverlayRuntime(cycleRuntimeOption), true);
|
|
||||||
|
|
||||||
const dictionary = parseArgs(['--dictionary']);
|
const dictionary = parseArgs(['--dictionary']);
|
||||||
assert.equal(dictionary.dictionary, true);
|
assert.equal(dictionary.dictionary, true);
|
||||||
assert.equal(hasExplicitCommand(dictionary), true);
|
assert.equal(hasExplicitCommand(dictionary), true);
|
||||||
|
|||||||
160
src/cli/args.ts
160
src/cli/args.ts
@@ -24,23 +24,7 @@ export interface CliArgs {
|
|||||||
triggerFieldGrouping: boolean;
|
triggerFieldGrouping: boolean;
|
||||||
triggerSubsync: boolean;
|
triggerSubsync: boolean;
|
||||||
markAudioCard: boolean;
|
markAudioCard: boolean;
|
||||||
toggleStatsOverlay: boolean;
|
|
||||||
toggleSubtitleSidebar: boolean;
|
|
||||||
openRuntimeOptions: boolean;
|
openRuntimeOptions: boolean;
|
||||||
openSessionHelp: boolean;
|
|
||||||
openControllerSelect: boolean;
|
|
||||||
openControllerDebug: boolean;
|
|
||||||
openJimaku: boolean;
|
|
||||||
openYoutubePicker: boolean;
|
|
||||||
openPlaylistBrowser: boolean;
|
|
||||||
replayCurrentSubtitle: boolean;
|
|
||||||
playNextSubtitle: boolean;
|
|
||||||
shiftSubDelayPrevLine: boolean;
|
|
||||||
shiftSubDelayNextLine: boolean;
|
|
||||||
cycleRuntimeOptionId?: string;
|
|
||||||
cycleRuntimeOptionDirection?: 1 | -1;
|
|
||||||
copySubtitleCount?: number;
|
|
||||||
mineSentenceCount?: number;
|
|
||||||
anilistStatus: boolean;
|
anilistStatus: boolean;
|
||||||
anilistLogout: boolean;
|
anilistLogout: boolean;
|
||||||
anilistSetup: boolean;
|
anilistSetup: boolean;
|
||||||
@@ -118,19 +102,7 @@ export function parseArgs(argv: string[]): CliArgs {
|
|||||||
triggerFieldGrouping: false,
|
triggerFieldGrouping: false,
|
||||||
triggerSubsync: false,
|
triggerSubsync: false,
|
||||||
markAudioCard: false,
|
markAudioCard: false,
|
||||||
toggleStatsOverlay: false,
|
|
||||||
toggleSubtitleSidebar: false,
|
|
||||||
openRuntimeOptions: false,
|
openRuntimeOptions: false,
|
||||||
openSessionHelp: false,
|
|
||||||
openControllerSelect: false,
|
|
||||||
openControllerDebug: false,
|
|
||||||
openJimaku: false,
|
|
||||||
openYoutubePicker: false,
|
|
||||||
openPlaylistBrowser: false,
|
|
||||||
replayCurrentSubtitle: false,
|
|
||||||
playNextSubtitle: false,
|
|
||||||
shiftSubDelayPrevLine: false,
|
|
||||||
shiftSubDelayNextLine: false,
|
|
||||||
anilistStatus: false,
|
anilistStatus: false,
|
||||||
anilistLogout: false,
|
anilistLogout: false,
|
||||||
anilistSetup: false,
|
anilistSetup: false,
|
||||||
@@ -166,24 +138,6 @@ export function parseArgs(argv: string[]): CliArgs {
|
|||||||
return value;
|
return value;
|
||||||
};
|
};
|
||||||
|
|
||||||
const parseCycleRuntimeOption = (
|
|
||||||
value: string | undefined,
|
|
||||||
): { id: string; direction: 1 | -1 } | null => {
|
|
||||||
if (!value) return null;
|
|
||||||
const separatorIndex = value.lastIndexOf(':');
|
|
||||||
if (separatorIndex <= 0 || separatorIndex === value.length - 1) return null;
|
|
||||||
const id = value.slice(0, separatorIndex).trim();
|
|
||||||
const rawDirection = value.slice(separatorIndex + 1).trim().toLowerCase();
|
|
||||||
if (!id) return null;
|
|
||||||
if (rawDirection === 'next' || rawDirection === '1') {
|
|
||||||
return { id, direction: 1 };
|
|
||||||
}
|
|
||||||
if (rawDirection === 'prev' || rawDirection === '-1') {
|
|
||||||
return { id, direction: -1 };
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
for (let i = 0; i < argv.length; i += 1) {
|
for (let i = 0; i < argv.length; i += 1) {
|
||||||
const arg = argv[i];
|
const arg = argv[i];
|
||||||
if (!arg || !arg.startsWith('--')) continue;
|
if (!arg || !arg.startsWith('--')) continue;
|
||||||
@@ -225,44 +179,8 @@ export function parseArgs(argv: string[]): CliArgs {
|
|||||||
else if (arg === '--trigger-field-grouping') args.triggerFieldGrouping = true;
|
else if (arg === '--trigger-field-grouping') args.triggerFieldGrouping = true;
|
||||||
else if (arg === '--trigger-subsync') args.triggerSubsync = true;
|
else if (arg === '--trigger-subsync') args.triggerSubsync = true;
|
||||||
else if (arg === '--mark-audio-card') args.markAudioCard = true;
|
else if (arg === '--mark-audio-card') args.markAudioCard = true;
|
||||||
else if (arg === '--toggle-stats-overlay') args.toggleStatsOverlay = true;
|
|
||||||
else if (arg === '--toggle-subtitle-sidebar') args.toggleSubtitleSidebar = true;
|
|
||||||
else if (arg === '--open-runtime-options') args.openRuntimeOptions = true;
|
else if (arg === '--open-runtime-options') args.openRuntimeOptions = true;
|
||||||
else if (arg === '--open-session-help') args.openSessionHelp = true;
|
else if (arg === '--anilist-status') args.anilistStatus = true;
|
||||||
else if (arg === '--open-controller-select') args.openControllerSelect = true;
|
|
||||||
else if (arg === '--open-controller-debug') args.openControllerDebug = true;
|
|
||||||
else if (arg === '--open-jimaku') args.openJimaku = true;
|
|
||||||
else if (arg === '--open-youtube-picker') args.openYoutubePicker = true;
|
|
||||||
else if (arg === '--open-playlist-browser') args.openPlaylistBrowser = true;
|
|
||||||
else if (arg === '--replay-current-subtitle') args.replayCurrentSubtitle = true;
|
|
||||||
else if (arg === '--play-next-subtitle') args.playNextSubtitle = true;
|
|
||||||
else if (arg === '--shift-sub-delay-prev-line') args.shiftSubDelayPrevLine = true;
|
|
||||||
else if (arg === '--shift-sub-delay-next-line') args.shiftSubDelayNextLine = true;
|
|
||||||
else if (arg.startsWith('--cycle-runtime-option=')) {
|
|
||||||
const parsed = parseCycleRuntimeOption(arg.split('=', 2)[1]);
|
|
||||||
if (parsed) {
|
|
||||||
args.cycleRuntimeOptionId = parsed.id;
|
|
||||||
args.cycleRuntimeOptionDirection = parsed.direction;
|
|
||||||
}
|
|
||||||
} else if (arg === '--cycle-runtime-option') {
|
|
||||||
const parsed = parseCycleRuntimeOption(readValue(argv[i + 1]));
|
|
||||||
if (parsed) {
|
|
||||||
args.cycleRuntimeOptionId = parsed.id;
|
|
||||||
args.cycleRuntimeOptionDirection = parsed.direction;
|
|
||||||
}
|
|
||||||
} else if (arg.startsWith('--copy-subtitle-count=')) {
|
|
||||||
const value = Number(arg.split('=', 2)[1]);
|
|
||||||
if (Number.isInteger(value) && value > 0) args.copySubtitleCount = value;
|
|
||||||
} else if (arg === '--copy-subtitle-count') {
|
|
||||||
const value = Number(readValue(argv[i + 1]));
|
|
||||||
if (Number.isInteger(value) && value > 0) args.copySubtitleCount = value;
|
|
||||||
} else if (arg.startsWith('--mine-sentence-count=')) {
|
|
||||||
const value = Number(arg.split('=', 2)[1]);
|
|
||||||
if (Number.isInteger(value) && value > 0) args.mineSentenceCount = value;
|
|
||||||
} else if (arg === '--mine-sentence-count') {
|
|
||||||
const value = Number(readValue(argv[i + 1]));
|
|
||||||
if (Number.isInteger(value) && value > 0) args.mineSentenceCount = value;
|
|
||||||
} else if (arg === '--anilist-status') args.anilistStatus = true;
|
|
||||||
else if (arg === '--anilist-logout') args.anilistLogout = true;
|
else if (arg === '--anilist-logout') args.anilistLogout = true;
|
||||||
else if (arg === '--anilist-setup') args.anilistSetup = true;
|
else if (arg === '--anilist-setup') args.anilistSetup = true;
|
||||||
else if (arg === '--anilist-retry-queue') args.anilistRetryQueue = true;
|
else if (arg === '--anilist-retry-queue') args.anilistRetryQueue = true;
|
||||||
@@ -453,22 +371,7 @@ export function hasExplicitCommand(args: CliArgs): boolean {
|
|||||||
args.triggerFieldGrouping ||
|
args.triggerFieldGrouping ||
|
||||||
args.triggerSubsync ||
|
args.triggerSubsync ||
|
||||||
args.markAudioCard ||
|
args.markAudioCard ||
|
||||||
args.toggleStatsOverlay ||
|
|
||||||
args.toggleSubtitleSidebar ||
|
|
||||||
args.openRuntimeOptions ||
|
args.openRuntimeOptions ||
|
||||||
args.openSessionHelp ||
|
|
||||||
args.openControllerSelect ||
|
|
||||||
args.openControllerDebug ||
|
|
||||||
args.openJimaku ||
|
|
||||||
args.openYoutubePicker ||
|
|
||||||
args.openPlaylistBrowser ||
|
|
||||||
args.replayCurrentSubtitle ||
|
|
||||||
args.playNextSubtitle ||
|
|
||||||
args.shiftSubDelayPrevLine ||
|
|
||||||
args.shiftSubDelayNextLine ||
|
|
||||||
args.cycleRuntimeOptionId !== undefined ||
|
|
||||||
args.copySubtitleCount !== undefined ||
|
|
||||||
args.mineSentenceCount !== undefined ||
|
|
||||||
args.anilistStatus ||
|
args.anilistStatus ||
|
||||||
args.anilistLogout ||
|
args.anilistLogout ||
|
||||||
args.anilistSetup ||
|
args.anilistSetup ||
|
||||||
@@ -520,22 +423,7 @@ export function isStandaloneTexthookerCommand(args: CliArgs): boolean {
|
|||||||
!args.triggerFieldGrouping &&
|
!args.triggerFieldGrouping &&
|
||||||
!args.triggerSubsync &&
|
!args.triggerSubsync &&
|
||||||
!args.markAudioCard &&
|
!args.markAudioCard &&
|
||||||
!args.toggleStatsOverlay &&
|
|
||||||
!args.toggleSubtitleSidebar &&
|
|
||||||
!args.openRuntimeOptions &&
|
!args.openRuntimeOptions &&
|
||||||
!args.openSessionHelp &&
|
|
||||||
!args.openControllerSelect &&
|
|
||||||
!args.openControllerDebug &&
|
|
||||||
!args.openJimaku &&
|
|
||||||
!args.openYoutubePicker &&
|
|
||||||
!args.openPlaylistBrowser &&
|
|
||||||
!args.replayCurrentSubtitle &&
|
|
||||||
!args.playNextSubtitle &&
|
|
||||||
!args.shiftSubDelayPrevLine &&
|
|
||||||
!args.shiftSubDelayNextLine &&
|
|
||||||
args.cycleRuntimeOptionId === undefined &&
|
|
||||||
args.copySubtitleCount === undefined &&
|
|
||||||
args.mineSentenceCount === undefined &&
|
|
||||||
!args.anilistStatus &&
|
!args.anilistStatus &&
|
||||||
!args.anilistLogout &&
|
!args.anilistLogout &&
|
||||||
!args.anilistSetup &&
|
!args.anilistSetup &&
|
||||||
@@ -578,22 +466,7 @@ export function shouldStartApp(args: CliArgs): boolean {
|
|||||||
args.triggerFieldGrouping ||
|
args.triggerFieldGrouping ||
|
||||||
args.triggerSubsync ||
|
args.triggerSubsync ||
|
||||||
args.markAudioCard ||
|
args.markAudioCard ||
|
||||||
args.toggleStatsOverlay ||
|
|
||||||
args.toggleSubtitleSidebar ||
|
|
||||||
args.openRuntimeOptions ||
|
args.openRuntimeOptions ||
|
||||||
args.openSessionHelp ||
|
|
||||||
args.openControllerSelect ||
|
|
||||||
args.openControllerDebug ||
|
|
||||||
args.openJimaku ||
|
|
||||||
args.openYoutubePicker ||
|
|
||||||
args.openPlaylistBrowser ||
|
|
||||||
args.replayCurrentSubtitle ||
|
|
||||||
args.playNextSubtitle ||
|
|
||||||
args.shiftSubDelayPrevLine ||
|
|
||||||
args.shiftSubDelayNextLine ||
|
|
||||||
args.cycleRuntimeOptionId !== undefined ||
|
|
||||||
args.copySubtitleCount !== undefined ||
|
|
||||||
args.mineSentenceCount !== undefined ||
|
|
||||||
args.dictionary ||
|
args.dictionary ||
|
||||||
args.stats ||
|
args.stats ||
|
||||||
args.jellyfin ||
|
args.jellyfin ||
|
||||||
@@ -631,22 +504,7 @@ export function shouldRunSettingsOnlyStartup(args: CliArgs): boolean {
|
|||||||
!args.triggerFieldGrouping &&
|
!args.triggerFieldGrouping &&
|
||||||
!args.triggerSubsync &&
|
!args.triggerSubsync &&
|
||||||
!args.markAudioCard &&
|
!args.markAudioCard &&
|
||||||
!args.toggleStatsOverlay &&
|
|
||||||
!args.toggleSubtitleSidebar &&
|
|
||||||
!args.openRuntimeOptions &&
|
!args.openRuntimeOptions &&
|
||||||
!args.openSessionHelp &&
|
|
||||||
!args.openControllerSelect &&
|
|
||||||
!args.openControllerDebug &&
|
|
||||||
!args.openJimaku &&
|
|
||||||
!args.openYoutubePicker &&
|
|
||||||
!args.openPlaylistBrowser &&
|
|
||||||
!args.replayCurrentSubtitle &&
|
|
||||||
!args.playNextSubtitle &&
|
|
||||||
!args.shiftSubDelayPrevLine &&
|
|
||||||
!args.shiftSubDelayNextLine &&
|
|
||||||
args.cycleRuntimeOptionId === undefined &&
|
|
||||||
args.copySubtitleCount === undefined &&
|
|
||||||
args.mineSentenceCount === undefined &&
|
|
||||||
!args.anilistStatus &&
|
!args.anilistStatus &&
|
||||||
!args.anilistLogout &&
|
!args.anilistLogout &&
|
||||||
!args.anilistSetup &&
|
!args.anilistSetup &&
|
||||||
@@ -686,24 +544,10 @@ export function commandNeedsOverlayRuntime(args: CliArgs): boolean {
|
|||||||
args.mineSentenceMultiple ||
|
args.mineSentenceMultiple ||
|
||||||
args.updateLastCardFromClipboard ||
|
args.updateLastCardFromClipboard ||
|
||||||
args.toggleSecondarySub ||
|
args.toggleSecondarySub ||
|
||||||
args.toggleSubtitleSidebar ||
|
|
||||||
args.triggerFieldGrouping ||
|
args.triggerFieldGrouping ||
|
||||||
args.triggerSubsync ||
|
args.triggerSubsync ||
|
||||||
args.markAudioCard ||
|
args.markAudioCard ||
|
||||||
args.openRuntimeOptions ||
|
args.openRuntimeOptions
|
||||||
args.openSessionHelp ||
|
|
||||||
args.openControllerSelect ||
|
|
||||||
args.openControllerDebug ||
|
|
||||||
args.openJimaku ||
|
|
||||||
args.openYoutubePicker ||
|
|
||||||
args.openPlaylistBrowser ||
|
|
||||||
args.replayCurrentSubtitle ||
|
|
||||||
args.playNextSubtitle ||
|
|
||||||
args.shiftSubDelayPrevLine ||
|
|
||||||
args.shiftSubDelayNextLine ||
|
|
||||||
args.cycleRuntimeOptionId !== undefined ||
|
|
||||||
args.copySubtitleCount !== undefined ||
|
|
||||||
args.mineSentenceCount !== undefined
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,11 +35,7 @@ ${B}Mining${R}
|
|||||||
--trigger-field-grouping Run Kiku field grouping
|
--trigger-field-grouping Run Kiku field grouping
|
||||||
--trigger-subsync Run subtitle sync
|
--trigger-subsync Run subtitle sync
|
||||||
--toggle-secondary-sub Cycle secondary subtitle mode
|
--toggle-secondary-sub Cycle secondary subtitle mode
|
||||||
--toggle-subtitle-sidebar Toggle subtitle sidebar panel
|
|
||||||
--open-runtime-options Open runtime options palette
|
--open-runtime-options Open runtime options palette
|
||||||
--open-session-help Open session help modal
|
|
||||||
--open-controller-select Open controller select modal
|
|
||||||
--open-controller-debug Open controller debug modal
|
|
||||||
|
|
||||||
${B}AniList${R}
|
${B}AniList${R}
|
||||||
--anilist-setup Open AniList authentication flow
|
--anilist-setup Open AniList authentication flow
|
||||||
|
|||||||
@@ -88,10 +88,6 @@ export const CORE_DEFAULT_CONFIG: Pick<
|
|||||||
markAudioCard: 'CommandOrControl+Shift+A',
|
markAudioCard: 'CommandOrControl+Shift+A',
|
||||||
openRuntimeOptions: 'CommandOrControl+Shift+O',
|
openRuntimeOptions: 'CommandOrControl+Shift+O',
|
||||||
openJimaku: 'Ctrl+Shift+J',
|
openJimaku: 'Ctrl+Shift+J',
|
||||||
openSessionHelp: 'CommandOrControl+Shift+H',
|
|
||||||
openControllerSelect: 'Alt+C',
|
|
||||||
openControllerDebug: 'Alt+Shift+C',
|
|
||||||
toggleSubtitleSidebar: '\\',
|
|
||||||
},
|
},
|
||||||
secondarySub: {
|
secondarySub: {
|
||||||
secondarySubLanguages: [],
|
secondarySubLanguages: [],
|
||||||
|
|||||||
@@ -28,21 +28,7 @@ function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
|||||||
triggerFieldGrouping: false,
|
triggerFieldGrouping: false,
|
||||||
triggerSubsync: false,
|
triggerSubsync: false,
|
||||||
markAudioCard: false,
|
markAudioCard: false,
|
||||||
toggleStatsOverlay: false,
|
|
||||||
toggleSubtitleSidebar: false,
|
|
||||||
openRuntimeOptions: false,
|
openRuntimeOptions: false,
|
||||||
openSessionHelp: false,
|
|
||||||
openControllerSelect: false,
|
|
||||||
openControllerDebug: false,
|
|
||||||
openJimaku: false,
|
|
||||||
openYoutubePicker: false,
|
|
||||||
openPlaylistBrowser: false,
|
|
||||||
replayCurrentSubtitle: false,
|
|
||||||
playNextSubtitle: false,
|
|
||||||
shiftSubDelayPrevLine: false,
|
|
||||||
shiftSubDelayNextLine: false,
|
|
||||||
cycleRuntimeOptionId: undefined,
|
|
||||||
cycleRuntimeOptionDirection: undefined,
|
|
||||||
anilistStatus: false,
|
anilistStatus: false,
|
||||||
anilistLogout: false,
|
anilistLogout: false,
|
||||||
anilistSetup: false,
|
anilistSetup: false,
|
||||||
|
|||||||
@@ -76,7 +76,9 @@ test('runAppReadyRuntime starts websocket in auto mode when plugin missing', asy
|
|||||||
);
|
);
|
||||||
assert.ok(calls.includes('startBackgroundWarmups'));
|
assert.ok(calls.includes('startBackgroundWarmups'));
|
||||||
assert.ok(
|
assert.ok(
|
||||||
calls.includes('log:Runtime ready: immersion tracker startup requested.'),
|
calls.includes(
|
||||||
|
'log:Runtime ready: immersion tracker startup deferred until first media activity.',
|
||||||
|
),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -101,17 +103,6 @@ test('runAppReadyRuntime starts texthooker on startup when enabled in config', a
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('runAppReadyRuntime creates immersion tracker during heavy startup', async () => {
|
|
||||||
const { deps, calls } = makeDeps({
|
|
||||||
shouldAutoInitializeOverlayRuntimeFromConfig: () => false,
|
|
||||||
});
|
|
||||||
|
|
||||||
await runAppReadyRuntime(deps);
|
|
||||||
|
|
||||||
assert.ok(calls.includes('createImmersionTracker'));
|
|
||||||
assert.ok(calls.indexOf('createImmersionTracker') < calls.indexOf('handleInitialArgs'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('runAppReadyRuntime keeps annotation websocket enabled when regular websocket auto-skips', async () => {
|
test('runAppReadyRuntime keeps annotation websocket enabled when regular websocket auto-skips', async () => {
|
||||||
const { deps, calls } = makeDeps({
|
const { deps, calls } = makeDeps({
|
||||||
getResolvedConfig: () => ({
|
getResolvedConfig: () => ({
|
||||||
|
|||||||
@@ -29,22 +29,8 @@ function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
|||||||
triggerFieldGrouping: false,
|
triggerFieldGrouping: false,
|
||||||
triggerSubsync: false,
|
triggerSubsync: false,
|
||||||
markAudioCard: false,
|
markAudioCard: false,
|
||||||
toggleStatsOverlay: false,
|
|
||||||
toggleSubtitleSidebar: false,
|
|
||||||
refreshKnownWords: false,
|
refreshKnownWords: false,
|
||||||
openRuntimeOptions: false,
|
openRuntimeOptions: false,
|
||||||
openSessionHelp: false,
|
|
||||||
openControllerSelect: false,
|
|
||||||
openControllerDebug: false,
|
|
||||||
openJimaku: false,
|
|
||||||
openYoutubePicker: false,
|
|
||||||
openPlaylistBrowser: false,
|
|
||||||
replayCurrentSubtitle: false,
|
|
||||||
playNextSubtitle: false,
|
|
||||||
shiftSubDelayPrevLine: false,
|
|
||||||
shiftSubDelayNextLine: false,
|
|
||||||
cycleRuntimeOptionId: undefined,
|
|
||||||
cycleRuntimeOptionDirection: undefined,
|
|
||||||
anilistStatus: false,
|
anilistStatus: false,
|
||||||
anilistLogout: false,
|
anilistLogout: false,
|
||||||
anilistSetup: false,
|
anilistSetup: false,
|
||||||
@@ -157,9 +143,6 @@ function createDeps(overrides: Partial<CliCommandServiceDeps> = {}) {
|
|||||||
openRuntimeOptionsPalette: () => {
|
openRuntimeOptionsPalette: () => {
|
||||||
calls.push('openRuntimeOptionsPalette');
|
calls.push('openRuntimeOptionsPalette');
|
||||||
},
|
},
|
||||||
dispatchSessionAction: async () => {
|
|
||||||
calls.push('dispatchSessionAction');
|
|
||||||
},
|
|
||||||
getAnilistStatus: () => ({
|
getAnilistStatus: () => ({
|
||||||
tokenStatus: 'resolved',
|
tokenStatus: 'resolved',
|
||||||
tokenSource: 'stored',
|
tokenSource: 'stored',
|
||||||
@@ -516,7 +499,6 @@ test('handleCliCommand handles visibility and utility command dispatches', () =>
|
|||||||
expected: 'startPendingMineSentenceMultiple:2500',
|
expected: 'startPendingMineSentenceMultiple:2500',
|
||||||
},
|
},
|
||||||
{ args: { toggleSecondarySub: true }, expected: 'cycleSecondarySubMode' },
|
{ args: { toggleSecondarySub: true }, expected: 'cycleSecondarySubMode' },
|
||||||
{ args: { toggleStatsOverlay: true }, expected: 'dispatchSessionAction' },
|
|
||||||
{
|
{
|
||||||
args: { openRuntimeOptions: true },
|
args: { openRuntimeOptions: true },
|
||||||
expected: 'openRuntimeOptionsPalette',
|
expected: 'openRuntimeOptionsPalette',
|
||||||
@@ -536,33 +518,6 @@ test('handleCliCommand handles visibility and utility command dispatches', () =>
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('handleCliCommand dispatches cycle-runtime-option session action', async () => {
|
|
||||||
let request: unknown = null;
|
|
||||||
const { deps } = createDeps({
|
|
||||||
dispatchSessionAction: async (nextRequest) => {
|
|
||||||
request = nextRequest;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
handleCliCommand(
|
|
||||||
makeArgs({
|
|
||||||
cycleRuntimeOptionId: 'anki.autoUpdateNewCards',
|
|
||||||
cycleRuntimeOptionDirection: -1,
|
|
||||||
}),
|
|
||||||
'initial',
|
|
||||||
deps,
|
|
||||||
);
|
|
||||||
await new Promise((resolve) => setImmediate(resolve));
|
|
||||||
|
|
||||||
assert.deepEqual(request, {
|
|
||||||
actionId: 'cycleRuntimeOption',
|
|
||||||
payload: {
|
|
||||||
runtimeOptionId: 'anki.autoUpdateNewCards',
|
|
||||||
direction: -1,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('handleCliCommand logs AniList status details', () => {
|
test('handleCliCommand logs AniList status details', () => {
|
||||||
const { deps, calls } = createDeps();
|
const { deps, calls } = createDeps();
|
||||||
handleCliCommand(makeArgs({ anilistStatus: true }), 'initial', deps);
|
handleCliCommand(makeArgs({ anilistStatus: true }), 'initial', deps);
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { CliArgs, CliCommandSource, commandNeedsOverlayRuntime } from '../../cli/args';
|
import { CliArgs, CliCommandSource, commandNeedsOverlayRuntime } from '../../cli/args';
|
||||||
import type { SessionActionDispatchRequest } from '../../types/runtime';
|
|
||||||
|
|
||||||
export interface CliCommandServiceDeps {
|
export interface CliCommandServiceDeps {
|
||||||
setLogLevel?: (level: NonNullable<CliArgs['logLevel']>) => void;
|
setLogLevel?: (level: NonNullable<CliArgs['logLevel']>) => void;
|
||||||
@@ -33,7 +32,6 @@ export interface CliCommandServiceDeps {
|
|||||||
triggerSubsyncFromConfig: () => Promise<void>;
|
triggerSubsyncFromConfig: () => Promise<void>;
|
||||||
markLastCardAsAudioCard: () => Promise<void>;
|
markLastCardAsAudioCard: () => Promise<void>;
|
||||||
openRuntimeOptionsPalette: () => void;
|
openRuntimeOptionsPalette: () => void;
|
||||||
dispatchSessionAction: (request: SessionActionDispatchRequest) => Promise<void>;
|
|
||||||
getAnilistStatus: () => {
|
getAnilistStatus: () => {
|
||||||
tokenStatus: 'not_checked' | 'resolved' | 'error';
|
tokenStatus: 'not_checked' | 'resolved' | 'error';
|
||||||
tokenSource: 'none' | 'literal' | 'stored';
|
tokenSource: 'none' | 'literal' | 'stored';
|
||||||
@@ -170,7 +168,6 @@ export interface CliCommandDepsRuntimeOptions {
|
|||||||
};
|
};
|
||||||
ui: UiCliRuntime;
|
ui: UiCliRuntime;
|
||||||
app: AppCliRuntime;
|
app: AppCliRuntime;
|
||||||
dispatchSessionAction: (request: SessionActionDispatchRequest) => Promise<void>;
|
|
||||||
getMultiCopyTimeoutMs: () => number;
|
getMultiCopyTimeoutMs: () => number;
|
||||||
schedule: (fn: () => void, delayMs: number) => unknown;
|
schedule: (fn: () => void, delayMs: number) => unknown;
|
||||||
log: (message: string) => void;
|
log: (message: string) => void;
|
||||||
@@ -229,7 +226,6 @@ export function createCliCommandDepsRuntime(
|
|||||||
triggerSubsyncFromConfig: options.mining.triggerSubsyncFromConfig,
|
triggerSubsyncFromConfig: options.mining.triggerSubsyncFromConfig,
|
||||||
markLastCardAsAudioCard: options.mining.markLastCardAsAudioCard,
|
markLastCardAsAudioCard: options.mining.markLastCardAsAudioCard,
|
||||||
openRuntimeOptionsPalette: options.ui.openRuntimeOptionsPalette,
|
openRuntimeOptionsPalette: options.ui.openRuntimeOptionsPalette,
|
||||||
dispatchSessionAction: options.dispatchSessionAction,
|
|
||||||
getAnilistStatus: options.anilist.getStatus,
|
getAnilistStatus: options.anilist.getStatus,
|
||||||
clearAnilistToken: options.anilist.clearToken,
|
clearAnilistToken: options.anilist.clearToken,
|
||||||
openAnilistSetup: options.anilist.openSetup,
|
openAnilistSetup: options.anilist.openSetup,
|
||||||
@@ -272,19 +268,6 @@ export function handleCliCommand(
|
|||||||
source: CliCommandSource = 'initial',
|
source: CliCommandSource = 'initial',
|
||||||
deps: CliCommandServiceDeps,
|
deps: CliCommandServiceDeps,
|
||||||
): void {
|
): void {
|
||||||
const dispatchCliSessionAction = (
|
|
||||||
request: SessionActionDispatchRequest,
|
|
||||||
logLabel: string,
|
|
||||||
osdLabel: string,
|
|
||||||
): void => {
|
|
||||||
runAsyncWithOsd(
|
|
||||||
() => deps.dispatchSessionAction?.(request) ?? Promise.resolve(),
|
|
||||||
deps,
|
|
||||||
logLabel,
|
|
||||||
osdLabel,
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (args.logLevel) {
|
if (args.logLevel) {
|
||||||
deps.setLogLevel?.(args.logLevel);
|
deps.setLogLevel?.(args.logLevel);
|
||||||
}
|
}
|
||||||
@@ -396,100 +379,8 @@ export function handleCliCommand(
|
|||||||
'markLastCardAsAudioCard',
|
'markLastCardAsAudioCard',
|
||||||
'Audio card failed',
|
'Audio card failed',
|
||||||
);
|
);
|
||||||
} else if (args.toggleStatsOverlay) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'toggleStatsOverlay' },
|
|
||||||
'toggleStatsOverlay',
|
|
||||||
'Stats toggle failed',
|
|
||||||
);
|
|
||||||
} else if (args.toggleSubtitleSidebar) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'toggleSubtitleSidebar' },
|
|
||||||
'toggleSubtitleSidebar',
|
|
||||||
'Subtitle sidebar toggle failed',
|
|
||||||
);
|
|
||||||
} else if (args.openRuntimeOptions) {
|
} else if (args.openRuntimeOptions) {
|
||||||
deps.openRuntimeOptionsPalette();
|
deps.openRuntimeOptionsPalette();
|
||||||
} else if (args.openSessionHelp) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'openSessionHelp' },
|
|
||||||
'openSessionHelp',
|
|
||||||
'Open session help failed',
|
|
||||||
);
|
|
||||||
} else if (args.openControllerSelect) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'openControllerSelect' },
|
|
||||||
'openControllerSelect',
|
|
||||||
'Open controller select failed',
|
|
||||||
);
|
|
||||||
} else if (args.openControllerDebug) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'openControllerDebug' },
|
|
||||||
'openControllerDebug',
|
|
||||||
'Open controller debug failed',
|
|
||||||
);
|
|
||||||
} else if (args.openJimaku) {
|
|
||||||
dispatchCliSessionAction({ actionId: 'openJimaku' }, 'openJimaku', 'Open jimaku failed');
|
|
||||||
} else if (args.openYoutubePicker) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'openYoutubePicker' },
|
|
||||||
'openYoutubePicker',
|
|
||||||
'Open YouTube picker failed',
|
|
||||||
);
|
|
||||||
} else if (args.openPlaylistBrowser) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'openPlaylistBrowser' },
|
|
||||||
'openPlaylistBrowser',
|
|
||||||
'Open playlist browser failed',
|
|
||||||
);
|
|
||||||
} else if (args.replayCurrentSubtitle) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'replayCurrentSubtitle' },
|
|
||||||
'replayCurrentSubtitle',
|
|
||||||
'Replay subtitle failed',
|
|
||||||
);
|
|
||||||
} else if (args.playNextSubtitle) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'playNextSubtitle' },
|
|
||||||
'playNextSubtitle',
|
|
||||||
'Play next subtitle failed',
|
|
||||||
);
|
|
||||||
} else if (args.shiftSubDelayPrevLine) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'shiftSubDelayPrevLine' },
|
|
||||||
'shiftSubDelayPrevLine',
|
|
||||||
'Shift subtitle delay failed',
|
|
||||||
);
|
|
||||||
} else if (args.shiftSubDelayNextLine) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'shiftSubDelayNextLine' },
|
|
||||||
'shiftSubDelayNextLine',
|
|
||||||
'Shift subtitle delay failed',
|
|
||||||
);
|
|
||||||
} else if (args.cycleRuntimeOptionId !== undefined) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{
|
|
||||||
actionId: 'cycleRuntimeOption',
|
|
||||||
payload: {
|
|
||||||
runtimeOptionId: args.cycleRuntimeOptionId,
|
|
||||||
direction: args.cycleRuntimeOptionDirection ?? 1,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
'cycleRuntimeOption',
|
|
||||||
'Runtime option change failed',
|
|
||||||
);
|
|
||||||
} else if (args.copySubtitleCount !== undefined) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'copySubtitleMultiple', payload: { count: args.copySubtitleCount } },
|
|
||||||
'copySubtitleMultiple',
|
|
||||||
'Copy failed',
|
|
||||||
);
|
|
||||||
} else if (args.mineSentenceCount !== undefined) {
|
|
||||||
dispatchCliSessionAction(
|
|
||||||
{ actionId: 'mineSentenceMultiple', payload: { count: args.mineSentenceCount } },
|
|
||||||
'mineSentenceMultiple',
|
|
||||||
'Mine sentence failed',
|
|
||||||
);
|
|
||||||
} else if (args.anilistStatus) {
|
} else if (args.anilistStatus) {
|
||||||
const status = deps.getAnilistStatus();
|
const status = deps.getAnilistStatus();
|
||||||
deps.log(`AniList token status: ${status.tokenStatus} (source=${status.tokenSource})`);
|
deps.log(`AniList token status: ${status.tokenStatus} (source=${status.tokenSource})`);
|
||||||
|
|||||||
@@ -3,11 +3,7 @@ import assert from 'node:assert/strict';
|
|||||||
|
|
||||||
import { createIpcDepsRuntime, registerIpcHandlers, type IpcServiceDeps } from './ipc';
|
import { createIpcDepsRuntime, registerIpcHandlers, type IpcServiceDeps } from './ipc';
|
||||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
||||||
import type {
|
import type { PlaylistBrowserSnapshot, SubtitleSidebarSnapshot } from '../../types';
|
||||||
PlaylistBrowserSnapshot,
|
|
||||||
SessionActionDispatchRequest,
|
|
||||||
SubtitleSidebarSnapshot,
|
|
||||||
} from '../../types';
|
|
||||||
|
|
||||||
interface FakeIpcRegistrar {
|
interface FakeIpcRegistrar {
|
||||||
on: Map<string, (event: unknown, ...args: unknown[]) => void>;
|
on: Map<string, (event: unknown, ...args: unknown[]) => void>;
|
||||||
@@ -131,9 +127,7 @@ function createRegisterIpcDeps(overrides: Partial<IpcServiceDeps> = {}): IpcServ
|
|||||||
setMecabEnabled: () => {},
|
setMecabEnabled: () => {},
|
||||||
handleMpvCommand: () => {},
|
handleMpvCommand: () => {},
|
||||||
getKeybindings: () => [],
|
getKeybindings: () => [],
|
||||||
getSessionBindings: () => [],
|
|
||||||
getConfiguredShortcuts: () => ({}),
|
getConfiguredShortcuts: () => ({}),
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getStatsToggleKey: () => 'Backquote',
|
getStatsToggleKey: () => 'Backquote',
|
||||||
getMarkWatchedKey: () => 'KeyW',
|
getMarkWatchedKey: () => 'KeyW',
|
||||||
getControllerConfig: () => createControllerConfigFixture(),
|
getControllerConfig: () => createControllerConfigFixture(),
|
||||||
@@ -232,9 +226,7 @@ test('createIpcDepsRuntime wires AniList handlers', async () => {
|
|||||||
getMecabTokenizer: () => null,
|
getMecabTokenizer: () => null,
|
||||||
handleMpvCommand: () => {},
|
handleMpvCommand: () => {},
|
||||||
getKeybindings: () => [],
|
getKeybindings: () => [],
|
||||||
getSessionBindings: () => [],
|
|
||||||
getConfiguredShortcuts: () => ({}),
|
getConfiguredShortcuts: () => ({}),
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getStatsToggleKey: () => 'Backquote',
|
getStatsToggleKey: () => 'Backquote',
|
||||||
getMarkWatchedKey: () => 'KeyW',
|
getMarkWatchedKey: () => 'KeyW',
|
||||||
getControllerConfig: () => createControllerConfigFixture(),
|
getControllerConfig: () => createControllerConfigFixture(),
|
||||||
@@ -390,9 +382,7 @@ test('registerIpcHandlers rejects malformed runtime-option payloads', async () =
|
|||||||
setMecabEnabled: () => {},
|
setMecabEnabled: () => {},
|
||||||
handleMpvCommand: () => {},
|
handleMpvCommand: () => {},
|
||||||
getKeybindings: () => [],
|
getKeybindings: () => [],
|
||||||
getSessionBindings: () => [],
|
|
||||||
getConfiguredShortcuts: () => ({}),
|
getConfiguredShortcuts: () => ({}),
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getStatsToggleKey: () => 'Backquote',
|
getStatsToggleKey: () => 'Backquote',
|
||||||
getMarkWatchedKey: () => 'KeyW',
|
getMarkWatchedKey: () => 'KeyW',
|
||||||
getControllerConfig: () => createControllerConfigFixture(),
|
getControllerConfig: () => createControllerConfigFixture(),
|
||||||
@@ -717,9 +707,7 @@ test('registerIpcHandlers ignores malformed fire-and-forget payloads', () => {
|
|||||||
setMecabEnabled: () => {},
|
setMecabEnabled: () => {},
|
||||||
handleMpvCommand: () => {},
|
handleMpvCommand: () => {},
|
||||||
getKeybindings: () => [],
|
getKeybindings: () => [],
|
||||||
getSessionBindings: () => [],
|
|
||||||
getConfiguredShortcuts: () => ({}),
|
getConfiguredShortcuts: () => ({}),
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getStatsToggleKey: () => 'Backquote',
|
getStatsToggleKey: () => 'Backquote',
|
||||||
getMarkWatchedKey: () => 'KeyW',
|
getMarkWatchedKey: () => 'KeyW',
|
||||||
getControllerConfig: () => createControllerConfigFixture(),
|
getControllerConfig: () => createControllerConfigFixture(),
|
||||||
@@ -798,9 +786,7 @@ test('registerIpcHandlers awaits saveControllerPreference through request-respon
|
|||||||
setMecabEnabled: () => {},
|
setMecabEnabled: () => {},
|
||||||
handleMpvCommand: () => {},
|
handleMpvCommand: () => {},
|
||||||
getKeybindings: () => [],
|
getKeybindings: () => [],
|
||||||
getSessionBindings: () => [],
|
|
||||||
getConfiguredShortcuts: () => ({}),
|
getConfiguredShortcuts: () => ({}),
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getStatsToggleKey: () => 'Backquote',
|
getStatsToggleKey: () => 'Backquote',
|
||||||
getMarkWatchedKey: () => 'KeyW',
|
getMarkWatchedKey: () => 'KeyW',
|
||||||
getControllerConfig: () => createControllerConfigFixture(),
|
getControllerConfig: () => createControllerConfigFixture(),
|
||||||
@@ -864,55 +850,6 @@ test('registerIpcHandlers awaits saveControllerPreference through request-respon
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('registerIpcHandlers validates dispatchSessionAction payloads', async () => {
|
|
||||||
const { registrar, handlers } = createFakeIpcRegistrar();
|
|
||||||
const dispatched: SessionActionDispatchRequest[] = [];
|
|
||||||
registerIpcHandlers(
|
|
||||||
createRegisterIpcDeps({
|
|
||||||
dispatchSessionAction: async (request) => {
|
|
||||||
dispatched.push(request);
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
registrar,
|
|
||||||
);
|
|
||||||
|
|
||||||
const dispatchHandler = handlers.handle.get(IPC_CHANNELS.command.dispatchSessionAction);
|
|
||||||
assert.ok(dispatchHandler);
|
|
||||||
|
|
||||||
await assert.rejects(async () => {
|
|
||||||
await dispatchHandler!({}, { actionId: 'cycleRuntimeOption', payload: { direction: 1 } });
|
|
||||||
}, /Invalid session action payload/);
|
|
||||||
await assert.rejects(async () => {
|
|
||||||
await dispatchHandler!({}, { actionId: 'unknown-action' });
|
|
||||||
}, /Invalid session action payload/);
|
|
||||||
|
|
||||||
await dispatchHandler!({}, {
|
|
||||||
actionId: 'copySubtitleMultiple',
|
|
||||||
payload: { count: 3 },
|
|
||||||
});
|
|
||||||
await dispatchHandler!({}, {
|
|
||||||
actionId: 'cycleRuntimeOption',
|
|
||||||
payload: {
|
|
||||||
runtimeOptionId: 'anki.autoUpdateNewCards',
|
|
||||||
direction: -1,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(dispatched, [
|
|
||||||
{
|
|
||||||
actionId: 'copySubtitleMultiple',
|
|
||||||
payload: { count: 3 },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
actionId: 'cycleRuntimeOption',
|
|
||||||
payload: {
|
|
||||||
runtimeOptionId: 'anki.autoUpdateNewCards',
|
|
||||||
direction: -1,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('registerIpcHandlers rejects malformed controller preference payloads', async () => {
|
test('registerIpcHandlers rejects malformed controller preference payloads', async () => {
|
||||||
const { registrar, handlers } = createFakeIpcRegistrar();
|
const { registrar, handlers } = createFakeIpcRegistrar();
|
||||||
registerIpcHandlers(
|
registerIpcHandlers(
|
||||||
@@ -935,9 +872,7 @@ test('registerIpcHandlers rejects malformed controller preference payloads', asy
|
|||||||
setMecabEnabled: () => {},
|
setMecabEnabled: () => {},
|
||||||
handleMpvCommand: () => {},
|
handleMpvCommand: () => {},
|
||||||
getKeybindings: () => [],
|
getKeybindings: () => [],
|
||||||
getSessionBindings: () => [],
|
|
||||||
getConfiguredShortcuts: () => ({}),
|
getConfiguredShortcuts: () => ({}),
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getStatsToggleKey: () => 'Backquote',
|
getStatsToggleKey: () => 'Backquote',
|
||||||
getMarkWatchedKey: () => 'KeyW',
|
getMarkWatchedKey: () => 'KeyW',
|
||||||
getControllerConfig: () => createControllerConfigFixture(),
|
getControllerConfig: () => createControllerConfigFixture(),
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import electron from 'electron';
|
import electron from 'electron';
|
||||||
import type { BrowserWindow as ElectronBrowserWindow, IpcMainEvent } from 'electron';
|
import type { IpcMainEvent } from 'electron';
|
||||||
import type {
|
import type {
|
||||||
CompiledSessionBinding,
|
|
||||||
ControllerConfigUpdate,
|
ControllerConfigUpdate,
|
||||||
PlaylistBrowserMutationResult,
|
PlaylistBrowserMutationResult,
|
||||||
PlaylistBrowserSnapshot,
|
PlaylistBrowserSnapshot,
|
||||||
@@ -13,7 +12,6 @@ import type {
|
|||||||
SubtitlePosition,
|
SubtitlePosition,
|
||||||
SubsyncManualRunRequest,
|
SubsyncManualRunRequest,
|
||||||
SubsyncResult,
|
SubsyncResult,
|
||||||
SessionActionDispatchRequest,
|
|
||||||
YoutubePickerResolveRequest,
|
YoutubePickerResolveRequest,
|
||||||
YoutubePickerResolveResult,
|
YoutubePickerResolveResult,
|
||||||
} from '../../types';
|
} from '../../types';
|
||||||
@@ -27,23 +25,16 @@ import {
|
|||||||
parseRuntimeOptionDirection,
|
parseRuntimeOptionDirection,
|
||||||
parseRuntimeOptionId,
|
parseRuntimeOptionId,
|
||||||
parseRuntimeOptionValue,
|
parseRuntimeOptionValue,
|
||||||
parseSessionActionDispatchRequest,
|
|
||||||
parseSubtitlePosition,
|
parseSubtitlePosition,
|
||||||
parseSubsyncManualRunRequest,
|
parseSubsyncManualRunRequest,
|
||||||
parseYoutubePickerResolveRequest,
|
parseYoutubePickerResolveRequest,
|
||||||
} from '../../shared/ipc/validators';
|
} from '../../shared/ipc/validators';
|
||||||
|
|
||||||
const { ipcMain } = electron;
|
const { BrowserWindow, ipcMain } = electron;
|
||||||
|
|
||||||
export interface IpcServiceDeps {
|
export interface IpcServiceDeps {
|
||||||
onOverlayModalClosed: (
|
onOverlayModalClosed: (modal: OverlayHostedModal) => void;
|
||||||
modal: OverlayHostedModal,
|
onOverlayModalOpened?: (modal: OverlayHostedModal) => void;
|
||||||
senderWindow: ElectronBrowserWindow | null,
|
|
||||||
) => void;
|
|
||||||
onOverlayModalOpened?: (
|
|
||||||
modal: OverlayHostedModal,
|
|
||||||
senderWindow: ElectronBrowserWindow | null,
|
|
||||||
) => void;
|
|
||||||
openYomitanSettings: () => void;
|
openYomitanSettings: () => void;
|
||||||
quitApp: () => void;
|
quitApp: () => void;
|
||||||
toggleDevTools: () => void;
|
toggleDevTools: () => void;
|
||||||
@@ -65,9 +56,7 @@ export interface IpcServiceDeps {
|
|||||||
setMecabEnabled: (enabled: boolean) => void;
|
setMecabEnabled: (enabled: boolean) => void;
|
||||||
handleMpvCommand: (command: Array<string | number>) => void;
|
handleMpvCommand: (command: Array<string | number>) => void;
|
||||||
getKeybindings: () => unknown;
|
getKeybindings: () => unknown;
|
||||||
getSessionBindings?: () => CompiledSessionBinding[];
|
|
||||||
getConfiguredShortcuts: () => unknown;
|
getConfiguredShortcuts: () => unknown;
|
||||||
dispatchSessionAction?: (request: SessionActionDispatchRequest) => void | Promise<void>;
|
|
||||||
getStatsToggleKey: () => string;
|
getStatsToggleKey: () => string;
|
||||||
getMarkWatchedKey: () => string;
|
getMarkWatchedKey: () => string;
|
||||||
getControllerConfig: () => ResolvedControllerConfig;
|
getControllerConfig: () => ResolvedControllerConfig;
|
||||||
@@ -164,14 +153,8 @@ interface IpcMainRegistrar {
|
|||||||
export interface IpcDepsRuntimeOptions {
|
export interface IpcDepsRuntimeOptions {
|
||||||
getMainWindow: () => WindowLike | null;
|
getMainWindow: () => WindowLike | null;
|
||||||
getVisibleOverlayVisibility: () => boolean;
|
getVisibleOverlayVisibility: () => boolean;
|
||||||
onOverlayModalClosed: (
|
onOverlayModalClosed: (modal: OverlayHostedModal) => void;
|
||||||
modal: OverlayHostedModal,
|
onOverlayModalOpened?: (modal: OverlayHostedModal) => void;
|
||||||
senderWindow: ElectronBrowserWindow | null,
|
|
||||||
) => void;
|
|
||||||
onOverlayModalOpened?: (
|
|
||||||
modal: OverlayHostedModal,
|
|
||||||
senderWindow: ElectronBrowserWindow | null,
|
|
||||||
) => void;
|
|
||||||
openYomitanSettings: () => void;
|
openYomitanSettings: () => void;
|
||||||
quitApp: () => void;
|
quitApp: () => void;
|
||||||
toggleVisibleOverlay: () => void;
|
toggleVisibleOverlay: () => void;
|
||||||
@@ -186,9 +169,7 @@ export interface IpcDepsRuntimeOptions {
|
|||||||
getMecabTokenizer: () => MecabTokenizerLike | null;
|
getMecabTokenizer: () => MecabTokenizerLike | null;
|
||||||
handleMpvCommand: (command: Array<string | number>) => void;
|
handleMpvCommand: (command: Array<string | number>) => void;
|
||||||
getKeybindings: () => unknown;
|
getKeybindings: () => unknown;
|
||||||
getSessionBindings?: () => CompiledSessionBinding[];
|
|
||||||
getConfiguredShortcuts: () => unknown;
|
getConfiguredShortcuts: () => unknown;
|
||||||
dispatchSessionAction?: (request: SessionActionDispatchRequest) => void | Promise<void>;
|
|
||||||
getStatsToggleKey: () => string;
|
getStatsToggleKey: () => string;
|
||||||
getMarkWatchedKey: () => string;
|
getMarkWatchedKey: () => string;
|
||||||
getControllerConfig: () => ResolvedControllerConfig;
|
getControllerConfig: () => ResolvedControllerConfig;
|
||||||
@@ -257,9 +238,7 @@ export function createIpcDepsRuntime(options: IpcDepsRuntimeOptions): IpcService
|
|||||||
},
|
},
|
||||||
handleMpvCommand: options.handleMpvCommand,
|
handleMpvCommand: options.handleMpvCommand,
|
||||||
getKeybindings: options.getKeybindings,
|
getKeybindings: options.getKeybindings,
|
||||||
getSessionBindings: options.getSessionBindings ?? (() => []),
|
|
||||||
getConfiguredShortcuts: options.getConfiguredShortcuts,
|
getConfiguredShortcuts: options.getConfiguredShortcuts,
|
||||||
dispatchSessionAction: options.dispatchSessionAction ?? (async () => {}),
|
|
||||||
getStatsToggleKey: options.getStatsToggleKey,
|
getStatsToggleKey: options.getStatsToggleKey,
|
||||||
getMarkWatchedKey: options.getMarkWatchedKey,
|
getMarkWatchedKey: options.getMarkWatchedKey,
|
||||||
getControllerConfig: options.getControllerConfig,
|
getControllerConfig: options.getControllerConfig,
|
||||||
@@ -320,28 +299,23 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
|
|||||||
(event: unknown, ignore: unknown, options: unknown = {}) => {
|
(event: unknown, ignore: unknown, options: unknown = {}) => {
|
||||||
if (typeof ignore !== 'boolean') return;
|
if (typeof ignore !== 'boolean') return;
|
||||||
const parsedOptions = parseOptionalForwardingOptions(options);
|
const parsedOptions = parseOptionalForwardingOptions(options);
|
||||||
const senderWindow =
|
const senderWindow = BrowserWindow.fromWebContents((event as IpcMainEvent).sender);
|
||||||
electron.BrowserWindow?.fromWebContents((event as IpcMainEvent).sender) ?? null;
|
|
||||||
if (senderWindow && !senderWindow.isDestroyed()) {
|
if (senderWindow && !senderWindow.isDestroyed()) {
|
||||||
senderWindow.setIgnoreMouseEvents(ignore, parsedOptions);
|
senderWindow.setIgnoreMouseEvents(ignore, parsedOptions);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
ipc.on(IPC_CHANNELS.command.overlayModalClosed, (event: unknown, modal: unknown) => {
|
ipc.on(IPC_CHANNELS.command.overlayModalClosed, (_event: unknown, modal: unknown) => {
|
||||||
const parsedModal = parseOverlayHostedModal(modal);
|
const parsedModal = parseOverlayHostedModal(modal);
|
||||||
if (!parsedModal) return;
|
if (!parsedModal) return;
|
||||||
const senderWindow =
|
deps.onOverlayModalClosed(parsedModal);
|
||||||
electron.BrowserWindow?.fromWebContents((event as IpcMainEvent).sender) ?? null;
|
|
||||||
deps.onOverlayModalClosed(parsedModal, senderWindow);
|
|
||||||
});
|
});
|
||||||
ipc.on(IPC_CHANNELS.command.overlayModalOpened, (event: unknown, modal: unknown) => {
|
ipc.on(IPC_CHANNELS.command.overlayModalOpened, (_event: unknown, modal: unknown) => {
|
||||||
const parsedModal = parseOverlayHostedModal(modal);
|
const parsedModal = parseOverlayHostedModal(modal);
|
||||||
if (!parsedModal) return;
|
if (!parsedModal) return;
|
||||||
if (!deps.onOverlayModalOpened) return;
|
if (!deps.onOverlayModalOpened) return;
|
||||||
const senderWindow =
|
deps.onOverlayModalOpened(parsedModal);
|
||||||
electron.BrowserWindow?.fromWebContents((event as IpcMainEvent).sender) ?? null;
|
|
||||||
deps.onOverlayModalOpened(parsedModal, senderWindow);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
ipc.handle(
|
ipc.handle(
|
||||||
@@ -457,25 +431,10 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
|
|||||||
deps.handleMpvCommand(parsedCommand);
|
deps.handleMpvCommand(parsedCommand);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipc.handle(
|
|
||||||
IPC_CHANNELS.command.dispatchSessionAction,
|
|
||||||
async (_event: unknown, request: unknown) => {
|
|
||||||
const parsedRequest = parseSessionActionDispatchRequest(request);
|
|
||||||
if (!parsedRequest) {
|
|
||||||
throw new Error('Invalid session action payload');
|
|
||||||
}
|
|
||||||
await deps.dispatchSessionAction?.(parsedRequest);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
ipc.handle(IPC_CHANNELS.request.getKeybindings, () => {
|
ipc.handle(IPC_CHANNELS.request.getKeybindings, () => {
|
||||||
return deps.getKeybindings();
|
return deps.getKeybindings();
|
||||||
});
|
});
|
||||||
|
|
||||||
ipc.handle(IPC_CHANNELS.request.getSessionBindings, () => {
|
|
||||||
return deps.getSessionBindings?.() ?? [];
|
|
||||||
});
|
|
||||||
|
|
||||||
ipc.handle(IPC_CHANNELS.request.getConfigShortcuts, () => {
|
ipc.handle(IPC_CHANNELS.request.getConfigShortcuts, () => {
|
||||||
return deps.getConfiguredShortcuts();
|
return deps.getConfiguredShortcuts();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,23 @@ import assert from 'node:assert/strict';
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import { initializeOverlayAnkiIntegration, initializeOverlayRuntime } from './overlay-runtime-init';
|
import { initializeOverlayAnkiIntegration, initializeOverlayRuntime } from './overlay-runtime-init';
|
||||||
|
|
||||||
|
function withPlatform(platform: NodeJS.Platform, run: () => void): void {
|
||||||
|
const originalPlatform = process.platform;
|
||||||
|
Object.defineProperty(process, 'platform', {
|
||||||
|
value: platform,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
run();
|
||||||
|
} finally {
|
||||||
|
Object.defineProperty(process, 'platform', {
|
||||||
|
value: originalPlatform,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
test('initializeOverlayRuntime skips Anki integration when ankiConnect.enabled is false', () => {
|
test('initializeOverlayRuntime skips Anki integration when ankiConnect.enabled is false', () => {
|
||||||
let createdIntegrations = 0;
|
let createdIntegrations = 0;
|
||||||
let startedIntegrations = 0;
|
let startedIntegrations = 0;
|
||||||
@@ -547,7 +564,8 @@ test('initializeOverlayRuntime hides overlay windows when tracker loses the targ
|
|||||||
assert.deepEqual(calls, ['hide-visible', 'hide-modal', 'sync-shortcuts']);
|
assert.deepEqual(calls, ['hide-visible', 'hide-modal', 'sync-shortcuts']);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('initializeOverlayRuntime hides visible overlay on Windows tracker loss when target is not minimized', () => {
|
test('initializeOverlayRuntime preserves visible overlay on Windows tracker loss when target is not minimized', () => {
|
||||||
|
withPlatform('win32', () => {
|
||||||
const calls: string[] = [];
|
const calls: string[] = [];
|
||||||
const tracker = {
|
const tracker = {
|
||||||
onGeometryChange: null as ((...args: unknown[]) => void) | null,
|
onGeometryChange: null as ((...args: unknown[]) => void) | null,
|
||||||
@@ -600,7 +618,8 @@ test('initializeOverlayRuntime hides visible overlay on Windows tracker loss whe
|
|||||||
calls.length = 0;
|
calls.length = 0;
|
||||||
tracker.onWindowLost?.();
|
tracker.onWindowLost?.();
|
||||||
|
|
||||||
assert.deepEqual(calls, ['hide-visible', 'sync-shortcuts']);
|
assert.deepEqual(calls, ['sync-shortcuts']);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test('initializeOverlayRuntime restores overlay bounds and visibility when tracker finds the target window again', () => {
|
test('initializeOverlayRuntime restores overlay bounds and visibility when tracker finds the target window again', () => {
|
||||||
|
|||||||
@@ -105,6 +105,15 @@ export function initializeOverlayRuntime(options: {
|
|||||||
};
|
};
|
||||||
windowTracker.onWindowLost = () => {
|
windowTracker.onWindowLost = () => {
|
||||||
options.releaseOverlayOwner?.();
|
options.releaseOverlayOwner?.();
|
||||||
|
if (
|
||||||
|
process.platform === 'win32' &&
|
||||||
|
typeof windowTracker.isTargetWindowMinimized === 'function' &&
|
||||||
|
!windowTracker.isTargetWindowMinimized()
|
||||||
|
) {
|
||||||
|
options.syncOverlayShortcuts();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
for (const window of options.getOverlayWindows()) {
|
for (const window of options.getOverlayWindows()) {
|
||||||
window.hide();
|
window.hide();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,11 +6,7 @@ import {
|
|||||||
OverlayShortcutRuntimeDeps,
|
OverlayShortcutRuntimeDeps,
|
||||||
runOverlayShortcutLocalFallback,
|
runOverlayShortcutLocalFallback,
|
||||||
} from './overlay-shortcut-handler';
|
} from './overlay-shortcut-handler';
|
||||||
import {
|
import { shouldActivateOverlayShortcuts } from './overlay-shortcut';
|
||||||
registerOverlayShortcutsRuntime,
|
|
||||||
shouldActivateOverlayShortcuts,
|
|
||||||
unregisterOverlayShortcutsRuntime,
|
|
||||||
} from './overlay-shortcut';
|
|
||||||
|
|
||||||
function makeShortcuts(overrides: Partial<ConfiguredShortcuts> = {}): ConfiguredShortcuts {
|
function makeShortcuts(overrides: Partial<ConfiguredShortcuts> = {}): ConfiguredShortcuts {
|
||||||
return {
|
return {
|
||||||
@@ -27,10 +23,6 @@ function makeShortcuts(overrides: Partial<ConfiguredShortcuts> = {}): Configured
|
|||||||
markAudioCard: null,
|
markAudioCard: null,
|
||||||
openRuntimeOptions: null,
|
openRuntimeOptions: null,
|
||||||
openJimaku: null,
|
openJimaku: null,
|
||||||
openSessionHelp: null,
|
|
||||||
openControllerSelect: null,
|
|
||||||
openControllerDebug: null,
|
|
||||||
toggleSubtitleSidebar: null,
|
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -321,59 +313,3 @@ test('shouldActivateOverlayShortcuts preserves non-macOS behavior', () => {
|
|||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('registerOverlayShortcutsRuntime reports active shortcuts when configured', () => {
|
|
||||||
const deps = {
|
|
||||||
getConfiguredShortcuts: () => makeShortcuts({ openJimaku: 'Ctrl+J' }),
|
|
||||||
getOverlayHandlers: () => ({
|
|
||||||
copySubtitle: () => {},
|
|
||||||
copySubtitleMultiple: () => {},
|
|
||||||
updateLastCardFromClipboard: () => {},
|
|
||||||
triggerFieldGrouping: () => {},
|
|
||||||
triggerSubsync: () => {},
|
|
||||||
mineSentence: () => {},
|
|
||||||
mineSentenceMultiple: () => {},
|
|
||||||
toggleSecondarySub: () => {},
|
|
||||||
markAudioCard: () => {},
|
|
||||||
openRuntimeOptions: () => {},
|
|
||||||
openJimaku: () => {},
|
|
||||||
}),
|
|
||||||
cancelPendingMultiCopy: () => {},
|
|
||||||
cancelPendingMineSentenceMultiple: () => {},
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = registerOverlayShortcutsRuntime(deps);
|
|
||||||
assert.equal(result, true);
|
|
||||||
assert.equal(unregisterOverlayShortcutsRuntime(result, deps), false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('unregisterOverlayShortcutsRuntime clears pending shortcut work when active', () => {
|
|
||||||
const calls: string[] = [];
|
|
||||||
const deps = {
|
|
||||||
getConfiguredShortcuts: () => makeShortcuts({ openJimaku: 'Ctrl+J' }),
|
|
||||||
getOverlayHandlers: () => ({
|
|
||||||
copySubtitle: () => {},
|
|
||||||
copySubtitleMultiple: () => {},
|
|
||||||
updateLastCardFromClipboard: () => {},
|
|
||||||
triggerFieldGrouping: () => {},
|
|
||||||
triggerSubsync: () => {},
|
|
||||||
mineSentence: () => {},
|
|
||||||
mineSentenceMultiple: () => {},
|
|
||||||
toggleSecondarySub: () => {},
|
|
||||||
markAudioCard: () => {},
|
|
||||||
openRuntimeOptions: () => {},
|
|
||||||
openJimaku: () => {},
|
|
||||||
}),
|
|
||||||
cancelPendingMultiCopy: () => {
|
|
||||||
calls.push('cancel-multi-copy');
|
|
||||||
},
|
|
||||||
cancelPendingMineSentenceMultiple: () => {
|
|
||||||
calls.push('cancel-mine-sentence-multiple');
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
assert.equal(registerOverlayShortcutsRuntime(deps), true);
|
|
||||||
const result = unregisterOverlayShortcutsRuntime(true, deps);
|
|
||||||
assert.equal(result, false);
|
|
||||||
assert.deepEqual(calls, ['cancel-multi-copy', 'cancel-mine-sentence-multiple']);
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import test from 'node:test';
|
|
||||||
import type { ConfiguredShortcuts } from '../utils/shortcut-config';
|
|
||||||
import {
|
|
||||||
registerOverlayShortcuts,
|
|
||||||
syncOverlayShortcutsRuntime,
|
|
||||||
unregisterOverlayShortcutsRuntime,
|
|
||||||
} from './overlay-shortcut';
|
|
||||||
|
|
||||||
function createShortcuts(overrides: Partial<ConfiguredShortcuts> = {}): ConfiguredShortcuts {
|
|
||||||
return {
|
|
||||||
toggleVisibleOverlayGlobal: null,
|
|
||||||
copySubtitle: null,
|
|
||||||
copySubtitleMultiple: null,
|
|
||||||
updateLastCardFromClipboard: null,
|
|
||||||
triggerFieldGrouping: null,
|
|
||||||
triggerSubsync: null,
|
|
||||||
mineSentence: null,
|
|
||||||
mineSentenceMultiple: null,
|
|
||||||
multiCopyTimeoutMs: 2500,
|
|
||||||
toggleSecondarySub: null,
|
|
||||||
markAudioCard: null,
|
|
||||||
openRuntimeOptions: null,
|
|
||||||
openJimaku: null,
|
|
||||||
openSessionHelp: null,
|
|
||||||
openControllerSelect: null,
|
|
||||||
openControllerDebug: null,
|
|
||||||
toggleSubtitleSidebar: null,
|
|
||||||
...overrides,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
test('registerOverlayShortcuts reports active overlay shortcuts when configured', () => {
|
|
||||||
assert.equal(
|
|
||||||
registerOverlayShortcuts(createShortcuts({ openJimaku: 'Ctrl+J' }), {
|
|
||||||
copySubtitle: () => {},
|
|
||||||
copySubtitleMultiple: () => {},
|
|
||||||
updateLastCardFromClipboard: () => {},
|
|
||||||
triggerFieldGrouping: () => {},
|
|
||||||
triggerSubsync: () => {},
|
|
||||||
mineSentence: () => {},
|
|
||||||
mineSentenceMultiple: () => {},
|
|
||||||
toggleSecondarySub: () => {},
|
|
||||||
markAudioCard: () => {},
|
|
||||||
openRuntimeOptions: () => {},
|
|
||||||
openJimaku: () => {},
|
|
||||||
}),
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('registerOverlayShortcuts stays inactive when overlay shortcuts are absent', () => {
|
|
||||||
assert.equal(
|
|
||||||
registerOverlayShortcuts(createShortcuts(), {
|
|
||||||
copySubtitle: () => {},
|
|
||||||
copySubtitleMultiple: () => {},
|
|
||||||
updateLastCardFromClipboard: () => {},
|
|
||||||
triggerFieldGrouping: () => {},
|
|
||||||
triggerSubsync: () => {},
|
|
||||||
mineSentence: () => {},
|
|
||||||
mineSentenceMultiple: () => {},
|
|
||||||
toggleSecondarySub: () => {},
|
|
||||||
markAudioCard: () => {},
|
|
||||||
openRuntimeOptions: () => {},
|
|
||||||
openJimaku: () => {},
|
|
||||||
}),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('syncOverlayShortcutsRuntime deactivates cleanly when shortcuts were active', () => {
|
|
||||||
const calls: string[] = [];
|
|
||||||
const result = syncOverlayShortcutsRuntime(false, true, {
|
|
||||||
getConfiguredShortcuts: () => createShortcuts(),
|
|
||||||
getOverlayHandlers: () => ({
|
|
||||||
copySubtitle: () => {},
|
|
||||||
copySubtitleMultiple: () => {},
|
|
||||||
updateLastCardFromClipboard: () => {},
|
|
||||||
triggerFieldGrouping: () => {},
|
|
||||||
triggerSubsync: () => {},
|
|
||||||
mineSentence: () => {},
|
|
||||||
mineSentenceMultiple: () => {},
|
|
||||||
toggleSecondarySub: () => {},
|
|
||||||
markAudioCard: () => {},
|
|
||||||
openRuntimeOptions: () => {},
|
|
||||||
openJimaku: () => {},
|
|
||||||
}),
|
|
||||||
cancelPendingMultiCopy: () => {
|
|
||||||
calls.push('cancel-multi-copy');
|
|
||||||
},
|
|
||||||
cancelPendingMineSentenceMultiple: () => {
|
|
||||||
calls.push('cancel-mine-sentence-multiple');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(result, false);
|
|
||||||
assert.deepEqual(calls, ['cancel-multi-copy', 'cancel-mine-sentence-multiple']);
|
|
||||||
});
|
|
||||||
@@ -1,4 +1,10 @@
|
|||||||
|
import electron from 'electron';
|
||||||
import { ConfiguredShortcuts } from '../utils/shortcut-config';
|
import { ConfiguredShortcuts } from '../utils/shortcut-config';
|
||||||
|
import { isGlobalShortcutRegisteredSafe } from './shortcut-fallback';
|
||||||
|
import { createLogger } from '../../logger';
|
||||||
|
|
||||||
|
const { globalShortcut } = electron;
|
||||||
|
const logger = createLogger('main:overlay-shortcut-service');
|
||||||
|
|
||||||
export interface OverlayShortcutHandlers {
|
export interface OverlayShortcutHandlers {
|
||||||
copySubtitle: () => void;
|
copySubtitle: () => void;
|
||||||
@@ -21,27 +27,6 @@ export interface OverlayShortcutLifecycleDeps {
|
|||||||
cancelPendingMineSentenceMultiple: () => void;
|
cancelPendingMineSentenceMultiple: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const OVERLAY_SHORTCUT_KEYS: Array<keyof Omit<ConfiguredShortcuts, 'multiCopyTimeoutMs'>> = [
|
|
||||||
'copySubtitle',
|
|
||||||
'copySubtitleMultiple',
|
|
||||||
'updateLastCardFromClipboard',
|
|
||||||
'triggerFieldGrouping',
|
|
||||||
'triggerSubsync',
|
|
||||||
'mineSentence',
|
|
||||||
'mineSentenceMultiple',
|
|
||||||
'toggleSecondarySub',
|
|
||||||
'markAudioCard',
|
|
||||||
'openRuntimeOptions',
|
|
||||||
'openJimaku',
|
|
||||||
];
|
|
||||||
|
|
||||||
function hasConfiguredOverlayShortcuts(shortcuts: ConfiguredShortcuts): boolean {
|
|
||||||
return OVERLAY_SHORTCUT_KEYS.some((key) => {
|
|
||||||
const shortcut = shortcuts[key];
|
|
||||||
return typeof shortcut === 'string' && shortcut.trim().length > 0;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function shouldActivateOverlayShortcuts(args: {
|
export function shouldActivateOverlayShortcuts(args: {
|
||||||
overlayRuntimeInitialized: boolean;
|
overlayRuntimeInitialized: boolean;
|
||||||
isMacOSPlatform: boolean;
|
isMacOSPlatform: boolean;
|
||||||
@@ -58,12 +43,139 @@ export function shouldActivateOverlayShortcuts(args: {
|
|||||||
|
|
||||||
export function registerOverlayShortcuts(
|
export function registerOverlayShortcuts(
|
||||||
shortcuts: ConfiguredShortcuts,
|
shortcuts: ConfiguredShortcuts,
|
||||||
_handlers: OverlayShortcutHandlers,
|
handlers: OverlayShortcutHandlers,
|
||||||
): boolean {
|
): boolean {
|
||||||
return hasConfiguredOverlayShortcuts(shortcuts);
|
let registeredAny = false;
|
||||||
|
const registerOverlayShortcut = (
|
||||||
|
accelerator: string,
|
||||||
|
handler: () => void,
|
||||||
|
label: string,
|
||||||
|
): void => {
|
||||||
|
if (isGlobalShortcutRegisteredSafe(accelerator)) {
|
||||||
|
registeredAny = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const ok = globalShortcut.register(accelerator, handler);
|
||||||
|
if (!ok) {
|
||||||
|
logger.warn(`Failed to register overlay shortcut ${label}: ${accelerator}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
registeredAny = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (shortcuts.copySubtitleMultiple) {
|
||||||
|
registerOverlayShortcut(
|
||||||
|
shortcuts.copySubtitleMultiple,
|
||||||
|
() => handlers.copySubtitleMultiple(shortcuts.multiCopyTimeoutMs),
|
||||||
|
'copySubtitleMultiple',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function unregisterOverlayShortcuts(_shortcuts: ConfiguredShortcuts): void {}
|
if (shortcuts.copySubtitle) {
|
||||||
|
registerOverlayShortcut(shortcuts.copySubtitle, () => handlers.copySubtitle(), 'copySubtitle');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shortcuts.triggerFieldGrouping) {
|
||||||
|
registerOverlayShortcut(
|
||||||
|
shortcuts.triggerFieldGrouping,
|
||||||
|
() => handlers.triggerFieldGrouping(),
|
||||||
|
'triggerFieldGrouping',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shortcuts.triggerSubsync) {
|
||||||
|
registerOverlayShortcut(
|
||||||
|
shortcuts.triggerSubsync,
|
||||||
|
() => handlers.triggerSubsync(),
|
||||||
|
'triggerSubsync',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shortcuts.mineSentence) {
|
||||||
|
registerOverlayShortcut(shortcuts.mineSentence, () => handlers.mineSentence(), 'mineSentence');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shortcuts.mineSentenceMultiple) {
|
||||||
|
registerOverlayShortcut(
|
||||||
|
shortcuts.mineSentenceMultiple,
|
||||||
|
() => handlers.mineSentenceMultiple(shortcuts.multiCopyTimeoutMs),
|
||||||
|
'mineSentenceMultiple',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shortcuts.toggleSecondarySub) {
|
||||||
|
registerOverlayShortcut(
|
||||||
|
shortcuts.toggleSecondarySub,
|
||||||
|
() => handlers.toggleSecondarySub(),
|
||||||
|
'toggleSecondarySub',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shortcuts.updateLastCardFromClipboard) {
|
||||||
|
registerOverlayShortcut(
|
||||||
|
shortcuts.updateLastCardFromClipboard,
|
||||||
|
() => handlers.updateLastCardFromClipboard(),
|
||||||
|
'updateLastCardFromClipboard',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shortcuts.markAudioCard) {
|
||||||
|
registerOverlayShortcut(
|
||||||
|
shortcuts.markAudioCard,
|
||||||
|
() => handlers.markAudioCard(),
|
||||||
|
'markAudioCard',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shortcuts.openRuntimeOptions) {
|
||||||
|
registerOverlayShortcut(
|
||||||
|
shortcuts.openRuntimeOptions,
|
||||||
|
() => handlers.openRuntimeOptions(),
|
||||||
|
'openRuntimeOptions',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (shortcuts.openJimaku) {
|
||||||
|
registerOverlayShortcut(shortcuts.openJimaku, () => handlers.openJimaku(), 'openJimaku');
|
||||||
|
}
|
||||||
|
|
||||||
|
return registeredAny;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unregisterOverlayShortcuts(shortcuts: ConfiguredShortcuts): void {
|
||||||
|
if (shortcuts.copySubtitle) {
|
||||||
|
globalShortcut.unregister(shortcuts.copySubtitle);
|
||||||
|
}
|
||||||
|
if (shortcuts.copySubtitleMultiple) {
|
||||||
|
globalShortcut.unregister(shortcuts.copySubtitleMultiple);
|
||||||
|
}
|
||||||
|
if (shortcuts.updateLastCardFromClipboard) {
|
||||||
|
globalShortcut.unregister(shortcuts.updateLastCardFromClipboard);
|
||||||
|
}
|
||||||
|
if (shortcuts.triggerFieldGrouping) {
|
||||||
|
globalShortcut.unregister(shortcuts.triggerFieldGrouping);
|
||||||
|
}
|
||||||
|
if (shortcuts.triggerSubsync) {
|
||||||
|
globalShortcut.unregister(shortcuts.triggerSubsync);
|
||||||
|
}
|
||||||
|
if (shortcuts.mineSentence) {
|
||||||
|
globalShortcut.unregister(shortcuts.mineSentence);
|
||||||
|
}
|
||||||
|
if (shortcuts.mineSentenceMultiple) {
|
||||||
|
globalShortcut.unregister(shortcuts.mineSentenceMultiple);
|
||||||
|
}
|
||||||
|
if (shortcuts.toggleSecondarySub) {
|
||||||
|
globalShortcut.unregister(shortcuts.toggleSecondarySub);
|
||||||
|
}
|
||||||
|
if (shortcuts.markAudioCard) {
|
||||||
|
globalShortcut.unregister(shortcuts.markAudioCard);
|
||||||
|
}
|
||||||
|
if (shortcuts.openRuntimeOptions) {
|
||||||
|
globalShortcut.unregister(shortcuts.openRuntimeOptions);
|
||||||
|
}
|
||||||
|
if (shortcuts.openJimaku) {
|
||||||
|
globalShortcut.unregister(shortcuts.openJimaku);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function registerOverlayShortcutsRuntime(deps: OverlayShortcutLifecycleDeps): boolean {
|
export function registerOverlayShortcutsRuntime(deps: OverlayShortcutLifecycleDeps): boolean {
|
||||||
return registerOverlayShortcuts(deps.getConfiguredShortcuts(), deps.getOverlayHandlers());
|
return registerOverlayShortcuts(deps.getConfiguredShortcuts(), deps.getOverlayHandlers());
|
||||||
|
|||||||
@@ -664,80 +664,6 @@ test('tracked Windows overlay stays interactive while the overlay window itself
|
|||||||
assert.ok(!calls.includes('enforce-order'));
|
assert.ok(!calls.includes('enforce-order'));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('tracked Windows overlay reshows click-through even if focus state is stale after a modal closes', () => {
|
|
||||||
const { window, calls, setFocused } = createMainWindowRecorder();
|
|
||||||
const tracker: WindowTrackerStub = {
|
|
||||||
isTracking: () => true,
|
|
||||||
getGeometry: () => ({ x: 0, y: 0, width: 1280, height: 720 }),
|
|
||||||
isTargetWindowFocused: () => false,
|
|
||||||
};
|
|
||||||
|
|
||||||
updateVisibleOverlayVisibility({
|
|
||||||
visibleOverlayVisible: true,
|
|
||||||
mainWindow: window as never,
|
|
||||||
windowTracker: tracker as never,
|
|
||||||
trackerNotReadyWarningShown: false,
|
|
||||||
setTrackerNotReadyWarningShown: () => {},
|
|
||||||
updateVisibleOverlayBounds: () => {
|
|
||||||
calls.push('update-bounds');
|
|
||||||
},
|
|
||||||
ensureOverlayWindowLevel: () => {
|
|
||||||
calls.push('ensure-level');
|
|
||||||
},
|
|
||||||
syncWindowsOverlayToMpvZOrder: () => {
|
|
||||||
calls.push('sync-windows-z-order');
|
|
||||||
},
|
|
||||||
syncPrimaryOverlayWindowLayer: () => {
|
|
||||||
calls.push('sync-layer');
|
|
||||||
},
|
|
||||||
enforceOverlayLayerOrder: () => {
|
|
||||||
calls.push('enforce-order');
|
|
||||||
},
|
|
||||||
syncOverlayShortcuts: () => {
|
|
||||||
calls.push('sync-shortcuts');
|
|
||||||
},
|
|
||||||
isMacOSPlatform: false,
|
|
||||||
isWindowsPlatform: true,
|
|
||||||
} as never);
|
|
||||||
|
|
||||||
calls.length = 0;
|
|
||||||
window.hide();
|
|
||||||
calls.length = 0;
|
|
||||||
setFocused(true);
|
|
||||||
|
|
||||||
updateVisibleOverlayVisibility({
|
|
||||||
visibleOverlayVisible: true,
|
|
||||||
mainWindow: window as never,
|
|
||||||
windowTracker: tracker as never,
|
|
||||||
trackerNotReadyWarningShown: false,
|
|
||||||
setTrackerNotReadyWarningShown: () => {},
|
|
||||||
updateVisibleOverlayBounds: () => {
|
|
||||||
calls.push('update-bounds');
|
|
||||||
},
|
|
||||||
ensureOverlayWindowLevel: () => {
|
|
||||||
calls.push('ensure-level');
|
|
||||||
},
|
|
||||||
syncWindowsOverlayToMpvZOrder: () => {
|
|
||||||
calls.push('sync-windows-z-order');
|
|
||||||
},
|
|
||||||
syncPrimaryOverlayWindowLayer: () => {
|
|
||||||
calls.push('sync-layer');
|
|
||||||
},
|
|
||||||
enforceOverlayLayerOrder: () => {
|
|
||||||
calls.push('enforce-order');
|
|
||||||
},
|
|
||||||
syncOverlayShortcuts: () => {
|
|
||||||
calls.push('sync-shortcuts');
|
|
||||||
},
|
|
||||||
isMacOSPlatform: false,
|
|
||||||
isWindowsPlatform: true,
|
|
||||||
} as never);
|
|
||||||
|
|
||||||
assert.ok(calls.includes('mouse-ignore:true:forward'));
|
|
||||||
assert.ok(calls.includes('show-inactive'));
|
|
||||||
assert.ok(!calls.includes('show'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('tracked Windows overlay binds above mpv even when tracker focus lags', () => {
|
test('tracked Windows overlay binds above mpv even when tracker focus lags', () => {
|
||||||
const { window, calls } = createMainWindowRecorder();
|
const { window, calls } = createMainWindowRecorder();
|
||||||
const tracker: WindowTrackerStub = {
|
const tracker: WindowTrackerStub = {
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import type { BrowserWindow } from 'electron';
|
import type { BrowserWindow } from 'electron';
|
||||||
import { BaseWindowTracker } from '../../window-trackers';
|
import { BaseWindowTracker } from '../../window-trackers';
|
||||||
import { WindowGeometry } from '../../types';
|
import { WindowGeometry } from '../../types';
|
||||||
import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags';
|
|
||||||
|
|
||||||
const WINDOWS_OVERLAY_REVEAL_DELAY_MS = 48;
|
const WINDOWS_OVERLAY_REVEAL_DELAY_MS = 48;
|
||||||
const pendingWindowsOverlayRevealTimeoutByWindow = new WeakMap<
|
const pendingWindowsOverlayRevealTimeoutByWindow = new WeakMap<
|
||||||
BrowserWindow,
|
BrowserWindow,
|
||||||
ReturnType<typeof setTimeout>
|
ReturnType<typeof setTimeout>
|
||||||
>();
|
>();
|
||||||
|
const OVERLAY_WINDOW_CONTENT_READY_FLAG = '__subminerOverlayContentReady';
|
||||||
|
|
||||||
function setOverlayWindowOpacity(window: BrowserWindow, opacity: number): void {
|
function setOverlayWindowOpacity(window: BrowserWindow, opacity: number): void {
|
||||||
const opacityCapableWindow = window as BrowserWindow & {
|
const opacityCapableWindow = window as BrowserWindow & {
|
||||||
setOpacity?: (opacity: number) => void;
|
setOpacity?: (opacity: number) => void;
|
||||||
@@ -91,7 +92,6 @@ export function updateVisibleOverlayVisibility(args: {
|
|||||||
|
|
||||||
const showPassiveVisibleOverlay = (): void => {
|
const showPassiveVisibleOverlay = (): void => {
|
||||||
const forceMousePassthrough = args.forceMousePassthrough === true;
|
const forceMousePassthrough = args.forceMousePassthrough === true;
|
||||||
const wasVisible = mainWindow.isVisible();
|
|
||||||
const shouldDefaultToPassthrough =
|
const shouldDefaultToPassthrough =
|
||||||
args.isMacOSPlatform || args.isWindowsPlatform || forceMousePassthrough;
|
args.isMacOSPlatform || args.isWindowsPlatform || forceMousePassthrough;
|
||||||
const isVisibleOverlayFocused =
|
const isVisibleOverlayFocused =
|
||||||
@@ -116,10 +116,8 @@ export function updateVisibleOverlayVisibility(args: {
|
|||||||
windowsForegroundProcessName === windowsOverlayProcessName)) &&
|
windowsForegroundProcessName === windowsOverlayProcessName)) &&
|
||||||
!isTrackedWindowsTargetMinimized &&
|
!isTrackedWindowsTargetMinimized &&
|
||||||
(args.windowTracker.isTracking() || args.windowTracker.getGeometry() !== null);
|
(args.windowTracker.isTracking() || args.windowTracker.getGeometry() !== null);
|
||||||
const shouldForcePassiveReshow = args.isWindowsPlatform && !wasVisible;
|
|
||||||
const shouldIgnoreMouseEvents =
|
const shouldIgnoreMouseEvents =
|
||||||
forceMousePassthrough ||
|
forceMousePassthrough || (shouldDefaultToPassthrough && !isVisibleOverlayFocused);
|
||||||
(shouldDefaultToPassthrough && (!isVisibleOverlayFocused || shouldForcePassiveReshow));
|
|
||||||
const shouldBindTrackedWindowsOverlay = args.isWindowsPlatform && !!args.windowTracker;
|
const shouldBindTrackedWindowsOverlay = args.isWindowsPlatform && !!args.windowTracker;
|
||||||
const shouldKeepTrackedWindowsOverlayTopmost =
|
const shouldKeepTrackedWindowsOverlayTopmost =
|
||||||
!args.isWindowsPlatform ||
|
!args.isWindowsPlatform ||
|
||||||
@@ -128,6 +126,8 @@ export function updateVisibleOverlayVisibility(args: {
|
|||||||
isTrackedWindowsTargetFocused ||
|
isTrackedWindowsTargetFocused ||
|
||||||
shouldPreserveWindowsOverlayDuringFocusHandoff ||
|
shouldPreserveWindowsOverlayDuringFocusHandoff ||
|
||||||
(hasWindowsForegroundProcessSignal && windowsForegroundProcessName === 'mpv');
|
(hasWindowsForegroundProcessSignal && windowsForegroundProcessName === 'mpv');
|
||||||
|
const wasVisible = mainWindow.isVisible();
|
||||||
|
|
||||||
if (shouldIgnoreMouseEvents) {
|
if (shouldIgnoreMouseEvents) {
|
||||||
mainWindow.setIgnoreMouseEvents(true, { forward: true });
|
mainWindow.setIgnoreMouseEvents(true, { forward: true });
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ test('overlay window config explicitly disables renderer sandbox for preload com
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('Windows visible overlay window config does not start as always-on-top', () => {
|
test('Windows visible overlay window config does not start as always-on-top', () => {
|
||||||
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
|
const originalPlatform = process.platform;
|
||||||
|
|
||||||
Object.defineProperty(process, 'platform', {
|
Object.defineProperty(process, 'platform', {
|
||||||
configurable: true,
|
configurable: true,
|
||||||
@@ -29,9 +29,10 @@ test('Windows visible overlay window config does not start as always-on-top', ()
|
|||||||
|
|
||||||
assert.equal(options.alwaysOnTop, false);
|
assert.equal(options.alwaysOnTop, false);
|
||||||
} finally {
|
} finally {
|
||||||
if (originalPlatformDescriptor) {
|
Object.defineProperty(process, 'platform', {
|
||||||
Object.defineProperty(process, 'platform', originalPlatformDescriptor);
|
configurable: true,
|
||||||
}
|
value: originalPlatform,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
export const OVERLAY_WINDOW_CONTENT_READY_FLAG = '__subminerOverlayContentReady';
|
|
||||||
@@ -10,17 +10,13 @@ import {
|
|||||||
} from './overlay-window-input';
|
} from './overlay-window-input';
|
||||||
import { buildOverlayWindowOptions } from './overlay-window-options';
|
import { buildOverlayWindowOptions } from './overlay-window-options';
|
||||||
import { normalizeOverlayWindowBoundsForPlatform } from './overlay-window-bounds';
|
import { normalizeOverlayWindowBoundsForPlatform } from './overlay-window-bounds';
|
||||||
import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags';
|
|
||||||
export { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags';
|
|
||||||
|
|
||||||
const logger = createLogger('main:overlay-window');
|
const logger = createLogger('main:overlay-window');
|
||||||
const overlayWindowLayerByInstance = new WeakMap<BrowserWindow, OverlayWindowKind>();
|
const overlayWindowLayerByInstance = new WeakMap<BrowserWindow, OverlayWindowKind>();
|
||||||
const overlayWindowContentReady = new WeakSet<BrowserWindow>();
|
const overlayWindowContentReady = new WeakSet<BrowserWindow>();
|
||||||
|
const OVERLAY_WINDOW_CONTENT_READY_FLAG = '__subminerOverlayContentReady';
|
||||||
|
|
||||||
export function isOverlayWindowContentReady(window: BrowserWindow): boolean {
|
export function isOverlayWindowContentReady(window: BrowserWindow): boolean {
|
||||||
if (window.isDestroyed()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return (
|
return (
|
||||||
overlayWindowContentReady.has(window) ||
|
overlayWindowContentReady.has(window) ||
|
||||||
(window as BrowserWindow & { [OVERLAY_WINDOW_CONTENT_READY_FLAG]?: boolean })[
|
(window as BrowserWindow & { [OVERLAY_WINDOW_CONTENT_READY_FLAG]?: boolean })[
|
||||||
@@ -98,9 +94,6 @@ export function createOverlayWindow(
|
|||||||
},
|
},
|
||||||
): BrowserWindow {
|
): BrowserWindow {
|
||||||
const window = new BrowserWindow(buildOverlayWindowOptions(kind, options));
|
const window = new BrowserWindow(buildOverlayWindowOptions(kind, options));
|
||||||
(window as BrowserWindow & { [OVERLAY_WINDOW_CONTENT_READY_FLAG]?: boolean })[
|
|
||||||
OVERLAY_WINDOW_CONTENT_READY_FLAG
|
|
||||||
] = false;
|
|
||||||
|
|
||||||
if (!(process.platform === 'win32' && kind === 'visible')) {
|
if (!(process.platform === 'win32' && kind === 'visible')) {
|
||||||
options.ensureOverlayWindowLevel(window);
|
options.ensureOverlayWindowLevel(window);
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
import type { RuntimeOptionApplyResult, RuntimeOptionId } from '../../types';
|
|
||||||
import type { SessionActionId } from '../../types/session-bindings';
|
|
||||||
import type { SessionActionDispatchRequest } from '../../types/runtime';
|
|
||||||
|
|
||||||
export interface SessionActionExecutorDeps {
|
|
||||||
toggleStatsOverlay: () => void;
|
|
||||||
toggleVisibleOverlay: () => void;
|
|
||||||
copyCurrentSubtitle: () => void;
|
|
||||||
copySubtitleCount: (count: number) => void;
|
|
||||||
updateLastCardFromClipboard: () => Promise<void>;
|
|
||||||
triggerFieldGrouping: () => Promise<void>;
|
|
||||||
triggerSubsyncFromConfig: () => Promise<void>;
|
|
||||||
mineSentenceCard: () => Promise<void>;
|
|
||||||
mineSentenceCount: (count: number) => void;
|
|
||||||
toggleSecondarySub: () => void;
|
|
||||||
toggleSubtitleSidebar: () => void;
|
|
||||||
markLastCardAsAudioCard: () => Promise<void>;
|
|
||||||
openRuntimeOptionsPalette: () => void;
|
|
||||||
openSessionHelp: () => void;
|
|
||||||
openControllerSelect: () => void;
|
|
||||||
openControllerDebug: () => void;
|
|
||||||
openJimaku: () => void;
|
|
||||||
openYoutubeTrackPicker: () => void | Promise<void>;
|
|
||||||
openPlaylistBrowser: () => boolean | void | Promise<boolean | void>;
|
|
||||||
replayCurrentSubtitle: () => void;
|
|
||||||
playNextSubtitle: () => void;
|
|
||||||
shiftSubDelayToAdjacentSubtitle: (direction: 'next' | 'previous') => Promise<void>;
|
|
||||||
cycleRuntimeOption: (id: RuntimeOptionId, direction: 1 | -1) => RuntimeOptionApplyResult;
|
|
||||||
showMpvOsd: (text: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveCount(count: number | undefined): number {
|
|
||||||
const normalized = typeof count === 'number' && Number.isInteger(count) ? count : 1;
|
|
||||||
return Math.min(9, Math.max(1, normalized));
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function dispatchSessionAction(
|
|
||||||
request: SessionActionDispatchRequest,
|
|
||||||
deps: SessionActionExecutorDeps,
|
|
||||||
): Promise<void> {
|
|
||||||
switch (request.actionId) {
|
|
||||||
case 'toggleStatsOverlay':
|
|
||||||
deps.toggleStatsOverlay();
|
|
||||||
return;
|
|
||||||
case 'toggleVisibleOverlay':
|
|
||||||
deps.toggleVisibleOverlay();
|
|
||||||
return;
|
|
||||||
case 'copySubtitle':
|
|
||||||
deps.copyCurrentSubtitle();
|
|
||||||
return;
|
|
||||||
case 'copySubtitleMultiple':
|
|
||||||
deps.copySubtitleCount(resolveCount(request.payload?.count));
|
|
||||||
return;
|
|
||||||
case 'updateLastCardFromClipboard':
|
|
||||||
await deps.updateLastCardFromClipboard();
|
|
||||||
return;
|
|
||||||
case 'triggerFieldGrouping':
|
|
||||||
await deps.triggerFieldGrouping();
|
|
||||||
return;
|
|
||||||
case 'triggerSubsync':
|
|
||||||
await deps.triggerSubsyncFromConfig();
|
|
||||||
return;
|
|
||||||
case 'mineSentence':
|
|
||||||
await deps.mineSentenceCard();
|
|
||||||
return;
|
|
||||||
case 'mineSentenceMultiple':
|
|
||||||
deps.mineSentenceCount(resolveCount(request.payload?.count));
|
|
||||||
return;
|
|
||||||
case 'toggleSecondarySub':
|
|
||||||
deps.toggleSecondarySub();
|
|
||||||
return;
|
|
||||||
case 'toggleSubtitleSidebar':
|
|
||||||
deps.toggleSubtitleSidebar();
|
|
||||||
return;
|
|
||||||
case 'markAudioCard':
|
|
||||||
await deps.markLastCardAsAudioCard();
|
|
||||||
return;
|
|
||||||
case 'openRuntimeOptions':
|
|
||||||
deps.openRuntimeOptionsPalette();
|
|
||||||
return;
|
|
||||||
case 'openSessionHelp':
|
|
||||||
deps.openSessionHelp();
|
|
||||||
return;
|
|
||||||
case 'openControllerSelect':
|
|
||||||
deps.openControllerSelect();
|
|
||||||
return;
|
|
||||||
case 'openControllerDebug':
|
|
||||||
deps.openControllerDebug();
|
|
||||||
return;
|
|
||||||
case 'openJimaku':
|
|
||||||
deps.openJimaku();
|
|
||||||
return;
|
|
||||||
case 'openYoutubePicker':
|
|
||||||
await deps.openYoutubeTrackPicker();
|
|
||||||
return;
|
|
||||||
case 'openPlaylistBrowser':
|
|
||||||
await deps.openPlaylistBrowser();
|
|
||||||
return;
|
|
||||||
case 'replayCurrentSubtitle':
|
|
||||||
deps.replayCurrentSubtitle();
|
|
||||||
return;
|
|
||||||
case 'playNextSubtitle':
|
|
||||||
deps.playNextSubtitle();
|
|
||||||
return;
|
|
||||||
case 'shiftSubDelayPrevLine':
|
|
||||||
await deps.shiftSubDelayToAdjacentSubtitle('previous');
|
|
||||||
return;
|
|
||||||
case 'shiftSubDelayNextLine':
|
|
||||||
await deps.shiftSubDelayToAdjacentSubtitle('next');
|
|
||||||
return;
|
|
||||||
case 'cycleRuntimeOption': {
|
|
||||||
const runtimeOptionId = request.payload?.runtimeOptionId as RuntimeOptionId | undefined;
|
|
||||||
if (!runtimeOptionId) {
|
|
||||||
deps.showMpvOsd('Runtime option id is required.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const direction = request.payload?.direction === -1 ? -1 : 1;
|
|
||||||
const result = deps.cycleRuntimeOption(runtimeOptionId, direction);
|
|
||||||
if (!result.ok && result.error) {
|
|
||||||
deps.showMpvOsd(result.error);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,277 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import test from 'node:test';
|
|
||||||
import type { Keybinding } from '../../types';
|
|
||||||
import type { ConfiguredShortcuts } from '../utils/shortcut-config';
|
|
||||||
import { SPECIAL_COMMANDS } from '../../config/definitions';
|
|
||||||
import { compileSessionBindings } from './session-bindings';
|
|
||||||
|
|
||||||
function createShortcuts(overrides: Partial<ConfiguredShortcuts> = {}): ConfiguredShortcuts {
|
|
||||||
return {
|
|
||||||
toggleVisibleOverlayGlobal: null,
|
|
||||||
copySubtitle: null,
|
|
||||||
copySubtitleMultiple: null,
|
|
||||||
updateLastCardFromClipboard: null,
|
|
||||||
triggerFieldGrouping: null,
|
|
||||||
triggerSubsync: null,
|
|
||||||
mineSentence: null,
|
|
||||||
mineSentenceMultiple: null,
|
|
||||||
multiCopyTimeoutMs: 2500,
|
|
||||||
toggleSecondarySub: null,
|
|
||||||
markAudioCard: null,
|
|
||||||
openRuntimeOptions: null,
|
|
||||||
openJimaku: null,
|
|
||||||
openSessionHelp: null,
|
|
||||||
openControllerSelect: null,
|
|
||||||
openControllerDebug: null,
|
|
||||||
toggleSubtitleSidebar: null,
|
|
||||||
...overrides,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createKeybinding(key: string, command: Keybinding['command']): Keybinding {
|
|
||||||
return { key, command };
|
|
||||||
}
|
|
||||||
|
|
||||||
test('compileSessionBindings merges shortcuts and keybindings into one canonical list', () => {
|
|
||||||
const result = compileSessionBindings({
|
|
||||||
shortcuts: createShortcuts({
|
|
||||||
toggleVisibleOverlayGlobal: 'Alt+Shift+O',
|
|
||||||
openJimaku: 'Ctrl+Shift+J',
|
|
||||||
openControllerSelect: 'Alt+C',
|
|
||||||
}),
|
|
||||||
keybindings: [
|
|
||||||
createKeybinding('KeyF', ['cycle', 'fullscreen']),
|
|
||||||
createKeybinding('Ctrl+Shift+Y', [SPECIAL_COMMANDS.YOUTUBE_PICKER_OPEN]),
|
|
||||||
],
|
|
||||||
platform: 'linux',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(result.warnings.length, 0);
|
|
||||||
assert.deepEqual(
|
|
||||||
result.bindings.map((binding) => ({
|
|
||||||
actionType: binding.actionType,
|
|
||||||
sourcePath: binding.sourcePath,
|
|
||||||
code: binding.key.code,
|
|
||||||
modifiers: binding.key.modifiers,
|
|
||||||
target:
|
|
||||||
binding.actionType === 'session-action'
|
|
||||||
? binding.actionId
|
|
||||||
: binding.command.join(' '),
|
|
||||||
})),
|
|
||||||
[
|
|
||||||
{
|
|
||||||
actionType: 'mpv-command',
|
|
||||||
sourcePath: 'keybindings[0].key',
|
|
||||||
code: 'KeyF',
|
|
||||||
modifiers: [],
|
|
||||||
target: 'cycle fullscreen',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
actionType: 'session-action',
|
|
||||||
sourcePath: 'keybindings[1].key',
|
|
||||||
code: 'KeyY',
|
|
||||||
modifiers: ['ctrl', 'shift'],
|
|
||||||
target: 'openYoutubePicker',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
actionType: 'session-action',
|
|
||||||
sourcePath: 'shortcuts.openControllerSelect',
|
|
||||||
code: 'KeyC',
|
|
||||||
modifiers: ['alt'],
|
|
||||||
target: 'openControllerSelect',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
actionType: 'session-action',
|
|
||||||
sourcePath: 'shortcuts.openJimaku',
|
|
||||||
code: 'KeyJ',
|
|
||||||
modifiers: ['ctrl', 'shift'],
|
|
||||||
target: 'openJimaku',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
actionType: 'session-action',
|
|
||||||
sourcePath: 'shortcuts.toggleVisibleOverlayGlobal',
|
|
||||||
code: 'KeyO',
|
|
||||||
modifiers: ['alt', 'shift'],
|
|
||||||
target: 'toggleVisibleOverlay',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('compileSessionBindings resolves CommandOrControl per platform', () => {
|
|
||||||
const input = {
|
|
||||||
shortcuts: createShortcuts({
|
|
||||||
toggleVisibleOverlayGlobal: 'CommandOrControl+Shift+O',
|
|
||||||
}),
|
|
||||||
keybindings: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
const windows = compileSessionBindings({ ...input, platform: 'win32' });
|
|
||||||
const mac = compileSessionBindings({ ...input, platform: 'darwin' });
|
|
||||||
|
|
||||||
assert.deepEqual(windows.bindings[0]?.key.modifiers, ['ctrl', 'shift']);
|
|
||||||
assert.deepEqual(mac.bindings[0]?.key.modifiers, ['shift', 'meta']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('compileSessionBindings resolves CommandOrControl in DOM key strings per platform', () => {
|
|
||||||
const input = {
|
|
||||||
shortcuts: createShortcuts(),
|
|
||||||
keybindings: [createKeybinding('CommandOrControl+Shift+J', ['cycle', 'fullscreen'])],
|
|
||||||
statsToggleKey: 'CommandOrControl+Backquote',
|
|
||||||
};
|
|
||||||
|
|
||||||
const windows = compileSessionBindings({ ...input, platform: 'win32' });
|
|
||||||
const mac = compileSessionBindings({ ...input, platform: 'darwin' });
|
|
||||||
|
|
||||||
assert.deepEqual(
|
|
||||||
windows.bindings
|
|
||||||
.map((binding) => ({
|
|
||||||
sourcePath: binding.sourcePath,
|
|
||||||
modifiers: binding.key.modifiers,
|
|
||||||
}))
|
|
||||||
.sort((left, right) => left.sourcePath.localeCompare(right.sourcePath)),
|
|
||||||
[
|
|
||||||
{
|
|
||||||
sourcePath: 'keybindings[0].key',
|
|
||||||
modifiers: ['ctrl', 'shift'],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
sourcePath: 'stats.toggleKey',
|
|
||||||
modifiers: ['ctrl'],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.deepEqual(
|
|
||||||
mac.bindings
|
|
||||||
.map((binding) => ({
|
|
||||||
sourcePath: binding.sourcePath,
|
|
||||||
modifiers: binding.key.modifiers,
|
|
||||||
}))
|
|
||||||
.sort((left, right) => left.sourcePath.localeCompare(right.sourcePath)),
|
|
||||||
[
|
|
||||||
{
|
|
||||||
sourcePath: 'keybindings[0].key',
|
|
||||||
modifiers: ['shift', 'meta'],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
sourcePath: 'stats.toggleKey',
|
|
||||||
modifiers: ['meta'],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('compileSessionBindings drops conflicting bindings that canonicalize to the same key', () => {
|
|
||||||
const result = compileSessionBindings({
|
|
||||||
shortcuts: createShortcuts({
|
|
||||||
openJimaku: 'Ctrl+Shift+J',
|
|
||||||
}),
|
|
||||||
keybindings: [createKeybinding('Ctrl+Shift+J', [SPECIAL_COMMANDS.PLAYLIST_BROWSER_OPEN])],
|
|
||||||
platform: 'linux',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(result.bindings, []);
|
|
||||||
assert.equal(result.warnings.length, 1);
|
|
||||||
assert.equal(result.warnings[0]?.kind, 'conflict');
|
|
||||||
assert.deepEqual(result.warnings[0]?.conflictingPaths, [
|
|
||||||
'shortcuts.openJimaku',
|
|
||||||
'keybindings[0].key',
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('compileSessionBindings omits disabled bindings', () => {
|
|
||||||
const result = compileSessionBindings({
|
|
||||||
shortcuts: createShortcuts({
|
|
||||||
openJimaku: null,
|
|
||||||
toggleVisibleOverlayGlobal: 'Alt+Shift+O',
|
|
||||||
}),
|
|
||||||
keybindings: [createKeybinding('Ctrl+Shift+J', null)],
|
|
||||||
platform: 'linux',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(result.warnings.length, 0);
|
|
||||||
assert.deepEqual(result.bindings.map((binding) => binding.sourcePath), [
|
|
||||||
'shortcuts.toggleVisibleOverlayGlobal',
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('compileSessionBindings warns on unsupported shortcut and keybinding syntax', () => {
|
|
||||||
const result = compileSessionBindings({
|
|
||||||
shortcuts: createShortcuts({
|
|
||||||
openJimaku: 'Hyper+J',
|
|
||||||
}),
|
|
||||||
keybindings: [createKeybinding('Ctrl+ß', ['cycle', 'fullscreen'])],
|
|
||||||
platform: 'linux',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(result.bindings, []);
|
|
||||||
assert.deepEqual(
|
|
||||||
result.warnings.map((warning) => `${warning.kind}:${warning.path}`),
|
|
||||||
['unsupported:shortcuts.openJimaku', 'unsupported:keybindings[0].key'],
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('compileSessionBindings rejects malformed command arrays', () => {
|
|
||||||
const result = compileSessionBindings({
|
|
||||||
shortcuts: createShortcuts(),
|
|
||||||
keybindings: [
|
|
||||||
createKeybinding('Ctrl+J', ['show-text', 3000]),
|
|
||||||
createKeybinding('Ctrl+K', ['show-text', { bad: true } as never] as never),
|
|
||||||
],
|
|
||||||
platform: 'linux',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(result.bindings.map((binding) => binding.sourcePath), ['keybindings[0].key']);
|
|
||||||
assert.equal(result.bindings[0]?.actionType, 'mpv-command');
|
|
||||||
assert.deepEqual(result.bindings[0]?.command, ['show-text', 3000]);
|
|
||||||
assert.deepEqual(result.warnings.map((warning) => `${warning.kind}:${warning.path}`), [
|
|
||||||
'unsupported:keybindings[1].key',
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('compileSessionBindings warns on deprecated toggleVisibleOverlayGlobal config', () => {
|
|
||||||
const result = compileSessionBindings({
|
|
||||||
shortcuts: createShortcuts(),
|
|
||||||
keybindings: [],
|
|
||||||
platform: 'linux',
|
|
||||||
rawConfig: {
|
|
||||||
shortcuts: {
|
|
||||||
toggleVisibleOverlayGlobal: 'Alt+Shift+O',
|
|
||||||
},
|
|
||||||
} as never,
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(result.bindings.length, 0);
|
|
||||||
assert.deepEqual(result.warnings, [
|
|
||||||
{
|
|
||||||
kind: 'deprecated-config',
|
|
||||||
path: 'shortcuts.toggleVisibleOverlayGlobal',
|
|
||||||
value: 'Alt+Shift+O',
|
|
||||||
message: 'Rename shortcuts.toggleVisibleOverlayGlobal to shortcuts.toggleVisibleOverlay.',
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('compileSessionBindings includes stats toggle in the shared session binding artifact', () => {
|
|
||||||
const result = compileSessionBindings({
|
|
||||||
shortcuts: createShortcuts(),
|
|
||||||
keybindings: [],
|
|
||||||
statsToggleKey: 'Backquote',
|
|
||||||
platform: 'win32',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(result.warnings.length, 0);
|
|
||||||
assert.deepEqual(result.bindings, [
|
|
||||||
{
|
|
||||||
sourcePath: 'stats.toggleKey',
|
|
||||||
originalKey: 'Backquote',
|
|
||||||
key: {
|
|
||||||
code: 'Backquote',
|
|
||||||
modifiers: [],
|
|
||||||
},
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: 'toggleStatsOverlay',
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
@@ -1,484 +0,0 @@
|
|||||||
import type { Keybinding, ResolvedConfig } from '../../types';
|
|
||||||
import type { ConfiguredShortcuts } from '../utils/shortcut-config';
|
|
||||||
import type {
|
|
||||||
CompiledMpvCommandBinding,
|
|
||||||
CompiledSessionActionBinding,
|
|
||||||
CompiledSessionBinding,
|
|
||||||
PluginSessionBindingsArtifact,
|
|
||||||
SessionActionId,
|
|
||||||
SessionBindingWarning,
|
|
||||||
SessionKeyModifier,
|
|
||||||
SessionKeySpec,
|
|
||||||
} from '../../types/session-bindings';
|
|
||||||
import { SPECIAL_COMMANDS } from '../../config';
|
|
||||||
|
|
||||||
type PlatformKeyModel = 'darwin' | 'win32' | 'linux';
|
|
||||||
|
|
||||||
type CompileSessionBindingsInput = {
|
|
||||||
keybindings: Keybinding[];
|
|
||||||
shortcuts: ConfiguredShortcuts;
|
|
||||||
statsToggleKey?: string | null;
|
|
||||||
platform: PlatformKeyModel;
|
|
||||||
rawConfig?: ResolvedConfig | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
type DraftBinding = {
|
|
||||||
binding: CompiledSessionBinding;
|
|
||||||
actionFingerprint: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const MODIFIER_ORDER: SessionKeyModifier[] = ['ctrl', 'alt', 'shift', 'meta'];
|
|
||||||
|
|
||||||
const SESSION_SHORTCUT_ACTIONS: Array<{
|
|
||||||
key: keyof Omit<ConfiguredShortcuts, 'multiCopyTimeoutMs'>;
|
|
||||||
actionId: SessionActionId;
|
|
||||||
}> = [
|
|
||||||
{ key: 'toggleVisibleOverlayGlobal', actionId: 'toggleVisibleOverlay' },
|
|
||||||
{ key: 'copySubtitle', actionId: 'copySubtitle' },
|
|
||||||
{ key: 'copySubtitleMultiple', actionId: 'copySubtitleMultiple' },
|
|
||||||
{ key: 'updateLastCardFromClipboard', actionId: 'updateLastCardFromClipboard' },
|
|
||||||
{ key: 'triggerFieldGrouping', actionId: 'triggerFieldGrouping' },
|
|
||||||
{ key: 'triggerSubsync', actionId: 'triggerSubsync' },
|
|
||||||
{ key: 'mineSentence', actionId: 'mineSentence' },
|
|
||||||
{ key: 'mineSentenceMultiple', actionId: 'mineSentenceMultiple' },
|
|
||||||
{ key: 'toggleSecondarySub', actionId: 'toggleSecondarySub' },
|
|
||||||
{ key: 'markAudioCard', actionId: 'markAudioCard' },
|
|
||||||
{ key: 'openRuntimeOptions', actionId: 'openRuntimeOptions' },
|
|
||||||
{ key: 'openJimaku', actionId: 'openJimaku' },
|
|
||||||
{ key: 'openSessionHelp', actionId: 'openSessionHelp' },
|
|
||||||
{ key: 'openControllerSelect', actionId: 'openControllerSelect' },
|
|
||||||
{ key: 'openControllerDebug', actionId: 'openControllerDebug' },
|
|
||||||
{ key: 'toggleSubtitleSidebar', actionId: 'toggleSubtitleSidebar' },
|
|
||||||
];
|
|
||||||
|
|
||||||
function normalizeModifiers(modifiers: SessionKeyModifier[]): SessionKeyModifier[] {
|
|
||||||
return [...new Set(modifiers)].sort(
|
|
||||||
(left, right) => MODIFIER_ORDER.indexOf(left) - MODIFIER_ORDER.indexOf(right),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isValidCommandEntry(value: unknown): value is string | number {
|
|
||||||
return typeof value === 'string' || typeof value === 'number';
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeCodeToken(token: string): string | null {
|
|
||||||
const normalized = token.trim();
|
|
||||||
if (!normalized) return null;
|
|
||||||
if (/^[a-z]$/i.test(normalized)) {
|
|
||||||
return `Key${normalized.toUpperCase()}`;
|
|
||||||
}
|
|
||||||
if (/^[0-9]$/.test(normalized)) {
|
|
||||||
return `Digit${normalized}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const exactMap: Record<string, string> = {
|
|
||||||
space: 'Space',
|
|
||||||
tab: 'Tab',
|
|
||||||
enter: 'Enter',
|
|
||||||
return: 'Enter',
|
|
||||||
esc: 'Escape',
|
|
||||||
escape: 'Escape',
|
|
||||||
up: 'ArrowUp',
|
|
||||||
down: 'ArrowDown',
|
|
||||||
left: 'ArrowLeft',
|
|
||||||
right: 'ArrowRight',
|
|
||||||
backspace: 'Backspace',
|
|
||||||
delete: 'Delete',
|
|
||||||
slash: 'Slash',
|
|
||||||
backslash: 'Backslash',
|
|
||||||
minus: 'Minus',
|
|
||||||
plus: 'Equal',
|
|
||||||
equal: 'Equal',
|
|
||||||
comma: 'Comma',
|
|
||||||
period: 'Period',
|
|
||||||
quote: 'Quote',
|
|
||||||
semicolon: 'Semicolon',
|
|
||||||
bracketleft: 'BracketLeft',
|
|
||||||
bracketright: 'BracketRight',
|
|
||||||
backquote: 'Backquote',
|
|
||||||
};
|
|
||||||
const lower = normalized.toLowerCase();
|
|
||||||
if (exactMap[lower]) return exactMap[lower];
|
|
||||||
if (
|
|
||||||
/^key[a-z]$/i.test(normalized) ||
|
|
||||||
/^digit[0-9]$/i.test(normalized) ||
|
|
||||||
/^arrow(?:up|down|left|right)$/i.test(normalized) ||
|
|
||||||
/^f\d{1,2}$/i.test(normalized)
|
|
||||||
) {
|
|
||||||
const keyMatch = normalized.match(/^key([a-z])$/i);
|
|
||||||
if (keyMatch) {
|
|
||||||
return `Key${keyMatch[1]!.toUpperCase()}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const digitMatch = normalized.match(/^digit([0-9])$/i);
|
|
||||||
if (digitMatch) {
|
|
||||||
return `Digit${digitMatch[1]}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const arrowMatch = normalized.match(/^arrow(up|down|left|right)$/i);
|
|
||||||
if (arrowMatch) {
|
|
||||||
const direction = arrowMatch[1]!;
|
|
||||||
return `Arrow${direction[0]!.toUpperCase()}${direction.slice(1).toLowerCase()}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const functionKeyMatch = normalized.match(/^f(\d{1,2})$/i);
|
|
||||||
if (functionKeyMatch) {
|
|
||||||
return `F${functionKeyMatch[1]}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseAccelerator(
|
|
||||||
accelerator: string,
|
|
||||||
platform: PlatformKeyModel,
|
|
||||||
): { key: SessionKeySpec | null; message?: string } {
|
|
||||||
const normalized = accelerator.replace(/\s+/g, '').replace(/cmdorctrl/gi, 'CommandOrControl');
|
|
||||||
if (!normalized) {
|
|
||||||
return { key: null, message: 'Empty accelerator is not supported.' };
|
|
||||||
}
|
|
||||||
|
|
||||||
const parts = normalized.split('+').filter(Boolean);
|
|
||||||
const keyToken = parts.pop();
|
|
||||||
if (!keyToken) {
|
|
||||||
return { key: null, message: 'Missing accelerator key token.' };
|
|
||||||
}
|
|
||||||
|
|
||||||
const modifiers: SessionKeyModifier[] = [];
|
|
||||||
for (const modifier of parts) {
|
|
||||||
const lower = modifier.toLowerCase();
|
|
||||||
if (lower === 'ctrl' || lower === 'control') {
|
|
||||||
modifiers.push('ctrl');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (lower === 'alt' || lower === 'option') {
|
|
||||||
modifiers.push('alt');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (lower === 'shift') {
|
|
||||||
modifiers.push('shift');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (lower === 'meta' || lower === 'super' || lower === 'command' || lower === 'cmd') {
|
|
||||||
modifiers.push('meta');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (lower === 'commandorcontrol') {
|
|
||||||
modifiers.push(platform === 'darwin' ? 'meta' : 'ctrl');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
key: null,
|
|
||||||
message: `Unsupported accelerator modifier: ${modifier}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const code = normalizeCodeToken(keyToken);
|
|
||||||
if (!code) {
|
|
||||||
return {
|
|
||||||
key: null,
|
|
||||||
message: `Unsupported accelerator key token: ${keyToken}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
key: {
|
|
||||||
code,
|
|
||||||
modifiers: normalizeModifiers(modifiers),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseDomKeyString(
|
|
||||||
key: string,
|
|
||||||
platform: PlatformKeyModel,
|
|
||||||
): { key: SessionKeySpec | null; message?: string } {
|
|
||||||
const parts = key
|
|
||||||
.split('+')
|
|
||||||
.map((part) => part.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
const keyToken = parts.pop();
|
|
||||||
if (!keyToken) {
|
|
||||||
return { key: null, message: 'Missing keybinding key token.' };
|
|
||||||
}
|
|
||||||
|
|
||||||
const modifiers: SessionKeyModifier[] = [];
|
|
||||||
for (const modifier of parts) {
|
|
||||||
const lower = modifier.toLowerCase();
|
|
||||||
if (lower === 'ctrl' || lower === 'control') {
|
|
||||||
modifiers.push('ctrl');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (lower === 'alt' || lower === 'option') {
|
|
||||||
modifiers.push('alt');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (lower === 'shift') {
|
|
||||||
modifiers.push('shift');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
lower === 'meta' ||
|
|
||||||
lower === 'super' ||
|
|
||||||
lower === 'command' ||
|
|
||||||
lower === 'cmd' ||
|
|
||||||
lower === 'commandorcontrol'
|
|
||||||
) {
|
|
||||||
modifiers.push(
|
|
||||||
lower === 'commandorcontrol' ? (platform === 'darwin' ? 'meta' : 'ctrl') : 'meta',
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
key: null,
|
|
||||||
message: `Unsupported keybinding modifier: ${modifier}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const code = normalizeCodeToken(keyToken);
|
|
||||||
if (!code) {
|
|
||||||
return {
|
|
||||||
key: null,
|
|
||||||
message: `Unsupported keybinding token: ${keyToken}`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
key: {
|
|
||||||
code,
|
|
||||||
modifiers: normalizeModifiers(modifiers),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getSessionKeySpecSignature(key: SessionKeySpec): string {
|
|
||||||
return [...key.modifiers, key.code].join('+');
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveCommandBinding(
|
|
||||||
binding: Keybinding,
|
|
||||||
):
|
|
||||||
| Omit<CompiledMpvCommandBinding, 'key' | 'sourcePath' | 'originalKey'>
|
|
||||||
| Omit<CompiledSessionActionBinding, 'key' | 'sourcePath' | 'originalKey'>
|
|
||||||
| null {
|
|
||||||
const command = binding.command;
|
|
||||||
if (!Array.isArray(command) || command.length === 0 || !command.every(isValidCommandEntry)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const first = command[0];
|
|
||||||
if (typeof first !== 'string') {
|
|
||||||
return {
|
|
||||||
actionType: 'mpv-command',
|
|
||||||
command,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (first === SPECIAL_COMMANDS.SUBSYNC_TRIGGER) {
|
|
||||||
return { actionType: 'session-action', actionId: 'triggerSubsync' };
|
|
||||||
}
|
|
||||||
if (first === SPECIAL_COMMANDS.RUNTIME_OPTIONS_OPEN) {
|
|
||||||
return { actionType: 'session-action', actionId: 'openRuntimeOptions' };
|
|
||||||
}
|
|
||||||
if (first === SPECIAL_COMMANDS.JIMAKU_OPEN) {
|
|
||||||
return { actionType: 'session-action', actionId: 'openJimaku' };
|
|
||||||
}
|
|
||||||
if (first === SPECIAL_COMMANDS.YOUTUBE_PICKER_OPEN) {
|
|
||||||
return { actionType: 'session-action', actionId: 'openYoutubePicker' };
|
|
||||||
}
|
|
||||||
if (first === SPECIAL_COMMANDS.PLAYLIST_BROWSER_OPEN) {
|
|
||||||
return { actionType: 'session-action', actionId: 'openPlaylistBrowser' };
|
|
||||||
}
|
|
||||||
if (first === SPECIAL_COMMANDS.REPLAY_SUBTITLE) {
|
|
||||||
return { actionType: 'session-action', actionId: 'replayCurrentSubtitle' };
|
|
||||||
}
|
|
||||||
if (first === SPECIAL_COMMANDS.PLAY_NEXT_SUBTITLE) {
|
|
||||||
return { actionType: 'session-action', actionId: 'playNextSubtitle' };
|
|
||||||
}
|
|
||||||
if (first === SPECIAL_COMMANDS.SHIFT_SUB_DELAY_TO_PREVIOUS_SUBTITLE_START) {
|
|
||||||
return { actionType: 'session-action', actionId: 'shiftSubDelayPrevLine' };
|
|
||||||
}
|
|
||||||
if (first === SPECIAL_COMMANDS.SHIFT_SUB_DELAY_TO_NEXT_SUBTITLE_START) {
|
|
||||||
return { actionType: 'session-action', actionId: 'shiftSubDelayNextLine' };
|
|
||||||
}
|
|
||||||
if (first.startsWith(SPECIAL_COMMANDS.RUNTIME_OPTION_CYCLE_PREFIX)) {
|
|
||||||
const parts = first.split(':');
|
|
||||||
if (parts.length !== 3) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const [, runtimeOptionId, rawDirection] = parts;
|
|
||||||
if (!runtimeOptionId || (rawDirection !== 'prev' && rawDirection !== 'next')) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: 'cycleRuntimeOption',
|
|
||||||
payload: {
|
|
||||||
runtimeOptionId,
|
|
||||||
direction: rawDirection === 'prev' ? -1 : 1,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
actionType: 'mpv-command',
|
|
||||||
command,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function getBindingFingerprint(binding: CompiledSessionBinding): string {
|
|
||||||
if (binding.actionType === 'mpv-command') {
|
|
||||||
return `mpv:${JSON.stringify(binding.command)}`;
|
|
||||||
}
|
|
||||||
return `session:${binding.actionId}:${JSON.stringify(binding.payload ?? null)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function compileSessionBindings(
|
|
||||||
input: CompileSessionBindingsInput,
|
|
||||||
): {
|
|
||||||
bindings: CompiledSessionBinding[];
|
|
||||||
warnings: SessionBindingWarning[];
|
|
||||||
} {
|
|
||||||
const warnings: SessionBindingWarning[] = [];
|
|
||||||
const candidates = new Map<string, DraftBinding[]>();
|
|
||||||
const legacyToggleVisibleOverlayGlobal = (
|
|
||||||
input.rawConfig?.shortcuts as Record<string, unknown> | undefined
|
|
||||||
)?.toggleVisibleOverlayGlobal;
|
|
||||||
const statsToggleKey = input.statsToggleKey ?? input.rawConfig?.stats?.toggleKey ?? null;
|
|
||||||
|
|
||||||
if (legacyToggleVisibleOverlayGlobal !== undefined) {
|
|
||||||
warnings.push({
|
|
||||||
kind: 'deprecated-config',
|
|
||||||
path: 'shortcuts.toggleVisibleOverlayGlobal',
|
|
||||||
value: legacyToggleVisibleOverlayGlobal,
|
|
||||||
message: 'Rename shortcuts.toggleVisibleOverlayGlobal to shortcuts.toggleVisibleOverlay.',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const shortcut of SESSION_SHORTCUT_ACTIONS) {
|
|
||||||
const accelerator = input.shortcuts[shortcut.key];
|
|
||||||
if (!accelerator) continue;
|
|
||||||
const parsed = parseAccelerator(accelerator, input.platform);
|
|
||||||
if (!parsed.key) {
|
|
||||||
warnings.push({
|
|
||||||
kind: 'unsupported',
|
|
||||||
path: `shortcuts.${shortcut.key}`,
|
|
||||||
value: accelerator,
|
|
||||||
message: parsed.message ?? 'Unsupported accelerator syntax.',
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const binding: CompiledSessionActionBinding = {
|
|
||||||
sourcePath: `shortcuts.${shortcut.key}`,
|
|
||||||
originalKey: accelerator,
|
|
||||||
key: parsed.key,
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: shortcut.actionId,
|
|
||||||
};
|
|
||||||
const signature = getSessionKeySpecSignature(parsed.key);
|
|
||||||
const draft = candidates.get(signature) ?? [];
|
|
||||||
draft.push({
|
|
||||||
binding,
|
|
||||||
actionFingerprint: getBindingFingerprint(binding),
|
|
||||||
});
|
|
||||||
candidates.set(signature, draft);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (statsToggleKey) {
|
|
||||||
const parsed = parseDomKeyString(statsToggleKey, input.platform);
|
|
||||||
if (!parsed.key) {
|
|
||||||
warnings.push({
|
|
||||||
kind: 'unsupported',
|
|
||||||
path: 'stats.toggleKey',
|
|
||||||
value: statsToggleKey,
|
|
||||||
message: parsed.message ?? 'Unsupported stats toggle key syntax.',
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
const binding: CompiledSessionActionBinding = {
|
|
||||||
sourcePath: 'stats.toggleKey',
|
|
||||||
originalKey: statsToggleKey,
|
|
||||||
key: parsed.key,
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: 'toggleStatsOverlay',
|
|
||||||
};
|
|
||||||
const signature = getSessionKeySpecSignature(parsed.key);
|
|
||||||
const draft = candidates.get(signature) ?? [];
|
|
||||||
draft.push({
|
|
||||||
binding,
|
|
||||||
actionFingerprint: getBindingFingerprint(binding),
|
|
||||||
});
|
|
||||||
candidates.set(signature, draft);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
input.keybindings.forEach((binding, index) => {
|
|
||||||
if (!binding.command) return;
|
|
||||||
const parsed = parseDomKeyString(binding.key, input.platform);
|
|
||||||
if (!parsed.key) {
|
|
||||||
warnings.push({
|
|
||||||
kind: 'unsupported',
|
|
||||||
path: `keybindings[${index}].key`,
|
|
||||||
value: binding.key,
|
|
||||||
message: parsed.message ?? 'Unsupported keybinding syntax.',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const resolved = resolveCommandBinding(binding);
|
|
||||||
if (!resolved) {
|
|
||||||
warnings.push({
|
|
||||||
kind: 'unsupported',
|
|
||||||
path: `keybindings[${index}].key`,
|
|
||||||
value: binding.command,
|
|
||||||
message: 'Unsupported keybinding command syntax.',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const compiled: CompiledSessionBinding = {
|
|
||||||
sourcePath: `keybindings[${index}].key`,
|
|
||||||
originalKey: binding.key,
|
|
||||||
key: parsed.key,
|
|
||||||
...resolved,
|
|
||||||
};
|
|
||||||
const signature = getSessionKeySpecSignature(parsed.key);
|
|
||||||
const draft = candidates.get(signature) ?? [];
|
|
||||||
draft.push({
|
|
||||||
binding: compiled,
|
|
||||||
actionFingerprint: getBindingFingerprint(compiled),
|
|
||||||
});
|
|
||||||
candidates.set(signature, draft);
|
|
||||||
});
|
|
||||||
|
|
||||||
const bindings: CompiledSessionBinding[] = [];
|
|
||||||
for (const [signature, draftBindings] of candidates.entries()) {
|
|
||||||
const uniqueFingerprints = new Set(draftBindings.map((entry) => entry.actionFingerprint));
|
|
||||||
if (uniqueFingerprints.size > 1) {
|
|
||||||
warnings.push({
|
|
||||||
kind: 'conflict',
|
|
||||||
path: draftBindings[0]!.binding.sourcePath,
|
|
||||||
value: signature,
|
|
||||||
conflictingPaths: draftBindings.map((entry) => entry.binding.sourcePath),
|
|
||||||
message: `Conflicting session bindings compile to ${signature}; SubMiner will bind neither action.`,
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
bindings.push(draftBindings[0]!.binding);
|
|
||||||
}
|
|
||||||
|
|
||||||
bindings.sort((left, right) => left.sourcePath.localeCompare(right.sourcePath));
|
|
||||||
return { bindings, warnings };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildPluginSessionBindingsArtifact(input: {
|
|
||||||
bindings: CompiledSessionBinding[];
|
|
||||||
warnings: SessionBindingWarning[];
|
|
||||||
numericSelectionTimeoutMs: number;
|
|
||||||
now?: Date;
|
|
||||||
}): PluginSessionBindingsArtifact {
|
|
||||||
return {
|
|
||||||
version: 1,
|
|
||||||
generatedAt: (input.now ?? new Date()).toISOString(),
|
|
||||||
numericSelectionTimeoutMs: input.numericSelectionTimeoutMs,
|
|
||||||
bindings: input.bindings,
|
|
||||||
warnings: input.warnings,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -20,6 +20,42 @@ export interface RegisterGlobalShortcutsServiceOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function registerGlobalShortcuts(options: RegisterGlobalShortcutsServiceOptions): void {
|
export function registerGlobalShortcuts(options: RegisterGlobalShortcutsServiceOptions): void {
|
||||||
|
const visibleShortcut = options.shortcuts.toggleVisibleOverlayGlobal;
|
||||||
|
const normalizedVisible = visibleShortcut?.replace(/\s+/g, '').toLowerCase();
|
||||||
|
const normalizedJimaku = options.shortcuts.openJimaku?.replace(/\s+/g, '').toLowerCase();
|
||||||
|
const normalizedSettings = 'alt+shift+y';
|
||||||
|
|
||||||
|
if (visibleShortcut) {
|
||||||
|
const toggleVisibleRegistered = globalShortcut.register(visibleShortcut, () => {
|
||||||
|
options.onToggleVisibleOverlay();
|
||||||
|
});
|
||||||
|
if (!toggleVisibleRegistered) {
|
||||||
|
logger.warn(
|
||||||
|
`Failed to register global shortcut toggleVisibleOverlayGlobal: ${visibleShortcut}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.shortcuts.openJimaku && options.onOpenJimaku) {
|
||||||
|
if (
|
||||||
|
normalizedJimaku &&
|
||||||
|
(normalizedJimaku === normalizedVisible || normalizedJimaku === normalizedSettings)
|
||||||
|
) {
|
||||||
|
logger.warn(
|
||||||
|
'Skipped registering openJimaku because it collides with another global shortcut',
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const openJimakuRegistered = globalShortcut.register(options.shortcuts.openJimaku, () => {
|
||||||
|
options.onOpenJimaku?.();
|
||||||
|
});
|
||||||
|
if (!openJimakuRegistered) {
|
||||||
|
logger.warn(
|
||||||
|
`Failed to register global shortcut openJimaku: ${options.shortcuts.openJimaku}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const settingsRegistered = globalShortcut.register('Alt+Shift+Y', () => {
|
const settingsRegistered = globalShortcut.register('Alt+Shift+Y', () => {
|
||||||
options.onOpenYomitanSettings();
|
options.onOpenYomitanSettings();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -28,21 +28,7 @@ function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
|||||||
triggerFieldGrouping: false,
|
triggerFieldGrouping: false,
|
||||||
triggerSubsync: false,
|
triggerSubsync: false,
|
||||||
markAudioCard: false,
|
markAudioCard: false,
|
||||||
toggleStatsOverlay: false,
|
|
||||||
toggleSubtitleSidebar: false,
|
|
||||||
openRuntimeOptions: false,
|
openRuntimeOptions: false,
|
||||||
openSessionHelp: false,
|
|
||||||
openControllerSelect: false,
|
|
||||||
openControllerDebug: false,
|
|
||||||
openJimaku: false,
|
|
||||||
openYoutubePicker: false,
|
|
||||||
openPlaylistBrowser: false,
|
|
||||||
replayCurrentSubtitle: false,
|
|
||||||
playNextSubtitle: false,
|
|
||||||
shiftSubDelayPrevLine: false,
|
|
||||||
shiftSubDelayNextLine: false,
|
|
||||||
cycleRuntimeOptionId: undefined,
|
|
||||||
cycleRuntimeOptionDirection: undefined,
|
|
||||||
anilistStatus: false,
|
anilistStatus: false,
|
||||||
anilistLogout: false,
|
anilistLogout: false,
|
||||||
anilistSetup: false,
|
anilistSetup: false,
|
||||||
|
|||||||
@@ -311,8 +311,7 @@ export async function runAppReadyRuntime(deps: AppReadyRuntimeDeps): Promise<voi
|
|||||||
|
|
||||||
deps.createSubtitleTimingTracker();
|
deps.createSubtitleTimingTracker();
|
||||||
if (deps.createImmersionTracker) {
|
if (deps.createImmersionTracker) {
|
||||||
deps.createImmersionTracker();
|
deps.log('Runtime ready: immersion tracker startup deferred until first media activity.');
|
||||||
deps.log('Runtime ready: immersion tracker startup requested.');
|
|
||||||
} else {
|
} else {
|
||||||
deps.log('Runtime ready: immersion tracker dependency is missing.');
|
deps.log('Runtime ready: immersion tracker dependency is missing.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,10 +14,6 @@ export interface ConfiguredShortcuts {
|
|||||||
markAudioCard: string | null | undefined;
|
markAudioCard: string | null | undefined;
|
||||||
openRuntimeOptions: string | null | undefined;
|
openRuntimeOptions: string | null | undefined;
|
||||||
openJimaku: string | null | undefined;
|
openJimaku: string | null | undefined;
|
||||||
openSessionHelp: string | null | undefined;
|
|
||||||
openControllerSelect: string | null | undefined;
|
|
||||||
openControllerDebug: string | null | undefined;
|
|
||||||
toggleSubtitleSidebar: string | null | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveConfiguredShortcuts(
|
export function resolveConfiguredShortcuts(
|
||||||
@@ -82,17 +78,5 @@ export function resolveConfiguredShortcuts(
|
|||||||
openJimaku: normalizeShortcut(
|
openJimaku: normalizeShortcut(
|
||||||
config.shortcuts?.openJimaku ?? defaultConfig.shortcuts?.openJimaku,
|
config.shortcuts?.openJimaku ?? defaultConfig.shortcuts?.openJimaku,
|
||||||
),
|
),
|
||||||
openSessionHelp: normalizeShortcut(
|
|
||||||
config.shortcuts?.openSessionHelp ?? defaultConfig.shortcuts?.openSessionHelp,
|
|
||||||
),
|
|
||||||
openControllerSelect: normalizeShortcut(
|
|
||||||
config.shortcuts?.openControllerSelect ?? defaultConfig.shortcuts?.openControllerSelect,
|
|
||||||
),
|
|
||||||
openControllerDebug: normalizeShortcut(
|
|
||||||
config.shortcuts?.openControllerDebug ?? defaultConfig.shortcuts?.openControllerDebug,
|
|
||||||
),
|
|
||||||
toggleSubtitleSidebar: normalizeShortcut(
|
|
||||||
config.shortcuts?.toggleSubtitleSidebar ?? defaultConfig.shortcuts?.toggleSubtitleSidebar,
|
|
||||||
),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
298
src/main.ts
298
src/main.ts
@@ -109,13 +109,11 @@ import * as os from 'os';
|
|||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import { MecabTokenizer } from './mecab-tokenizer';
|
import { MecabTokenizer } from './mecab-tokenizer';
|
||||||
import type {
|
import type {
|
||||||
CompiledSessionBinding,
|
|
||||||
JimakuApiResponse,
|
JimakuApiResponse,
|
||||||
KikuFieldGroupingChoice,
|
KikuFieldGroupingChoice,
|
||||||
MpvSubtitleRenderMetrics,
|
MpvSubtitleRenderMetrics,
|
||||||
ResolvedConfig,
|
ResolvedConfig,
|
||||||
RuntimeOptionState,
|
RuntimeOptionState,
|
||||||
SessionActionDispatchRequest,
|
|
||||||
SecondarySubMode,
|
SecondarySubMode,
|
||||||
SubtitleData,
|
SubtitleData,
|
||||||
SubtitlePosition,
|
SubtitlePosition,
|
||||||
@@ -133,12 +131,13 @@ import {
|
|||||||
} from './logger';
|
} from './logger';
|
||||||
import { createWindowTracker as createWindowTrackerCore } from './window-trackers';
|
import { createWindowTracker as createWindowTrackerCore } from './window-trackers';
|
||||||
import {
|
import {
|
||||||
bindWindowsOverlayAboveMpv,
|
bindWindowsOverlayAboveMpvNative,
|
||||||
clearWindowsOverlayOwner,
|
clearWindowsOverlayOwnerNative,
|
||||||
ensureWindowsOverlayTransparency,
|
ensureWindowsOverlayTransparencyNative,
|
||||||
findWindowsMpvTargetWindowHandle,
|
getWindowsForegroundProcessNameNative,
|
||||||
getWindowsForegroundProcessName,
|
queryWindowsForegroundProcessName,
|
||||||
setWindowsOverlayOwner,
|
setWindowsOverlayOwnerNative,
|
||||||
|
syncWindowsOverlayToMpvZOrder,
|
||||||
} from './window-trackers/windows-helper';
|
} from './window-trackers/windows-helper';
|
||||||
import {
|
import {
|
||||||
commandNeedsOverlayStartupPrereqs,
|
commandNeedsOverlayStartupPrereqs,
|
||||||
@@ -352,7 +351,6 @@ import { resolveYoutubePlaybackUrl } from './core/services/youtube/playback-reso
|
|||||||
import { probeYoutubeTracks } from './core/services/youtube/track-probe';
|
import { probeYoutubeTracks } from './core/services/youtube/track-probe';
|
||||||
import { startStatsServer } from './core/services/stats-server';
|
import { startStatsServer } from './core/services/stats-server';
|
||||||
import { registerStatsOverlayToggle, destroyStatsWindow } from './core/services/stats-window.js';
|
import { registerStatsOverlayToggle, destroyStatsWindow } from './core/services/stats-window.js';
|
||||||
import { toggleStatsOverlay as toggleStatsOverlayWindow } from './core/services/stats-window.js';
|
|
||||||
import {
|
import {
|
||||||
createFirstRunSetupService,
|
createFirstRunSetupService,
|
||||||
getFirstRunSetupCompletionMessage,
|
getFirstRunSetupCompletionMessage,
|
||||||
@@ -415,8 +413,6 @@ import { createAnilistRateLimiter } from './core/services/anilist/rate-limiter';
|
|||||||
import { createJellyfinTokenStore } from './core/services/jellyfin-token-store';
|
import { createJellyfinTokenStore } from './core/services/jellyfin-token-store';
|
||||||
import { applyRuntimeOptionResultRuntime } from './core/services/runtime-options-ipc';
|
import { applyRuntimeOptionResultRuntime } from './core/services/runtime-options-ipc';
|
||||||
import { createAnilistTokenStore } from './core/services/anilist/anilist-token-store';
|
import { createAnilistTokenStore } from './core/services/anilist/anilist-token-store';
|
||||||
import { buildPluginSessionBindingsArtifact, compileSessionBindings } from './core/services/session-bindings';
|
|
||||||
import { dispatchSessionAction as dispatchSessionActionCore } from './core/services/session-actions';
|
|
||||||
import { createBuildOverlayShortcutsRuntimeMainDepsHandler } from './main/runtime/domains/shortcuts';
|
import { createBuildOverlayShortcutsRuntimeMainDepsHandler } from './main/runtime/domains/shortcuts';
|
||||||
import { createMainRuntimeRegistry } from './main/runtime/registry';
|
import { createMainRuntimeRegistry } from './main/runtime/registry';
|
||||||
import {
|
import {
|
||||||
@@ -452,14 +448,7 @@ import { handleCliCommandRuntimeServiceWithContext } from './main/cli-runtime';
|
|||||||
import { createOverlayModalRuntimeService } from './main/overlay-runtime';
|
import { createOverlayModalRuntimeService } from './main/overlay-runtime';
|
||||||
import { createOverlayModalInputState } from './main/runtime/overlay-modal-input-state';
|
import { createOverlayModalInputState } from './main/runtime/overlay-modal-input-state';
|
||||||
import { openYoutubeTrackPicker } from './main/runtime/youtube-picker-open';
|
import { openYoutubeTrackPicker } from './main/runtime/youtube-picker-open';
|
||||||
import { openRuntimeOptionsModal as openRuntimeOptionsModalRuntime } from './main/runtime/runtime-options-open';
|
|
||||||
import { openJimakuModal as openJimakuModalRuntime } from './main/runtime/jimaku-open';
|
|
||||||
import { openSessionHelpModal as openSessionHelpModalRuntime } from './main/runtime/session-help-open';
|
|
||||||
import { openControllerSelectModal as openControllerSelectModalRuntime } from './main/runtime/controller-select-open';
|
|
||||||
import { openControllerDebugModal as openControllerDebugModalRuntime } from './main/runtime/controller-debug-open';
|
|
||||||
import { createPlaylistBrowserIpcRuntime } from './main/runtime/playlist-browser-ipc';
|
import { createPlaylistBrowserIpcRuntime } from './main/runtime/playlist-browser-ipc';
|
||||||
import { writeSessionBindingsArtifact } from './main/runtime/session-bindings-artifact';
|
|
||||||
import { openOverlayHostedModal } from './main/runtime/overlay-hosted-modal-open';
|
|
||||||
import { createOverlayShortcutsRuntimeService } from './main/overlay-shortcuts-runtime';
|
import { createOverlayShortcutsRuntimeService } from './main/overlay-shortcuts-runtime';
|
||||||
import {
|
import {
|
||||||
createFrequencyDictionaryRuntimeService,
|
createFrequencyDictionaryRuntimeService,
|
||||||
@@ -1490,7 +1479,9 @@ const overlayShortcutsRuntime = createOverlayShortcutsRuntimeService(
|
|||||||
openRuntimeOptionsPalette();
|
openRuntimeOptionsPalette();
|
||||||
},
|
},
|
||||||
openJimaku: () => {
|
openJimaku: () => {
|
||||||
openJimakuOverlay();
|
sendToActiveOverlayWindow('jimaku:open', undefined, {
|
||||||
|
restoreOnModalClose: 'jimaku',
|
||||||
|
});
|
||||||
},
|
},
|
||||||
markAudioCard: () => markLastCardAsAudioCard(),
|
markAudioCard: () => markLastCardAsAudioCard(),
|
||||||
copySubtitleMultiple: (timeoutMs: number) => {
|
copySubtitleMultiple: (timeoutMs: number) => {
|
||||||
@@ -1544,9 +1535,6 @@ const buildConfigHotReloadAppliedMainDepsHandler = createBuildConfigHotReloadApp
|
|||||||
setKeybindings: (keybindings) => {
|
setKeybindings: (keybindings) => {
|
||||||
appState.keybindings = keybindings;
|
appState.keybindings = keybindings;
|
||||||
},
|
},
|
||||||
setSessionBindings: (sessionBindings) => {
|
|
||||||
persistSessionBindings(sessionBindings);
|
|
||||||
},
|
|
||||||
refreshGlobalAndOverlayShortcuts: () => {
|
refreshGlobalAndOverlayShortcuts: () => {
|
||||||
refreshGlobalAndOverlayShortcuts();
|
refreshGlobalAndOverlayShortcuts();
|
||||||
},
|
},
|
||||||
@@ -1907,6 +1895,7 @@ let windowsVisibleOverlayZOrderRetryTimeouts: Array<ReturnType<typeof setTimeout
|
|||||||
let windowsVisibleOverlayZOrderSyncInFlight = false;
|
let windowsVisibleOverlayZOrderSyncInFlight = false;
|
||||||
let windowsVisibleOverlayZOrderSyncQueued = false;
|
let windowsVisibleOverlayZOrderSyncQueued = false;
|
||||||
let windowsVisibleOverlayForegroundPollInterval: ReturnType<typeof setInterval> | null = null;
|
let windowsVisibleOverlayForegroundPollInterval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let windowsVisibleOverlayForegroundPollInFlight = false;
|
||||||
let lastWindowsVisibleOverlayForegroundProcessName: string | null = null;
|
let lastWindowsVisibleOverlayForegroundProcessName: string | null = null;
|
||||||
let lastWindowsVisibleOverlayBlurredAtMs = 0;
|
let lastWindowsVisibleOverlayBlurredAtMs = 0;
|
||||||
|
|
||||||
@@ -1938,19 +1927,6 @@ function getWindowsNativeWindowHandleNumber(window: BrowserWindow): number {
|
|||||||
: handle.readUInt32LE(0);
|
: handle.readUInt32LE(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveWindowsOverlayBindTargetHandle(targetMpvSocketPath?: string | null): number | null {
|
|
||||||
if (process.platform !== 'win32') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
void targetMpvSocketPath;
|
|
||||||
return findWindowsMpvTargetWindowHandle();
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function syncWindowsVisibleOverlayToMpvZOrder(): Promise<boolean> {
|
async function syncWindowsVisibleOverlayToMpvZOrder(): Promise<boolean> {
|
||||||
if (process.platform !== 'win32') {
|
if (process.platform !== 'win32') {
|
||||||
return false;
|
return false;
|
||||||
@@ -1983,12 +1959,19 @@ async function syncWindowsVisibleOverlayToMpvZOrder(): Promise<boolean> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
|
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
|
||||||
const targetWindowHwnd = resolveWindowsOverlayBindTargetHandle(appState.mpvSocketPath);
|
if (bindWindowsOverlayAboveMpvNative(overlayHwnd)) {
|
||||||
if (targetWindowHwnd !== null && bindWindowsOverlayAboveMpv(overlayHwnd, targetWindowHwnd)) {
|
|
||||||
(mainWindow as BrowserWindow & { setOpacity?: (opacity: number) => void }).setOpacity?.(1);
|
(mainWindow as BrowserWindow & { setOpacity?: (opacity: number) => void }).setOpacity?.(1);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
|
||||||
|
const synced = await syncWindowsOverlayToMpvZOrder({
|
||||||
|
overlayWindowHandle: getWindowsNativeWindowHandle(mainWindow),
|
||||||
|
targetMpvSocketPath: appState.mpvSocketPath,
|
||||||
|
});
|
||||||
|
if (synced) {
|
||||||
|
(mainWindow as BrowserWindow & { setOpacity?: (opacity: number) => void }).setOpacity?.(1);
|
||||||
|
}
|
||||||
|
return synced;
|
||||||
}
|
}
|
||||||
|
|
||||||
function requestWindowsVisibleOverlayZOrderSync(): void {
|
function requestWindowsVisibleOverlayZOrderSync(): void {
|
||||||
@@ -2076,7 +2059,7 @@ function maybePollWindowsVisibleOverlayForegroundProcess(): void {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const processName = getWindowsForegroundProcessName();
|
const processName = getWindowsForegroundProcessNameNative();
|
||||||
const normalizedProcessName = processName?.trim().toLowerCase() ?? null;
|
const normalizedProcessName = processName?.trim().toLowerCase() ?? null;
|
||||||
const previousProcessName = lastWindowsVisibleOverlayForegroundProcessName;
|
const previousProcessName = lastWindowsVisibleOverlayForegroundProcessName;
|
||||||
lastWindowsVisibleOverlayForegroundProcessName = normalizedProcessName;
|
lastWindowsVisibleOverlayForegroundProcessName = normalizedProcessName;
|
||||||
@@ -2099,15 +2082,6 @@ function ensureWindowsVisibleOverlayForegroundPollLoop(): void {
|
|||||||
}, WINDOWS_VISIBLE_OVERLAY_FOREGROUND_POLL_INTERVAL_MS);
|
}, WINDOWS_VISIBLE_OVERLAY_FOREGROUND_POLL_INTERVAL_MS);
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearWindowsVisibleOverlayForegroundPollLoop(): void {
|
|
||||||
if (windowsVisibleOverlayForegroundPollInterval === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
clearInterval(windowsVisibleOverlayForegroundPollInterval);
|
|
||||||
windowsVisibleOverlayForegroundPollInterval = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleVisibleOverlayBlurRefresh(): void {
|
function scheduleVisibleOverlayBlurRefresh(): void {
|
||||||
if (process.platform !== 'win32') {
|
if (process.platform !== 'win32') {
|
||||||
return;
|
return;
|
||||||
@@ -2215,84 +2189,8 @@ function setOverlayDebugVisualizationEnabled(enabled: boolean): void {
|
|||||||
overlayVisibilityComposer.setOverlayDebugVisualizationEnabled(enabled);
|
overlayVisibilityComposer.setOverlayDebugVisualizationEnabled(enabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
function createOverlayHostedModalOpenDeps(): {
|
|
||||||
ensureOverlayStartupPrereqs: () => void;
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
|
||||||
sendToActiveOverlayWindow: (
|
|
||||||
channel: string,
|
|
||||||
payload?: unknown,
|
|
||||||
runtimeOptions?: {
|
|
||||||
restoreOnModalClose?: OverlayHostedModal;
|
|
||||||
preferModalWindow?: boolean;
|
|
||||||
},
|
|
||||||
) => boolean;
|
|
||||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
|
||||||
logWarn: (message: string) => void;
|
|
||||||
} {
|
|
||||||
return {
|
|
||||||
ensureOverlayStartupPrereqs: () => ensureOverlayStartupPrereqs(),
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () =>
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions(),
|
|
||||||
sendToActiveOverlayWindow: (channel, payload, runtimeOptions) =>
|
|
||||||
sendToActiveOverlayWindow(channel, payload, runtimeOptions),
|
|
||||||
waitForModalOpen: (modal, timeoutMs) => overlayModalRuntime.waitForModalOpen(modal, timeoutMs),
|
|
||||||
logWarn: (message) => logger.warn(message),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function openOverlayHostedModalWithOsd(
|
|
||||||
openModal: (deps: ReturnType<typeof createOverlayHostedModalOpenDeps>) => Promise<boolean>,
|
|
||||||
unavailableMessage: string,
|
|
||||||
failureLogMessage: string,
|
|
||||||
): void {
|
|
||||||
void openModal(createOverlayHostedModalOpenDeps()).then((opened) => {
|
|
||||||
if (!opened) {
|
|
||||||
showMpvOsd(unavailableMessage);
|
|
||||||
}
|
|
||||||
}).catch((error) => {
|
|
||||||
logger.error(failureLogMessage, error);
|
|
||||||
showMpvOsd(unavailableMessage);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function openRuntimeOptionsPalette(): void {
|
function openRuntimeOptionsPalette(): void {
|
||||||
openOverlayHostedModalWithOsd(
|
overlayVisibilityComposer.openRuntimeOptionsPalette();
|
||||||
openRuntimeOptionsModalRuntime,
|
|
||||||
'Runtime options overlay unavailable.',
|
|
||||||
'Failed to open runtime options overlay.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function openJimakuOverlay(): void {
|
|
||||||
openOverlayHostedModalWithOsd(
|
|
||||||
openJimakuModalRuntime,
|
|
||||||
'Jimaku overlay unavailable.',
|
|
||||||
'Failed to open Jimaku overlay.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function openSessionHelpOverlay(): void {
|
|
||||||
openOverlayHostedModalWithOsd(
|
|
||||||
openSessionHelpModalRuntime,
|
|
||||||
'Session help overlay unavailable.',
|
|
||||||
'Failed to open session help overlay.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function openControllerSelectOverlay(): void {
|
|
||||||
openOverlayHostedModalWithOsd(
|
|
||||||
openControllerSelectModalRuntime,
|
|
||||||
'Controller select overlay unavailable.',
|
|
||||||
'Failed to open controller select overlay.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function openControllerDebugOverlay(): void {
|
|
||||||
openOverlayHostedModalWithOsd(
|
|
||||||
openControllerDebugModalRuntime,
|
|
||||||
'Controller debug overlay unavailable.',
|
|
||||||
'Failed to open controller debug overlay.',
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function openPlaylistBrowser(): void {
|
function openPlaylistBrowser(): void {
|
||||||
@@ -2300,11 +2198,16 @@ function openPlaylistBrowser(): void {
|
|||||||
showMpvOsd('Playlist browser requires active playback.');
|
showMpvOsd('Playlist browser requires active playback.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
openOverlayHostedModalWithOsd(
|
const opened = openPlaylistBrowserRuntime({
|
||||||
openPlaylistBrowserRuntime,
|
ensureOverlayStartupPrereqs: () => ensureOverlayStartupPrereqs(),
|
||||||
'Playlist browser overlay unavailable.',
|
ensureOverlayWindowsReadyForVisibilityActions: () =>
|
||||||
'Failed to open playlist browser overlay.',
|
ensureOverlayWindowsReadyForVisibilityActions(),
|
||||||
);
|
sendToActiveOverlayWindow: (channel, payload, runtimeOptions) =>
|
||||||
|
sendToActiveOverlayWindow(channel, payload, runtimeOptions),
|
||||||
|
});
|
||||||
|
if (!opened) {
|
||||||
|
showMpvOsd('Playlist browser overlay unavailable.');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getResolvedConfig() {
|
function getResolvedConfig() {
|
||||||
@@ -3075,8 +2978,6 @@ const {
|
|||||||
annotationSubtitleWsService.stop();
|
annotationSubtitleWsService.stop();
|
||||||
},
|
},
|
||||||
stopTexthookerService: () => texthookerService.stop(),
|
stopTexthookerService: () => texthookerService.stop(),
|
||||||
clearWindowsVisibleOverlayForegroundPollLoop: () =>
|
|
||||||
clearWindowsVisibleOverlayForegroundPollLoop(),
|
|
||||||
getMainOverlayWindow: () => overlayManager.getMainWindow(),
|
getMainOverlayWindow: () => overlayManager.getMainWindow(),
|
||||||
clearMainOverlayWindow: () => overlayManager.setMainWindow(null),
|
clearMainOverlayWindow: () => overlayManager.setMainWindow(null),
|
||||||
getModalOverlayWindow: () => overlayManager.getModalWindow(),
|
getModalOverlayWindow: () => overlayManager.getModalWindow(),
|
||||||
@@ -3477,7 +3378,6 @@ const { appReadyRuntimeRunner } = composeAppReadyRuntime({
|
|||||||
loadSubtitlePosition: () => loadSubtitlePosition(),
|
loadSubtitlePosition: () => loadSubtitlePosition(),
|
||||||
resolveKeybindings: () => {
|
resolveKeybindings: () => {
|
||||||
appState.keybindings = resolveKeybindings(getResolvedConfig(), DEFAULT_KEYBINDINGS);
|
appState.keybindings = resolveKeybindings(getResolvedConfig(), DEFAULT_KEYBINDINGS);
|
||||||
refreshCurrentSessionBindings();
|
|
||||||
},
|
},
|
||||||
createMpvClient: () => {
|
createMpvClient: () => {
|
||||||
appState.mpvClient = createMpvClientRuntimeService();
|
appState.mpvClient = createMpvClientRuntimeService();
|
||||||
@@ -3620,9 +3520,6 @@ function ensureOverlayStartupPrereqs(): void {
|
|||||||
}
|
}
|
||||||
if (appState.keybindings.length === 0) {
|
if (appState.keybindings.length === 0) {
|
||||||
appState.keybindings = resolveKeybindings(getResolvedConfig(), DEFAULT_KEYBINDINGS);
|
appState.keybindings = resolveKeybindings(getResolvedConfig(), DEFAULT_KEYBINDINGS);
|
||||||
refreshCurrentSessionBindings();
|
|
||||||
} else if (appState.sessionBindings.length === 0) {
|
|
||||||
refreshCurrentSessionBindings();
|
|
||||||
}
|
}
|
||||||
if (!appState.mpvClient) {
|
if (!appState.mpvClient) {
|
||||||
appState.mpvClient = createMpvClientRuntimeService();
|
appState.mpvClient = createMpvClientRuntimeService();
|
||||||
@@ -4140,7 +4037,7 @@ function createMainWindow(): BrowserWindow {
|
|||||||
const window = createMainWindowHandler();
|
const window = createMainWindowHandler();
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
const overlayHwnd = getWindowsNativeWindowHandleNumber(window);
|
const overlayHwnd = getWindowsNativeWindowHandleNumber(window);
|
||||||
if (!ensureWindowsOverlayTransparency(overlayHwnd)) {
|
if (!ensureWindowsOverlayTransparencyNative(overlayHwnd)) {
|
||||||
logger.warn('Failed to eagerly extend Windows overlay transparency via koffi');
|
logger.warn('Failed to eagerly extend Windows overlay transparency via koffi');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4221,54 +4118,6 @@ const {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
function resolveSessionBindingPlatform(): 'darwin' | 'win32' | 'linux' {
|
|
||||||
if (process.platform === 'darwin') return 'darwin';
|
|
||||||
if (process.platform === 'win32') return 'win32';
|
|
||||||
return 'linux';
|
|
||||||
}
|
|
||||||
|
|
||||||
function compileCurrentSessionBindings(): {
|
|
||||||
bindings: CompiledSessionBinding[];
|
|
||||||
warnings: ReturnType<typeof compileSessionBindings>['warnings'];
|
|
||||||
} {
|
|
||||||
return compileSessionBindings({
|
|
||||||
keybindings: appState.keybindings,
|
|
||||||
shortcuts: getConfiguredShortcuts(),
|
|
||||||
statsToggleKey: getResolvedConfig().stats.toggleKey,
|
|
||||||
platform: resolveSessionBindingPlatform(),
|
|
||||||
rawConfig: getResolvedConfig(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function persistSessionBindings(
|
|
||||||
bindings: CompiledSessionBinding[],
|
|
||||||
warnings: ReturnType<typeof compileSessionBindings>['warnings'] = [],
|
|
||||||
): void {
|
|
||||||
appState.sessionBindings = bindings;
|
|
||||||
writeSessionBindingsArtifact(
|
|
||||||
CONFIG_DIR,
|
|
||||||
buildPluginSessionBindingsArtifact({
|
|
||||||
bindings,
|
|
||||||
warnings,
|
|
||||||
numericSelectionTimeoutMs: getConfiguredShortcuts().multiCopyTimeoutMs,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
if (appState.mpvClient?.connected) {
|
|
||||||
sendMpvCommandRuntime(appState.mpvClient, [
|
|
||||||
'script-message',
|
|
||||||
'subminer-reload-session-bindings',
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function refreshCurrentSessionBindings(): void {
|
|
||||||
const compiled = compileCurrentSessionBindings();
|
|
||||||
for (const warning of compiled.warnings) {
|
|
||||||
logger.warn(`[session-bindings] ${warning.message}`);
|
|
||||||
}
|
|
||||||
persistSessionBindings(compiled.bindings, compiled.warnings);
|
|
||||||
}
|
|
||||||
|
|
||||||
const { flushMpvLog, showMpvOsd } = createMpvOsdRuntimeHandlers({
|
const { flushMpvLog, showMpvOsd } = createMpvOsdRuntimeHandlers({
|
||||||
appendToMpvLogMainDeps: {
|
appendToMpvLogMainDeps: {
|
||||||
logPath: DEFAULT_MPV_LOG_PATH,
|
logPath: DEFAULT_MPV_LOG_PATH,
|
||||||
@@ -4319,10 +4168,6 @@ function handleCycleSecondarySubMode(): void {
|
|||||||
cycleSecondarySubMode();
|
cycleSecondarySubMode();
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleSubtitleSidebar(): void {
|
|
||||||
broadcastToOverlayWindows(IPC_CHANNELS.event.subtitleSidebarToggle);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function triggerSubsyncFromConfig(): Promise<void> {
|
async function triggerSubsyncFromConfig(): Promise<void> {
|
||||||
await subsyncRuntime.triggerFromConfig();
|
await subsyncRuntime.triggerFromConfig();
|
||||||
}
|
}
|
||||||
@@ -4584,55 +4429,6 @@ const shiftSubtitleDelayToAdjacentCueHandler = createShiftSubtitleDelayToAdjacen
|
|||||||
showMpvOsd: (text) => showMpvOsd(text),
|
showMpvOsd: (text) => showMpvOsd(text),
|
||||||
});
|
});
|
||||||
|
|
||||||
async function dispatchSessionAction(request: SessionActionDispatchRequest): Promise<void> {
|
|
||||||
await dispatchSessionActionCore(request, {
|
|
||||||
toggleStatsOverlay: () =>
|
|
||||||
toggleStatsOverlayWindow({
|
|
||||||
staticDir: statsDistPath,
|
|
||||||
preloadPath: statsPreloadPath,
|
|
||||||
getApiBaseUrl: () => ensureStatsServerStarted(),
|
|
||||||
getToggleKey: () => getResolvedConfig().stats.toggleKey,
|
|
||||||
resolveBounds: () => getCurrentOverlayGeometry(),
|
|
||||||
onVisibilityChanged: (visible) => {
|
|
||||||
appState.statsOverlayVisible = visible;
|
|
||||||
overlayVisibilityRuntime.updateVisibleOverlayVisibility();
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
toggleVisibleOverlay: () => toggleVisibleOverlay(),
|
|
||||||
copyCurrentSubtitle: () => copyCurrentSubtitle(),
|
|
||||||
copySubtitleCount: (count) => handleMultiCopyDigit(count),
|
|
||||||
updateLastCardFromClipboard: () => updateLastCardFromClipboard(),
|
|
||||||
triggerFieldGrouping: () => triggerFieldGrouping(),
|
|
||||||
triggerSubsyncFromConfig: () => triggerSubsyncFromConfig(),
|
|
||||||
mineSentenceCard: () => mineSentenceCard(),
|
|
||||||
mineSentenceCount: (count) => handleMineSentenceDigit(count),
|
|
||||||
toggleSecondarySub: () => handleCycleSecondarySubMode(),
|
|
||||||
toggleSubtitleSidebar: () => toggleSubtitleSidebar(),
|
|
||||||
markLastCardAsAudioCard: () => markLastCardAsAudioCard(),
|
|
||||||
openRuntimeOptionsPalette: () => openRuntimeOptionsPalette(),
|
|
||||||
openJimaku: () => openJimakuOverlay(),
|
|
||||||
openSessionHelp: () => openSessionHelpOverlay(),
|
|
||||||
openControllerSelect: () => openControllerSelectOverlay(),
|
|
||||||
openControllerDebug: () => openControllerDebugOverlay(),
|
|
||||||
openYoutubeTrackPicker: () => openYoutubeTrackPickerFromPlayback(),
|
|
||||||
openPlaylistBrowser: () => openPlaylistBrowser(),
|
|
||||||
replayCurrentSubtitle: () => replayCurrentSubtitleRuntime(appState.mpvClient),
|
|
||||||
playNextSubtitle: () => playNextSubtitleRuntime(appState.mpvClient),
|
|
||||||
shiftSubDelayToAdjacentSubtitle: (direction) =>
|
|
||||||
shiftSubtitleDelayToAdjacentCueHandler(direction),
|
|
||||||
cycleRuntimeOption: (id, direction) => {
|
|
||||||
if (!appState.runtimeOptionsManager) {
|
|
||||||
return { ok: false, error: 'Runtime options manager unavailable' };
|
|
||||||
}
|
|
||||||
return applyRuntimeOptionResultRuntime(
|
|
||||||
appState.runtimeOptionsManager.cycleOption(id, direction),
|
|
||||||
(text) => showMpvOsd(text),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
showMpvOsd: (text) => showMpvOsd(text),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const { playlistBrowserMainDeps } = createPlaylistBrowserIpcRuntime(() => appState.mpvClient, {
|
const { playlistBrowserMainDeps } = createPlaylistBrowserIpcRuntime(() => appState.mpvClient, {
|
||||||
getPrimarySubtitleLanguages: () => getResolvedConfig().youtube.primarySubLanguages,
|
getPrimarySubtitleLanguages: () => getResolvedConfig().youtube.primarySubLanguages,
|
||||||
getSecondarySubtitleLanguages: () => getResolvedConfig().secondarySub.secondarySubLanguages,
|
getSecondarySubtitleLanguages: () => getResolvedConfig().secondarySub.secondarySubLanguages,
|
||||||
@@ -4642,7 +4438,7 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
|||||||
mpvCommandMainDeps: {
|
mpvCommandMainDeps: {
|
||||||
triggerSubsyncFromConfig: () => triggerSubsyncFromConfig(),
|
triggerSubsyncFromConfig: () => triggerSubsyncFromConfig(),
|
||||||
openRuntimeOptionsPalette: () => openRuntimeOptionsPalette(),
|
openRuntimeOptionsPalette: () => openRuntimeOptionsPalette(),
|
||||||
openJimaku: () => openJimakuOverlay(),
|
openJimaku: () => overlayModalRuntime.openJimaku(),
|
||||||
openYoutubeTrackPicker: () => openYoutubeTrackPickerFromPlayback(),
|
openYoutubeTrackPicker: () => openYoutubeTrackPickerFromPlayback(),
|
||||||
openPlaylistBrowser: () => openPlaylistBrowser(),
|
openPlaylistBrowser: () => openPlaylistBrowser(),
|
||||||
cycleRuntimeOption: (id, direction) => {
|
cycleRuntimeOption: (id, direction) => {
|
||||||
@@ -4682,17 +4478,7 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
|||||||
mainWindow.focus();
|
mainWindow.focus();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onOverlayModalClosed: (modal, senderWindow) => {
|
onOverlayModalClosed: (modal) => {
|
||||||
const modalWindow = overlayManager.getModalWindow();
|
|
||||||
if (
|
|
||||||
senderWindow &&
|
|
||||||
modalWindow &&
|
|
||||||
senderWindow === modalWindow &&
|
|
||||||
!senderWindow.isDestroyed()
|
|
||||||
) {
|
|
||||||
senderWindow.setIgnoreMouseEvents(true, { forward: true });
|
|
||||||
senderWindow.hide();
|
|
||||||
}
|
|
||||||
handleOverlayModalClosed(modal);
|
handleOverlayModalClosed(modal);
|
||||||
},
|
},
|
||||||
onOverlayModalOpened: (modal) => {
|
onOverlayModalOpened: (modal) => {
|
||||||
@@ -4800,9 +4586,7 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
|
|||||||
saveSubtitlePosition: (position) => saveSubtitlePosition(position),
|
saveSubtitlePosition: (position) => saveSubtitlePosition(position),
|
||||||
getMecabTokenizer: () => appState.mecabTokenizer,
|
getMecabTokenizer: () => appState.mecabTokenizer,
|
||||||
getKeybindings: () => appState.keybindings,
|
getKeybindings: () => appState.keybindings,
|
||||||
getSessionBindings: () => appState.sessionBindings,
|
|
||||||
getConfiguredShortcuts: () => getConfiguredShortcuts(),
|
getConfiguredShortcuts: () => getConfiguredShortcuts(),
|
||||||
dispatchSessionAction: (request) => dispatchSessionAction(request),
|
|
||||||
getStatsToggleKey: () => getResolvedConfig().stats.toggleKey,
|
getStatsToggleKey: () => getResolvedConfig().stats.toggleKey,
|
||||||
getMarkWatchedKey: () => getResolvedConfig().stats.markWatchedKey,
|
getMarkWatchedKey: () => getResolvedConfig().stats.markWatchedKey,
|
||||||
getControllerConfig: () => getResolvedConfig().controller,
|
getControllerConfig: () => getResolvedConfig().controller,
|
||||||
@@ -4923,7 +4707,6 @@ const { handleCliCommand, handleInitialArgs } = composeCliStartupHandlers({
|
|||||||
printHelp: () => printHelp(DEFAULT_TEXTHOOKER_PORT),
|
printHelp: () => printHelp(DEFAULT_TEXTHOOKER_PORT),
|
||||||
stopApp: () => requestAppQuit(),
|
stopApp: () => requestAppQuit(),
|
||||||
hasMainWindow: () => Boolean(overlayManager.getMainWindow()),
|
hasMainWindow: () => Boolean(overlayManager.getMainWindow()),
|
||||||
dispatchSessionAction: (request: SessionActionDispatchRequest) => dispatchSessionAction(request),
|
|
||||||
getMultiCopyTimeoutMs: () => getConfiguredShortcuts().multiCopyTimeoutMs,
|
getMultiCopyTimeoutMs: () => getConfiguredShortcuts().multiCopyTimeoutMs,
|
||||||
schedule: (fn: () => void, delayMs: number) => setTimeout(fn, delayMs),
|
schedule: (fn: () => void, delayMs: number) => setTimeout(fn, delayMs),
|
||||||
logInfo: (message: string) => logger.info(message),
|
logInfo: (message: string) => logger.info(message),
|
||||||
@@ -5190,8 +4973,7 @@ const { initializeOverlayRuntime: initializeOverlayRuntimeHandler } =
|
|||||||
const mainWindow = overlayManager.getMainWindow();
|
const mainWindow = overlayManager.getMainWindow();
|
||||||
if (process.platform !== 'win32' || !mainWindow || mainWindow.isDestroyed()) return;
|
if (process.platform !== 'win32' || !mainWindow || mainWindow.isDestroyed()) return;
|
||||||
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
|
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
|
||||||
const targetWindowHwnd = resolveWindowsOverlayBindTargetHandle(appState.mpvSocketPath);
|
if (bindWindowsOverlayAboveMpvNative(overlayHwnd)) {
|
||||||
if (targetWindowHwnd !== null && bindWindowsOverlayAboveMpv(overlayHwnd, targetWindowHwnd)) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const tracker = appState.windowTracker;
|
const tracker = appState.windowTracker;
|
||||||
@@ -5201,14 +4983,14 @@ const { initializeOverlayRuntime: initializeOverlayRuntimeHandler } =
|
|||||||
const win32 = require('./window-trackers/win32') as typeof import('./window-trackers/win32');
|
const win32 = require('./window-trackers/win32') as typeof import('./window-trackers/win32');
|
||||||
const poll = win32.findMpvWindows();
|
const poll = win32.findMpvWindows();
|
||||||
const focused = poll.matches.find((m) => m.isForeground);
|
const focused = poll.matches.find((m) => m.isForeground);
|
||||||
return focused ?? [...poll.matches].sort((a, b) => b.area - a.area)[0] ?? null;
|
return focused ?? poll.matches.sort((a, b) => b.area - a.area)[0] ?? null;
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
})()
|
})()
|
||||||
: null;
|
: null;
|
||||||
if (!mpvResult) return;
|
if (!mpvResult) return;
|
||||||
if (!setWindowsOverlayOwner(overlayHwnd, mpvResult.hwnd)) {
|
if (!setWindowsOverlayOwnerNative(overlayHwnd, mpvResult.hwnd)) {
|
||||||
logger.warn('Failed to set overlay owner via koffi');
|
logger.warn('Failed to set overlay owner via koffi');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -5216,7 +4998,7 @@ const { initializeOverlayRuntime: initializeOverlayRuntimeHandler } =
|
|||||||
const mainWindow = overlayManager.getMainWindow();
|
const mainWindow = overlayManager.getMainWindow();
|
||||||
if (process.platform !== 'win32' || !mainWindow || mainWindow.isDestroyed()) return;
|
if (process.platform !== 'win32' || !mainWindow || mainWindow.isDestroyed()) return;
|
||||||
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
|
const overlayHwnd = getWindowsNativeWindowHandleNumber(mainWindow);
|
||||||
if (!clearWindowsOverlayOwner(overlayHwnd)) {
|
if (!clearWindowsOverlayOwnerNative(overlayHwnd)) {
|
||||||
logger.warn('Failed to clear overlay owner via koffi');
|
logger.warn('Failed to clear overlay owner via koffi');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ test('createMainBootServices builds boot-phase service bundle', () => {
|
|||||||
{ kind: string },
|
{ kind: string },
|
||||||
{ scope: string; warn: () => void; info: () => void; error: () => void },
|
{ scope: string; warn: () => void; info: () => void; error: () => void },
|
||||||
{ registry: boolean },
|
{ registry: boolean },
|
||||||
{ getMainWindow: () => null; getModalWindow: () => null },
|
{ getModalWindow: () => null },
|
||||||
{
|
{
|
||||||
inputState: boolean;
|
inputState: boolean;
|
||||||
getModalInputExclusive: () => boolean;
|
getModalInputExclusive: () => boolean;
|
||||||
@@ -82,7 +82,6 @@ test('createMainBootServices builds boot-phase service bundle', () => {
|
|||||||
}) as const,
|
}) as const,
|
||||||
createMainRuntimeRegistry: () => ({ registry: true }),
|
createMainRuntimeRegistry: () => ({ registry: true }),
|
||||||
createOverlayManager: () => ({
|
createOverlayManager: () => ({
|
||||||
getMainWindow: () => null,
|
|
||||||
getModalWindow: () => null,
|
getModalWindow: () => null,
|
||||||
}),
|
}),
|
||||||
createOverlayModalInputState: () => ({
|
createOverlayModalInputState: () => ({
|
||||||
|
|||||||
@@ -74,7 +74,6 @@ export interface MainBootServicesParams<
|
|||||||
getModalWindow: () => BrowserWindow | null;
|
getModalWindow: () => BrowserWindow | null;
|
||||||
syncOverlayShortcutsForModal: (isActive: boolean) => void;
|
syncOverlayShortcutsForModal: (isActive: boolean) => void;
|
||||||
syncOverlayVisibilityForModal: () => void;
|
syncOverlayVisibilityForModal: () => void;
|
||||||
restoreMainWindowFocus?: () => void;
|
|
||||||
}) => TOverlayModalInputState;
|
}) => TOverlayModalInputState;
|
||||||
createOverlayContentMeasurementStore: (params: {
|
createOverlayContentMeasurementStore: (params: {
|
||||||
logger: TLogger;
|
logger: TLogger;
|
||||||
@@ -132,7 +131,7 @@ export function createMainBootServices<
|
|||||||
TSubtitleWebSocket,
|
TSubtitleWebSocket,
|
||||||
TLogger,
|
TLogger,
|
||||||
TRuntimeRegistry,
|
TRuntimeRegistry,
|
||||||
TOverlayManager extends { getMainWindow: () => BrowserWindow | null; getModalWindow: () => BrowserWindow | null },
|
TOverlayManager extends { getModalWindow: () => BrowserWindow | null },
|
||||||
TOverlayModalInputState extends OverlayModalInputStateShape,
|
TOverlayModalInputState extends OverlayModalInputStateShape,
|
||||||
TOverlayContentMeasurementStore,
|
TOverlayContentMeasurementStore,
|
||||||
TOverlayModalRuntime,
|
TOverlayModalRuntime,
|
||||||
@@ -213,26 +212,6 @@ export function createMainBootServices<
|
|||||||
syncOverlayVisibilityForModal: () => {
|
syncOverlayVisibilityForModal: () => {
|
||||||
params.getSyncOverlayVisibilityForModal()();
|
params.getSyncOverlayVisibilityForModal()();
|
||||||
},
|
},
|
||||||
restoreMainWindowFocus: () => {
|
|
||||||
const mainWindow = overlayManager.getMainWindow();
|
|
||||||
if (!mainWindow || mainWindow.isDestroyed() || !mainWindow.isVisible()) return;
|
|
||||||
try {
|
|
||||||
const electron = require('electron') as {
|
|
||||||
app?: { focus?: (options?: { steal?: boolean }) => void };
|
|
||||||
};
|
|
||||||
electron.app?.focus?.({ steal: true });
|
|
||||||
} catch {
|
|
||||||
// Ignore in non-Electron environments.
|
|
||||||
}
|
|
||||||
const maybeFocusable = mainWindow as typeof mainWindow & {
|
|
||||||
setFocusable?: (focusable: boolean) => void;
|
|
||||||
};
|
|
||||||
maybeFocusable.setFocusable?.(true);
|
|
||||||
mainWindow.focus();
|
|
||||||
if (!mainWindow.webContents.isFocused()) {
|
|
||||||
mainWindow.webContents.focus();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
const overlayContentMeasurementStore = params.createOverlayContentMeasurementStore({
|
const overlayContentMeasurementStore = params.createOverlayContentMeasurementStore({
|
||||||
logger,
|
logger,
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ export interface CliCommandRuntimeServiceContext {
|
|||||||
triggerFieldGrouping: () => Promise<void>;
|
triggerFieldGrouping: () => Promise<void>;
|
||||||
triggerSubsyncFromConfig: () => Promise<void>;
|
triggerSubsyncFromConfig: () => Promise<void>;
|
||||||
markLastCardAsAudioCard: () => Promise<void>;
|
markLastCardAsAudioCard: () => Promise<void>;
|
||||||
dispatchSessionAction: CliCommandRuntimeServiceDepsParams['dispatchSessionAction'];
|
|
||||||
getAnilistStatus: CliCommandRuntimeServiceDepsParams['anilist']['getStatus'];
|
getAnilistStatus: CliCommandRuntimeServiceDepsParams['anilist']['getStatus'];
|
||||||
clearAnilistToken: CliCommandRuntimeServiceDepsParams['anilist']['clearToken'];
|
clearAnilistToken: CliCommandRuntimeServiceDepsParams['anilist']['clearToken'];
|
||||||
openAnilistSetup: CliCommandRuntimeServiceDepsParams['anilist']['openSetup'];
|
openAnilistSetup: CliCommandRuntimeServiceDepsParams['anilist']['openSetup'];
|
||||||
@@ -114,7 +113,6 @@ function createCliCommandDepsFromContext(
|
|||||||
hasMainWindow: context.hasMainWindow,
|
hasMainWindow: context.hasMainWindow,
|
||||||
runYoutubePlaybackFlow: context.runYoutubePlaybackFlow,
|
runYoutubePlaybackFlow: context.runYoutubePlaybackFlow,
|
||||||
},
|
},
|
||||||
dispatchSessionAction: context.dispatchSessionAction,
|
|
||||||
ui: {
|
ui: {
|
||||||
openFirstRunSetup: context.openFirstRunSetup,
|
openFirstRunSetup: context.openFirstRunSetup,
|
||||||
openYomitanSettings: context.openYomitanSettings,
|
openYomitanSettings: context.openYomitanSettings,
|
||||||
|
|||||||
@@ -73,9 +73,7 @@ export interface MainIpcRuntimeServiceDepsParams {
|
|||||||
getMecabTokenizer: IpcDepsRuntimeOptions['getMecabTokenizer'];
|
getMecabTokenizer: IpcDepsRuntimeOptions['getMecabTokenizer'];
|
||||||
handleMpvCommand: IpcDepsRuntimeOptions['handleMpvCommand'];
|
handleMpvCommand: IpcDepsRuntimeOptions['handleMpvCommand'];
|
||||||
getKeybindings: IpcDepsRuntimeOptions['getKeybindings'];
|
getKeybindings: IpcDepsRuntimeOptions['getKeybindings'];
|
||||||
getSessionBindings: IpcDepsRuntimeOptions['getSessionBindings'];
|
|
||||||
getConfiguredShortcuts: IpcDepsRuntimeOptions['getConfiguredShortcuts'];
|
getConfiguredShortcuts: IpcDepsRuntimeOptions['getConfiguredShortcuts'];
|
||||||
dispatchSessionAction: IpcDepsRuntimeOptions['dispatchSessionAction'];
|
|
||||||
getStatsToggleKey: IpcDepsRuntimeOptions['getStatsToggleKey'];
|
getStatsToggleKey: IpcDepsRuntimeOptions['getStatsToggleKey'];
|
||||||
getMarkWatchedKey: IpcDepsRuntimeOptions['getMarkWatchedKey'];
|
getMarkWatchedKey: IpcDepsRuntimeOptions['getMarkWatchedKey'];
|
||||||
getControllerConfig: IpcDepsRuntimeOptions['getControllerConfig'];
|
getControllerConfig: IpcDepsRuntimeOptions['getControllerConfig'];
|
||||||
@@ -180,7 +178,6 @@ export interface CliCommandRuntimeServiceDepsParams {
|
|||||||
hasMainWindow: CliCommandDepsRuntimeOptions['app']['hasMainWindow'];
|
hasMainWindow: CliCommandDepsRuntimeOptions['app']['hasMainWindow'];
|
||||||
runYoutubePlaybackFlow: CliCommandDepsRuntimeOptions['app']['runYoutubePlaybackFlow'];
|
runYoutubePlaybackFlow: CliCommandDepsRuntimeOptions['app']['runYoutubePlaybackFlow'];
|
||||||
};
|
};
|
||||||
dispatchSessionAction: CliCommandDepsRuntimeOptions['dispatchSessionAction'];
|
|
||||||
ui: {
|
ui: {
|
||||||
openFirstRunSetup: CliCommandDepsRuntimeOptions['ui']['openFirstRunSetup'];
|
openFirstRunSetup: CliCommandDepsRuntimeOptions['ui']['openFirstRunSetup'];
|
||||||
openYomitanSettings: CliCommandDepsRuntimeOptions['ui']['openYomitanSettings'];
|
openYomitanSettings: CliCommandDepsRuntimeOptions['ui']['openYomitanSettings'];
|
||||||
@@ -236,9 +233,7 @@ export function createMainIpcRuntimeServiceDeps(
|
|||||||
getMecabTokenizer: params.getMecabTokenizer,
|
getMecabTokenizer: params.getMecabTokenizer,
|
||||||
handleMpvCommand: params.handleMpvCommand,
|
handleMpvCommand: params.handleMpvCommand,
|
||||||
getKeybindings: params.getKeybindings,
|
getKeybindings: params.getKeybindings,
|
||||||
getSessionBindings: params.getSessionBindings,
|
|
||||||
getConfiguredShortcuts: params.getConfiguredShortcuts,
|
getConfiguredShortcuts: params.getConfiguredShortcuts,
|
||||||
dispatchSessionAction: params.dispatchSessionAction,
|
|
||||||
getStatsToggleKey: params.getStatsToggleKey,
|
getStatsToggleKey: params.getStatsToggleKey,
|
||||||
getMarkWatchedKey: params.getMarkWatchedKey,
|
getMarkWatchedKey: params.getMarkWatchedKey,
|
||||||
getControllerConfig: params.getControllerConfig,
|
getControllerConfig: params.getControllerConfig,
|
||||||
@@ -352,7 +347,6 @@ export function createCliCommandRuntimeServiceDeps(
|
|||||||
hasMainWindow: params.app.hasMainWindow,
|
hasMainWindow: params.app.hasMainWindow,
|
||||||
runYoutubePlaybackFlow: params.app.runYoutubePlaybackFlow,
|
runYoutubePlaybackFlow: params.app.runYoutubePlaybackFlow,
|
||||||
},
|
},
|
||||||
dispatchSessionAction: params.dispatchSessionAction,
|
|
||||||
ui: {
|
ui: {
|
||||||
openFirstRunSetup: params.ui.openFirstRunSetup,
|
openFirstRunSetup: params.ui.openFirstRunSetup,
|
||||||
openYomitanSettings: params.ui.openYomitanSettings,
|
openYomitanSettings: params.ui.openYomitanSettings,
|
||||||
|
|||||||
@@ -7,16 +7,13 @@ type MockWindow = {
|
|||||||
visible: boolean;
|
visible: boolean;
|
||||||
focused: boolean;
|
focused: boolean;
|
||||||
ignoreMouseEvents: boolean;
|
ignoreMouseEvents: boolean;
|
||||||
forwardedIgnoreMouseEvents: boolean;
|
|
||||||
webContentsFocused: boolean;
|
webContentsFocused: boolean;
|
||||||
showCount: number;
|
showCount: number;
|
||||||
hideCount: number;
|
hideCount: number;
|
||||||
sent: unknown[][];
|
sent: unknown[][];
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
url: string;
|
url: string;
|
||||||
contentReady: boolean;
|
|
||||||
loadCallbacks: Array<() => void>;
|
loadCallbacks: Array<() => void>;
|
||||||
readyToShowCallbacks: Array<() => void>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function createMockWindow(): MockWindow & {
|
function createMockWindow(): MockWindow & {
|
||||||
@@ -31,9 +28,7 @@ function createMockWindow(): MockWindow & {
|
|||||||
getHideCount: () => number;
|
getHideCount: () => number;
|
||||||
show: () => void;
|
show: () => void;
|
||||||
hide: () => void;
|
hide: () => void;
|
||||||
destroy: () => void;
|
|
||||||
focus: () => void;
|
focus: () => void;
|
||||||
once: (event: 'ready-to-show', cb: () => void) => void;
|
|
||||||
webContents: {
|
webContents: {
|
||||||
focused: boolean;
|
focused: boolean;
|
||||||
isLoading: () => boolean;
|
isLoading: () => boolean;
|
||||||
@@ -49,16 +44,13 @@ function createMockWindow(): MockWindow & {
|
|||||||
visible: false,
|
visible: false,
|
||||||
focused: false,
|
focused: false,
|
||||||
ignoreMouseEvents: false,
|
ignoreMouseEvents: false,
|
||||||
forwardedIgnoreMouseEvents: false,
|
|
||||||
webContentsFocused: false,
|
webContentsFocused: false,
|
||||||
showCount: 0,
|
showCount: 0,
|
||||||
hideCount: 0,
|
hideCount: 0,
|
||||||
sent: [],
|
sent: [],
|
||||||
loading: false,
|
loading: false,
|
||||||
url: 'file:///overlay/index.html?layer=modal',
|
url: 'file:///overlay/index.html?layer=modal',
|
||||||
contentReady: true,
|
|
||||||
loadCallbacks: [],
|
loadCallbacks: [],
|
||||||
readyToShowCallbacks: [],
|
|
||||||
};
|
};
|
||||||
const window = {
|
const window = {
|
||||||
...state,
|
...state,
|
||||||
@@ -66,9 +58,8 @@ function createMockWindow(): MockWindow & {
|
|||||||
isVisible: () => state.visible,
|
isVisible: () => state.visible,
|
||||||
isFocused: () => state.focused,
|
isFocused: () => state.focused,
|
||||||
getURL: () => state.url,
|
getURL: () => state.url,
|
||||||
setIgnoreMouseEvents: (ignore: boolean, options?: { forward?: boolean }) => {
|
setIgnoreMouseEvents: (ignore: boolean, _options?: { forward?: boolean }) => {
|
||||||
state.ignoreMouseEvents = ignore;
|
state.ignoreMouseEvents = ignore;
|
||||||
state.forwardedIgnoreMouseEvents = options?.forward === true;
|
|
||||||
},
|
},
|
||||||
setAlwaysOnTop: (_flag: boolean, _level?: string, _relativeLevel?: number) => {},
|
setAlwaysOnTop: (_flag: boolean, _level?: string, _relativeLevel?: number) => {},
|
||||||
moveTop: () => {},
|
moveTop: () => {},
|
||||||
@@ -82,16 +73,9 @@ function createMockWindow(): MockWindow & {
|
|||||||
state.visible = false;
|
state.visible = false;
|
||||||
state.hideCount += 1;
|
state.hideCount += 1;
|
||||||
},
|
},
|
||||||
destroy: () => {
|
|
||||||
state.destroyed = true;
|
|
||||||
state.visible = false;
|
|
||||||
},
|
|
||||||
focus: () => {
|
focus: () => {
|
||||||
state.focused = true;
|
state.focused = true;
|
||||||
},
|
},
|
||||||
once: (_event: 'ready-to-show', cb: () => void) => {
|
|
||||||
state.readyToShowCallbacks.push(cb);
|
|
||||||
},
|
|
||||||
webContents: {
|
webContents: {
|
||||||
isLoading: () => state.loading,
|
isLoading: () => state.loading,
|
||||||
getURL: () => state.url,
|
getURL: () => state.url,
|
||||||
@@ -155,25 +139,6 @@ function createMockWindow(): MockWindow & {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Object.defineProperty(window, 'forwardedIgnoreMouseEvents', {
|
|
||||||
get: () => state.forwardedIgnoreMouseEvents,
|
|
||||||
set: (value: boolean) => {
|
|
||||||
state.forwardedIgnoreMouseEvents = value;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
Object.defineProperty(window, 'contentReady', {
|
|
||||||
get: () => state.contentReady,
|
|
||||||
set: (value: boolean) => {
|
|
||||||
state.contentReady = value;
|
|
||||||
(window as typeof window & { __subminerOverlayContentReady?: boolean }).__subminerOverlayContentReady =
|
|
||||||
value;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
(window as typeof window & { __subminerOverlayContentReady?: boolean }).__subminerOverlayContentReady =
|
|
||||||
state.contentReady;
|
|
||||||
|
|
||||||
return window;
|
return window;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,29 +195,10 @@ test('sendToActiveOverlayWindow creates modal window lazily when absent', () =>
|
|||||||
assert.deepEqual(window.sent, [['jimaku:open']]);
|
assert.deepEqual(window.sent, [['jimaku:open']]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('sendToActiveOverlayWindow does not retain restore state when modal creation fails', () => {
|
|
||||||
const runtime = createOverlayModalRuntimeService({
|
|
||||||
getMainWindow: () => null,
|
|
||||||
getModalWindow: () => null,
|
|
||||||
createModalWindow: () => null,
|
|
||||||
getModalGeometry: () => ({ x: 0, y: 0, width: 400, height: 300 }),
|
|
||||||
setModalWindowBounds: () => {},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(
|
|
||||||
runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
}),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.equal(runtime.getRestoreVisibleOverlayOnModalClose().has('runtime-options'), false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('sendToActiveOverlayWindow waits for blank modal URL before sending open command', () => {
|
test('sendToActiveOverlayWindow waits for blank modal URL before sending open command', () => {
|
||||||
const window = createMockWindow();
|
const window = createMockWindow();
|
||||||
window.url = '';
|
window.url = '';
|
||||||
window.loading = true;
|
window.loading = true;
|
||||||
window.contentReady = false;
|
|
||||||
const runtime = createOverlayModalRuntimeService({
|
const runtime = createOverlayModalRuntimeService({
|
||||||
getMainWindow: () => null,
|
getMainWindow: () => null,
|
||||||
getModalWindow: () => window as never,
|
getModalWindow: () => window as never,
|
||||||
@@ -271,14 +217,9 @@ test('sendToActiveOverlayWindow waits for blank modal URL before sending open co
|
|||||||
assert.deepEqual(window.sent, []);
|
assert.deepEqual(window.sent, []);
|
||||||
|
|
||||||
assert.equal(window.loadCallbacks.length, 1);
|
assert.equal(window.loadCallbacks.length, 1);
|
||||||
assert.equal(window.readyToShowCallbacks.length, 1);
|
|
||||||
window.loading = false;
|
window.loading = false;
|
||||||
window.url = 'file:///overlay/index.html?layer=modal';
|
window.url = 'file:///overlay/index.html?layer=modal';
|
||||||
window.loadCallbacks[0]!();
|
window.loadCallbacks[0]!();
|
||||||
assert.deepEqual(window.sent, []);
|
|
||||||
|
|
||||||
window.contentReady = true;
|
|
||||||
window.readyToShowCallbacks[0]!();
|
|
||||||
|
|
||||||
runtime.notifyOverlayModalOpened('runtime-options');
|
runtime.notifyOverlayModalOpened('runtime-options');
|
||||||
assert.deepEqual(window.sent, [['runtime-options:open']]);
|
assert.deepEqual(window.sent, [['runtime-options:open']]);
|
||||||
@@ -307,10 +248,10 @@ test('handleOverlayModalClosed hides modal window only after all pending modals
|
|||||||
);
|
);
|
||||||
|
|
||||||
runtime.handleOverlayModalClosed('runtime-options');
|
runtime.handleOverlayModalClosed('runtime-options');
|
||||||
assert.equal(window.isDestroyed(), false);
|
assert.equal(window.getHideCount(), 0);
|
||||||
|
|
||||||
runtime.handleOverlayModalClosed('subsync');
|
runtime.handleOverlayModalClosed('subsync');
|
||||||
assert.equal(window.isDestroyed(), true);
|
assert.equal(window.getHideCount(), 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('sendToActiveOverlayWindow prefers visible main overlay window for modal open', () => {
|
test('sendToActiveOverlayWindow prefers visible main overlay window for modal open', () => {
|
||||||
@@ -384,12 +325,11 @@ test('modal window path makes visible main overlay click-through until modal clo
|
|||||||
|
|
||||||
assert.equal(sent, true);
|
assert.equal(sent, true);
|
||||||
assert.equal(mainWindow.ignoreMouseEvents, true);
|
assert.equal(mainWindow.ignoreMouseEvents, true);
|
||||||
assert.equal(mainWindow.forwardedIgnoreMouseEvents, true);
|
|
||||||
assert.equal(modalWindow.ignoreMouseEvents, false);
|
assert.equal(modalWindow.ignoreMouseEvents, false);
|
||||||
|
|
||||||
runtime.handleOverlayModalClosed('youtube-track-picker');
|
runtime.handleOverlayModalClosed('youtube-track-picker');
|
||||||
|
|
||||||
assert.equal(mainWindow.ignoreMouseEvents, true);
|
assert.equal(mainWindow.ignoreMouseEvents, false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('modal window path hides visible main overlay until modal closes', () => {
|
test('modal window path hides visible main overlay until modal closes', () => {
|
||||||
@@ -419,8 +359,8 @@ test('modal window path hides visible main overlay until modal closes', () => {
|
|||||||
|
|
||||||
runtime.handleOverlayModalClosed('youtube-track-picker');
|
runtime.handleOverlayModalClosed('youtube-track-picker');
|
||||||
|
|
||||||
assert.equal(mainWindow.getShowCount(), 0);
|
assert.equal(mainWindow.getShowCount(), 1);
|
||||||
assert.equal(mainWindow.isVisible(), false);
|
assert.equal(mainWindow.isVisible(), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('modal runtime notifies callers when modal input state becomes active/inactive', () => {
|
test('modal runtime notifies callers when modal input state becomes active/inactive', () => {
|
||||||
@@ -497,7 +437,7 @@ test('notifyOverlayModalOpened enables input on visible main overlay window when
|
|||||||
assert.equal(mainWindow.webContentsFocused, true);
|
assert.equal(mainWindow.webContentsFocused, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('handleOverlayModalClosed is a no-op when no modal window can be targeted', () => {
|
test('handleOverlayModalClosed resets modal state even when modal window does not exist', () => {
|
||||||
const state: boolean[] = [];
|
const state: boolean[] = [];
|
||||||
const runtime = createOverlayModalRuntimeService(
|
const runtime = createOverlayModalRuntimeService(
|
||||||
{
|
{
|
||||||
@@ -514,17 +454,16 @@ test('handleOverlayModalClosed is a no-op when no modal window can be targeted',
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const sent = runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
|
runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
|
||||||
restoreOnModalClose: 'runtime-options',
|
restoreOnModalClose: 'runtime-options',
|
||||||
});
|
});
|
||||||
assert.equal(sent, false);
|
|
||||||
runtime.notifyOverlayModalOpened('runtime-options');
|
runtime.notifyOverlayModalOpened('runtime-options');
|
||||||
runtime.handleOverlayModalClosed('runtime-options');
|
runtime.handleOverlayModalClosed('runtime-options');
|
||||||
|
|
||||||
assert.deepEqual(state, []);
|
assert.deepEqual(state, [true, false]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('handleOverlayModalClosed destroys modal window for single kiku modal', () => {
|
test('handleOverlayModalClosed hides modal window for single kiku modal', () => {
|
||||||
const window = createMockWindow();
|
const window = createMockWindow();
|
||||||
const runtime = createOverlayModalRuntimeService({
|
const runtime = createOverlayModalRuntimeService({
|
||||||
getMainWindow: () => null,
|
getMainWindow: () => null,
|
||||||
@@ -543,11 +482,11 @@ test('handleOverlayModalClosed destroys modal window for single kiku modal', ()
|
|||||||
);
|
);
|
||||||
runtime.handleOverlayModalClosed('kiku');
|
runtime.handleOverlayModalClosed('kiku');
|
||||||
|
|
||||||
assert.equal(window.isDestroyed(), true);
|
assert.equal(window.getHideCount(), 1);
|
||||||
assert.equal(runtime.getRestoreVisibleOverlayOnModalClose().size, 0);
|
assert.equal(runtime.getRestoreVisibleOverlayOnModalClose().size, 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('modal fallback reveal skips showing window when content is not ready', async () => {
|
test('modal fallback reveal keeps mouse events ignored until modal confirms open', async () => {
|
||||||
const window = createMockWindow();
|
const window = createMockWindow();
|
||||||
const runtime = createOverlayModalRuntimeService({
|
const runtime = createOverlayModalRuntimeService({
|
||||||
getMainWindow: () => null,
|
getMainWindow: () => null,
|
||||||
@@ -561,164 +500,30 @@ test('modal fallback reveal skips showing window when content is not ready', asy
|
|||||||
|
|
||||||
window.loading = true;
|
window.loading = true;
|
||||||
window.url = '';
|
window.url = '';
|
||||||
window.contentReady = false;
|
|
||||||
|
|
||||||
const sent = runtime.sendToActiveOverlayWindow('jimaku:open', undefined, {
|
const sent = runtime.sendToActiveOverlayWindow('jimaku:open', undefined, {
|
||||||
restoreOnModalClose: 'jimaku',
|
restoreOnModalClose: 'jimaku',
|
||||||
});
|
});
|
||||||
|
|
||||||
assert.equal(sent, true);
|
assert.equal(sent, true);
|
||||||
|
assert.equal(window.ignoreMouseEvents, false);
|
||||||
|
|
||||||
await new Promise<void>((resolve) => {
|
await new Promise<void>((resolve) => {
|
||||||
setTimeout(resolve, 260);
|
setTimeout(resolve, 260);
|
||||||
});
|
});
|
||||||
|
|
||||||
assert.equal(window.getShowCount(), 0);
|
|
||||||
|
|
||||||
runtime.notifyOverlayModalOpened('jimaku');
|
|
||||||
assert.equal(window.getShowCount(), 1);
|
assert.equal(window.getShowCount(), 1);
|
||||||
assert.equal(window.ignoreMouseEvents, false);
|
assert.equal(window.ignoreMouseEvents, false);
|
||||||
});
|
|
||||||
|
|
||||||
test('sendToActiveOverlayWindow waits for modal ready-to-show before delivering open event', () => {
|
runtime.notifyOverlayModalOpened('jimaku');
|
||||||
const window = createMockWindow();
|
|
||||||
window.contentReady = false;
|
|
||||||
const runtime = createOverlayModalRuntimeService({
|
|
||||||
getMainWindow: () => null,
|
|
||||||
getModalWindow: () => window as never,
|
|
||||||
createModalWindow: () => {
|
|
||||||
throw new Error('modal window should not be created when already present');
|
|
||||||
},
|
|
||||||
getModalGeometry: () => ({ x: 0, y: 0, width: 400, height: 300 }),
|
|
||||||
setModalWindowBounds: () => {},
|
|
||||||
});
|
|
||||||
|
|
||||||
const sent = runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(sent, true);
|
|
||||||
assert.deepEqual(window.sent, []);
|
|
||||||
assert.equal(window.loadCallbacks.length, 1);
|
|
||||||
assert.equal(window.readyToShowCallbacks.length, 1);
|
|
||||||
|
|
||||||
window.loadCallbacks[0]!();
|
|
||||||
assert.deepEqual(window.sent, []);
|
|
||||||
|
|
||||||
window.contentReady = true;
|
|
||||||
window.readyToShowCallbacks[0]!();
|
|
||||||
assert.deepEqual(window.sent, [['runtime-options:open']]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('modal reopen creates a fresh window after close destroys the previous one', () => {
|
|
||||||
const firstWindow = createMockWindow();
|
|
||||||
const secondWindow = createMockWindow();
|
|
||||||
let currentModal: ReturnType<typeof createMockWindow> | null = firstWindow;
|
|
||||||
|
|
||||||
const runtime = createOverlayModalRuntimeService({
|
|
||||||
getMainWindow: () => null,
|
|
||||||
getModalWindow: () =>
|
|
||||||
currentModal && !currentModal.isDestroyed() ? (currentModal as never) : null,
|
|
||||||
createModalWindow: () => {
|
|
||||||
currentModal = secondWindow;
|
|
||||||
return secondWindow as never;
|
|
||||||
},
|
|
||||||
getModalGeometry: () => ({ x: 0, y: 0, width: 400, height: 300 }),
|
|
||||||
setModalWindowBounds: () => {},
|
|
||||||
});
|
|
||||||
|
|
||||||
runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
});
|
|
||||||
runtime.notifyOverlayModalOpened('runtime-options');
|
|
||||||
runtime.handleOverlayModalClosed('runtime-options');
|
|
||||||
|
|
||||||
assert.equal(firstWindow.isDestroyed(), true);
|
|
||||||
|
|
||||||
const sent = runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(sent, true);
|
|
||||||
assert.equal(currentModal, secondWindow);
|
|
||||||
assert.equal(secondWindow.getShowCount(), 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('modal reopen after close-destroy notifies state change on fresh window lifecycle', () => {
|
|
||||||
const firstWindow = createMockWindow();
|
|
||||||
const secondWindow = createMockWindow();
|
|
||||||
let currentModal: ReturnType<typeof createMockWindow> | null = firstWindow;
|
|
||||||
const state: boolean[] = [];
|
|
||||||
|
|
||||||
const runtime = createOverlayModalRuntimeService(
|
|
||||||
{
|
|
||||||
getMainWindow: () => null,
|
|
||||||
getModalWindow: () =>
|
|
||||||
currentModal && !currentModal.isDestroyed() ? (currentModal as never) : null,
|
|
||||||
createModalWindow: () => {
|
|
||||||
currentModal = secondWindow;
|
|
||||||
return secondWindow as never;
|
|
||||||
},
|
|
||||||
getModalGeometry: () => ({ x: 0, y: 0, width: 400, height: 300 }),
|
|
||||||
setModalWindowBounds: () => {},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onModalStateChange: (active: boolean): void => {
|
|
||||||
state.push(active);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
});
|
|
||||||
runtime.notifyOverlayModalOpened('runtime-options');
|
|
||||||
runtime.handleOverlayModalClosed('runtime-options');
|
|
||||||
|
|
||||||
assert.deepEqual(state, [true, false]);
|
|
||||||
assert.equal(firstWindow.isDestroyed(), true);
|
|
||||||
|
|
||||||
runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
});
|
|
||||||
runtime.notifyOverlayModalOpened('runtime-options');
|
|
||||||
|
|
||||||
assert.deepEqual(state, [true, false, true]);
|
|
||||||
assert.equal(currentModal, secondWindow);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('visible stale modal window is made interactive again before reopening', () => {
|
|
||||||
const window = createMockWindow();
|
|
||||||
window.visible = true;
|
|
||||||
window.focused = true;
|
|
||||||
window.webContentsFocused = false;
|
|
||||||
window.ignoreMouseEvents = true;
|
|
||||||
|
|
||||||
const runtime = createOverlayModalRuntimeService({
|
|
||||||
getMainWindow: () => null,
|
|
||||||
getModalWindow: () => window as never,
|
|
||||||
createModalWindow: () => window as never,
|
|
||||||
getModalGeometry: () => ({ x: 0, y: 0, width: 400, height: 300 }),
|
|
||||||
setModalWindowBounds: () => {},
|
|
||||||
});
|
|
||||||
|
|
||||||
const sent = runtime.sendToActiveOverlayWindow('runtime-options:open', undefined, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(sent, true);
|
|
||||||
assert.equal(window.ignoreMouseEvents, false);
|
assert.equal(window.ignoreMouseEvents, false);
|
||||||
assert.equal(window.isFocused(), true);
|
|
||||||
assert.equal(window.webContentsFocused, true);
|
|
||||||
assert.deepEqual(window.sent, [['runtime-options:open']]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('waitForModalOpen resolves true after modal acknowledgement', async () => {
|
test('waitForModalOpen resolves true after modal acknowledgement', async () => {
|
||||||
const modalWindow = createMockWindow();
|
|
||||||
const runtime = createOverlayModalRuntimeService({
|
const runtime = createOverlayModalRuntimeService({
|
||||||
getMainWindow: () => null,
|
getMainWindow: () => null,
|
||||||
getModalWindow: () => modalWindow as never,
|
getModalWindow: () => null,
|
||||||
createModalWindow: () => modalWindow as never,
|
createModalWindow: () => null,
|
||||||
getModalGeometry: () => ({ x: 0, y: 0, width: 400, height: 300 }),
|
getModalGeometry: () => ({ x: 0, y: 0, width: 400, height: 300 }),
|
||||||
setModalWindowBounds: () => {},
|
setModalWindowBounds: () => {},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,30 +1,9 @@
|
|||||||
import type { BrowserWindow } from 'electron';
|
import type { BrowserWindow } from 'electron';
|
||||||
import type { OverlayHostedModal } from '../shared/ipc/contracts';
|
import type { OverlayHostedModal } from '../shared/ipc/contracts';
|
||||||
import type { WindowGeometry } from '../types';
|
import type { WindowGeometry } from '../types';
|
||||||
import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from '../core/services/overlay-window-flags';
|
|
||||||
|
|
||||||
const MODAL_REVEAL_FALLBACK_DELAY_MS = 250;
|
const MODAL_REVEAL_FALLBACK_DELAY_MS = 250;
|
||||||
|
|
||||||
function requestOverlayApplicationFocus(): void {
|
|
||||||
try {
|
|
||||||
const electron = require('electron') as {
|
|
||||||
app?: {
|
|
||||||
focus?: (options?: { steal?: boolean }) => void;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
electron.app?.focus?.({ steal: true });
|
|
||||||
} catch {
|
|
||||||
// Ignore focus-steal failures in non-Electron test environments.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function setWindowFocusable(window: BrowserWindow): void {
|
|
||||||
const maybeFocusableWindow = window as BrowserWindow & {
|
|
||||||
setFocusable?: (focusable: boolean) => void;
|
|
||||||
};
|
|
||||||
maybeFocusableWindow.setFocusable?.(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OverlayWindowResolver {
|
export interface OverlayWindowResolver {
|
||||||
getMainWindow: () => BrowserWindow | null;
|
getMainWindow: () => BrowserWindow | null;
|
||||||
getModalWindow: () => BrowserWindow | null;
|
getModalWindow: () => BrowserWindow | null;
|
||||||
@@ -63,7 +42,6 @@ export function createOverlayModalRuntimeService(
|
|||||||
let modalActive = false;
|
let modalActive = false;
|
||||||
let mainWindowMousePassthroughForcedByModal = false;
|
let mainWindowMousePassthroughForcedByModal = false;
|
||||||
let mainWindowHiddenByModal = false;
|
let mainWindowHiddenByModal = false;
|
||||||
let modalWindowPrimedForImmediateShow = false;
|
|
||||||
let pendingModalWindowReveal: BrowserWindow | null = null;
|
let pendingModalWindowReveal: BrowserWindow | null = null;
|
||||||
let pendingModalWindowRevealTimeout: ReturnType<typeof setTimeout> | null = null;
|
let pendingModalWindowRevealTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
@@ -109,21 +87,9 @@ export function createOverlayModalRuntimeService(
|
|||||||
};
|
};
|
||||||
|
|
||||||
const isWindowReadyForIpc = (window: BrowserWindow): boolean => {
|
const isWindowReadyForIpc = (window: BrowserWindow): boolean => {
|
||||||
if (window.isDestroyed()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (window.webContents.isLoading()) {
|
if (window.webContents.isLoading()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const overlayWindow = window as BrowserWindow & {
|
|
||||||
[OVERLAY_WINDOW_CONTENT_READY_FLAG]?: boolean;
|
|
||||||
};
|
|
||||||
if (
|
|
||||||
typeof overlayWindow[OVERLAY_WINDOW_CONTENT_READY_FLAG] === 'boolean' &&
|
|
||||||
overlayWindow[OVERLAY_WINDOW_CONTENT_READY_FLAG] !== true
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
const currentURL = window.webContents.getURL();
|
const currentURL = window.webContents.getURL();
|
||||||
return currentURL !== '' && currentURL !== 'about:blank';
|
return currentURL !== '' && currentURL !== 'about:blank';
|
||||||
};
|
};
|
||||||
@@ -143,17 +109,11 @@ export function createOverlayModalRuntimeService(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let delivered = false;
|
window.webContents.once('did-finish-load', () => {
|
||||||
const deliverWhenReady = (): void => {
|
if (!window.isDestroyed() && !window.webContents.isLoading()) {
|
||||||
if (delivered || window.isDestroyed() || !isWindowReadyForIpc(window)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
delivered = true;
|
|
||||||
sendNow(window);
|
sendNow(window);
|
||||||
};
|
}
|
||||||
|
});
|
||||||
window.webContents.once('did-finish-load', deliverWhenReady);
|
|
||||||
window.once('ready-to-show', deliverWhenReady);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const showModalWindow = (
|
const showModalWindow = (
|
||||||
@@ -162,8 +122,6 @@ export function createOverlayModalRuntimeService(
|
|||||||
passThroughMouseEvents: boolean;
|
passThroughMouseEvents: boolean;
|
||||||
} = { passThroughMouseEvents: false },
|
} = { passThroughMouseEvents: false },
|
||||||
): void => {
|
): void => {
|
||||||
setWindowFocusable(window);
|
|
||||||
requestOverlayApplicationFocus();
|
|
||||||
if (!window.isVisible()) {
|
if (!window.isVisible()) {
|
||||||
window.show();
|
window.show();
|
||||||
}
|
}
|
||||||
@@ -180,14 +138,15 @@ export function createOverlayModalRuntimeService(
|
|||||||
};
|
};
|
||||||
|
|
||||||
const ensureModalWindowInteractive = (window: BrowserWindow): void => {
|
const ensureModalWindowInteractive = (window: BrowserWindow): void => {
|
||||||
setWindowFocusable(window);
|
|
||||||
requestOverlayApplicationFocus();
|
|
||||||
window.setIgnoreMouseEvents(false);
|
|
||||||
elevateModalWindow(window);
|
|
||||||
|
|
||||||
if (window.isVisible()) {
|
if (window.isVisible()) {
|
||||||
|
window.setIgnoreMouseEvents(false);
|
||||||
|
if (!window.isFocused()) {
|
||||||
window.focus();
|
window.focus();
|
||||||
|
}
|
||||||
|
if (!window.webContents.isFocused()) {
|
||||||
window.webContents.focus();
|
window.webContents.focus();
|
||||||
|
}
|
||||||
|
elevateModalWindow(window);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -272,9 +231,6 @@ export function createOverlayModalRuntimeService(
|
|||||||
if (!targetWindow || targetWindow.isDestroyed() || targetWindow.isVisible()) {
|
if (!targetWindow || targetWindow.isDestroyed() || targetWindow.isVisible()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!isWindowReadyForIpc(targetWindow)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
showModalWindow(targetWindow, { passThroughMouseEvents: false });
|
showModalWindow(targetWindow, { passThroughMouseEvents: false });
|
||||||
}, MODAL_REVEAL_FALLBACK_DELAY_MS);
|
}, MODAL_REVEAL_FALLBACK_DELAY_MS);
|
||||||
};
|
};
|
||||||
@@ -300,9 +256,9 @@ export function createOverlayModalRuntimeService(
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (restoreOnModalClose) {
|
if (restoreOnModalClose) {
|
||||||
|
restoreVisibleOverlayOnModalClose.add(restoreOnModalClose);
|
||||||
const mainWindow = getTargetOverlayWindow();
|
const mainWindow = getTargetOverlayWindow();
|
||||||
if (!preferModalWindow && mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()) {
|
if (!preferModalWindow && mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()) {
|
||||||
restoreVisibleOverlayOnModalClose.add(restoreOnModalClose);
|
|
||||||
sendOrQueueForWindow(mainWindow, (window) => {
|
sendOrQueueForWindow(mainWindow, (window) => {
|
||||||
if (payload === undefined) {
|
if (payload === undefined) {
|
||||||
window.webContents.send(channel);
|
window.webContents.send(channel);
|
||||||
@@ -316,23 +272,15 @@ export function createOverlayModalRuntimeService(
|
|||||||
const modalWindow = resolveModalWindow();
|
const modalWindow = resolveModalWindow();
|
||||||
if (!modalWindow) return false;
|
if (!modalWindow) return false;
|
||||||
|
|
||||||
restoreVisibleOverlayOnModalClose.add(restoreOnModalClose);
|
|
||||||
deps.setModalWindowBounds(deps.getModalGeometry());
|
deps.setModalWindowBounds(deps.getModalGeometry());
|
||||||
const wasVisible = modalWindow.isVisible();
|
const wasVisible = modalWindow.isVisible();
|
||||||
if (!wasVisible) {
|
if (!wasVisible) {
|
||||||
if (modalWindowPrimedForImmediateShow && isWindowReadyForIpc(modalWindow)) {
|
|
||||||
showModalWindow(modalWindow);
|
|
||||||
} else {
|
|
||||||
scheduleModalWindowReveal(modalWindow);
|
scheduleModalWindowReveal(modalWindow);
|
||||||
}
|
|
||||||
} else if (!modalWindow.isFocused()) {
|
} else if (!modalWindow.isFocused()) {
|
||||||
showModalWindow(modalWindow);
|
showModalWindow(modalWindow);
|
||||||
}
|
}
|
||||||
|
|
||||||
sendOrQueueForWindow(modalWindow, (window) => {
|
sendOrQueueForWindow(modalWindow, (window) => {
|
||||||
if (window.isVisible()) {
|
|
||||||
ensureModalWindowInteractive(window);
|
|
||||||
}
|
|
||||||
if (payload === undefined) {
|
if (payload === undefined) {
|
||||||
window.webContents.send(channel);
|
window.webContents.send(channel);
|
||||||
} else {
|
} else {
|
||||||
@@ -372,13 +320,12 @@ export function createOverlayModalRuntimeService(
|
|||||||
const modalWindow = deps.getModalWindow();
|
const modalWindow = deps.getModalWindow();
|
||||||
if (restoreVisibleOverlayOnModalClose.size === 0) {
|
if (restoreVisibleOverlayOnModalClose.size === 0) {
|
||||||
clearPendingModalWindowReveal();
|
clearPendingModalWindowReveal();
|
||||||
if (modalWindow && !modalWindow.isDestroyed()) {
|
|
||||||
modalWindow.destroy();
|
|
||||||
}
|
|
||||||
modalWindowPrimedForImmediateShow = false;
|
|
||||||
mainWindowMousePassthroughForcedByModal = false;
|
|
||||||
mainWindowHiddenByModal = false;
|
|
||||||
notifyModalStateChange(false);
|
notifyModalStateChange(false);
|
||||||
|
setMainWindowMousePassthroughForModal(false);
|
||||||
|
setMainWindowVisibilityForModal(false);
|
||||||
|
if (modalWindow && !modalWindow.isDestroyed()) {
|
||||||
|
modalWindow.hide();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -403,7 +350,14 @@ export function createOverlayModalRuntimeService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (targetWindow.isVisible()) {
|
if (targetWindow.isVisible()) {
|
||||||
ensureModalWindowInteractive(targetWindow);
|
targetWindow.setIgnoreMouseEvents(false);
|
||||||
|
elevateModalWindow(targetWindow);
|
||||||
|
if (!targetWindow.isFocused()) {
|
||||||
|
targetWindow.focus();
|
||||||
|
}
|
||||||
|
if (!targetWindow.webContents.isFocused()) {
|
||||||
|
targetWindow.webContents.focus();
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ test('on will quit cleanup handler runs all cleanup steps', () => {
|
|||||||
unregisterAllGlobalShortcuts: () => calls.push('unregister-shortcuts'),
|
unregisterAllGlobalShortcuts: () => calls.push('unregister-shortcuts'),
|
||||||
stopSubtitleWebsocket: () => calls.push('stop-ws'),
|
stopSubtitleWebsocket: () => calls.push('stop-ws'),
|
||||||
stopTexthookerService: () => calls.push('stop-texthooker'),
|
stopTexthookerService: () => calls.push('stop-texthooker'),
|
||||||
clearWindowsVisibleOverlayForegroundPollLoop: () => calls.push('clear-windows-visible-overlay-poll'),
|
|
||||||
destroyMainOverlayWindow: () => calls.push('destroy-main-overlay-window'),
|
destroyMainOverlayWindow: () => calls.push('destroy-main-overlay-window'),
|
||||||
destroyModalOverlayWindow: () => calls.push('destroy-modal-overlay-window'),
|
destroyModalOverlayWindow: () => calls.push('destroy-modal-overlay-window'),
|
||||||
destroyYomitanParserWindow: () => calls.push('destroy-yomitan-window'),
|
destroyYomitanParserWindow: () => calls.push('destroy-yomitan-window'),
|
||||||
@@ -41,10 +40,9 @@ test('on will quit cleanup handler runs all cleanup steps', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
cleanup();
|
cleanup();
|
||||||
assert.equal(calls.length, 29);
|
assert.equal(calls.length, 28);
|
||||||
assert.equal(calls[0], 'destroy-tray');
|
assert.equal(calls[0], 'destroy-tray');
|
||||||
assert.equal(calls[calls.length - 1], 'stop-discord-presence');
|
assert.equal(calls[calls.length - 1], 'stop-discord-presence');
|
||||||
assert.ok(calls.includes('clear-windows-visible-overlay-poll'));
|
|
||||||
assert.ok(calls.indexOf('flush-mpv-log') < calls.indexOf('destroy-socket'));
|
assert.ok(calls.indexOf('flush-mpv-log') < calls.indexOf('destroy-socket'));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ export function createOnWillQuitCleanupHandler(deps: {
|
|||||||
unregisterAllGlobalShortcuts: () => void;
|
unregisterAllGlobalShortcuts: () => void;
|
||||||
stopSubtitleWebsocket: () => void;
|
stopSubtitleWebsocket: () => void;
|
||||||
stopTexthookerService: () => void;
|
stopTexthookerService: () => void;
|
||||||
clearWindowsVisibleOverlayForegroundPollLoop: () => void;
|
|
||||||
destroyMainOverlayWindow: () => void;
|
destroyMainOverlayWindow: () => void;
|
||||||
destroyModalOverlayWindow: () => void;
|
destroyModalOverlayWindow: () => void;
|
||||||
destroyYomitanParserWindow: () => void;
|
destroyYomitanParserWindow: () => void;
|
||||||
@@ -37,7 +36,6 @@ export function createOnWillQuitCleanupHandler(deps: {
|
|||||||
deps.unregisterAllGlobalShortcuts();
|
deps.unregisterAllGlobalShortcuts();
|
||||||
deps.stopSubtitleWebsocket();
|
deps.stopSubtitleWebsocket();
|
||||||
deps.stopTexthookerService();
|
deps.stopTexthookerService();
|
||||||
deps.clearWindowsVisibleOverlayForegroundPollLoop();
|
|
||||||
deps.destroyMainOverlayWindow();
|
deps.destroyMainOverlayWindow();
|
||||||
deps.destroyModalOverlayWindow();
|
deps.destroyModalOverlayWindow();
|
||||||
deps.destroyYomitanParserWindow();
|
deps.destroyYomitanParserWindow();
|
||||||
|
|||||||
@@ -18,8 +18,6 @@ test('cleanup deps builder returns handlers that guard optional runtime objects'
|
|||||||
unregisterAllGlobalShortcuts: () => calls.push('unregister-shortcuts'),
|
unregisterAllGlobalShortcuts: () => calls.push('unregister-shortcuts'),
|
||||||
stopSubtitleWebsocket: () => calls.push('stop-ws'),
|
stopSubtitleWebsocket: () => calls.push('stop-ws'),
|
||||||
stopTexthookerService: () => calls.push('stop-texthooker'),
|
stopTexthookerService: () => calls.push('stop-texthooker'),
|
||||||
clearWindowsVisibleOverlayForegroundPollLoop: () =>
|
|
||||||
calls.push('clear-windows-visible-overlay-foreground-poll-loop'),
|
|
||||||
getMainOverlayWindow: () => ({
|
getMainOverlayWindow: () => ({
|
||||||
isDestroyed: () => false,
|
isDestroyed: () => false,
|
||||||
destroy: () => calls.push('destroy-main-overlay-window'),
|
destroy: () => calls.push('destroy-main-overlay-window'),
|
||||||
@@ -87,7 +85,6 @@ test('cleanup deps builder returns handlers that guard optional runtime objects'
|
|||||||
assert.ok(calls.includes('destroy-yomitan-settings-window'));
|
assert.ok(calls.includes('destroy-yomitan-settings-window'));
|
||||||
assert.ok(calls.includes('stop-jellyfin-remote'));
|
assert.ok(calls.includes('stop-jellyfin-remote'));
|
||||||
assert.ok(calls.includes('stop-discord-presence'));
|
assert.ok(calls.includes('stop-discord-presence'));
|
||||||
assert.ok(calls.includes('clear-windows-visible-overlay-foreground-poll-loop'));
|
|
||||||
assert.equal(reconnectTimer, null);
|
assert.equal(reconnectTimer, null);
|
||||||
assert.equal(immersionTracker, null);
|
assert.equal(immersionTracker, null);
|
||||||
});
|
});
|
||||||
@@ -102,7 +99,6 @@ test('cleanup deps builder skips destroyed yomitan window', () => {
|
|||||||
unregisterAllGlobalShortcuts: () => {},
|
unregisterAllGlobalShortcuts: () => {},
|
||||||
stopSubtitleWebsocket: () => {},
|
stopSubtitleWebsocket: () => {},
|
||||||
stopTexthookerService: () => {},
|
stopTexthookerService: () => {},
|
||||||
clearWindowsVisibleOverlayForegroundPollLoop: () => {},
|
|
||||||
getMainOverlayWindow: () => ({
|
getMainOverlayWindow: () => ({
|
||||||
isDestroyed: () => true,
|
isDestroyed: () => true,
|
||||||
destroy: () => calls.push('destroy-main-overlay-window'),
|
destroy: () => calls.push('destroy-main-overlay-window'),
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ export function createBuildOnWillQuitCleanupDepsHandler(deps: {
|
|||||||
unregisterAllGlobalShortcuts: () => void;
|
unregisterAllGlobalShortcuts: () => void;
|
||||||
stopSubtitleWebsocket: () => void;
|
stopSubtitleWebsocket: () => void;
|
||||||
stopTexthookerService: () => void;
|
stopTexthookerService: () => void;
|
||||||
clearWindowsVisibleOverlayForegroundPollLoop: () => void;
|
|
||||||
getMainOverlayWindow: () => DestroyableWindow | null;
|
getMainOverlayWindow: () => DestroyableWindow | null;
|
||||||
clearMainOverlayWindow: () => void;
|
clearMainOverlayWindow: () => void;
|
||||||
getModalOverlayWindow: () => DestroyableWindow | null;
|
getModalOverlayWindow: () => DestroyableWindow | null;
|
||||||
@@ -65,8 +64,6 @@ export function createBuildOnWillQuitCleanupDepsHandler(deps: {
|
|||||||
unregisterAllGlobalShortcuts: () => deps.unregisterAllGlobalShortcuts(),
|
unregisterAllGlobalShortcuts: () => deps.unregisterAllGlobalShortcuts(),
|
||||||
stopSubtitleWebsocket: () => deps.stopSubtitleWebsocket(),
|
stopSubtitleWebsocket: () => deps.stopSubtitleWebsocket(),
|
||||||
stopTexthookerService: () => deps.stopTexthookerService(),
|
stopTexthookerService: () => deps.stopTexthookerService(),
|
||||||
clearWindowsVisibleOverlayForegroundPollLoop: () =>
|
|
||||||
deps.clearWindowsVisibleOverlayForegroundPollLoop(),
|
|
||||||
destroyMainOverlayWindow: () => {
|
destroyMainOverlayWindow: () => {
|
||||||
const window = deps.getMainOverlayWindow();
|
const window = deps.getMainOverlayWindow();
|
||||||
if (!window) return;
|
if (!window) return;
|
||||||
|
|||||||
@@ -42,7 +42,6 @@ test('build cli command context deps maps handlers and values', () => {
|
|||||||
markLastCardAsAudioCard: async () => {
|
markLastCardAsAudioCard: async () => {
|
||||||
calls.push('mark');
|
calls.push('mark');
|
||||||
},
|
},
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getAnilistStatus: () => ({}) as never,
|
getAnilistStatus: () => ({}) as never,
|
||||||
clearAnilistToken: () => calls.push('clear-token'),
|
clearAnilistToken: () => calls.push('clear-token'),
|
||||||
openAnilistSetup: () => calls.push('anilist'),
|
openAnilistSetup: () => calls.push('anilist'),
|
||||||
|
|||||||
@@ -28,7 +28,6 @@ export function createBuildCliCommandContextDepsHandler(deps: {
|
|||||||
triggerFieldGrouping: () => Promise<void>;
|
triggerFieldGrouping: () => Promise<void>;
|
||||||
triggerSubsyncFromConfig: () => Promise<void>;
|
triggerSubsyncFromConfig: () => Promise<void>;
|
||||||
markLastCardAsAudioCard: () => Promise<void>;
|
markLastCardAsAudioCard: () => Promise<void>;
|
||||||
dispatchSessionAction: CliCommandContextFactoryDeps['dispatchSessionAction'];
|
|
||||||
getAnilistStatus: CliCommandContextFactoryDeps['getAnilistStatus'];
|
getAnilistStatus: CliCommandContextFactoryDeps['getAnilistStatus'];
|
||||||
clearAnilistToken: CliCommandContextFactoryDeps['clearAnilistToken'];
|
clearAnilistToken: CliCommandContextFactoryDeps['clearAnilistToken'];
|
||||||
openAnilistSetup: CliCommandContextFactoryDeps['openAnilistSetup'];
|
openAnilistSetup: CliCommandContextFactoryDeps['openAnilistSetup'];
|
||||||
@@ -78,7 +77,6 @@ export function createBuildCliCommandContextDepsHandler(deps: {
|
|||||||
triggerFieldGrouping: deps.triggerFieldGrouping,
|
triggerFieldGrouping: deps.triggerFieldGrouping,
|
||||||
triggerSubsyncFromConfig: deps.triggerSubsyncFromConfig,
|
triggerSubsyncFromConfig: deps.triggerSubsyncFromConfig,
|
||||||
markLastCardAsAudioCard: deps.markLastCardAsAudioCard,
|
markLastCardAsAudioCard: deps.markLastCardAsAudioCard,
|
||||||
dispatchSessionAction: deps.dispatchSessionAction,
|
|
||||||
getAnilistStatus: deps.getAnilistStatus,
|
getAnilistStatus: deps.getAnilistStatus,
|
||||||
clearAnilistToken: deps.clearAnilistToken,
|
clearAnilistToken: deps.clearAnilistToken,
|
||||||
openAnilistSetup: deps.openAnilistSetup,
|
openAnilistSetup: deps.openAnilistSetup,
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ test('cli command context factory composes main deps and context handlers', () =
|
|||||||
triggerFieldGrouping: async () => {},
|
triggerFieldGrouping: async () => {},
|
||||||
triggerSubsyncFromConfig: async () => {},
|
triggerSubsyncFromConfig: async () => {},
|
||||||
markLastCardAsAudioCard: async () => {},
|
markLastCardAsAudioCard: async () => {},
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getAnilistStatus: () => ({
|
getAnilistStatus: () => ({
|
||||||
tokenStatus: 'resolved',
|
tokenStatus: 'resolved',
|
||||||
tokenSource: 'literal',
|
tokenSource: 'literal',
|
||||||
|
|||||||
@@ -53,7 +53,6 @@ test('cli command context main deps builder maps state and callbacks', async ()
|
|||||||
markLastCardAsAudioCard: async () => {
|
markLastCardAsAudioCard: async () => {
|
||||||
calls.push('mark-audio');
|
calls.push('mark-audio');
|
||||||
},
|
},
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
|
|
||||||
getAnilistStatus: () => ({
|
getAnilistStatus: () => ({
|
||||||
tokenStatus: 'resolved',
|
tokenStatus: 'resolved',
|
||||||
|
|||||||
@@ -39,7 +39,6 @@ export function createBuildCliCommandContextMainDepsHandler(deps: {
|
|||||||
triggerFieldGrouping: () => Promise<void>;
|
triggerFieldGrouping: () => Promise<void>;
|
||||||
triggerSubsyncFromConfig: () => Promise<void>;
|
triggerSubsyncFromConfig: () => Promise<void>;
|
||||||
markLastCardAsAudioCard: () => Promise<void>;
|
markLastCardAsAudioCard: () => Promise<void>;
|
||||||
dispatchSessionAction: CliCommandContextFactoryDeps['dispatchSessionAction'];
|
|
||||||
|
|
||||||
getAnilistStatus: CliCommandContextFactoryDeps['getAnilistStatus'];
|
getAnilistStatus: CliCommandContextFactoryDeps['getAnilistStatus'];
|
||||||
clearAnilistToken: () => void;
|
clearAnilistToken: () => void;
|
||||||
@@ -104,7 +103,6 @@ export function createBuildCliCommandContextMainDepsHandler(deps: {
|
|||||||
triggerFieldGrouping: () => deps.triggerFieldGrouping(),
|
triggerFieldGrouping: () => deps.triggerFieldGrouping(),
|
||||||
triggerSubsyncFromConfig: () => deps.triggerSubsyncFromConfig(),
|
triggerSubsyncFromConfig: () => deps.triggerSubsyncFromConfig(),
|
||||||
markLastCardAsAudioCard: () => deps.markLastCardAsAudioCard(),
|
markLastCardAsAudioCard: () => deps.markLastCardAsAudioCard(),
|
||||||
dispatchSessionAction: (request) => deps.dispatchSessionAction(request),
|
|
||||||
getAnilistStatus: () => deps.getAnilistStatus(),
|
getAnilistStatus: () => deps.getAnilistStatus(),
|
||||||
clearAnilistToken: () => deps.clearAnilistToken(),
|
clearAnilistToken: () => deps.clearAnilistToken(),
|
||||||
openAnilistSetup: () => deps.openAnilistSetupWindow(),
|
openAnilistSetup: () => deps.openAnilistSetupWindow(),
|
||||||
|
|||||||
@@ -36,7 +36,6 @@ function createDeps() {
|
|||||||
triggerFieldGrouping: async () => {},
|
triggerFieldGrouping: async () => {},
|
||||||
triggerSubsyncFromConfig: async () => {},
|
triggerSubsyncFromConfig: async () => {},
|
||||||
markLastCardAsAudioCard: async () => {},
|
markLastCardAsAudioCard: async () => {},
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getAnilistStatus: () => ({}) as never,
|
getAnilistStatus: () => ({}) as never,
|
||||||
clearAnilistToken: () => {},
|
clearAnilistToken: () => {},
|
||||||
openAnilistSetup: () => {},
|
openAnilistSetup: () => {},
|
||||||
|
|||||||
@@ -33,7 +33,6 @@ export type CliCommandContextFactoryDeps = {
|
|||||||
triggerFieldGrouping: () => Promise<void>;
|
triggerFieldGrouping: () => Promise<void>;
|
||||||
triggerSubsyncFromConfig: () => Promise<void>;
|
triggerSubsyncFromConfig: () => Promise<void>;
|
||||||
markLastCardAsAudioCard: () => Promise<void>;
|
markLastCardAsAudioCard: () => Promise<void>;
|
||||||
dispatchSessionAction: CliCommandRuntimeServiceContext['dispatchSessionAction'];
|
|
||||||
getAnilistStatus: CliCommandRuntimeServiceContext['getAnilistStatus'];
|
getAnilistStatus: CliCommandRuntimeServiceContext['getAnilistStatus'];
|
||||||
clearAnilistToken: CliCommandRuntimeServiceContext['clearAnilistToken'];
|
clearAnilistToken: CliCommandRuntimeServiceContext['clearAnilistToken'];
|
||||||
openAnilistSetup: CliCommandRuntimeServiceContext['openAnilistSetup'];
|
openAnilistSetup: CliCommandRuntimeServiceContext['openAnilistSetup'];
|
||||||
@@ -90,7 +89,6 @@ export function createCliCommandContext(
|
|||||||
triggerFieldGrouping: deps.triggerFieldGrouping,
|
triggerFieldGrouping: deps.triggerFieldGrouping,
|
||||||
triggerSubsyncFromConfig: deps.triggerSubsyncFromConfig,
|
triggerSubsyncFromConfig: deps.triggerSubsyncFromConfig,
|
||||||
markLastCardAsAudioCard: deps.markLastCardAsAudioCard,
|
markLastCardAsAudioCard: deps.markLastCardAsAudioCard,
|
||||||
dispatchSessionAction: deps.dispatchSessionAction,
|
|
||||||
getAnilistStatus: deps.getAnilistStatus,
|
getAnilistStatus: deps.getAnilistStatus,
|
||||||
clearAnilistToken: deps.clearAnilistToken,
|
clearAnilistToken: deps.clearAnilistToken,
|
||||||
openAnilistSetup: deps.openAnilistSetup,
|
openAnilistSetup: deps.openAnilistSetup,
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ test('composeCliStartupHandlers returns callable CLI startup handlers', () => {
|
|||||||
triggerFieldGrouping: async () => {},
|
triggerFieldGrouping: async () => {},
|
||||||
triggerSubsyncFromConfig: async () => {},
|
triggerSubsyncFromConfig: async () => {},
|
||||||
markLastCardAsAudioCard: async () => {},
|
markLastCardAsAudioCard: async () => {},
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getAnilistStatus: () => ({}) as never,
|
getAnilistStatus: () => ({}) as never,
|
||||||
clearAnilistToken: () => {},
|
clearAnilistToken: () => {},
|
||||||
openAnilistSetupWindow: () => {},
|
openAnilistSetupWindow: () => {},
|
||||||
|
|||||||
@@ -53,9 +53,7 @@ test('composeIpcRuntimeHandlers returns callable IPC handlers and registration b
|
|||||||
saveSubtitlePosition: () => {},
|
saveSubtitlePosition: () => {},
|
||||||
getMecabTokenizer: () => null,
|
getMecabTokenizer: () => null,
|
||||||
getKeybindings: () => [],
|
getKeybindings: () => [],
|
||||||
getSessionBindings: () => [],
|
|
||||||
getConfiguredShortcuts: () => ({}) as never,
|
getConfiguredShortcuts: () => ({}) as never,
|
||||||
dispatchSessionAction: async () => {},
|
|
||||||
getStatsToggleKey: () => 'Backquote',
|
getStatsToggleKey: () => 'Backquote',
|
||||||
getMarkWatchedKey: () => 'KeyW',
|
getMarkWatchedKey: () => 'KeyW',
|
||||||
getControllerConfig: () => ({}) as never,
|
getControllerConfig: () => ({}) as never,
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ test('composeStartupLifecycleHandlers returns callable startup lifecycle handler
|
|||||||
unregisterAllGlobalShortcuts: () => {},
|
unregisterAllGlobalShortcuts: () => {},
|
||||||
stopSubtitleWebsocket: () => {},
|
stopSubtitleWebsocket: () => {},
|
||||||
stopTexthookerService: () => {},
|
stopTexthookerService: () => {},
|
||||||
clearWindowsVisibleOverlayForegroundPollLoop: () => {},
|
|
||||||
getMainOverlayWindow: () => null,
|
getMainOverlayWindow: () => null,
|
||||||
clearMainOverlayWindow: () => {},
|
clearMainOverlayWindow: () => {},
|
||||||
getModalOverlayWindow: () => null,
|
getModalOverlayWindow: () => null,
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ test('createConfigHotReloadAppliedHandler runs all hot-reload effects', () => {
|
|||||||
|
|
||||||
const applyHotReload = createConfigHotReloadAppliedHandler({
|
const applyHotReload = createConfigHotReloadAppliedHandler({
|
||||||
setKeybindings: () => calls.push('set:keybindings'),
|
setKeybindings: () => calls.push('set:keybindings'),
|
||||||
setSessionBindings: () => calls.push('set:session-bindings'),
|
|
||||||
refreshGlobalAndOverlayShortcuts: () => calls.push('refresh:shortcuts'),
|
refreshGlobalAndOverlayShortcuts: () => calls.push('refresh:shortcuts'),
|
||||||
setSecondarySubMode: (mode) => calls.push(`set:secondary:${mode}`),
|
setSecondarySubMode: (mode) => calls.push(`set:secondary:${mode}`),
|
||||||
broadcastToOverlayWindows: (channel, payload) =>
|
broadcastToOverlayWindows: (channel, payload) =>
|
||||||
@@ -38,7 +37,6 @@ test('createConfigHotReloadAppliedHandler runs all hot-reload effects', () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
assert.ok(calls.includes('set:keybindings'));
|
assert.ok(calls.includes('set:keybindings'));
|
||||||
assert.ok(calls.includes('set:session-bindings'));
|
|
||||||
assert.ok(calls.includes('refresh:shortcuts'));
|
assert.ok(calls.includes('refresh:shortcuts'));
|
||||||
assert.ok(calls.includes(`set:secondary:${config.secondarySub.defaultMode}`));
|
assert.ok(calls.includes(`set:secondary:${config.secondarySub.defaultMode}`));
|
||||||
assert.ok(calls.some((entry) => entry.startsWith('broadcast:secondary-subtitle:mode:')));
|
assert.ok(calls.some((entry) => entry.startsWith('broadcast:secondary-subtitle:mode:')));
|
||||||
@@ -52,7 +50,6 @@ test('createConfigHotReloadAppliedHandler skips optional effects when no hot fie
|
|||||||
|
|
||||||
const applyHotReload = createConfigHotReloadAppliedHandler({
|
const applyHotReload = createConfigHotReloadAppliedHandler({
|
||||||
setKeybindings: () => calls.push('set:keybindings'),
|
setKeybindings: () => calls.push('set:keybindings'),
|
||||||
setSessionBindings: () => calls.push('set:session-bindings'),
|
|
||||||
refreshGlobalAndOverlayShortcuts: () => calls.push('refresh:shortcuts'),
|
refreshGlobalAndOverlayShortcuts: () => calls.push('refresh:shortcuts'),
|
||||||
setSecondarySubMode: () => calls.push('set:secondary'),
|
setSecondarySubMode: () => calls.push('set:secondary'),
|
||||||
broadcastToOverlayWindows: (channel) => calls.push(`broadcast:${channel}`),
|
broadcastToOverlayWindows: (channel) => calls.push(`broadcast:${channel}`),
|
||||||
@@ -67,7 +64,7 @@ test('createConfigHotReloadAppliedHandler skips optional effects when no hot fie
|
|||||||
config,
|
config,
|
||||||
);
|
);
|
||||||
|
|
||||||
assert.deepEqual(calls, ['set:keybindings', 'set:session-bindings']);
|
assert.deepEqual(calls, ['set:keybindings']);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('createConfigHotReloadMessageHandler mirrors message to OSD and desktop notification', () => {
|
test('createConfigHotReloadMessageHandler mirrors message to OSD and desktop notification', () => {
|
||||||
|
|||||||
@@ -1,13 +1,10 @@
|
|||||||
import type { ConfigHotReloadDiff } from '../../core/services/config-hot-reload';
|
import type { ConfigHotReloadDiff } from '../../core/services/config-hot-reload';
|
||||||
import { compileSessionBindings } from '../../core/services/session-bindings';
|
|
||||||
import { resolveKeybindings } from '../../core/utils/keybindings';
|
import { resolveKeybindings } from '../../core/utils/keybindings';
|
||||||
import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config';
|
import { DEFAULT_KEYBINDINGS } from '../../config';
|
||||||
import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config';
|
|
||||||
import type { ConfigHotReloadPayload, ResolvedConfig, SecondarySubMode } from '../../types';
|
import type { ConfigHotReloadPayload, ResolvedConfig, SecondarySubMode } from '../../types';
|
||||||
|
|
||||||
type ConfigHotReloadAppliedDeps = {
|
type ConfigHotReloadAppliedDeps = {
|
||||||
setKeybindings: (keybindings: ConfigHotReloadPayload['keybindings']) => void;
|
setKeybindings: (keybindings: ConfigHotReloadPayload['keybindings']) => void;
|
||||||
setSessionBindings: (sessionBindings: ConfigHotReloadPayload['sessionBindings']) => void;
|
|
||||||
refreshGlobalAndOverlayShortcuts: () => void;
|
refreshGlobalAndOverlayShortcuts: () => void;
|
||||||
setSecondarySubMode: (mode: SecondarySubMode) => void;
|
setSecondarySubMode: (mode: SecondarySubMode) => void;
|
||||||
broadcastToOverlayWindows: (channel: string, payload: unknown) => void;
|
broadcastToOverlayWindows: (channel: string, payload: unknown) => void;
|
||||||
@@ -36,21 +33,8 @@ export function resolveSubtitleStyleForRenderer(config: ResolvedConfig) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function buildConfigHotReloadPayload(config: ResolvedConfig): ConfigHotReloadPayload {
|
export function buildConfigHotReloadPayload(config: ResolvedConfig): ConfigHotReloadPayload {
|
||||||
const keybindings = resolveKeybindings(config, DEFAULT_KEYBINDINGS);
|
|
||||||
const { bindings: sessionBindings } = compileSessionBindings({
|
|
||||||
keybindings,
|
|
||||||
shortcuts: resolveConfiguredShortcuts(config, DEFAULT_CONFIG),
|
|
||||||
platform:
|
|
||||||
process.platform === 'darwin'
|
|
||||||
? 'darwin'
|
|
||||||
: process.platform === 'win32'
|
|
||||||
? 'win32'
|
|
||||||
: 'linux',
|
|
||||||
rawConfig: config,
|
|
||||||
});
|
|
||||||
return {
|
return {
|
||||||
keybindings,
|
keybindings: resolveKeybindings(config, DEFAULT_KEYBINDINGS),
|
||||||
sessionBindings,
|
|
||||||
subtitleStyle: resolveSubtitleStyleForRenderer(config),
|
subtitleStyle: resolveSubtitleStyleForRenderer(config),
|
||||||
subtitleSidebar: config.subtitleSidebar,
|
subtitleSidebar: config.subtitleSidebar,
|
||||||
secondarySubMode: config.secondarySub.defaultMode,
|
secondarySubMode: config.secondarySub.defaultMode,
|
||||||
@@ -61,7 +45,6 @@ export function createConfigHotReloadAppliedHandler(deps: ConfigHotReloadApplied
|
|||||||
return (diff: ConfigHotReloadDiff, config: ResolvedConfig): void => {
|
return (diff: ConfigHotReloadDiff, config: ResolvedConfig): void => {
|
||||||
const payload = buildConfigHotReloadPayload(config);
|
const payload = buildConfigHotReloadPayload(config);
|
||||||
deps.setKeybindings(payload.keybindings);
|
deps.setKeybindings(payload.keybindings);
|
||||||
deps.setSessionBindings(payload.sessionBindings);
|
|
||||||
|
|
||||||
if (diff.hotReloadFields.includes('shortcuts')) {
|
if (diff.hotReloadFields.includes('shortcuts')) {
|
||||||
deps.refreshGlobalAndOverlayShortcuts();
|
deps.refreshGlobalAndOverlayShortcuts();
|
||||||
|
|||||||
@@ -86,25 +86,21 @@ test('config hot reload message main deps builder maps notifications', () => {
|
|||||||
|
|
||||||
test('config hot reload applied main deps builder maps callbacks', () => {
|
test('config hot reload applied main deps builder maps callbacks', () => {
|
||||||
const calls: string[] = [];
|
const calls: string[] = [];
|
||||||
const buildDeps = createBuildConfigHotReloadAppliedMainDepsHandler({
|
const deps = createBuildConfigHotReloadAppliedMainDepsHandler({
|
||||||
setKeybindings: () => calls.push('keybindings'),
|
setKeybindings: () => calls.push('keybindings'),
|
||||||
setSessionBindings: () => calls.push('session-bindings'),
|
|
||||||
refreshGlobalAndOverlayShortcuts: () => calls.push('refresh-shortcuts'),
|
refreshGlobalAndOverlayShortcuts: () => calls.push('refresh-shortcuts'),
|
||||||
setSecondarySubMode: () => calls.push('set-secondary'),
|
setSecondarySubMode: () => calls.push('set-secondary'),
|
||||||
broadcastToOverlayWindows: (channel) => calls.push(`broadcast:${channel}`),
|
broadcastToOverlayWindows: (channel) => calls.push(`broadcast:${channel}`),
|
||||||
applyAnkiRuntimeConfigPatch: () => calls.push('apply-anki'),
|
applyAnkiRuntimeConfigPatch: () => calls.push('apply-anki'),
|
||||||
});
|
})();
|
||||||
|
|
||||||
const deps = buildDeps();
|
|
||||||
deps.setKeybindings([]);
|
deps.setKeybindings([]);
|
||||||
deps.setSessionBindings([]);
|
|
||||||
deps.refreshGlobalAndOverlayShortcuts();
|
deps.refreshGlobalAndOverlayShortcuts();
|
||||||
deps.setSecondarySubMode('hover');
|
deps.setSecondarySubMode('hover');
|
||||||
deps.broadcastToOverlayWindows('config:hot-reload', {});
|
deps.broadcastToOverlayWindows('config:hot-reload', {});
|
||||||
deps.applyAnkiRuntimeConfigPatch({ ai: true });
|
deps.applyAnkiRuntimeConfigPatch({ ai: true });
|
||||||
assert.deepEqual(calls, [
|
assert.deepEqual(calls, [
|
||||||
'keybindings',
|
'keybindings',
|
||||||
'session-bindings',
|
|
||||||
'refresh-shortcuts',
|
'refresh-shortcuts',
|
||||||
'set-secondary',
|
'set-secondary',
|
||||||
'broadcast:config:hot-reload',
|
'broadcast:config:hot-reload',
|
||||||
|
|||||||
@@ -62,7 +62,6 @@ export function createBuildConfigHotReloadMessageMainDepsHandler(
|
|||||||
|
|
||||||
export function createBuildConfigHotReloadAppliedMainDepsHandler(deps: {
|
export function createBuildConfigHotReloadAppliedMainDepsHandler(deps: {
|
||||||
setKeybindings: (keybindings: ConfigHotReloadPayload['keybindings']) => void;
|
setKeybindings: (keybindings: ConfigHotReloadPayload['keybindings']) => void;
|
||||||
setSessionBindings: (sessionBindings: ConfigHotReloadPayload['sessionBindings']) => void;
|
|
||||||
refreshGlobalAndOverlayShortcuts: () => void;
|
refreshGlobalAndOverlayShortcuts: () => void;
|
||||||
setSecondarySubMode: (mode: SecondarySubMode) => void;
|
setSecondarySubMode: (mode: SecondarySubMode) => void;
|
||||||
broadcastToOverlayWindows: (channel: string, payload: unknown) => void;
|
broadcastToOverlayWindows: (channel: string, payload: unknown) => void;
|
||||||
@@ -73,8 +72,6 @@ export function createBuildConfigHotReloadAppliedMainDepsHandler(deps: {
|
|||||||
return () => ({
|
return () => ({
|
||||||
setKeybindings: (keybindings: ConfigHotReloadPayload['keybindings']) =>
|
setKeybindings: (keybindings: ConfigHotReloadPayload['keybindings']) =>
|
||||||
deps.setKeybindings(keybindings),
|
deps.setKeybindings(keybindings),
|
||||||
setSessionBindings: (sessionBindings: ConfigHotReloadPayload['sessionBindings']) =>
|
|
||||||
deps.setSessionBindings(sessionBindings),
|
|
||||||
refreshGlobalAndOverlayShortcuts: () => deps.refreshGlobalAndOverlayShortcuts(),
|
refreshGlobalAndOverlayShortcuts: () => deps.refreshGlobalAndOverlayShortcuts(),
|
||||||
setSecondarySubMode: (mode: SecondarySubMode) => deps.setSecondarySubMode(mode),
|
setSecondarySubMode: (mode: SecondarySubMode) => deps.setSecondarySubMode(mode),
|
||||||
broadcastToOverlayWindows: (channel: string, payload: unknown) =>
|
broadcastToOverlayWindows: (channel: string, payload: unknown) =>
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
|
||||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
|
||||||
import { openOverlayHostedModal, retryOverlayModalOpen } from './overlay-hosted-modal-open';
|
|
||||||
|
|
||||||
const CONTROLLER_DEBUG_MODAL: OverlayHostedModal = 'controller-debug';
|
|
||||||
const CONTROLLER_DEBUG_OPEN_TIMEOUT_MS = 1500;
|
|
||||||
|
|
||||||
export async function openControllerDebugModal(deps: {
|
|
||||||
ensureOverlayStartupPrereqs: () => void;
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
|
||||||
sendToActiveOverlayWindow: (
|
|
||||||
channel: string,
|
|
||||||
payload?: unknown,
|
|
||||||
runtimeOptions?: {
|
|
||||||
restoreOnModalClose?: OverlayHostedModal;
|
|
||||||
preferModalWindow?: boolean;
|
|
||||||
},
|
|
||||||
) => boolean;
|
|
||||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
|
||||||
logWarn: (message: string) => void;
|
|
||||||
}): Promise<boolean> {
|
|
||||||
return await retryOverlayModalOpen(
|
|
||||||
{
|
|
||||||
waitForModalOpen: deps.waitForModalOpen,
|
|
||||||
logWarn: deps.logWarn,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
modal: CONTROLLER_DEBUG_MODAL,
|
|
||||||
timeoutMs: CONTROLLER_DEBUG_OPEN_TIMEOUT_MS,
|
|
||||||
retryWarning:
|
|
||||||
'Controller debug modal did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
|
||||||
sendOpen: () =>
|
|
||||||
openOverlayHostedModal(
|
|
||||||
{
|
|
||||||
ensureOverlayStartupPrereqs: deps.ensureOverlayStartupPrereqs,
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions:
|
|
||||||
deps.ensureOverlayWindowsReadyForVisibilityActions,
|
|
||||||
sendToActiveOverlayWindow: deps.sendToActiveOverlayWindow,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
channel: IPC_CHANNELS.event.controllerDebugOpen,
|
|
||||||
modal: CONTROLLER_DEBUG_MODAL,
|
|
||||||
preferModalWindow: true,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
|
||||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
|
||||||
import { openOverlayHostedModal, retryOverlayModalOpen } from './overlay-hosted-modal-open';
|
|
||||||
|
|
||||||
const CONTROLLER_SELECT_MODAL: OverlayHostedModal = 'controller-select';
|
|
||||||
const CONTROLLER_SELECT_OPEN_TIMEOUT_MS = 1500;
|
|
||||||
|
|
||||||
export async function openControllerSelectModal(deps: {
|
|
||||||
ensureOverlayStartupPrereqs: () => void;
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
|
||||||
sendToActiveOverlayWindow: (
|
|
||||||
channel: string,
|
|
||||||
payload?: unknown,
|
|
||||||
runtimeOptions?: {
|
|
||||||
restoreOnModalClose?: OverlayHostedModal;
|
|
||||||
preferModalWindow?: boolean;
|
|
||||||
},
|
|
||||||
) => boolean;
|
|
||||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
|
||||||
logWarn: (message: string) => void;
|
|
||||||
}): Promise<boolean> {
|
|
||||||
return await retryOverlayModalOpen(
|
|
||||||
{
|
|
||||||
waitForModalOpen: deps.waitForModalOpen,
|
|
||||||
logWarn: deps.logWarn,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
modal: CONTROLLER_SELECT_MODAL,
|
|
||||||
timeoutMs: CONTROLLER_SELECT_OPEN_TIMEOUT_MS,
|
|
||||||
retryWarning:
|
|
||||||
'Controller select modal did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
|
||||||
sendOpen: () =>
|
|
||||||
openOverlayHostedModal(
|
|
||||||
{
|
|
||||||
ensureOverlayStartupPrereqs: deps.ensureOverlayStartupPrereqs,
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions:
|
|
||||||
deps.ensureOverlayWindowsReadyForVisibilityActions,
|
|
||||||
sendToActiveOverlayWindow: deps.sendToActiveOverlayWindow,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
channel: IPC_CHANNELS.event.controllerSelectOpen,
|
|
||||||
modal: CONTROLLER_SELECT_MODAL,
|
|
||||||
preferModalWindow: true,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -42,21 +42,7 @@ function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
|||||||
triggerFieldGrouping: false,
|
triggerFieldGrouping: false,
|
||||||
triggerSubsync: false,
|
triggerSubsync: false,
|
||||||
markAudioCard: false,
|
markAudioCard: false,
|
||||||
toggleStatsOverlay: false,
|
|
||||||
toggleSubtitleSidebar: false,
|
|
||||||
openRuntimeOptions: false,
|
openRuntimeOptions: false,
|
||||||
openSessionHelp: false,
|
|
||||||
openControllerSelect: false,
|
|
||||||
openControllerDebug: false,
|
|
||||||
openJimaku: false,
|
|
||||||
openYoutubePicker: false,
|
|
||||||
openPlaylistBrowser: false,
|
|
||||||
replayCurrentSubtitle: false,
|
|
||||||
playNextSubtitle: false,
|
|
||||||
shiftSubDelayPrevLine: false,
|
|
||||||
shiftSubDelayNextLine: false,
|
|
||||||
cycleRuntimeOptionId: undefined,
|
|
||||||
cycleRuntimeOptionDirection: undefined,
|
|
||||||
anilistStatus: false,
|
anilistStatus: false,
|
||||||
anilistLogout: false,
|
anilistLogout: false,
|
||||||
anilistSetup: false,
|
anilistSetup: false,
|
||||||
@@ -93,17 +79,6 @@ test('shouldAutoOpenFirstRunSetup only for startup/setup intents', () => {
|
|||||||
assert.equal(shouldAutoOpenFirstRunSetup(makeArgs({ settings: true })), false);
|
assert.equal(shouldAutoOpenFirstRunSetup(makeArgs({ settings: true })), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('shouldAutoOpenFirstRunSetup treats numeric startup counts as explicit commands', () => {
|
|
||||||
assert.equal(
|
|
||||||
shouldAutoOpenFirstRunSetup(makeArgs({ start: true, copySubtitleCount: 2 })),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.equal(
|
|
||||||
shouldAutoOpenFirstRunSetup(makeArgs({ background: true, mineSentenceCount: 1 })),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('setup service auto-completes legacy installs with config and dictionaries', async () => {
|
test('setup service auto-completes legacy installs with config and dictionaries', async () => {
|
||||||
await withTempDir(async (root) => {
|
await withTempDir(async (root) => {
|
||||||
const configDir = path.join(root, 'SubMiner');
|
const configDir = path.join(root, 'SubMiner');
|
||||||
|
|||||||
@@ -68,26 +68,15 @@ function hasAnyStartupCommandBeyondSetup(args: CliArgs): boolean {
|
|||||||
args.hideVisibleOverlay ||
|
args.hideVisibleOverlay ||
|
||||||
args.copySubtitle ||
|
args.copySubtitle ||
|
||||||
args.copySubtitleMultiple ||
|
args.copySubtitleMultiple ||
|
||||||
args.copySubtitleCount !== undefined ||
|
|
||||||
args.mineSentence ||
|
args.mineSentence ||
|
||||||
args.mineSentenceMultiple ||
|
args.mineSentenceMultiple ||
|
||||||
args.mineSentenceCount !== undefined ||
|
|
||||||
args.updateLastCardFromClipboard ||
|
args.updateLastCardFromClipboard ||
|
||||||
args.refreshKnownWords ||
|
args.refreshKnownWords ||
|
||||||
args.toggleSecondarySub ||
|
args.toggleSecondarySub ||
|
||||||
args.triggerFieldGrouping ||
|
args.triggerFieldGrouping ||
|
||||||
args.triggerSubsync ||
|
args.triggerSubsync ||
|
||||||
args.markAudioCard ||
|
args.markAudioCard ||
|
||||||
args.toggleStatsOverlay ||
|
|
||||||
args.openRuntimeOptions ||
|
args.openRuntimeOptions ||
|
||||||
args.openJimaku ||
|
|
||||||
args.openYoutubePicker ||
|
|
||||||
args.openPlaylistBrowser ||
|
|
||||||
args.replayCurrentSubtitle ||
|
|
||||||
args.playNextSubtitle ||
|
|
||||||
args.shiftSubDelayPrevLine ||
|
|
||||||
args.shiftSubDelayNextLine ||
|
|
||||||
args.cycleRuntimeOptionId !== undefined ||
|
|
||||||
args.anilistStatus ||
|
args.anilistStatus ||
|
||||||
args.anilistLogout ||
|
args.anilistLogout ||
|
||||||
args.anilistSetup ||
|
args.anilistSetup ||
|
||||||
|
|||||||
@@ -18,10 +18,6 @@ function createShortcuts(): ConfiguredShortcuts {
|
|||||||
markAudioCard: null,
|
markAudioCard: null,
|
||||||
openRuntimeOptions: null,
|
openRuntimeOptions: null,
|
||||||
openJimaku: null,
|
openJimaku: null,
|
||||||
openSessionHelp: null,
|
|
||||||
openControllerSelect: null,
|
|
||||||
openControllerDebug: null,
|
|
||||||
toggleSubtitleSidebar: null,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,10 +22,6 @@ function createShortcuts(): ConfiguredShortcuts {
|
|||||||
markAudioCard: null,
|
markAudioCard: null,
|
||||||
openRuntimeOptions: null,
|
openRuntimeOptions: null,
|
||||||
openJimaku: null,
|
openJimaku: null,
|
||||||
openSessionHelp: null,
|
|
||||||
openControllerSelect: null,
|
|
||||||
openControllerDebug: null,
|
|
||||||
toggleSubtitleSidebar: null,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -161,44 +161,6 @@ test('createImmersionTrackerStartupHandler creates tracker and auto-connects mpv
|
|||||||
assert.ok(calls.includes('info:Auto-connecting MPV client for immersion tracking'));
|
assert.ok(calls.includes('info:Auto-connecting MPV client for immersion tracking'));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('createImmersionTrackerStartupHandler keeps tracker startup alive when mpv auto-connect throws', () => {
|
|
||||||
const calls: string[] = [];
|
|
||||||
const trackerInstance = { kind: 'tracker' };
|
|
||||||
let assignedTracker: unknown = null;
|
|
||||||
const handler = createImmersionTrackerStartupHandler({
|
|
||||||
getResolvedConfig: () => makeConfig(),
|
|
||||||
getConfiguredDbPath: () => '/tmp/subminer.db',
|
|
||||||
createTrackerService: () => trackerInstance,
|
|
||||||
setTracker: (nextTracker) => {
|
|
||||||
assignedTracker = nextTracker;
|
|
||||||
},
|
|
||||||
getMpvClient: () => ({
|
|
||||||
connected: false,
|
|
||||||
connect: () => {
|
|
||||||
throw new Error('socket not ready');
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
seedTrackerFromCurrentMedia: () => calls.push('seedTracker'),
|
|
||||||
logInfo: (message) => calls.push(`info:${message}`),
|
|
||||||
logDebug: (message) => calls.push(`debug:${message}`),
|
|
||||||
logWarn: (message, details) => calls.push(`warn:${message}:${(details as Error).message}`),
|
|
||||||
});
|
|
||||||
|
|
||||||
handler();
|
|
||||||
|
|
||||||
assert.equal(assignedTracker, trackerInstance);
|
|
||||||
assert.ok(calls.includes('seedTracker'));
|
|
||||||
assert.ok(
|
|
||||||
calls.includes(
|
|
||||||
'warn:MPV auto-connect failed during immersion tracker startup; continuing.:socket not ready',
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert.equal(
|
|
||||||
calls.some((entry) => entry.startsWith('warn:Immersion tracker startup failed; disabling tracking.')),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('createImmersionTrackerStartupHandler disables tracker on failure', () => {
|
test('createImmersionTrackerStartupHandler disables tracker on failure', () => {
|
||||||
const calls: string[] = [];
|
const calls: string[] = [];
|
||||||
let assignedTracker: unknown = 'initial';
|
let assignedTracker: unknown = 'initial';
|
||||||
|
|||||||
@@ -102,11 +102,7 @@ export function createImmersionTrackerStartupHandler(
|
|||||||
const mpvClient = deps.getMpvClient();
|
const mpvClient = deps.getMpvClient();
|
||||||
if ((deps.shouldAutoConnectMpv?.() ?? true) && mpvClient && !mpvClient.connected) {
|
if ((deps.shouldAutoConnectMpv?.() ?? true) && mpvClient && !mpvClient.connected) {
|
||||||
deps.logInfo('Auto-connecting MPV client for immersion tracking');
|
deps.logInfo('Auto-connecting MPV client for immersion tracking');
|
||||||
try {
|
|
||||||
mpvClient.connect();
|
mpvClient.connect();
|
||||||
} catch (error) {
|
|
||||||
deps.logWarn('MPV auto-connect failed during immersion tracker startup; continuing.', error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
deps.seedTrackerFromCurrentMedia();
|
deps.seedTrackerFromCurrentMedia();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
|
||||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
|
||||||
import { openOverlayHostedModal, retryOverlayModalOpen } from './overlay-hosted-modal-open';
|
|
||||||
|
|
||||||
const JIMAKU_MODAL: OverlayHostedModal = 'jimaku';
|
|
||||||
const JIMAKU_OPEN_TIMEOUT_MS = 1500;
|
|
||||||
|
|
||||||
export async function openJimakuModal(deps: {
|
|
||||||
ensureOverlayStartupPrereqs: () => void;
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
|
||||||
sendToActiveOverlayWindow: (
|
|
||||||
channel: string,
|
|
||||||
payload?: unknown,
|
|
||||||
runtimeOptions?: {
|
|
||||||
restoreOnModalClose?: OverlayHostedModal;
|
|
||||||
preferModalWindow?: boolean;
|
|
||||||
},
|
|
||||||
) => boolean;
|
|
||||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
|
||||||
logWarn: (message: string) => void;
|
|
||||||
}): Promise<boolean> {
|
|
||||||
return await retryOverlayModalOpen(
|
|
||||||
{
|
|
||||||
waitForModalOpen: deps.waitForModalOpen,
|
|
||||||
logWarn: deps.logWarn,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
modal: JIMAKU_MODAL,
|
|
||||||
timeoutMs: JIMAKU_OPEN_TIMEOUT_MS,
|
|
||||||
retryWarning:
|
|
||||||
'Jimaku modal did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
|
||||||
sendOpen: () =>
|
|
||||||
openOverlayHostedModal(
|
|
||||||
{
|
|
||||||
ensureOverlayStartupPrereqs: deps.ensureOverlayStartupPrereqs,
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions:
|
|
||||||
deps.ensureOverlayWindowsReadyForVisibilityActions,
|
|
||||||
sendToActiveOverlayWindow: deps.sendToActiveOverlayWindow,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
channel: IPC_CHANNELS.event.jimakuOpen,
|
|
||||||
modal: JIMAKU_MODAL,
|
|
||||||
preferModalWindow: true,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import test from 'node:test';
|
|
||||||
import { openOverlayHostedModal } from './overlay-hosted-modal-open';
|
|
||||||
|
|
||||||
test('openOverlayHostedModal ensures overlay readiness before sending the open event', () => {
|
|
||||||
const calls: string[] = [];
|
|
||||||
|
|
||||||
const opened = openOverlayHostedModal(
|
|
||||||
{
|
|
||||||
ensureOverlayStartupPrereqs: () => {
|
|
||||||
calls.push('ensureOverlayStartupPrereqs');
|
|
||||||
},
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => {
|
|
||||||
calls.push('ensureOverlayWindowsReadyForVisibilityActions');
|
|
||||||
},
|
|
||||||
sendToActiveOverlayWindow: (channel, payload, runtimeOptions) => {
|
|
||||||
calls.push(`send:${channel}`);
|
|
||||||
assert.equal(payload, undefined);
|
|
||||||
assert.deepEqual(runtimeOptions, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
preferModalWindow: undefined,
|
|
||||||
});
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
channel: 'runtime-options:open',
|
|
||||||
modal: 'runtime-options',
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.equal(opened, true);
|
|
||||||
assert.deepEqual(calls, [
|
|
||||||
'ensureOverlayStartupPrereqs',
|
|
||||||
'ensureOverlayWindowsReadyForVisibilityActions',
|
|
||||||
'send:runtime-options:open',
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('openOverlayHostedModal forwards payload and modal-window preference', () => {
|
|
||||||
const payload = { sessionId: 'yt-1' };
|
|
||||||
|
|
||||||
const opened = openOverlayHostedModal(
|
|
||||||
{
|
|
||||||
ensureOverlayStartupPrereqs: () => {},
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => {},
|
|
||||||
sendToActiveOverlayWindow: (channel, forwardedPayload, runtimeOptions) => {
|
|
||||||
assert.equal(channel, 'youtube:picker-open');
|
|
||||||
assert.deepEqual(forwardedPayload, payload);
|
|
||||||
assert.deepEqual(runtimeOptions, {
|
|
||||||
restoreOnModalClose: 'youtube-track-picker',
|
|
||||||
preferModalWindow: true,
|
|
||||||
});
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
channel: 'youtube:picker-open',
|
|
||||||
modal: 'youtube-track-picker',
|
|
||||||
payload,
|
|
||||||
preferModalWindow: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.equal(opened, false);
|
|
||||||
});
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
|
||||||
|
|
||||||
export function openOverlayHostedModal(
|
|
||||||
deps: {
|
|
||||||
ensureOverlayStartupPrereqs: () => void;
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
|
||||||
sendToActiveOverlayWindow: (
|
|
||||||
channel: string,
|
|
||||||
payload?: unknown,
|
|
||||||
runtimeOptions?: {
|
|
||||||
restoreOnModalClose?: OverlayHostedModal;
|
|
||||||
preferModalWindow?: boolean;
|
|
||||||
},
|
|
||||||
) => boolean;
|
|
||||||
},
|
|
||||||
input: {
|
|
||||||
channel: string;
|
|
||||||
modal: OverlayHostedModal;
|
|
||||||
payload?: unknown;
|
|
||||||
preferModalWindow?: boolean;
|
|
||||||
},
|
|
||||||
): boolean {
|
|
||||||
deps.ensureOverlayStartupPrereqs();
|
|
||||||
deps.ensureOverlayWindowsReadyForVisibilityActions();
|
|
||||||
return deps.sendToActiveOverlayWindow(input.channel, input.payload, {
|
|
||||||
restoreOnModalClose: input.modal,
|
|
||||||
preferModalWindow: input.preferModalWindow,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function retryOverlayModalOpen(
|
|
||||||
deps: {
|
|
||||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
|
||||||
logWarn: (message: string) => void;
|
|
||||||
},
|
|
||||||
input: {
|
|
||||||
modal: OverlayHostedModal;
|
|
||||||
timeoutMs: number;
|
|
||||||
retryWarning: string;
|
|
||||||
sendOpen: () => boolean;
|
|
||||||
},
|
|
||||||
): Promise<boolean> {
|
|
||||||
if (!input.sendOpen()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (await deps.waitForModalOpen(input.modal, input.timeoutMs)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
deps.logWarn(input.retryWarning);
|
|
||||||
if (!input.sendOpen()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return await deps.waitForModalOpen(input.modal, input.timeoutMs);
|
|
||||||
}
|
|
||||||
@@ -23,9 +23,6 @@ function createModalWindow() {
|
|||||||
setIgnoreMouseEvents: (ignore: boolean) => {
|
setIgnoreMouseEvents: (ignore: boolean) => {
|
||||||
calls.push(`ignore:${ignore}`);
|
calls.push(`ignore:${ignore}`);
|
||||||
},
|
},
|
||||||
setFocusable: (focusable: boolean) => {
|
|
||||||
calls.push(`focusable:${focusable}`);
|
|
||||||
},
|
|
||||||
setAlwaysOnTop: (flag: boolean, level?: string, relativeLevel?: number) => {
|
setAlwaysOnTop: (flag: boolean, level?: string, relativeLevel?: number) => {
|
||||||
calls.push(`top:${flag}:${level ?? ''}:${relativeLevel ?? ''}`);
|
calls.push(`top:${flag}:${level ?? ''}:${relativeLevel ?? ''}`);
|
||||||
},
|
},
|
||||||
@@ -61,7 +58,6 @@ test('overlay modal input state activates modal window interactivity and syncs d
|
|||||||
|
|
||||||
assert.equal(state.getModalInputExclusive(), true);
|
assert.equal(state.getModalInputExclusive(), true);
|
||||||
assert.deepEqual(modalWindow.calls, [
|
assert.deepEqual(modalWindow.calls, [
|
||||||
'focusable:true',
|
|
||||||
'ignore:false',
|
'ignore:false',
|
||||||
'top:true:screen-saver:1',
|
'top:true:screen-saver:1',
|
||||||
'focus',
|
'focus',
|
||||||
@@ -70,25 +66,6 @@ test('overlay modal input state activates modal window interactivity and syncs d
|
|||||||
assert.deepEqual(calls, ['shortcuts:true', 'visibility']);
|
assert.deepEqual(calls, ['shortcuts:true', 'visibility']);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('overlay modal input state restores main window focus on deactivation', () => {
|
|
||||||
const modalWindow = createModalWindow();
|
|
||||||
const calls: string[] = [];
|
|
||||||
const state = createOverlayModalInputState({
|
|
||||||
getModalWindow: () => modalWindow as never,
|
|
||||||
syncOverlayShortcutsForModal: () => {},
|
|
||||||
syncOverlayVisibilityForModal: () => {},
|
|
||||||
restoreMainWindowFocus: () => {
|
|
||||||
calls.push('restore-focus');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
state.handleModalInputStateChange(true);
|
|
||||||
assert.deepEqual(calls, []);
|
|
||||||
|
|
||||||
state.handleModalInputStateChange(false);
|
|
||||||
assert.deepEqual(calls, ['restore-focus']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('overlay modal input state is idempotent for unchanged state', () => {
|
test('overlay modal input state is idempotent for unchanged state', () => {
|
||||||
const calls: string[] = [];
|
const calls: string[] = [];
|
||||||
const state = createOverlayModalInputState({
|
const state = createOverlayModalInputState({
|
||||||
|
|||||||
@@ -1,30 +1,9 @@
|
|||||||
import type { BrowserWindow } from 'electron';
|
import type { BrowserWindow } from 'electron';
|
||||||
|
|
||||||
function requestOverlayApplicationFocus(): void {
|
|
||||||
try {
|
|
||||||
const electron = require('electron') as {
|
|
||||||
app?: {
|
|
||||||
focus?: (options?: { steal?: boolean }) => void;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
electron.app?.focus?.({ steal: true });
|
|
||||||
} catch {
|
|
||||||
// Ignore focus-steal failures in non-Electron test environments.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function setWindowFocusable(window: BrowserWindow): void {
|
|
||||||
const maybeFocusableWindow = window as BrowserWindow & {
|
|
||||||
setFocusable?: (focusable: boolean) => void;
|
|
||||||
};
|
|
||||||
maybeFocusableWindow.setFocusable?.(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
export type OverlayModalInputStateDeps = {
|
export type OverlayModalInputStateDeps = {
|
||||||
getModalWindow: () => BrowserWindow | null;
|
getModalWindow: () => BrowserWindow | null;
|
||||||
syncOverlayShortcutsForModal: (isActive: boolean) => void;
|
syncOverlayShortcutsForModal: (isActive: boolean) => void;
|
||||||
syncOverlayVisibilityForModal: () => void;
|
syncOverlayVisibilityForModal: () => void;
|
||||||
restoreMainWindowFocus?: () => void;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createOverlayModalInputState(deps: OverlayModalInputStateDeps) {
|
export function createOverlayModalInputState(deps: OverlayModalInputStateDeps) {
|
||||||
@@ -39,8 +18,6 @@ export function createOverlayModalInputState(deps: OverlayModalInputStateDeps) {
|
|||||||
if (isActive) {
|
if (isActive) {
|
||||||
const modalWindow = deps.getModalWindow();
|
const modalWindow = deps.getModalWindow();
|
||||||
if (modalWindow && !modalWindow.isDestroyed()) {
|
if (modalWindow && !modalWindow.isDestroyed()) {
|
||||||
setWindowFocusable(modalWindow);
|
|
||||||
requestOverlayApplicationFocus();
|
|
||||||
modalWindow.setIgnoreMouseEvents(false);
|
modalWindow.setIgnoreMouseEvents(false);
|
||||||
modalWindow.setAlwaysOnTop(true, 'screen-saver', 1);
|
modalWindow.setAlwaysOnTop(true, 'screen-saver', 1);
|
||||||
modalWindow.focus();
|
modalWindow.focus();
|
||||||
@@ -52,9 +29,6 @@ export function createOverlayModalInputState(deps: OverlayModalInputStateDeps) {
|
|||||||
|
|
||||||
deps.syncOverlayShortcutsForModal(isActive);
|
deps.syncOverlayShortcutsForModal(isActive);
|
||||||
deps.syncOverlayVisibilityForModal();
|
deps.syncOverlayVisibilityForModal();
|
||||||
if (!isActive) {
|
|
||||||
deps.restoreMainWindowFocus?.();
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -3,10 +3,10 @@ import test from 'node:test';
|
|||||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
||||||
import { openPlaylistBrowser } from './playlist-browser-open';
|
import { openPlaylistBrowser } from './playlist-browser-open';
|
||||||
|
|
||||||
test('playlist browser open bootstraps overlay runtime and sends modal event with preferModalWindow', async () => {
|
test('playlist browser open bootstraps overlay runtime before dispatching the modal event', () => {
|
||||||
const calls: string[] = [];
|
const calls: string[] = [];
|
||||||
|
|
||||||
const opened = await openPlaylistBrowser({
|
const opened = openPlaylistBrowser({
|
||||||
ensureOverlayStartupPrereqs: () => {
|
ensureOverlayStartupPrereqs: () => {
|
||||||
calls.push('prereqs');
|
calls.push('prereqs');
|
||||||
},
|
},
|
||||||
@@ -18,31 +18,11 @@ test('playlist browser open bootstraps overlay runtime and sends modal event wit
|
|||||||
assert.equal(payload, undefined);
|
assert.equal(payload, undefined);
|
||||||
assert.deepEqual(runtimeOptions, {
|
assert.deepEqual(runtimeOptions, {
|
||||||
restoreOnModalClose: 'playlist-browser',
|
restoreOnModalClose: 'playlist-browser',
|
||||||
preferModalWindow: true,
|
|
||||||
});
|
});
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
waitForModalOpen: async () => true,
|
|
||||||
logWarn: () => {},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
assert.equal(opened, true);
|
assert.equal(opened, true);
|
||||||
assert.deepEqual(calls, ['prereqs', 'windows', `send:${IPC_CHANNELS.event.playlistBrowserOpen}`]);
|
assert.deepEqual(calls, ['prereqs', 'windows', `send:${IPC_CHANNELS.event.playlistBrowserOpen}`]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('playlist browser open retries after first attempt timeout', async () => {
|
|
||||||
let attempt = 0;
|
|
||||||
const opened = await openPlaylistBrowser({
|
|
||||||
ensureOverlayStartupPrereqs: () => {},
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => {},
|
|
||||||
sendToActiveOverlayWindow: () => true,
|
|
||||||
waitForModalOpen: async () => {
|
|
||||||
attempt += 1;
|
|
||||||
return attempt >= 2;
|
|
||||||
},
|
|
||||||
logWarn: () => {},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(opened, true);
|
|
||||||
assert.equal(attempt, 2);
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
||||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
||||||
import { openOverlayHostedModal, retryOverlayModalOpen } from './overlay-hosted-modal-open';
|
|
||||||
|
|
||||||
const PLAYLIST_BROWSER_MODAL: OverlayHostedModal = 'playlist-browser';
|
const PLAYLIST_BROWSER_MODAL: OverlayHostedModal = 'playlist-browser';
|
||||||
const PLAYLIST_BROWSER_OPEN_TIMEOUT_MS = 1500;
|
|
||||||
|
|
||||||
export async function openPlaylistBrowser(deps: {
|
export function openPlaylistBrowser(deps: {
|
||||||
ensureOverlayStartupPrereqs: () => void;
|
ensureOverlayStartupPrereqs: () => void;
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
||||||
sendToActiveOverlayWindow: (
|
sendToActiveOverlayWindow: (
|
||||||
@@ -16,33 +14,10 @@ export async function openPlaylistBrowser(deps: {
|
|||||||
preferModalWindow?: boolean;
|
preferModalWindow?: boolean;
|
||||||
},
|
},
|
||||||
) => boolean;
|
) => boolean;
|
||||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
}): boolean {
|
||||||
logWarn: (message: string) => void;
|
deps.ensureOverlayStartupPrereqs();
|
||||||
}): Promise<boolean> {
|
deps.ensureOverlayWindowsReadyForVisibilityActions();
|
||||||
return await retryOverlayModalOpen(
|
return deps.sendToActiveOverlayWindow(IPC_CHANNELS.event.playlistBrowserOpen, undefined, {
|
||||||
{
|
restoreOnModalClose: PLAYLIST_BROWSER_MODAL,
|
||||||
waitForModalOpen: deps.waitForModalOpen,
|
});
|
||||||
logWarn: deps.logWarn,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
modal: PLAYLIST_BROWSER_MODAL,
|
|
||||||
timeoutMs: PLAYLIST_BROWSER_OPEN_TIMEOUT_MS,
|
|
||||||
retryWarning:
|
|
||||||
'Playlist browser modal did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
|
||||||
sendOpen: () =>
|
|
||||||
openOverlayHostedModal(
|
|
||||||
{
|
|
||||||
ensureOverlayStartupPrereqs: deps.ensureOverlayStartupPrereqs,
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions:
|
|
||||||
deps.ensureOverlayWindowsReadyForVisibilityActions,
|
|
||||||
sendToActiveOverlayWindow: deps.sendToActiveOverlayWindow,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
channel: IPC_CHANNELS.event.playlistBrowserOpen,
|
|
||||||
modal: PLAYLIST_BROWSER_MODAL,
|
|
||||||
preferModalWindow: true,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,99 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import test from 'node:test';
|
|
||||||
import { openRuntimeOptionsModal } from './runtime-options-open';
|
|
||||||
|
|
||||||
test('runtime options open prefers dedicated modal window on first attempt', async () => {
|
|
||||||
const calls: string[] = [];
|
|
||||||
|
|
||||||
const opened = await openRuntimeOptionsModal({
|
|
||||||
ensureOverlayStartupPrereqs: () => {
|
|
||||||
calls.push('ensure-startup');
|
|
||||||
},
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => {
|
|
||||||
calls.push('ensure-windows');
|
|
||||||
},
|
|
||||||
sendToActiveOverlayWindow: (channel, payload, options) => {
|
|
||||||
calls.push(`send:${channel}`);
|
|
||||||
assert.equal(payload, undefined);
|
|
||||||
assert.deepEqual(options, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
preferModalWindow: true,
|
|
||||||
});
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
waitForModalOpen: async (modal, timeoutMs) => {
|
|
||||||
assert.equal(modal, 'runtime-options');
|
|
||||||
assert.equal(timeoutMs, 1500);
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
logWarn: () => {
|
|
||||||
throw new Error('should not warn on first-attempt success');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(opened, true);
|
|
||||||
assert.deepEqual(calls, ['ensure-startup', 'ensure-windows', 'send:runtime-options:open']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('runtime options open retries after an open timeout', async () => {
|
|
||||||
const calls: string[] = [];
|
|
||||||
const warnings: string[] = [];
|
|
||||||
let waitCalls = 0;
|
|
||||||
|
|
||||||
const opened = await openRuntimeOptionsModal({
|
|
||||||
ensureOverlayStartupPrereqs: () => {
|
|
||||||
calls.push('ensure-startup');
|
|
||||||
},
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => {
|
|
||||||
calls.push('ensure-windows');
|
|
||||||
},
|
|
||||||
sendToActiveOverlayWindow: (channel, payload, options) => {
|
|
||||||
calls.push(`send:${channel}`);
|
|
||||||
assert.equal(payload, undefined);
|
|
||||||
assert.deepEqual(options, {
|
|
||||||
restoreOnModalClose: 'runtime-options',
|
|
||||||
preferModalWindow: true,
|
|
||||||
});
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
waitForModalOpen: async (modal, timeoutMs) => {
|
|
||||||
assert.equal(modal, 'runtime-options');
|
|
||||||
assert.equal(timeoutMs, 1500);
|
|
||||||
waitCalls += 1;
|
|
||||||
return waitCalls === 2;
|
|
||||||
},
|
|
||||||
logWarn: (message) => {
|
|
||||||
warnings.push(message);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(opened, true);
|
|
||||||
assert.deepEqual(calls, [
|
|
||||||
'ensure-startup',
|
|
||||||
'ensure-windows',
|
|
||||||
'send:runtime-options:open',
|
|
||||||
'ensure-startup',
|
|
||||||
'ensure-windows',
|
|
||||||
'send:runtime-options:open',
|
|
||||||
]);
|
|
||||||
assert.deepEqual(warnings, [
|
|
||||||
'Runtime options modal did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('runtime options open fails when no overlay window can be targeted', async () => {
|
|
||||||
let waitCalls = 0;
|
|
||||||
const opened = await openRuntimeOptionsModal({
|
|
||||||
ensureOverlayStartupPrereqs: () => {},
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => {},
|
|
||||||
sendToActiveOverlayWindow: () => false,
|
|
||||||
waitForModalOpen: async () => {
|
|
||||||
waitCalls += 1;
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
logWarn: () => {},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(opened, false);
|
|
||||||
assert.equal(waitCalls, 0);
|
|
||||||
});
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
|
||||||
import { openOverlayHostedModal, retryOverlayModalOpen } from './overlay-hosted-modal-open';
|
|
||||||
|
|
||||||
const RUNTIME_OPTIONS_MODAL: OverlayHostedModal = 'runtime-options';
|
|
||||||
const RUNTIME_OPTIONS_OPEN_TIMEOUT_MS = 1500;
|
|
||||||
|
|
||||||
export async function openRuntimeOptionsModal(deps: {
|
|
||||||
ensureOverlayStartupPrereqs: () => void;
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
|
||||||
sendToActiveOverlayWindow: (
|
|
||||||
channel: string,
|
|
||||||
payload?: unknown,
|
|
||||||
runtimeOptions?: {
|
|
||||||
restoreOnModalClose?: OverlayHostedModal;
|
|
||||||
preferModalWindow?: boolean;
|
|
||||||
},
|
|
||||||
) => boolean;
|
|
||||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
|
||||||
logWarn: (message: string) => void;
|
|
||||||
}): Promise<boolean> {
|
|
||||||
return await retryOverlayModalOpen(
|
|
||||||
{
|
|
||||||
waitForModalOpen: deps.waitForModalOpen,
|
|
||||||
logWarn: deps.logWarn,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
modal: RUNTIME_OPTIONS_MODAL,
|
|
||||||
timeoutMs: RUNTIME_OPTIONS_OPEN_TIMEOUT_MS,
|
|
||||||
retryWarning:
|
|
||||||
'Runtime options modal did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
|
||||||
sendOpen: () =>
|
|
||||||
openOverlayHostedModal(
|
|
||||||
{
|
|
||||||
ensureOverlayStartupPrereqs: deps.ensureOverlayStartupPrereqs,
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions:
|
|
||||||
deps.ensureOverlayWindowsReadyForVisibilityActions,
|
|
||||||
sendToActiveOverlayWindow: deps.sendToActiveOverlayWindow,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
channel: 'runtime-options:open',
|
|
||||||
modal: RUNTIME_OPTIONS_MODAL,
|
|
||||||
preferModalWindow: true,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import fs from 'node:fs';
|
|
||||||
import path from 'node:path';
|
|
||||||
import type { PluginSessionBindingsArtifact } from '../../types';
|
|
||||||
|
|
||||||
export function getSessionBindingsArtifactPath(configDir: string): string {
|
|
||||||
return path.join(configDir, 'session-bindings.json');
|
|
||||||
}
|
|
||||||
|
|
||||||
export function writeSessionBindingsArtifact(
|
|
||||||
configDir: string,
|
|
||||||
artifact: PluginSessionBindingsArtifact,
|
|
||||||
): string {
|
|
||||||
const artifactPath = getSessionBindingsArtifactPath(configDir);
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
fs.writeFileSync(artifactPath, `${JSON.stringify(artifact, null, 2)}\n`, 'utf8');
|
|
||||||
return artifactPath;
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
|
||||||
import { IPC_CHANNELS } from '../../shared/ipc/contracts';
|
|
||||||
import { openOverlayHostedModal, retryOverlayModalOpen } from './overlay-hosted-modal-open';
|
|
||||||
|
|
||||||
const SESSION_HELP_MODAL: OverlayHostedModal = 'session-help';
|
|
||||||
const SESSION_HELP_OPEN_TIMEOUT_MS = 1500;
|
|
||||||
|
|
||||||
export async function openSessionHelpModal(deps: {
|
|
||||||
ensureOverlayStartupPrereqs: () => void;
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions: () => void;
|
|
||||||
sendToActiveOverlayWindow: (
|
|
||||||
channel: string,
|
|
||||||
payload?: unknown,
|
|
||||||
runtimeOptions?: {
|
|
||||||
restoreOnModalClose?: OverlayHostedModal;
|
|
||||||
preferModalWindow?: boolean;
|
|
||||||
},
|
|
||||||
) => boolean;
|
|
||||||
waitForModalOpen: (modal: OverlayHostedModal, timeoutMs: number) => Promise<boolean>;
|
|
||||||
logWarn: (message: string) => void;
|
|
||||||
}): Promise<boolean> {
|
|
||||||
return await retryOverlayModalOpen(
|
|
||||||
{
|
|
||||||
waitForModalOpen: deps.waitForModalOpen,
|
|
||||||
logWarn: deps.logWarn,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
modal: SESSION_HELP_MODAL,
|
|
||||||
timeoutMs: SESSION_HELP_OPEN_TIMEOUT_MS,
|
|
||||||
retryWarning:
|
|
||||||
'Session help modal did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
|
||||||
sendOpen: () =>
|
|
||||||
openOverlayHostedModal(
|
|
||||||
{
|
|
||||||
ensureOverlayStartupPrereqs: deps.ensureOverlayStartupPrereqs,
|
|
||||||
ensureOverlayWindowsReadyForVisibilityActions:
|
|
||||||
deps.ensureOverlayWindowsReadyForVisibilityActions,
|
|
||||||
sendToActiveOverlayWindow: deps.sendToActiveOverlayWindow,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
channel: IPC_CHANNELS.event.sessionHelpOpen,
|
|
||||||
modal: SESSION_HELP_MODAL,
|
|
||||||
preferModalWindow: true,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import type { YoutubePickerOpenPayload } from '../../types';
|
import type { YoutubePickerOpenPayload } from '../../types';
|
||||||
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
import type { OverlayHostedModal } from '../../shared/ipc/contracts';
|
||||||
import { retryOverlayModalOpen } from './overlay-hosted-modal-open';
|
|
||||||
|
|
||||||
const YOUTUBE_PICKER_MODAL: OverlayHostedModal = 'youtube-track-picker';
|
const YOUTUBE_PICKER_MODAL: OverlayHostedModal = 'youtube-track-picker';
|
||||||
const YOUTUBE_PICKER_OPEN_TIMEOUT_MS = 1500;
|
const YOUTUBE_PICKER_OPEN_TIMEOUT_MS = 1500;
|
||||||
@@ -20,21 +19,24 @@ export async function openYoutubeTrackPicker(
|
|||||||
},
|
},
|
||||||
payload: YoutubePickerOpenPayload,
|
payload: YoutubePickerOpenPayload,
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
return await retryOverlayModalOpen(
|
const sendPickerOpen = (): boolean =>
|
||||||
{
|
|
||||||
waitForModalOpen: deps.waitForModalOpen,
|
|
||||||
logWarn: deps.logWarn,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
modal: YOUTUBE_PICKER_MODAL,
|
|
||||||
timeoutMs: YOUTUBE_PICKER_OPEN_TIMEOUT_MS,
|
|
||||||
retryWarning:
|
|
||||||
'YouTube subtitle picker did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
|
||||||
sendOpen: () =>
|
|
||||||
deps.sendToActiveOverlayWindow('youtube:picker-open', payload, {
|
deps.sendToActiveOverlayWindow('youtube:picker-open', payload, {
|
||||||
restoreOnModalClose: YOUTUBE_PICKER_MODAL,
|
restoreOnModalClose: YOUTUBE_PICKER_MODAL,
|
||||||
preferModalWindow: true,
|
preferModalWindow: true,
|
||||||
}),
|
});
|
||||||
},
|
|
||||||
);
|
if (!sendPickerOpen()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (await deps.waitForModalOpen(YOUTUBE_PICKER_MODAL, YOUTUBE_PICKER_OPEN_TIMEOUT_MS)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
deps.logWarn(
|
||||||
|
'YouTube subtitle picker did not acknowledge modal open on first attempt; retrying dedicated modal window.',
|
||||||
|
);
|
||||||
|
if (!sendPickerOpen()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return await deps.waitForModalOpen(YOUTUBE_PICKER_MODAL, YOUTUBE_PICKER_OPEN_TIMEOUT_MS);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import type { BrowserWindow, Extension, Session } from 'electron';
|
import type { BrowserWindow, Extension, Session } from 'electron';
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
CompiledSessionBinding,
|
|
||||||
Keybinding,
|
Keybinding,
|
||||||
MpvSubtitleRenderMetrics,
|
MpvSubtitleRenderMetrics,
|
||||||
SecondarySubMode,
|
SecondarySubMode,
|
||||||
@@ -171,7 +170,6 @@ export interface AppState {
|
|||||||
anilistClientSecretState: AnilistSecretResolutionState;
|
anilistClientSecretState: AnilistSecretResolutionState;
|
||||||
mecabTokenizer: MecabTokenizer | null;
|
mecabTokenizer: MecabTokenizer | null;
|
||||||
keybindings: Keybinding[];
|
keybindings: Keybinding[];
|
||||||
sessionBindings: CompiledSessionBinding[];
|
|
||||||
subtitleTimingTracker: SubtitleTimingTracker | null;
|
subtitleTimingTracker: SubtitleTimingTracker | null;
|
||||||
immersionTracker: ImmersionTrackerService | null;
|
immersionTracker: ImmersionTrackerService | null;
|
||||||
ankiIntegration: AnkiIntegration | null;
|
ankiIntegration: AnkiIntegration | null;
|
||||||
@@ -254,7 +252,6 @@ export function createAppState(values: AppStateInitialValues): AppState {
|
|||||||
anilistClientSecretState: createInitialAnilistSecretResolutionState(),
|
anilistClientSecretState: createInitialAnilistSecretResolutionState(),
|
||||||
mecabTokenizer: null,
|
mecabTokenizer: null,
|
||||||
keybindings: [],
|
keybindings: [],
|
||||||
sessionBindings: [],
|
|
||||||
subtitleTimingTracker: null,
|
subtitleTimingTracker: null,
|
||||||
immersionTracker: null,
|
immersionTracker: null,
|
||||||
ankiIntegration: null,
|
ankiIntegration: null,
|
||||||
|
|||||||
@@ -123,9 +123,6 @@ function createQueuedIpcListenerWithPayload<T>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const onOpenRuntimeOptionsEvent = createQueuedIpcListener(IPC_CHANNELS.event.runtimeOptionsOpen);
|
const onOpenRuntimeOptionsEvent = createQueuedIpcListener(IPC_CHANNELS.event.runtimeOptionsOpen);
|
||||||
const onOpenSessionHelpEvent = createQueuedIpcListener(IPC_CHANNELS.event.sessionHelpOpen);
|
|
||||||
const onOpenControllerSelectEvent = createQueuedIpcListener(IPC_CHANNELS.event.controllerSelectOpen);
|
|
||||||
const onOpenControllerDebugEvent = createQueuedIpcListener(IPC_CHANNELS.event.controllerDebugOpen);
|
|
||||||
const onOpenJimakuEvent = createQueuedIpcListener(IPC_CHANNELS.event.jimakuOpen);
|
const onOpenJimakuEvent = createQueuedIpcListener(IPC_CHANNELS.event.jimakuOpen);
|
||||||
const onOpenYoutubeTrackPickerEvent = createQueuedIpcListenerWithPayload<YoutubePickerOpenPayload>(
|
const onOpenYoutubeTrackPickerEvent = createQueuedIpcListenerWithPayload<YoutubePickerOpenPayload>(
|
||||||
IPC_CHANNELS.event.youtubePickerOpen,
|
IPC_CHANNELS.event.youtubePickerOpen,
|
||||||
@@ -145,9 +142,6 @@ const onSubsyncManualOpenEvent = createQueuedIpcListenerWithPayload<SubsyncManua
|
|||||||
IPC_CHANNELS.event.subsyncOpenManual,
|
IPC_CHANNELS.event.subsyncOpenManual,
|
||||||
(payload) => payload as SubsyncManualPayload,
|
(payload) => payload as SubsyncManualPayload,
|
||||||
);
|
);
|
||||||
const onSubtitleSidebarToggleEvent = createQueuedIpcListener(
|
|
||||||
IPC_CHANNELS.event.subtitleSidebarToggle,
|
|
||||||
);
|
|
||||||
const onKikuFieldGroupingRequestEvent =
|
const onKikuFieldGroupingRequestEvent =
|
||||||
createQueuedIpcListenerWithPayload<KikuFieldGroupingRequestData>(
|
createQueuedIpcListenerWithPayload<KikuFieldGroupingRequestData>(
|
||||||
IPC_CHANNELS.event.kikuFieldGroupingRequest,
|
IPC_CHANNELS.event.kikuFieldGroupingRequest,
|
||||||
@@ -229,11 +223,8 @@ const electronAPI: ElectronAPI = {
|
|||||||
|
|
||||||
getKeybindings: (): Promise<Keybinding[]> =>
|
getKeybindings: (): Promise<Keybinding[]> =>
|
||||||
ipcRenderer.invoke(IPC_CHANNELS.request.getKeybindings),
|
ipcRenderer.invoke(IPC_CHANNELS.request.getKeybindings),
|
||||||
getSessionBindings: () => ipcRenderer.invoke(IPC_CHANNELS.request.getSessionBindings),
|
|
||||||
getConfiguredShortcuts: (): Promise<Required<ShortcutsConfig>> =>
|
getConfiguredShortcuts: (): Promise<Required<ShortcutsConfig>> =>
|
||||||
ipcRenderer.invoke(IPC_CHANNELS.request.getConfigShortcuts),
|
ipcRenderer.invoke(IPC_CHANNELS.request.getConfigShortcuts),
|
||||||
dispatchSessionAction: (actionId, payload) =>
|
|
||||||
ipcRenderer.invoke(IPC_CHANNELS.command.dispatchSessionAction, { actionId, payload }),
|
|
||||||
getStatsToggleKey: (): Promise<string> =>
|
getStatsToggleKey: (): Promise<string> =>
|
||||||
ipcRenderer.invoke(IPC_CHANNELS.request.getStatsToggleKey),
|
ipcRenderer.invoke(IPC_CHANNELS.request.getStatsToggleKey),
|
||||||
getMarkWatchedKey: (): Promise<string> =>
|
getMarkWatchedKey: (): Promise<string> =>
|
||||||
@@ -332,13 +323,9 @@ const electronAPI: ElectronAPI = {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
onOpenRuntimeOptions: onOpenRuntimeOptionsEvent,
|
onOpenRuntimeOptions: onOpenRuntimeOptionsEvent,
|
||||||
onOpenSessionHelp: onOpenSessionHelpEvent,
|
|
||||||
onOpenControllerSelect: onOpenControllerSelectEvent,
|
|
||||||
onOpenControllerDebug: onOpenControllerDebugEvent,
|
|
||||||
onOpenJimaku: onOpenJimakuEvent,
|
onOpenJimaku: onOpenJimakuEvent,
|
||||||
onOpenYoutubeTrackPicker: onOpenYoutubeTrackPickerEvent,
|
onOpenYoutubeTrackPicker: onOpenYoutubeTrackPickerEvent,
|
||||||
onOpenPlaylistBrowser: onOpenPlaylistBrowserEvent,
|
onOpenPlaylistBrowser: onOpenPlaylistBrowserEvent,
|
||||||
onSubtitleSidebarToggle: onSubtitleSidebarToggleEvent,
|
|
||||||
onCancelYoutubeTrackPicker: onCancelYoutubeTrackPickerEvent,
|
onCancelYoutubeTrackPicker: onCancelYoutubeTrackPickerEvent,
|
||||||
onKeyboardModeToggleRequested: onKeyboardModeToggleRequestedEvent,
|
onKeyboardModeToggleRequested: onKeyboardModeToggleRequestedEvent,
|
||||||
onLookupWindowToggleRequested: onLookupWindowToggleRequestedEvent,
|
onLookupWindowToggleRequested: onLookupWindowToggleRequestedEvent,
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import test from 'node:test';
|
|||||||
|
|
||||||
import { createKeyboardHandlers } from './keyboard.js';
|
import { createKeyboardHandlers } from './keyboard.js';
|
||||||
import { createRendererState } from '../state.js';
|
import { createRendererState } from '../state.js';
|
||||||
import type { CompiledSessionBinding } from '../../types';
|
|
||||||
import { YOMITAN_POPUP_COMMAND_EVENT, YOMITAN_POPUP_HIDDEN_EVENT } from '../yomitan-popup.js';
|
import { YOMITAN_POPUP_COMMAND_EVENT, YOMITAN_POPUP_HIDDEN_EVENT } from '../yomitan-popup.js';
|
||||||
|
|
||||||
type CommandEventDetail = {
|
type CommandEventDetail = {
|
||||||
@@ -51,8 +50,6 @@ function installKeyboardTestGlobals() {
|
|||||||
const windowListeners = new Map<string, Array<(event: unknown) => void>>();
|
const windowListeners = new Map<string, Array<(event: unknown) => void>>();
|
||||||
const commandEvents: CommandEventDetail[] = [];
|
const commandEvents: CommandEventDetail[] = [];
|
||||||
const mpvCommands: Array<Array<string | number>> = [];
|
const mpvCommands: Array<Array<string | number>> = [];
|
||||||
const sessionActions: Array<{ actionId: string; payload?: unknown }> = [];
|
|
||||||
let sessionBindings: CompiledSessionBinding[] = [];
|
|
||||||
let playbackPausedResponse: boolean | null = false;
|
let playbackPausedResponse: boolean | null = false;
|
||||||
let statsToggleKey = 'Backquote';
|
let statsToggleKey = 'Backquote';
|
||||||
let markWatchedKey = 'KeyW';
|
let markWatchedKey = 'KeyW';
|
||||||
@@ -69,10 +66,6 @@ function installKeyboardTestGlobals() {
|
|||||||
markAudioCard: '',
|
markAudioCard: '',
|
||||||
openRuntimeOptions: 'CommandOrControl+Shift+O',
|
openRuntimeOptions: 'CommandOrControl+Shift+O',
|
||||||
openJimaku: 'Ctrl+Shift+J',
|
openJimaku: 'Ctrl+Shift+J',
|
||||||
openSessionHelp: 'CommandOrControl+Shift+H',
|
|
||||||
openControllerSelect: 'Alt+C',
|
|
||||||
openControllerDebug: 'Alt+Shift+C',
|
|
||||||
toggleSubtitleSidebar: '',
|
|
||||||
toggleVisibleOverlayGlobal: '',
|
toggleVisibleOverlayGlobal: '',
|
||||||
};
|
};
|
||||||
let markActiveVideoWatchedResult = true;
|
let markActiveVideoWatchedResult = true;
|
||||||
@@ -160,14 +153,10 @@ function installKeyboardTestGlobals() {
|
|||||||
},
|
},
|
||||||
electronAPI: {
|
electronAPI: {
|
||||||
getKeybindings: async () => [],
|
getKeybindings: async () => [],
|
||||||
getSessionBindings: async () => sessionBindings,
|
|
||||||
getConfiguredShortcuts: async () => configuredShortcuts,
|
getConfiguredShortcuts: async () => configuredShortcuts,
|
||||||
sendMpvCommand: (command: Array<string | number>) => {
|
sendMpvCommand: (command: Array<string | number>) => {
|
||||||
mpvCommands.push(command);
|
mpvCommands.push(command);
|
||||||
},
|
},
|
||||||
dispatchSessionAction: async (actionId: string, payload?: unknown) => {
|
|
||||||
sessionActions.push({ actionId, payload });
|
|
||||||
},
|
|
||||||
getPlaybackPaused: async () => playbackPausedResponse,
|
getPlaybackPaused: async () => playbackPausedResponse,
|
||||||
getStatsToggleKey: async () => statsToggleKey,
|
getStatsToggleKey: async () => statsToggleKey,
|
||||||
getMarkWatchedKey: async () => markWatchedKey,
|
getMarkWatchedKey: async () => markWatchedKey,
|
||||||
@@ -284,7 +273,6 @@ function installKeyboardTestGlobals() {
|
|||||||
return {
|
return {
|
||||||
commandEvents,
|
commandEvents,
|
||||||
mpvCommands,
|
mpvCommands,
|
||||||
sessionActions,
|
|
||||||
overlay,
|
overlay,
|
||||||
overlayFocusCalls,
|
overlayFocusCalls,
|
||||||
focusMainWindowCalls: () => focusMainWindowCalls,
|
focusMainWindowCalls: () => focusMainWindowCalls,
|
||||||
@@ -304,9 +292,6 @@ function installKeyboardTestGlobals() {
|
|||||||
setConfiguredShortcuts: (value: typeof configuredShortcuts) => {
|
setConfiguredShortcuts: (value: typeof configuredShortcuts) => {
|
||||||
configuredShortcuts = value;
|
configuredShortcuts = value;
|
||||||
},
|
},
|
||||||
setSessionBindings: (value: CompiledSessionBinding[]) => {
|
|
||||||
sessionBindings = value;
|
|
||||||
},
|
|
||||||
setMarkActiveVideoWatchedResult: (value: boolean) => {
|
setMarkActiveVideoWatchedResult: (value: boolean) => {
|
||||||
markActiveVideoWatchedResult = value;
|
markActiveVideoWatchedResult = value;
|
||||||
},
|
},
|
||||||
@@ -325,6 +310,8 @@ function installKeyboardTestGlobals() {
|
|||||||
function createKeyboardHandlerHarness() {
|
function createKeyboardHandlerHarness() {
|
||||||
const testGlobals = installKeyboardTestGlobals();
|
const testGlobals = installKeyboardTestGlobals();
|
||||||
const subtitleRootClassList = createClassList();
|
const subtitleRootClassList = createClassList();
|
||||||
|
let controllerSelectOpenCount = 0;
|
||||||
|
let controllerDebugOpenCount = 0;
|
||||||
let controllerSelectKeydownCount = 0;
|
let controllerSelectKeydownCount = 0;
|
||||||
let playlistBrowserKeydownCount = 0;
|
let playlistBrowserKeydownCount = 0;
|
||||||
|
|
||||||
@@ -375,12 +362,20 @@ function createKeyboardHandlerHarness() {
|
|||||||
openSessionHelpModal: () => {},
|
openSessionHelpModal: () => {},
|
||||||
appendClipboardVideoToQueue: () => {},
|
appendClipboardVideoToQueue: () => {},
|
||||||
getPlaybackPaused: () => testGlobals.getPlaybackPaused(),
|
getPlaybackPaused: () => testGlobals.getPlaybackPaused(),
|
||||||
|
openControllerSelectModal: () => {
|
||||||
|
controllerSelectOpenCount += 1;
|
||||||
|
},
|
||||||
|
openControllerDebugModal: () => {
|
||||||
|
controllerDebugOpenCount += 1;
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
ctx,
|
ctx,
|
||||||
handlers,
|
handlers,
|
||||||
testGlobals,
|
testGlobals,
|
||||||
|
controllerSelectOpenCount: () => controllerSelectOpenCount,
|
||||||
|
controllerDebugOpenCount: () => controllerDebugOpenCount,
|
||||||
controllerSelectKeydownCount: () => controllerSelectKeydownCount,
|
controllerSelectKeydownCount: () => controllerSelectKeydownCount,
|
||||||
playlistBrowserKeydownCount: () => playlistBrowserKeydownCount,
|
playlistBrowserKeydownCount: () => playlistBrowserKeydownCount,
|
||||||
setWordCount: (count: number) => {
|
setWordCount: (count: number) => {
|
||||||
@@ -526,19 +521,13 @@ test('popup-visible mpv keybindings still fire for bound keys', async () => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await handlers.setupMpvInputForwarding();
|
await handlers.setupMpvInputForwarding();
|
||||||
handlers.updateSessionBindings([
|
handlers.updateKeybindings([
|
||||||
{
|
{
|
||||||
sourcePath: 'keybindings[0].key',
|
key: 'Space',
|
||||||
originalKey: 'Space',
|
|
||||||
key: { code: 'Space', modifiers: [] },
|
|
||||||
actionType: 'mpv-command',
|
|
||||||
command: ['cycle', 'pause'],
|
command: ['cycle', 'pause'],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
sourcePath: 'keybindings[1].key',
|
key: 'KeyQ',
|
||||||
originalKey: 'KeyQ',
|
|
||||||
key: { code: 'KeyQ', modifiers: [] },
|
|
||||||
actionType: 'mpv-command',
|
|
||||||
command: ['quit'],
|
command: ['quit'],
|
||||||
},
|
},
|
||||||
] as never);
|
] as never);
|
||||||
@@ -560,12 +549,9 @@ test('paused configured subtitle-jump keybinding re-applies pause after backward
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await handlers.setupMpvInputForwarding();
|
await handlers.setupMpvInputForwarding();
|
||||||
handlers.updateSessionBindings([
|
handlers.updateKeybindings([
|
||||||
{
|
{
|
||||||
sourcePath: 'keybindings[0].key',
|
key: 'Shift+KeyH',
|
||||||
originalKey: 'Shift+KeyH',
|
|
||||||
key: { code: 'KeyH', modifiers: ['shift'] },
|
|
||||||
actionType: 'mpv-command',
|
|
||||||
command: ['sub-seek', -1],
|
command: ['sub-seek', -1],
|
||||||
},
|
},
|
||||||
] as never);
|
] as never);
|
||||||
@@ -588,12 +574,9 @@ test('configured subtitle-jump keybinding preserves pause when pause state is un
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await handlers.setupMpvInputForwarding();
|
await handlers.setupMpvInputForwarding();
|
||||||
handlers.updateSessionBindings([
|
handlers.updateKeybindings([
|
||||||
{
|
{
|
||||||
sourcePath: 'keybindings[0].key',
|
key: 'Shift+KeyH',
|
||||||
originalKey: 'Shift+KeyH',
|
|
||||||
key: { code: 'KeyH', modifiers: ['shift'] },
|
|
||||||
actionType: 'mpv-command',
|
|
||||||
command: ['sub-seek', -1],
|
command: ['sub-seek', -1],
|
||||||
},
|
},
|
||||||
] as never);
|
] as never);
|
||||||
@@ -653,78 +636,11 @@ test('keyboard mode: controller helpers dispatch popup audio play/cycle and scro
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('keyboard mode: configured controller debug binding dispatches session action', async () => {
|
test('keyboard mode: Alt+Shift+C opens controller debug modal', async () => {
|
||||||
const { testGlobals, handlers } = createKeyboardHandlerHarness();
|
const { testGlobals, handlers, controllerDebugOpenCount } = createKeyboardHandlerHarness();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await handlers.setupMpvInputForwarding();
|
await handlers.setupMpvInputForwarding();
|
||||||
handlers.updateSessionBindings([
|
|
||||||
{
|
|
||||||
sourcePath: 'shortcuts.openControllerDebug',
|
|
||||||
originalKey: 'Alt+Shift+D',
|
|
||||||
key: { code: 'KeyD', modifiers: ['alt', 'shift'] },
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: 'openControllerDebug',
|
|
||||||
},
|
|
||||||
] as never);
|
|
||||||
|
|
||||||
testGlobals.dispatchKeydown({
|
|
||||||
key: 'D',
|
|
||||||
code: 'KeyD',
|
|
||||||
altKey: true,
|
|
||||||
shiftKey: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(testGlobals.sessionActions, [{ actionId: 'openControllerDebug', payload: undefined }]);
|
|
||||||
} finally {
|
|
||||||
testGlobals.restore();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('keyboard mode: configured controller debug binding is not swallowed while popup is visible', async () => {
|
|
||||||
const { ctx, testGlobals, handlers } = createKeyboardHandlerHarness();
|
|
||||||
|
|
||||||
try {
|
|
||||||
await handlers.setupMpvInputForwarding();
|
|
||||||
ctx.state.yomitanPopupVisible = true;
|
|
||||||
testGlobals.setPopupVisible(true);
|
|
||||||
handlers.updateSessionBindings([
|
|
||||||
{
|
|
||||||
sourcePath: 'shortcuts.openControllerDebug',
|
|
||||||
originalKey: 'Alt+Shift+D',
|
|
||||||
key: { code: 'KeyD', modifiers: ['alt', 'shift'] },
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: 'openControllerDebug',
|
|
||||||
},
|
|
||||||
] as never);
|
|
||||||
|
|
||||||
testGlobals.dispatchKeydown({
|
|
||||||
key: 'D',
|
|
||||||
code: 'KeyD',
|
|
||||||
altKey: true,
|
|
||||||
shiftKey: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(testGlobals.sessionActions, [{ actionId: 'openControllerDebug', payload: undefined }]);
|
|
||||||
} finally {
|
|
||||||
testGlobals.restore();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('keyboard mode: former fixed Alt+Shift+C does nothing when controller debug is remapped', async () => {
|
|
||||||
const { testGlobals, handlers } = createKeyboardHandlerHarness();
|
|
||||||
|
|
||||||
try {
|
|
||||||
await handlers.setupMpvInputForwarding();
|
|
||||||
handlers.updateSessionBindings([
|
|
||||||
{
|
|
||||||
sourcePath: 'shortcuts.openControllerDebug',
|
|
||||||
originalKey: 'Alt+Shift+D',
|
|
||||||
key: { code: 'KeyD', modifiers: ['alt', 'shift'] },
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: 'openControllerDebug',
|
|
||||||
},
|
|
||||||
] as never);
|
|
||||||
|
|
||||||
testGlobals.dispatchKeydown({
|
testGlobals.dispatchKeydown({
|
||||||
key: 'C',
|
key: 'C',
|
||||||
@@ -733,7 +649,27 @@ test('keyboard mode: former fixed Alt+Shift+C does nothing when controller debug
|
|||||||
shiftKey: true,
|
shiftKey: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
assert.deepEqual(testGlobals.sessionActions, []);
|
assert.equal(controllerDebugOpenCount(), 1);
|
||||||
|
} finally {
|
||||||
|
testGlobals.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('keyboard mode: Alt+Shift+C opens controller debug modal even while popup is visible', async () => {
|
||||||
|
const { ctx, testGlobals, handlers, controllerDebugOpenCount } = createKeyboardHandlerHarness();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await handlers.setupMpvInputForwarding();
|
||||||
|
ctx.state.yomitanPopupVisible = true;
|
||||||
|
|
||||||
|
testGlobals.dispatchKeydown({
|
||||||
|
key: 'C',
|
||||||
|
code: 'KeyC',
|
||||||
|
altKey: true,
|
||||||
|
shiftKey: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(controllerDebugOpenCount(), 1);
|
||||||
} finally {
|
} finally {
|
||||||
testGlobals.restore();
|
testGlobals.restore();
|
||||||
}
|
}
|
||||||
@@ -827,19 +763,13 @@ test('youtube picker: unhandled keys still dispatch mpv keybindings', async () =
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await handlers.setupMpvInputForwarding();
|
await handlers.setupMpvInputForwarding();
|
||||||
handlers.updateSessionBindings([
|
handlers.updateKeybindings([
|
||||||
{
|
{
|
||||||
sourcePath: 'keybindings[0].key',
|
key: 'Space',
|
||||||
originalKey: 'Space',
|
|
||||||
key: { code: 'Space', modifiers: [] },
|
|
||||||
actionType: 'mpv-command',
|
|
||||||
command: ['cycle', 'pause'],
|
command: ['cycle', 'pause'],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
sourcePath: 'keybindings[1].key',
|
key: 'KeyQ',
|
||||||
originalKey: 'KeyQ',
|
|
||||||
key: { code: 'KeyQ', modifiers: [] },
|
|
||||||
actionType: 'mpv-command',
|
|
||||||
command: ['quit'],
|
command: ['quit'],
|
||||||
},
|
},
|
||||||
] as never);
|
] as never);
|
||||||
@@ -855,72 +785,46 @@ test('youtube picker: unhandled keys still dispatch mpv keybindings', async () =
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('session binding: Ctrl+Alt+S dispatches subsync action locally', async () => {
|
test('linux overlay shortcut: Ctrl+Alt+S dispatches subsync special command locally', async () => {
|
||||||
const { handlers, testGlobals } = createKeyboardHandlerHarness();
|
const { ctx, handlers, testGlobals } = createKeyboardHandlerHarness();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
ctx.platform.isLinuxPlatform = true;
|
||||||
await handlers.setupMpvInputForwarding();
|
await handlers.setupMpvInputForwarding();
|
||||||
handlers.updateSessionBindings([
|
|
||||||
{
|
|
||||||
sourcePath: 'shortcuts.triggerSubsync',
|
|
||||||
originalKey: 'Ctrl+Alt+S',
|
|
||||||
key: { code: 'KeyS', modifiers: ['ctrl', 'alt'] },
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: 'triggerSubsync',
|
|
||||||
},
|
|
||||||
] as never);
|
|
||||||
|
|
||||||
testGlobals.dispatchKeydown({ key: 's', code: 'KeyS', ctrlKey: true, altKey: true });
|
testGlobals.dispatchKeydown({ key: 's', code: 'KeyS', ctrlKey: true, altKey: true });
|
||||||
|
|
||||||
assert.deepEqual(testGlobals.sessionActions, [{ actionId: 'triggerSubsync', payload: undefined }]);
|
assert.deepEqual(testGlobals.mpvCommands, [['__subsync-trigger']]);
|
||||||
} finally {
|
} finally {
|
||||||
testGlobals.restore();
|
testGlobals.restore();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('session binding: Ctrl+Shift+J dispatches jimaku action locally', async () => {
|
test('linux overlay shortcut: Ctrl+Shift+J dispatches jimaku special command locally', async () => {
|
||||||
const { handlers, testGlobals } = createKeyboardHandlerHarness();
|
const { ctx, handlers, testGlobals } = createKeyboardHandlerHarness();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
ctx.platform.isLinuxPlatform = true;
|
||||||
await handlers.setupMpvInputForwarding();
|
await handlers.setupMpvInputForwarding();
|
||||||
handlers.updateSessionBindings([
|
|
||||||
{
|
|
||||||
sourcePath: 'shortcuts.openJimaku',
|
|
||||||
originalKey: 'Ctrl+Shift+J',
|
|
||||||
key: { code: 'KeyJ', modifiers: ['ctrl', 'shift'] },
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: 'openJimaku',
|
|
||||||
},
|
|
||||||
] as never);
|
|
||||||
|
|
||||||
testGlobals.dispatchKeydown({ key: 'J', code: 'KeyJ', ctrlKey: true, shiftKey: true });
|
testGlobals.dispatchKeydown({ key: 'J', code: 'KeyJ', ctrlKey: true, shiftKey: true });
|
||||||
|
|
||||||
assert.deepEqual(testGlobals.sessionActions, [{ actionId: 'openJimaku', payload: undefined }]);
|
assert.deepEqual(testGlobals.mpvCommands, [['__jimaku-open']]);
|
||||||
} finally {
|
} finally {
|
||||||
testGlobals.restore();
|
testGlobals.restore();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('session binding: Ctrl+Shift+O dispatches runtime options locally', async () => {
|
test('linux overlay shortcut: CommandOrControl+Shift+O dispatches runtime options locally', async () => {
|
||||||
const { handlers, testGlobals } = createKeyboardHandlerHarness();
|
const { ctx, handlers, testGlobals } = createKeyboardHandlerHarness();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
ctx.platform.isLinuxPlatform = true;
|
||||||
await handlers.setupMpvInputForwarding();
|
await handlers.setupMpvInputForwarding();
|
||||||
handlers.updateSessionBindings([
|
|
||||||
{
|
|
||||||
sourcePath: 'shortcuts.openRuntimeOptions',
|
|
||||||
originalKey: 'CommandOrControl+Shift+O',
|
|
||||||
key: { code: 'KeyO', modifiers: ['ctrl', 'shift'] },
|
|
||||||
actionType: 'session-action',
|
|
||||||
actionId: 'openRuntimeOptions',
|
|
||||||
},
|
|
||||||
] as never);
|
|
||||||
|
|
||||||
testGlobals.dispatchKeydown({ key: 'O', code: 'KeyO', ctrlKey: true, shiftKey: true });
|
testGlobals.dispatchKeydown({ key: 'O', code: 'KeyO', ctrlKey: true, shiftKey: true });
|
||||||
|
|
||||||
assert.deepEqual(testGlobals.sessionActions, [
|
assert.deepEqual(testGlobals.mpvCommands, [['__runtime-options-open']]);
|
||||||
{ actionId: 'openRuntimeOptions', payload: undefined },
|
|
||||||
]);
|
|
||||||
} finally {
|
} finally {
|
||||||
testGlobals.restore();
|
testGlobals.restore();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import type { CompiledSessionBinding, ShortcutsConfig } from '../../types';
|
import { SPECIAL_COMMANDS } from '../../config/definitions';
|
||||||
|
import type { Keybinding, ShortcutsConfig } from '../../types';
|
||||||
import type { RendererContext } from '../context';
|
import type { RendererContext } from '../context';
|
||||||
import {
|
import {
|
||||||
|
YOMITAN_POPUP_HOST_SELECTOR,
|
||||||
YOMITAN_POPUP_HIDDEN_EVENT,
|
YOMITAN_POPUP_HIDDEN_EVENT,
|
||||||
YOMITAN_POPUP_SHOWN_EVENT,
|
YOMITAN_POPUP_SHOWN_EVENT,
|
||||||
YOMITAN_POPUP_COMMAND_EVENT,
|
YOMITAN_POPUP_COMMAND_EVENT,
|
||||||
@@ -27,22 +29,19 @@ export function createKeyboardHandlers(
|
|||||||
}) => void;
|
}) => void;
|
||||||
appendClipboardVideoToQueue: () => void;
|
appendClipboardVideoToQueue: () => void;
|
||||||
getPlaybackPaused: () => Promise<boolean | null>;
|
getPlaybackPaused: () => Promise<boolean | null>;
|
||||||
|
openControllerSelectModal: () => void;
|
||||||
|
openControllerDebugModal: () => void;
|
||||||
toggleSubtitleSidebarModal?: () => void;
|
toggleSubtitleSidebarModal?: () => void;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
// Timeout for the modal chord capture window (e.g. Y followed by H/K).
|
// Timeout for the modal chord capture window (e.g. Y followed by H/K).
|
||||||
const CHORD_TIMEOUT_MS = 1000;
|
const CHORD_TIMEOUT_MS = 1000;
|
||||||
const KEYBOARD_SELECTED_WORD_CLASS = 'keyboard-selected';
|
const KEYBOARD_SELECTED_WORD_CLASS = 'keyboard-selected';
|
||||||
|
const linuxOverlayShortcutCommands = new Map<string, (string | number)[]>();
|
||||||
let pendingSelectionAnchorAfterSubtitleSeek: 'start' | 'end' | null = null;
|
let pendingSelectionAnchorAfterSubtitleSeek: 'start' | 'end' | null = null;
|
||||||
let pendingLookupRefreshAfterSubtitleSeek = false;
|
let pendingLookupRefreshAfterSubtitleSeek = false;
|
||||||
let resetSelectionToStartOnNextSubtitleSync = false;
|
let resetSelectionToStartOnNextSubtitleSync = false;
|
||||||
let lookupScanFallbackTimer: ReturnType<typeof setTimeout> | null = null;
|
let lookupScanFallbackTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
let pendingNumericSelection:
|
|
||||||
| {
|
|
||||||
actionId: 'copySubtitleMultiple' | 'mineSentenceMultiple';
|
|
||||||
timeout: ReturnType<typeof setTimeout> | null;
|
|
||||||
}
|
|
||||||
| null = null;
|
|
||||||
|
|
||||||
const CHORD_MAP = new Map<
|
const CHORD_MAP = new Map<
|
||||||
string,
|
string,
|
||||||
@@ -63,6 +62,9 @@ export function createKeyboardHandlers(
|
|||||||
if (target.closest('.modal')) return true;
|
if (target.closest('.modal')) return true;
|
||||||
if (ctx.dom.subtitleContainer.contains(target)) return true;
|
if (ctx.dom.subtitleContainer.contains(target)) return true;
|
||||||
if (isYomitanPopupIframe(target)) return true;
|
if (isYomitanPopupIframe(target)) return true;
|
||||||
|
if (target.closest && target.closest(YOMITAN_POPUP_HOST_SELECTOR)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
if (target.closest && target.closest('iframe.yomitan-popup, iframe[id^="yomitan-popup"]'))
|
if (target.closest && target.closest('iframe.yomitan-popup, iframe[id^="yomitan-popup"]'))
|
||||||
return true;
|
return true;
|
||||||
return false;
|
return false;
|
||||||
@@ -78,117 +80,115 @@ export function createKeyboardHandlers(
|
|||||||
return parts.join('+');
|
return parts.join('+');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function acceleratorToKeyToken(token: string): string | null {
|
||||||
|
const normalized = token.trim();
|
||||||
|
if (!normalized) return null;
|
||||||
|
if (/^[a-z]$/i.test(normalized)) {
|
||||||
|
return `Key${normalized.toUpperCase()}`;
|
||||||
|
}
|
||||||
|
if (/^[0-9]$/.test(normalized)) {
|
||||||
|
return `Digit${normalized}`;
|
||||||
|
}
|
||||||
|
const exactMap: Record<string, string> = {
|
||||||
|
space: 'Space',
|
||||||
|
tab: 'Tab',
|
||||||
|
enter: 'Enter',
|
||||||
|
return: 'Enter',
|
||||||
|
esc: 'Escape',
|
||||||
|
escape: 'Escape',
|
||||||
|
up: 'ArrowUp',
|
||||||
|
down: 'ArrowDown',
|
||||||
|
left: 'ArrowLeft',
|
||||||
|
right: 'ArrowRight',
|
||||||
|
backspace: 'Backspace',
|
||||||
|
delete: 'Delete',
|
||||||
|
slash: 'Slash',
|
||||||
|
backslash: 'Backslash',
|
||||||
|
minus: 'Minus',
|
||||||
|
plus: 'Equal',
|
||||||
|
equal: 'Equal',
|
||||||
|
comma: 'Comma',
|
||||||
|
period: 'Period',
|
||||||
|
quote: 'Quote',
|
||||||
|
semicolon: 'Semicolon',
|
||||||
|
bracketleft: 'BracketLeft',
|
||||||
|
bracketright: 'BracketRight',
|
||||||
|
backquote: 'Backquote',
|
||||||
|
};
|
||||||
|
const lower = normalized.toLowerCase();
|
||||||
|
if (exactMap[lower]) return exactMap[lower];
|
||||||
|
if (/^key[a-z]$/i.test(normalized) || /^digit[0-9]$/i.test(normalized)) {
|
||||||
|
return normalized[0]!.toUpperCase() + normalized.slice(1);
|
||||||
|
}
|
||||||
|
if (/^arrow(?:up|down|left|right)$/i.test(normalized)) {
|
||||||
|
return normalized[0]!.toUpperCase() + normalized.slice(1);
|
||||||
|
}
|
||||||
|
if (/^f\d{1,2}$/i.test(normalized)) {
|
||||||
|
return normalized.toUpperCase();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function acceleratorToKeyString(accelerator: string): string | null {
|
||||||
|
const normalized = accelerator.replace(/\s+/g, '').replace(/cmdorctrl/gi, 'CommandOrControl');
|
||||||
|
if (!normalized) return null;
|
||||||
|
const parts = normalized.split('+').filter(Boolean);
|
||||||
|
const keyToken = parts.pop();
|
||||||
|
if (!keyToken) return null;
|
||||||
|
|
||||||
|
const eventParts: string[] = [];
|
||||||
|
for (const modifier of parts) {
|
||||||
|
const lower = modifier.toLowerCase();
|
||||||
|
if (lower === 'ctrl' || lower === 'control') {
|
||||||
|
eventParts.push('Ctrl');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (lower === 'alt' || lower === 'option') {
|
||||||
|
eventParts.push('Alt');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (lower === 'shift') {
|
||||||
|
eventParts.push('Shift');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (lower === 'meta' || lower === 'super' || lower === 'command' || lower === 'cmd') {
|
||||||
|
eventParts.push('Meta');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (lower === 'commandorcontrol') {
|
||||||
|
eventParts.push(ctx.platform.isMacOSPlatform ? 'Meta' : 'Ctrl');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedKey = acceleratorToKeyToken(keyToken);
|
||||||
|
if (!normalizedKey) return null;
|
||||||
|
eventParts.push(normalizedKey);
|
||||||
|
return eventParts.join('+');
|
||||||
|
}
|
||||||
|
|
||||||
function updateConfiguredShortcuts(shortcuts: Required<ShortcutsConfig>): void {
|
function updateConfiguredShortcuts(shortcuts: Required<ShortcutsConfig>): void {
|
||||||
ctx.state.sessionActionTimeoutMs = shortcuts.multiCopyTimeoutMs;
|
linuxOverlayShortcutCommands.clear();
|
||||||
|
const bindings: Array<[string | null, (string | number)[]]> = [
|
||||||
|
[shortcuts.triggerSubsync, [SPECIAL_COMMANDS.SUBSYNC_TRIGGER]],
|
||||||
|
[shortcuts.openRuntimeOptions, [SPECIAL_COMMANDS.RUNTIME_OPTIONS_OPEN]],
|
||||||
|
[shortcuts.openJimaku, [SPECIAL_COMMANDS.JIMAKU_OPEN]],
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const [accelerator, command] of bindings) {
|
||||||
|
if (!accelerator) continue;
|
||||||
|
const keyString = acceleratorToKeyString(accelerator);
|
||||||
|
if (keyString) {
|
||||||
|
linuxOverlayShortcutCommands.set(keyString, command);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refreshConfiguredShortcuts(): Promise<void> {
|
async function refreshConfiguredShortcuts(): Promise<void> {
|
||||||
updateConfiguredShortcuts(await window.electronAPI.getConfiguredShortcuts());
|
updateConfiguredShortcuts(await window.electronAPI.getConfiguredShortcuts());
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateSessionBindings(bindings: CompiledSessionBinding[]): void {
|
|
||||||
ctx.state.sessionBindings = bindings;
|
|
||||||
ctx.state.sessionBindingMap = new Map(
|
|
||||||
bindings.map((binding) => [keyEventToStringFromBinding(binding), binding]),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function keyEventToStringFromBinding(binding: CompiledSessionBinding): string {
|
|
||||||
const parts: string[] = [];
|
|
||||||
for (const modifier of binding.key.modifiers) {
|
|
||||||
if (modifier === 'ctrl') parts.push('Ctrl');
|
|
||||||
else if (modifier === 'alt') parts.push('Alt');
|
|
||||||
else if (modifier === 'shift') parts.push('Shift');
|
|
||||||
else if (modifier === 'meta') parts.push('Meta');
|
|
||||||
}
|
|
||||||
parts.push(binding.key.code);
|
|
||||||
return parts.join('+');
|
|
||||||
}
|
|
||||||
|
|
||||||
function isTextEntryTarget(target: EventTarget | null): boolean {
|
|
||||||
if (!target || typeof target !== 'object' || !('closest' in target)) return false;
|
|
||||||
const element = target as { closest: (selector: string) => unknown };
|
|
||||||
if (element.closest('[contenteditable="true"]')) return true;
|
|
||||||
return Boolean(element.closest('input, textarea, select'));
|
|
||||||
}
|
|
||||||
|
|
||||||
function showSessionSelectionMessage(message: string): void {
|
|
||||||
window.electronAPI.sendMpvCommand(['show-text', message, '3000']);
|
|
||||||
}
|
|
||||||
|
|
||||||
function cancelPendingNumericSelection(showCancelled: boolean): void {
|
|
||||||
if (!pendingNumericSelection) return;
|
|
||||||
if (pendingNumericSelection.timeout !== null) {
|
|
||||||
clearTimeout(pendingNumericSelection.timeout);
|
|
||||||
}
|
|
||||||
pendingNumericSelection = null;
|
|
||||||
if (showCancelled) {
|
|
||||||
showSessionSelectionMessage('Cancelled');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function startPendingNumericSelection(
|
|
||||||
actionId: 'copySubtitleMultiple' | 'mineSentenceMultiple',
|
|
||||||
): void {
|
|
||||||
cancelPendingNumericSelection(false);
|
|
||||||
const timeoutMessage = actionId === 'copySubtitleMultiple' ? 'Copy timeout' : 'Mine timeout';
|
|
||||||
const promptMessage =
|
|
||||||
actionId === 'copySubtitleMultiple'
|
|
||||||
? 'Copy how many lines? Press 1-9 (Esc to cancel)'
|
|
||||||
: 'Mine how many lines? Press 1-9 (Esc to cancel)';
|
|
||||||
pendingNumericSelection = {
|
|
||||||
actionId,
|
|
||||||
timeout: setTimeout(() => {
|
|
||||||
pendingNumericSelection = null;
|
|
||||||
showSessionSelectionMessage(timeoutMessage);
|
|
||||||
}, ctx.state.sessionActionTimeoutMs),
|
|
||||||
};
|
|
||||||
showSessionSelectionMessage(promptMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
function beginSessionNumericSelection(
|
|
||||||
actionId: 'copySubtitleMultiple' | 'mineSentenceMultiple',
|
|
||||||
): void {
|
|
||||||
startPendingNumericSelection(actionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
function handlePendingNumericSelection(e: KeyboardEvent): boolean {
|
|
||||||
if (!pendingNumericSelection) return false;
|
|
||||||
if (e.key === 'Escape') {
|
|
||||||
e.preventDefault();
|
|
||||||
cancelPendingNumericSelection(true);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!/^[1-9]$/.test(e.key) || e.ctrlKey || e.metaKey || e.altKey) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
e.preventDefault();
|
|
||||||
const count = Number(e.key);
|
|
||||||
const actionId = pendingNumericSelection.actionId;
|
|
||||||
cancelPendingNumericSelection(false);
|
|
||||||
void window.electronAPI.dispatchSessionAction(actionId, { count });
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function dispatchSessionBinding(binding: CompiledSessionBinding): void {
|
|
||||||
if (
|
|
||||||
binding.actionType === 'session-action' &&
|
|
||||||
(binding.actionId === 'copySubtitleMultiple' || binding.actionId === 'mineSentenceMultiple')
|
|
||||||
) {
|
|
||||||
startPendingNumericSelection(binding.actionId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (binding.actionType === 'mpv-command') {
|
|
||||||
dispatchConfiguredMpvCommand(binding.command);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void window.electronAPI.dispatchSessionAction(binding.actionId, binding.payload);
|
|
||||||
}
|
|
||||||
|
|
||||||
function dispatchYomitanPopupKeydown(
|
function dispatchYomitanPopupKeydown(
|
||||||
key: string,
|
key: string,
|
||||||
code: string,
|
code: string,
|
||||||
@@ -296,6 +296,10 @@ export function createKeyboardHandlers(
|
|||||||
return isPrimaryModifierPressed(e) && !e.altKey && !e.shiftKey && isYKey && !e.repeat;
|
return isPrimaryModifierPressed(e) && !e.altKey && !e.shiftKey && isYKey && !e.repeat;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isControllerModalShortcut(e: KeyboardEvent): boolean {
|
||||||
|
return !e.ctrlKey && !e.metaKey && e.altKey && !e.repeat && e.code === 'KeyC';
|
||||||
|
}
|
||||||
|
|
||||||
function isSubtitleSidebarToggle(e: KeyboardEvent): boolean {
|
function isSubtitleSidebarToggle(e: KeyboardEvent): boolean {
|
||||||
const toggleKey = ctx.state.subtitleSidebarToggleKey;
|
const toggleKey = ctx.state.subtitleSidebarToggleKey;
|
||||||
if (!toggleKey) return false;
|
if (!toggleKey) return false;
|
||||||
@@ -508,7 +512,7 @@ export function createKeyboardHandlers(
|
|||||||
clientY: number,
|
clientY: number,
|
||||||
modifiers: ScanModifierState = {},
|
modifiers: ScanModifierState = {},
|
||||||
): void {
|
): void {
|
||||||
if (typeof PointerEvent === 'function') {
|
if (typeof PointerEvent !== 'undefined') {
|
||||||
const pointerEventInit = {
|
const pointerEventInit = {
|
||||||
bubbles: true,
|
bubbles: true,
|
||||||
cancelable: true,
|
cancelable: true,
|
||||||
@@ -531,7 +535,6 @@ export function createKeyboardHandlers(
|
|||||||
target.dispatchEvent(new PointerEvent('pointerup', pointerEventInit));
|
target.dispatchEvent(new PointerEvent('pointerup', pointerEventInit));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof MouseEvent === 'function') {
|
|
||||||
const mouseEventInit = {
|
const mouseEventInit = {
|
||||||
bubbles: true,
|
bubbles: true,
|
||||||
cancelable: true,
|
cancelable: true,
|
||||||
@@ -550,7 +553,6 @@ export function createKeyboardHandlers(
|
|||||||
target.dispatchEvent(new MouseEvent('mouseup', mouseEventInit));
|
target.dispatchEvent(new MouseEvent('mouseup', mouseEventInit));
|
||||||
target.dispatchEvent(new MouseEvent('click', mouseEventInit));
|
target.dispatchEvent(new MouseEvent('click', mouseEventInit));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
function emitLookupScanFallback(target: Element, clientX: number, clientY: number): void {
|
function emitLookupScanFallback(target: Element, clientX: number, clientY: number): void {
|
||||||
emitSyntheticScanEvents(target, clientX, clientY, {});
|
emitSyntheticScanEvents(target, clientX, clientY, {});
|
||||||
@@ -822,7 +824,7 @@ export function createKeyboardHandlers(
|
|||||||
if (modifierOnlyCodes.has(e.code)) return false;
|
if (modifierOnlyCodes.has(e.code)) return false;
|
||||||
|
|
||||||
const keyString = keyEventToString(e);
|
const keyString = keyEventToString(e);
|
||||||
if (ctx.state.sessionBindingMap.has(keyString)) {
|
if (ctx.state.keybindingsMap.has(keyString)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -848,7 +850,7 @@ export function createKeyboardHandlers(
|
|||||||
fallbackUnavailable: boolean;
|
fallbackUnavailable: boolean;
|
||||||
} {
|
} {
|
||||||
const firstChoice = 'KeyH';
|
const firstChoice = 'KeyH';
|
||||||
if (!ctx.state.sessionBindingMap.has('KeyH')) {
|
if (!ctx.state.keybindingsMap.has('KeyH')) {
|
||||||
return {
|
return {
|
||||||
bindingKey: firstChoice,
|
bindingKey: firstChoice,
|
||||||
fallbackUsed: false,
|
fallbackUsed: false,
|
||||||
@@ -856,18 +858,18 @@ export function createKeyboardHandlers(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ctx.state.sessionBindingMap.has('KeyK')) {
|
if (ctx.state.keybindingsMap.has('KeyK')) {
|
||||||
return {
|
return {
|
||||||
bindingKey: 'KeyK',
|
bindingKey: 'KeyK',
|
||||||
fallbackUsed: true,
|
fallbackUsed: true,
|
||||||
fallbackUnavailable: false,
|
fallbackUnavailable: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
bindingKey: 'KeyK',
|
bindingKey: 'KeyK',
|
||||||
fallbackUsed: true,
|
fallbackUsed: true,
|
||||||
fallbackUnavailable: true,
|
fallbackUnavailable: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -892,13 +894,13 @@ export function createKeyboardHandlers(
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function setupMpvInputForwarding(): Promise<void> {
|
async function setupMpvInputForwarding(): Promise<void> {
|
||||||
const [sessionBindings, shortcuts, statsToggleKey, markWatchedKey] = await Promise.all([
|
const [keybindings, shortcuts, statsToggleKey, markWatchedKey] = await Promise.all([
|
||||||
window.electronAPI.getSessionBindings(),
|
window.electronAPI.getKeybindings(),
|
||||||
window.electronAPI.getConfiguredShortcuts(),
|
window.electronAPI.getConfiguredShortcuts(),
|
||||||
window.electronAPI.getStatsToggleKey(),
|
window.electronAPI.getStatsToggleKey(),
|
||||||
window.electronAPI.getMarkWatchedKey(),
|
window.electronAPI.getMarkWatchedKey(),
|
||||||
]);
|
]);
|
||||||
updateSessionBindings(sessionBindings);
|
updateKeybindings(keybindings);
|
||||||
updateConfiguredShortcuts(shortcuts);
|
updateConfiguredShortcuts(shortcuts);
|
||||||
ctx.state.statsToggleKey = statsToggleKey;
|
ctx.state.statsToggleKey = statsToggleKey;
|
||||||
ctx.state.markWatchedKey = markWatchedKey;
|
ctx.state.markWatchedKey = markWatchedKey;
|
||||||
@@ -1008,14 +1010,6 @@ export function createKeyboardHandlers(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isTextEntryTarget(e.target)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (handlePendingNumericSelection(e)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isStatsOverlayToggle(e)) {
|
if (isStatsOverlayToggle(e)) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
window.electronAPI.toggleStatsOverlay();
|
window.electronAPI.toggleStatsOverlay();
|
||||||
@@ -1034,7 +1028,10 @@ export function createKeyboardHandlers(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ctx.state.yomitanPopupVisible || isYomitanPopupVisible(document)) {
|
if (
|
||||||
|
(ctx.state.yomitanPopupVisible || isYomitanPopupVisible(document)) &&
|
||||||
|
!isControllerModalShortcut(e)
|
||||||
|
) {
|
||||||
if (handleYomitanPopupKeybind(e)) {
|
if (handleYomitanPopupKeybind(e)) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
return;
|
return;
|
||||||
@@ -1091,11 +1088,30 @@ export function createKeyboardHandlers(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const keyString = keyEventToString(e);
|
if (isControllerModalShortcut(e)) {
|
||||||
const binding = ctx.state.sessionBindingMap.get(keyString);
|
|
||||||
if (binding) {
|
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
dispatchSessionBinding(binding);
|
if (e.shiftKey) {
|
||||||
|
options.openControllerDebugModal();
|
||||||
|
} else {
|
||||||
|
options.openControllerSelectModal();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const keyString = keyEventToString(e);
|
||||||
|
const linuxOverlayCommand = ctx.platform.isLinuxPlatform
|
||||||
|
? linuxOverlayShortcutCommands.get(keyString)
|
||||||
|
: undefined;
|
||||||
|
if (linuxOverlayCommand) {
|
||||||
|
e.preventDefault();
|
||||||
|
dispatchConfiguredMpvCommand(linuxOverlayCommand);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const command = ctx.state.keybindingsMap.get(keyString);
|
||||||
|
|
||||||
|
if (command) {
|
||||||
|
e.preventDefault();
|
||||||
|
dispatchConfiguredMpvCommand(command);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1113,11 +1129,19 @@ export function createKeyboardHandlers(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function updateKeybindings(keybindings: Keybinding[]): void {
|
||||||
|
ctx.state.keybindingsMap = new Map();
|
||||||
|
for (const binding of keybindings) {
|
||||||
|
if (binding.command) {
|
||||||
|
ctx.state.keybindingsMap.set(binding.key, binding.command);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
beginSessionNumericSelection,
|
|
||||||
setupMpvInputForwarding,
|
setupMpvInputForwarding,
|
||||||
refreshConfiguredShortcuts,
|
refreshConfiguredShortcuts,
|
||||||
updateSessionBindings,
|
updateKeybindings,
|
||||||
syncKeyboardTokenSelection,
|
syncKeyboardTokenSelection,
|
||||||
handleSubtitleContentUpdated,
|
handleSubtitleContentUpdated,
|
||||||
handleKeyboardModeToggleRequested,
|
handleKeyboardModeToggleRequested,
|
||||||
|
|||||||
@@ -1,215 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import test from 'node:test';
|
|
||||||
|
|
||||||
import type { ElectronAPI, RuntimeOptionState } from '../../types';
|
|
||||||
import { createRendererState } from '../state.js';
|
|
||||||
import { createRuntimeOptionsModal } from './runtime-options.js';
|
|
||||||
|
|
||||||
function createClassList(initialTokens: string[] = []) {
|
|
||||||
const tokens = new Set(initialTokens);
|
|
||||||
return {
|
|
||||||
add: (...entries: string[]) => {
|
|
||||||
for (const entry of entries) tokens.add(entry);
|
|
||||||
},
|
|
||||||
remove: (...entries: string[]) => {
|
|
||||||
for (const entry of entries) tokens.delete(entry);
|
|
||||||
},
|
|
||||||
toggle: (entry: string, force?: boolean) => {
|
|
||||||
if (force === undefined) {
|
|
||||||
if (tokens.has(entry)) {
|
|
||||||
tokens.delete(entry);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
tokens.add(entry);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (force) tokens.add(entry);
|
|
||||||
else tokens.delete(entry);
|
|
||||||
return force;
|
|
||||||
},
|
|
||||||
contains: (entry: string) => tokens.has(entry),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createElementStub() {
|
|
||||||
return {
|
|
||||||
className: '',
|
|
||||||
textContent: '',
|
|
||||||
title: '',
|
|
||||||
classList: createClassList(),
|
|
||||||
appendChild: () => {},
|
|
||||||
addEventListener: () => {},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createRuntimeOptionsListStub() {
|
|
||||||
return {
|
|
||||||
innerHTML: '',
|
|
||||||
appendChild: () => {},
|
|
||||||
querySelector: () => null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createDeferred<T>() {
|
|
||||||
let resolve!: (value: T) => void;
|
|
||||||
let reject!: (reason?: unknown) => void;
|
|
||||||
const promise = new Promise<T>((nextResolve, nextReject) => {
|
|
||||||
resolve = nextResolve;
|
|
||||||
reject = nextReject;
|
|
||||||
});
|
|
||||||
return { promise, resolve, reject };
|
|
||||||
}
|
|
||||||
|
|
||||||
function flushAsyncWork(): Promise<void> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
setTimeout(resolve, 0);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function withRuntimeOptionsModal(
|
|
||||||
getRuntimeOptions: () => Promise<RuntimeOptionState[]>,
|
|
||||||
run: (input: {
|
|
||||||
modal: ReturnType<typeof createRuntimeOptionsModal>;
|
|
||||||
state: ReturnType<typeof createRendererState>;
|
|
||||||
overlayClassList: ReturnType<typeof createClassList>;
|
|
||||||
modalClassList: ReturnType<typeof createClassList>;
|
|
||||||
statusNode: {
|
|
||||||
textContent: string;
|
|
||||||
classList: ReturnType<typeof createClassList>;
|
|
||||||
};
|
|
||||||
syncCalls: string[];
|
|
||||||
}) => Promise<void> | void,
|
|
||||||
): Promise<void> {
|
|
||||||
const globals = globalThis as typeof globalThis & { window?: unknown; document?: unknown };
|
|
||||||
const previousWindow = globals.window;
|
|
||||||
const previousDocument = globals.document;
|
|
||||||
|
|
||||||
const statusNode = {
|
|
||||||
textContent: '',
|
|
||||||
classList: createClassList(),
|
|
||||||
};
|
|
||||||
const overlayClassList = createClassList();
|
|
||||||
const modalClassList = createClassList(['hidden']);
|
|
||||||
const syncCalls: string[] = [];
|
|
||||||
const state = createRendererState();
|
|
||||||
|
|
||||||
Object.defineProperty(globalThis, 'window', {
|
|
||||||
configurable: true,
|
|
||||||
writable: true,
|
|
||||||
value: {
|
|
||||||
electronAPI: {
|
|
||||||
getRuntimeOptions,
|
|
||||||
setRuntimeOptionValue: async () => ({ ok: true }),
|
|
||||||
notifyOverlayModalClosed: () => {},
|
|
||||||
} satisfies Pick<
|
|
||||||
ElectronAPI,
|
|
||||||
'getRuntimeOptions' | 'setRuntimeOptionValue' | 'notifyOverlayModalClosed'
|
|
||||||
>,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
Object.defineProperty(globalThis, 'document', {
|
|
||||||
configurable: true,
|
|
||||||
writable: true,
|
|
||||||
value: {
|
|
||||||
createElement: () => createElementStub(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const modal = createRuntimeOptionsModal(
|
|
||||||
{
|
|
||||||
dom: {
|
|
||||||
overlay: { classList: overlayClassList },
|
|
||||||
runtimeOptionsModal: {
|
|
||||||
classList: modalClassList,
|
|
||||||
setAttribute: () => {},
|
|
||||||
},
|
|
||||||
runtimeOptionsClose: {
|
|
||||||
addEventListener: () => {},
|
|
||||||
},
|
|
||||||
runtimeOptionsList: createRuntimeOptionsListStub(),
|
|
||||||
runtimeOptionsStatus: statusNode,
|
|
||||||
},
|
|
||||||
state,
|
|
||||||
} as never,
|
|
||||||
{
|
|
||||||
modalStateReader: { isAnyModalOpen: () => false },
|
|
||||||
syncSettingsModalSubtitleSuppression: () => {
|
|
||||||
syncCalls.push('sync');
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
return Promise.resolve()
|
|
||||||
.then(() =>
|
|
||||||
run({
|
|
||||||
modal,
|
|
||||||
state,
|
|
||||||
overlayClassList,
|
|
||||||
modalClassList,
|
|
||||||
statusNode,
|
|
||||||
syncCalls,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.finally(() => {
|
|
||||||
Object.defineProperty(globalThis, 'window', {
|
|
||||||
configurable: true,
|
|
||||||
writable: true,
|
|
||||||
value: previousWindow,
|
|
||||||
});
|
|
||||||
Object.defineProperty(globalThis, 'document', {
|
|
||||||
configurable: true,
|
|
||||||
writable: true,
|
|
||||||
value: previousDocument,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
test('openRuntimeOptionsModal shows loading shell before runtime options resolve', async () => {
|
|
||||||
const deferred = createDeferred<RuntimeOptionState[]>();
|
|
||||||
|
|
||||||
await withRuntimeOptionsModal(() => deferred.promise, async (input) => {
|
|
||||||
input.modal.openRuntimeOptionsModal();
|
|
||||||
|
|
||||||
assert.equal(input.state.runtimeOptionsModalOpen, true);
|
|
||||||
assert.equal(input.overlayClassList.contains('interactive'), true);
|
|
||||||
assert.equal(input.modalClassList.contains('hidden'), false);
|
|
||||||
assert.equal(input.statusNode.textContent, 'Loading runtime options...');
|
|
||||||
assert.deepEqual(input.syncCalls, ['sync']);
|
|
||||||
|
|
||||||
deferred.resolve([
|
|
||||||
{
|
|
||||||
id: 'anki.autoUpdateNewCards',
|
|
||||||
label: 'Auto-update new cards',
|
|
||||||
scope: 'ankiConnect',
|
|
||||||
valueType: 'boolean',
|
|
||||||
value: true,
|
|
||||||
allowedValues: [true, false],
|
|
||||||
requiresRestart: false,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
await flushAsyncWork();
|
|
||||||
|
|
||||||
assert.equal(
|
|
||||||
input.statusNode.textContent,
|
|
||||||
'Use arrow keys. Click value to cycle. Enter or double-click to apply.',
|
|
||||||
);
|
|
||||||
assert.equal(input.statusNode.classList.contains('error'), false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('openRuntimeOptionsModal keeps modal visible when loading fails', async () => {
|
|
||||||
const deferred = createDeferred<RuntimeOptionState[]>();
|
|
||||||
|
|
||||||
await withRuntimeOptionsModal(() => deferred.promise, async (input) => {
|
|
||||||
input.modal.openRuntimeOptionsModal();
|
|
||||||
deferred.reject(new Error('boom'));
|
|
||||||
await flushAsyncWork();
|
|
||||||
|
|
||||||
assert.equal(input.state.runtimeOptionsModalOpen, true);
|
|
||||||
assert.equal(input.overlayClassList.contains('interactive'), true);
|
|
||||||
assert.equal(input.modalClassList.contains('hidden'), false);
|
|
||||||
assert.equal(input.statusNode.textContent, 'Failed to load runtime options');
|
|
||||||
assert.equal(input.statusNode.classList.contains('error'), true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -22,9 +22,6 @@ export function createRuntimeOptionsModal(
|
|||||||
syncSettingsModalSubtitleSuppression: () => void;
|
syncSettingsModalSubtitleSuppression: () => void;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const DEFAULT_STATUS_MESSAGE =
|
|
||||||
'Use arrow keys. Click value to cycle. Enter or double-click to apply.';
|
|
||||||
|
|
||||||
function formatRuntimeOptionValue(value: RuntimeOptionValue): string {
|
function formatRuntimeOptionValue(value: RuntimeOptionValue): string {
|
||||||
if (typeof value === 'boolean') {
|
if (typeof value === 'boolean') {
|
||||||
return value ? 'On' : 'Off';
|
return value ? 'On' : 'Off';
|
||||||
@@ -180,13 +177,10 @@ export function createRuntimeOptionsModal(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refreshRuntimeOptions(): Promise<void> {
|
async function openRuntimeOptionsModal(): Promise<void> {
|
||||||
const optionsList = await window.electronAPI.getRuntimeOptions();
|
const optionsList = await window.electronAPI.getRuntimeOptions();
|
||||||
updateRuntimeOptions(optionsList);
|
updateRuntimeOptions(optionsList);
|
||||||
setRuntimeOptionsStatus(DEFAULT_STATUS_MESSAGE);
|
|
||||||
}
|
|
||||||
|
|
||||||
function showRuntimeOptionsModalShell(): void {
|
|
||||||
ctx.state.runtimeOptionsModalOpen = true;
|
ctx.state.runtimeOptionsModalOpen = true;
|
||||||
options.syncSettingsModalSubtitleSuppression();
|
options.syncSettingsModalSubtitleSuppression();
|
||||||
|
|
||||||
@@ -194,19 +188,9 @@ export function createRuntimeOptionsModal(
|
|||||||
ctx.dom.runtimeOptionsModal.classList.remove('hidden');
|
ctx.dom.runtimeOptionsModal.classList.remove('hidden');
|
||||||
ctx.dom.runtimeOptionsModal.setAttribute('aria-hidden', 'false');
|
ctx.dom.runtimeOptionsModal.setAttribute('aria-hidden', 'false');
|
||||||
|
|
||||||
setRuntimeOptionsStatus('Loading runtime options...');
|
setRuntimeOptionsStatus(
|
||||||
}
|
'Use arrow keys. Click value to cycle. Enter or double-click to apply.',
|
||||||
|
);
|
||||||
function openRuntimeOptionsModal(): void {
|
|
||||||
if (!ctx.state.runtimeOptionsModalOpen) {
|
|
||||||
showRuntimeOptionsModalShell();
|
|
||||||
} else {
|
|
||||||
setRuntimeOptionsStatus('Refreshing runtime options...');
|
|
||||||
}
|
|
||||||
|
|
||||||
void refreshRuntimeOptions().catch(() => {
|
|
||||||
setRuntimeOptionsStatus('Failed to load runtime options', true);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleRuntimeOptionsKeydown(e: KeyboardEvent): boolean {
|
function handleRuntimeOptionsKeydown(e: KeyboardEvent): boolean {
|
||||||
|
|||||||
@@ -586,10 +586,31 @@ export function createSessionHelpModal(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function openSessionHelpModal(opening: SessionHelpBindingInfo): void {
|
async function openSessionHelpModal(opening: SessionHelpBindingInfo): Promise<void> {
|
||||||
openBinding = opening;
|
openBinding = opening;
|
||||||
priorFocus = document.activeElement;
|
priorFocus = document.activeElement;
|
||||||
|
|
||||||
|
const dataLoaded = await render();
|
||||||
|
|
||||||
|
ctx.dom.sessionHelpShortcut.textContent = `Session help opened with ${formatBindingHint(openBinding)}`;
|
||||||
|
if (openBinding.fallbackUnavailable) {
|
||||||
|
ctx.dom.sessionHelpWarning.textContent =
|
||||||
|
'Both Y-H and Y-K are bound; Y-K remains the fallback for this session.';
|
||||||
|
} else if (openBinding.fallbackUsed) {
|
||||||
|
ctx.dom.sessionHelpWarning.textContent = 'Y-H is already bound; using Y-K as fallback.';
|
||||||
|
} else {
|
||||||
|
ctx.dom.sessionHelpWarning.textContent = '';
|
||||||
|
}
|
||||||
|
if (dataLoaded) {
|
||||||
|
ctx.dom.sessionHelpStatus.textContent =
|
||||||
|
'Use Arrow keys, J/K/H/L, mouse, click, or / then type to filter. Esc closes.';
|
||||||
|
} else {
|
||||||
|
ctx.dom.sessionHelpStatus.textContent =
|
||||||
|
'Session help data is unavailable right now. Press Esc to close.';
|
||||||
|
ctx.dom.sessionHelpWarning.textContent =
|
||||||
|
'Unable to load latest shortcut settings from the runtime.';
|
||||||
|
}
|
||||||
|
|
||||||
ctx.state.sessionHelpModalOpen = true;
|
ctx.state.sessionHelpModalOpen = true;
|
||||||
options.syncSettingsModalSubtitleSuppression();
|
options.syncSettingsModalSubtitleSuppression();
|
||||||
ctx.dom.overlay.classList.add('interactive');
|
ctx.dom.overlay.classList.add('interactive');
|
||||||
@@ -602,17 +623,6 @@ export function createSessionHelpModal(
|
|||||||
window.electronAPI.setIgnoreMouseEvents(false);
|
window.electronAPI.setIgnoreMouseEvents(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.dom.sessionHelpShortcut.textContent = `Session help opened with ${formatBindingHint(openBinding)}`;
|
|
||||||
if (openBinding.fallbackUnavailable) {
|
|
||||||
ctx.dom.sessionHelpWarning.textContent =
|
|
||||||
'Both Y-H and Y-K are bound; Y-K remains the fallback for this session.';
|
|
||||||
} else if (openBinding.fallbackUsed) {
|
|
||||||
ctx.dom.sessionHelpWarning.textContent = 'Y-H is already bound; using Y-K as fallback.';
|
|
||||||
} else {
|
|
||||||
ctx.dom.sessionHelpWarning.textContent = '';
|
|
||||||
}
|
|
||||||
ctx.dom.sessionHelpStatus.textContent = 'Loading session help data...';
|
|
||||||
|
|
||||||
if (focusGuard === null) {
|
if (focusGuard === null) {
|
||||||
focusGuard = (event: FocusEvent) => {
|
focusGuard = (event: FocusEvent) => {
|
||||||
if (!ctx.state.sessionHelpModalOpen) return;
|
if (!ctx.state.sessionHelpModalOpen) return;
|
||||||
@@ -629,19 +639,6 @@ export function createSessionHelpModal(
|
|||||||
requestOverlayFocus();
|
requestOverlayFocus();
|
||||||
window.focus();
|
window.focus();
|
||||||
enforceModalFocus();
|
enforceModalFocus();
|
||||||
|
|
||||||
void render().then((dataLoaded) => {
|
|
||||||
if (!ctx.state.sessionHelpModalOpen) return;
|
|
||||||
if (dataLoaded) {
|
|
||||||
ctx.dom.sessionHelpStatus.textContent =
|
|
||||||
'Use Arrow keys, J/K/H/L, mouse, click, or / then type to filter. Esc closes.';
|
|
||||||
} else {
|
|
||||||
ctx.dom.sessionHelpStatus.textContent =
|
|
||||||
'Session help data is unavailable right now. Press Esc to close.';
|
|
||||||
ctx.dom.sessionHelpWarning.textContent =
|
|
||||||
'Unable to load latest shortcut settings from the runtime.';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeSessionHelpModal(): void {
|
function closeSessionHelpModal(): void {
|
||||||
@@ -651,7 +648,6 @@ export function createSessionHelpModal(
|
|||||||
options.syncSettingsModalSubtitleSuppression();
|
options.syncSettingsModalSubtitleSuppression();
|
||||||
ctx.dom.sessionHelpModal.classList.add('hidden');
|
ctx.dom.sessionHelpModal.classList.add('hidden');
|
||||||
ctx.dom.sessionHelpModal.setAttribute('aria-hidden', 'true');
|
ctx.dom.sessionHelpModal.setAttribute('aria-hidden', 'true');
|
||||||
window.electronAPI.notifyOverlayModalClosed('session-help');
|
|
||||||
if (!ctx.state.isOverSubtitle && !options.modalStateReader.isAnyModalOpen()) {
|
if (!ctx.state.isOverSubtitle && !options.modalStateReader.isAnyModalOpen()) {
|
||||||
ctx.dom.overlay.classList.remove('interactive');
|
ctx.dom.overlay.classList.remove('interactive');
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user