mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-22 16:46:10 -08:00
refactor(main): move plugins, session actions and subtitle generation into assemblies (#327)
* refactor(main): build overlay geometry and pointer interaction in the overlay assembly Inject Electron's screen (and the stats-window promotion) into the overlay geometry and visible-overlay interaction runtimes so they load under bun test, then construct both in createOverlayAssembly together with the overlay visibility composer and the mpv subtitle suppression handlers. Replace the three regex tests that pinned the moved Linux input and shape code with behaviour tests on the runtimes. * refactor(main): move the autoplay-ready gate into the playback assembly The autoplay-ready gate, its post-warm subtitle prime, the current-media tokenization gate and managed local subtitle selection all read playback state, and playback signals through the gate, so createPlaybackAssembly now builds them. The overlay reaches the gate through a getter. Replace the last four regex guards with behaviour tests: the gate holds the release until the visible overlay has measured the line and ignores untokenized lines during warmup (playback), cached autoplay priming never paints raw first and the sidebar media path is tagged only after prefetch loads (priming runtime), and dashboard mining overrides the Hachidori Anki server only when the proxy is on (stats server runtime). main-wiring.test.ts is now empty and removed. * refactor(main): move the plugin host, panel and windows into a plugins assembly * refactor(main): move session action dispatch and renderer mpv commands into an assembly createSessionActionsAssembly owns the session action dispatcher, the secondary-subtitle mode cycle, queueing the clipboard's video, and the mpv commands the overlay renderer sends. The runtime option cycle both paths used is now one function. * refactor(main): move Whisper subtitle generation into an assembly * refactor(main): resolve subtitle annotation options in a runtime module The runtime-option-over-config resolution that the texthooker page and the MeCab startup decision share moves out of main.ts into createAnnotationOptions. * test(main): cover a non-boolean runtime annotation option value * docs: describe the plugins, session actions and subtitle generation assemblies Update ownership for overlay geometry and pointer interaction, the autoplay-ready gate, and annotation options; point the overlay priming entry points at their new modules; the main-wiring regex debt is gone. * build: export MpvClientEvents so declaration emit can name the plugins assembly's return type
This commit is contained in:
1 parent
14ef7e823c
commit
f89f78b861
28 files changed
+2005
-1147
No files matched your search
@@ -0,0 +1,56 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { DEFAULT_CONFIG } from '../../config/definitions';
|
||||
import type { ResolvedConfig } from '../../types';
|
||||
import type { RuntimeOptionValue } from '../../types/runtime-options';
|
||||
import { createAnnotationOptions, type AnnotationRuntimeOptionId } from './annotation-options';
|
||||
|
||||
/** Every annotation off in config; `runtime` holds the options the user has cycled. */
|
||||
function setup(runtime: Partial<Record<AnnotationRuntimeOptionId, RuntimeOptionValue>> = {}) {
|
||||
const config: ResolvedConfig = {
|
||||
...DEFAULT_CONFIG,
|
||||
ankiConnect: {
|
||||
...DEFAULT_CONFIG.ankiConnect,
|
||||
knownWords: { ...DEFAULT_CONFIG.ankiConnect.knownWords, highlightEnabled: false },
|
||||
nPlusOne: { ...DEFAULT_CONFIG.ankiConnect.nPlusOne, enabled: false },
|
||||
},
|
||||
subtitleStyle: {
|
||||
...DEFAULT_CONFIG.subtitleStyle,
|
||||
enableJlpt: false,
|
||||
nameMatchEnabled: true,
|
||||
frequencyDictionary: { ...DEFAULT_CONFIG.subtitleStyle.frequencyDictionary, enabled: false },
|
||||
},
|
||||
};
|
||||
return createAnnotationOptions({
|
||||
getConfig: () => config,
|
||||
getRuntimeOptionValue: (id) => runtime[id],
|
||||
isCharacterDictionaryEnabled: () => false,
|
||||
});
|
||||
}
|
||||
|
||||
test('MeCab starts only when some annotation, from config or a runtime option, needs tokens', () => {
|
||||
assert.equal(setup().shouldInitializeMecabForAnnotations(), false);
|
||||
assert.equal(
|
||||
setup({ 'subtitle.annotation.jlpt': true }).shouldInitializeMecabForAnnotations(),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('a runtime option overrides config only when it holds a boolean', () => {
|
||||
const options = setup({ 'subtitle.annotation.nPlusOne': true, 'subtitle.annotation.jlpt': 'on' });
|
||||
|
||||
assert.equal(options.getRuntimeBooleanOption('subtitle.annotation.nPlusOne', false), true);
|
||||
assert.equal(options.getRuntimeBooleanOption('subtitle.annotation.jlpt', false), false);
|
||||
assert.equal(options.getRuntimeBooleanOption('subtitle.annotation.frequency', true), true);
|
||||
});
|
||||
|
||||
test('the texthooker colors names only while the character dictionary is enabled', () => {
|
||||
const settings = setup({
|
||||
'subtitle.annotation.knownWords.highlightEnabled': true,
|
||||
}).getTexthookerBootstrapSettings();
|
||||
|
||||
assert.equal(settings.enableKnownWordColoring, true);
|
||||
assert.equal(settings.enableNPlusOneColoring, false);
|
||||
assert.equal(settings.characterDictionaryEnabled, false);
|
||||
assert.equal(settings.enableNameMatchColoring, false);
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { TexthookerBootstrapSettings } from '../../core/services/texthooker';
|
||||
import type { ResolvedConfig } from '../../types';
|
||||
import type { RuntimeOptionId, RuntimeOptionValue } from '../../types/runtime-options';
|
||||
|
||||
/** The subtitle annotation toggles the user can flip at runtime from the options palette. */
|
||||
export type AnnotationRuntimeOptionId = Extract<
|
||||
RuntimeOptionId,
|
||||
| 'subtitle.annotation.knownWords.highlightEnabled'
|
||||
| 'subtitle.annotation.nPlusOne'
|
||||
| 'subtitle.annotation.jlpt'
|
||||
| 'subtitle.annotation.frequency'
|
||||
>;
|
||||
|
||||
export interface AnnotationOptionsDeps {
|
||||
getConfig: () => ResolvedConfig;
|
||||
/** The runtime option's current value; undefined before the options manager exists. */
|
||||
getRuntimeOptionValue: (id: AnnotationRuntimeOptionId) => RuntimeOptionValue | undefined;
|
||||
isCharacterDictionaryEnabled: () => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves which subtitle annotations are on. A runtime option the user cycled wins over its
|
||||
* config value; the texthooker page and the MeCab startup decision both read through here.
|
||||
*/
|
||||
export function createAnnotationOptions(deps: AnnotationOptionsDeps) {
|
||||
function getRuntimeBooleanOption(id: AnnotationRuntimeOptionId, fallback: boolean): boolean {
|
||||
const value = deps.getRuntimeOptionValue(id);
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
/** MeCab is only worth starting when at least one annotation needs tokens. */
|
||||
function shouldInitializeMecabForAnnotations(): boolean {
|
||||
const config = deps.getConfig();
|
||||
const knownWordsEnabled = getRuntimeBooleanOption(
|
||||
'subtitle.annotation.knownWords.highlightEnabled',
|
||||
config.ankiConnect.knownWords.highlightEnabled,
|
||||
);
|
||||
const nPlusOneEnabled = getRuntimeBooleanOption(
|
||||
'subtitle.annotation.nPlusOne',
|
||||
config.ankiConnect.nPlusOne.enabled,
|
||||
);
|
||||
const jlptEnabled = getRuntimeBooleanOption(
|
||||
'subtitle.annotation.jlpt',
|
||||
config.subtitleStyle.enableJlpt,
|
||||
);
|
||||
const frequencyEnabled = getRuntimeBooleanOption(
|
||||
'subtitle.annotation.frequency',
|
||||
config.subtitleStyle.frequencyDictionary.enabled,
|
||||
);
|
||||
return knownWordsEnabled || nPlusOneEnabled || jlptEnabled || frequencyEnabled;
|
||||
}
|
||||
|
||||
/** Annotation colors and toggles the texthooker page renders with. */
|
||||
function getTexthookerBootstrapSettings(): TexthookerBootstrapSettings {
|
||||
const config = deps.getConfig();
|
||||
const characterDictionaryEnabled =
|
||||
config.subtitleStyle.nameMatchEnabled && deps.isCharacterDictionaryEnabled();
|
||||
const knownWordColoringEnabled = getRuntimeBooleanOption(
|
||||
'subtitle.annotation.knownWords.highlightEnabled',
|
||||
config.ankiConnect.knownWords.highlightEnabled,
|
||||
);
|
||||
const nPlusOneColoringEnabled = getRuntimeBooleanOption(
|
||||
'subtitle.annotation.nPlusOne',
|
||||
config.ankiConnect.nPlusOne.enabled,
|
||||
);
|
||||
|
||||
return {
|
||||
enableKnownWordColoring: knownWordColoringEnabled,
|
||||
enableNPlusOneColoring: nPlusOneColoringEnabled,
|
||||
enableNameMatchColoring: config.subtitleStyle.nameMatchEnabled && characterDictionaryEnabled,
|
||||
enableFrequencyColoring: getRuntimeBooleanOption(
|
||||
'subtitle.annotation.frequency',
|
||||
config.subtitleStyle.frequencyDictionary.enabled,
|
||||
),
|
||||
enableJlptColoring: getRuntimeBooleanOption(
|
||||
'subtitle.annotation.jlpt',
|
||||
config.subtitleStyle.enableJlpt,
|
||||
),
|
||||
characterDictionaryEnabled,
|
||||
knownWordColor: config.subtitleStyle.knownWordColor,
|
||||
nPlusOneColor: config.subtitleStyle.nPlusOneColor,
|
||||
nameMatchColor: config.subtitleStyle.nameMatchColor,
|
||||
hoverTokenColor: config.subtitleStyle.hoverTokenColor,
|
||||
hoverTokenBackgroundColor: config.subtitleStyle.hoverTokenBackgroundColor,
|
||||
jlptColors: config.subtitleStyle.jlptColors,
|
||||
frequencyDictionary: {
|
||||
singleColor: config.subtitleStyle.frequencyDictionary.singleColor,
|
||||
bandedColors: config.subtitleStyle.frequencyDictionary.bandedColors,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
getRuntimeBooleanOption,
|
||||
shouldInitializeMecabForAnnotations,
|
||||
getTexthookerBootstrapSettings,
|
||||
};
|
||||
}
|
||||
@@ -465,3 +465,121 @@ test('prefetch stays paused until tokenization of an uncached line completes', a
|
||||
'prefetch:resume',
|
||||
]);
|
||||
});
|
||||
|
||||
/** Deps whose calls append to `calls`; tests override what they exercise. */
|
||||
function makeRecordingDeps(
|
||||
calls: string[],
|
||||
overrides: Partial<Parameters<typeof createAutoplaySubtitlePrimingRuntime>[0]> = {},
|
||||
): Parameters<typeof createAutoplaySubtitlePrimingRuntime>[0] {
|
||||
let currentSubText = '';
|
||||
return {
|
||||
getCurrentMediaPath: () => '/media/video.mkv',
|
||||
getMpvClient: () => null,
|
||||
setCurrentSubText: (text) => {
|
||||
currentSubText = text;
|
||||
calls.push(`set:${text}`);
|
||||
},
|
||||
getCurrentSubText: () => currentSubText,
|
||||
getCurrentSubtitleData: () => null,
|
||||
getActiveParsedSubtitleCues: () => [],
|
||||
setActiveParsedSubtitleMediaPath: (mediaPath) => calls.push(`tag:${mediaPath}`),
|
||||
subtitleProcessingController: {
|
||||
consumeCachedSubtitle: (text) => {
|
||||
calls.push(`consume:${text}`);
|
||||
return null;
|
||||
},
|
||||
onSubtitleChange: (text) => {
|
||||
calls.push(`change:${text}`);
|
||||
return true;
|
||||
},
|
||||
refreshCurrentSubtitle: (text) => {
|
||||
calls.push(`refresh:${text}`);
|
||||
return true;
|
||||
},
|
||||
notePlainSubtitleEmitted: () => {},
|
||||
},
|
||||
emitSubtitlePayload: (payload) =>
|
||||
calls.push(`emit:${payload.text}:${payload.tokens ? 'annotated' : 'raw'}`),
|
||||
getSubtitlePrefetchService: () => null,
|
||||
getLastObservedTimePos: () => 12,
|
||||
getVisibleOverlayVisible: () => true,
|
||||
emitSecondarySubtitle: () => {},
|
||||
initSubtitlePrefetch: async (sourcePath) => {
|
||||
calls.push(`init:${sourcePath}`);
|
||||
},
|
||||
refreshSubtitlePrefetchFromActiveTrack: async () => {},
|
||||
logDebug: () => {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test('a cached line primes with its annotated payload and never paints it raw first', async () => {
|
||||
const calls: string[] = [];
|
||||
const mediaPath = '/media/video.mkv';
|
||||
const cached: SubtitleData = { text: '起動字幕', tokens: [] };
|
||||
const runtime = createAutoplaySubtitlePrimingRuntime(
|
||||
makeRecordingDeps(calls, {
|
||||
getMpvClient: () => ({
|
||||
connected: true,
|
||||
currentVideoPath: mediaPath,
|
||||
requestProperty: async (name) => (name === 'sub-text' ? '起動字幕' : null),
|
||||
}),
|
||||
subtitleProcessingController: {
|
||||
consumeCachedSubtitle: (text) => {
|
||||
calls.push(`consume:${text}`);
|
||||
return cached;
|
||||
},
|
||||
onSubtitleChange: (text) => {
|
||||
calls.push(`change:${text}`);
|
||||
return false;
|
||||
},
|
||||
refreshCurrentSubtitle: () => true,
|
||||
notePlainSubtitleEmitted: () => {},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await runtime.primeCurrentSubtitleForAutoplay(mediaPath);
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
'set:起動字幕',
|
||||
// Consumed before the controller hears about the line, which would otherwise schedule
|
||||
// its own tokenization of it.
|
||||
'consume:起動字幕',
|
||||
'change:起動字幕',
|
||||
'emit:起動字幕:annotated',
|
||||
]);
|
||||
});
|
||||
|
||||
test('the subtitle sidebar tags its media path only once prefetch has loaded the source', async () => {
|
||||
const calls: string[] = [];
|
||||
const runtime = createAutoplaySubtitlePrimingRuntime(makeRecordingDeps(calls));
|
||||
|
||||
await runtime.refreshSubtitleSidebarFromSource('/subs/episode.srt', ' /media/other.mkv ');
|
||||
await runtime.refreshSubtitleSidebarFromSource('/subs/episode.srt');
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
'init:/subs/episode.srt',
|
||||
'tag:/media/other.mkv',
|
||||
'init:/subs/episode.srt',
|
||||
// Without an explicit media path the tag falls back to the current media.
|
||||
'tag:/media/video.mkv',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a failed subtitle sidebar prefetch leaves the media path untagged', async () => {
|
||||
const calls: string[] = [];
|
||||
const runtime = createAutoplaySubtitlePrimingRuntime(
|
||||
makeRecordingDeps(calls, {
|
||||
initSubtitlePrefetch: async () => {
|
||||
throw new Error('unreadable subtitle file');
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
runtime.refreshSubtitleSidebarFromSource('/subs/episode.srt', '/media/other.mkv'),
|
||||
/unreadable subtitle file/,
|
||||
);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test, { type TestContext } from 'node:test';
|
||||
import type { BrowserWindow, Display } from 'electron';
|
||||
import type { HyprlandPlacementStatus } from '../../core/services/hyprland-window-placement';
|
||||
import {
|
||||
createOverlayGeometryRuntime,
|
||||
type OverlayGeometryRuntimeDeps,
|
||||
} from './overlay-geometry-runtime';
|
||||
|
||||
const NO_PLACEMENT: HyprlandPlacementStatus = {
|
||||
applicable: false,
|
||||
clientFound: false,
|
||||
dispatched: false,
|
||||
};
|
||||
const DISPLAY = { bounds: { x: 0, y: 0, width: 1920, height: 1080 } } as Display;
|
||||
|
||||
/** Builds the runtime with `process.platform` set and a visible overlay window that logs calls. */
|
||||
function setup(t: TestContext, platform: NodeJS.Platform) {
|
||||
const originalPlatform = process.platform;
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
t.after(() => Object.defineProperty(process, 'platform', { value: originalPlatform }));
|
||||
|
||||
const windowCalls: string[] = [];
|
||||
const record =
|
||||
(name: string) =>
|
||||
(..._args: unknown[]) => {
|
||||
windowCalls.push(name);
|
||||
};
|
||||
const mainWindow = {
|
||||
isDestroyed: () => false,
|
||||
getTitle: () => 'SubMiner Overlay',
|
||||
getBounds: () => ({ x: 0, y: 0, width: 1280, height: 720 }),
|
||||
setShape: record('setShape'),
|
||||
setAlwaysOnTop: record('setAlwaysOnTop'),
|
||||
setVisibleOnAllWorkspaces: record('setVisibleOnAllWorkspaces'),
|
||||
setFullScreenable: record('setFullScreenable'),
|
||||
moveTop: record('moveTop'),
|
||||
} as unknown as BrowserWindow;
|
||||
const noop = () => {};
|
||||
const deps: OverlayGeometryRuntimeDeps = {
|
||||
screen: {
|
||||
getCursorScreenPoint: () => ({ x: 0, y: 0 }),
|
||||
getDisplayNearestPoint: () => DISPLAY,
|
||||
getDisplayMatching: () => DISPLAY,
|
||||
},
|
||||
promoteStatsOverlayAbovePlayback: noop,
|
||||
overlayManager: {
|
||||
getMainWindow: () => mainWindow,
|
||||
getModalWindow: () => null,
|
||||
getVisibleOverlayVisible: () => true,
|
||||
setOverlayWindowBounds: () => NO_PLACEMENT,
|
||||
setModalWindowBounds: () => NO_PLACEMENT,
|
||||
},
|
||||
getTrackedWindowGeometry: () => null,
|
||||
getTrackedWindowMediaSourceId: () => null,
|
||||
getTrackedWindowNativeId: () => null,
|
||||
getStatsOverlayVisible: () => false,
|
||||
getOverlayForegroundSeparateWindows: () => [],
|
||||
getLinuxVisibleOverlayWindowMode: () => 'managed',
|
||||
getLinuxTrackedMpvFullscreen: () => false,
|
||||
getLinuxTrackedMpvFullscreenChangedAtMs: () => 0,
|
||||
syncLinuxVisibleOverlayMpvFullscreenMode: noop,
|
||||
getLinuxVisibleOverlayOwnerBindingKey: () => null,
|
||||
setLinuxVisibleOverlayOwnerBindingKey: noop,
|
||||
clearVisibleOverlayX11OwnerBinding: noop,
|
||||
getNativeWindowHandleDecimal: () => '0',
|
||||
enqueueVisibleOverlayX11OwnerBindingOperation: noop,
|
||||
scheduleWindowsVisibleOverlayZOrderSyncBurst: noop,
|
||||
logDebug: noop,
|
||||
};
|
||||
return { geometry: createOverlayGeometryRuntime(deps), windowCalls };
|
||||
}
|
||||
|
||||
// New mpv bounds can leave the X11 input shape sized for the old window; restore it to the full
|
||||
// window before re-asserting the overlay's level so the whole overlay stays clickable.
|
||||
test('a Linux bounds update restores the overlay window shape before raising it', (t) => {
|
||||
const { geometry, windowCalls } = setup(t, 'linux');
|
||||
|
||||
geometry.updateVisibleOverlayBounds({ x: 10, y: 20, width: 1280, height: 720 });
|
||||
|
||||
const shapeIndex = windowCalls.indexOf('setShape');
|
||||
assert.ok(shapeIndex >= 0, 'window shape was not restored');
|
||||
assert.ok(shapeIndex < windowCalls.indexOf('setAlwaysOnTop'));
|
||||
});
|
||||
|
||||
test('a macOS bounds update raises the overlay without touching the window shape', (t) => {
|
||||
const { geometry, windowCalls } = setup(t, 'darwin');
|
||||
|
||||
geometry.updateVisibleOverlayBounds({ x: 10, y: 20, width: 1280, height: 720 });
|
||||
|
||||
assert.ok(windowCalls.includes('setAlwaysOnTop'));
|
||||
assert.ok(!windowCalls.includes('setShape'));
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type BrowserWindow, screen } from 'electron';
|
||||
import type { BrowserWindow, Screen } from 'electron';
|
||||
import type { WindowGeometry } from '../../types';
|
||||
import { hasHyprlandWindowPlacementBoundsMismatch } from '../../core/services/hyprland-window-placement';
|
||||
import { normalizeOverlayWindowBoundsForPlatform } from '../../core/services/overlay-window-bounds';
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
ensureOverlayWindowLevel as ensureOverlayWindowLevelCore,
|
||||
syncOverlayWindowLayer,
|
||||
} from '../../core/services/overlay-window';
|
||||
import { promoteStatsOverlayAbovePlayback } from '../../core/services/stats-window.js';
|
||||
import { restoreLinuxOverlayWindowShape } from './linux-overlay-window-shape';
|
||||
import { shouldRunLinuxOverlayZOrderKeepAlive } from './linux-overlay-zorder-keepalive';
|
||||
import {
|
||||
@@ -25,6 +24,9 @@ import { shouldSuppressVisibleOverlayRaiseForSeparateWindow } from './settings-w
|
||||
const LINUX_VISIBLE_OVERLAY_FULLSCREEN_GEOMETRY_GRACE_MS = 1_200;
|
||||
|
||||
export interface OverlayGeometryRuntimeDeps {
|
||||
/** Injected so this module loads without Electron (and under `bun test`). */
|
||||
screen: Pick<Screen, 'getCursorScreenPoint' | 'getDisplayNearestPoint' | 'getDisplayMatching'>;
|
||||
promoteStatsOverlayAbovePlayback: () => void;
|
||||
overlayManager: {
|
||||
getMainWindow: () => BrowserWindow | null;
|
||||
getModalWindow: () => BrowserWindow | null;
|
||||
@@ -60,8 +62,8 @@ export function createOverlayGeometryRuntime(deps: OverlayGeometryRuntimeDeps) {
|
||||
let lastOverlayWindowGeometry: WindowGeometry | null = null;
|
||||
|
||||
function getOverlayGeometryFallback(): WindowGeometry {
|
||||
const cursorPoint = screen.getCursorScreenPoint();
|
||||
const display = screen.getDisplayNearestPoint(cursorPoint);
|
||||
const cursorPoint = deps.screen.getCursorScreenPoint();
|
||||
const display = deps.screen.getDisplayNearestPoint(cursorPoint);
|
||||
const bounds = display.workArea;
|
||||
return {
|
||||
x: bounds.x,
|
||||
@@ -106,7 +108,7 @@ export function createOverlayGeometryRuntime(deps: OverlayGeometryRuntimeDeps) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const displayBounds = screen.getDisplayMatching(geometry).bounds;
|
||||
const displayBounds = deps.screen.getDisplayMatching(geometry).bounds;
|
||||
return shouldExitFullscreenOverrideForTrackedGeometry({
|
||||
currentMode: deps.getLinuxVisibleOverlayWindowMode(),
|
||||
trackedFullscreen: deps.getLinuxTrackedMpvFullscreen(),
|
||||
@@ -137,7 +139,8 @@ export function createOverlayGeometryRuntime(deps: OverlayGeometryRuntimeDeps) {
|
||||
}
|
||||
return hasHyprlandWindowPlacementBoundsMismatch({
|
||||
title: window.getTitle(),
|
||||
bounds: normalizeOverlayWindowBoundsForPlatform(geometry, process.platform, screen, window),
|
||||
// Linux bounds come from the window's content insets; the DIP converter is Windows-only.
|
||||
bounds: normalizeOverlayWindowBoundsForPlatform(geometry, process.platform, null, window),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -190,7 +193,7 @@ export function createOverlayGeometryRuntime(deps: OverlayGeometryRuntimeDeps) {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
moveVisibleOverlayAboveTrackedPlaybackWindow(mainWindow);
|
||||
}
|
||||
promoteStatsOverlayAbovePlayback();
|
||||
deps.promoteStatsOverlayAbovePlayback();
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -73,7 +73,10 @@ function createRuntimeHarness(
|
||||
return { runtime, appStateValues };
|
||||
}
|
||||
|
||||
test('dashboard word mining keeps the configured proxy as Hachidori Anki endpoint', async () => {
|
||||
/** Mines a word from the stats dashboard; returns the Anki settings sent to Hachidori. */
|
||||
async function mineDashboardWord(
|
||||
ankiConnect: Partial<(typeof DEFAULT_CONFIG)['ankiConnect']>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const settings: unknown[] = [];
|
||||
const context = vm.createContext({
|
||||
chrome: {},
|
||||
@@ -95,25 +98,40 @@ test('dashboard word mining keeps the configured proxy as Hachidori Anki endpoin
|
||||
...createDeps(async (script) => structuredClone(await vm.runInContext(script, context))),
|
||||
getResolvedConfig: () => ({
|
||||
...DEFAULT_CONFIG,
|
||||
ankiConnect: {
|
||||
...DEFAULT_CONFIG.ankiConnect,
|
||||
enabled: true,
|
||||
url: 'http://127.0.0.1:8765',
|
||||
proxy: {
|
||||
...DEFAULT_CONFIG.ankiConnect.proxy,
|
||||
enabled: true,
|
||||
host: '127.0.0.1',
|
||||
port: 8766,
|
||||
},
|
||||
},
|
||||
ankiConnect: { ...DEFAULT_CONFIG.ankiConnect, ...ankiConnect },
|
||||
}),
|
||||
},
|
||||
);
|
||||
await runtime.ensureStatsServerStarted();
|
||||
assert.equal(await configs[0]?.addYomitanNote?.('入れる'), 123);
|
||||
assert.ok(settings[0] && typeof settings[0] === 'object' && 'server' in settings[0]);
|
||||
assert.equal(settings[0].server, 'http://127.0.0.1:8766');
|
||||
await runtime.stopStatsServer();
|
||||
const sent = settings[0];
|
||||
assert.ok(sent && typeof sent === 'object');
|
||||
return sent as Record<string, unknown>;
|
||||
}
|
||||
|
||||
test('dashboard word mining keeps the configured proxy as Hachidori Anki endpoint', async () => {
|
||||
const sent = await mineDashboardWord({
|
||||
enabled: true,
|
||||
url: 'http://127.0.0.1:8765',
|
||||
proxy: { ...DEFAULT_CONFIG.ankiConnect.proxy, enabled: true, host: '127.0.0.1', port: 8766 },
|
||||
});
|
||||
|
||||
assert.equal(sent.server, 'http://127.0.0.1:8766');
|
||||
assert.equal(sent.forceOverride, true);
|
||||
});
|
||||
|
||||
// Without the proxy SubMiner does not own the endpoint, so a server the user set in
|
||||
// Yomitan/Hachidori must survive dashboard mining.
|
||||
test('dashboard word mining without the proxy does not override the Hachidori Anki server', async () => {
|
||||
const sent = await mineDashboardWord({
|
||||
enabled: true,
|
||||
url: 'http://127.0.0.1:8765',
|
||||
proxy: { ...DEFAULT_CONFIG.ankiConnect.proxy, enabled: false },
|
||||
});
|
||||
|
||||
assert.equal(sent.server, 'http://127.0.0.1:8765');
|
||||
assert.equal(sent.forceOverride, false);
|
||||
});
|
||||
|
||||
test('stopBackgroundStatsServer clears stale state when daemon identity mismatches', async () => {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test, { type TestContext } from 'node:test';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import { stopLinuxOverlayPointerInteractionLoop } from './linux-overlay-pointer-interaction';
|
||||
import { stopLinuxOverlayZOrderKeepAliveLoop } from './linux-overlay-zorder-keepalive';
|
||||
import {
|
||||
createVisibleOverlayInteractionRuntime,
|
||||
type VisibleOverlayInteractionRuntimeDeps,
|
||||
} from './visible-overlay-interaction-runtime';
|
||||
|
||||
type MouseEventsCall = { ignore: boolean; options?: { forward?: boolean } };
|
||||
|
||||
/** Builds the runtime with `process.platform` set, a visible overlay and a fake main window. */
|
||||
function setup(t: TestContext, platform: NodeJS.Platform) {
|
||||
const originalPlatform = process.platform;
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
t.after(() => {
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform });
|
||||
// Construction on Linux starts the shared pointer poll and z-order keep-alive loops.
|
||||
stopLinuxOverlayPointerInteractionLoop();
|
||||
stopLinuxOverlayZOrderKeepAliveLoop();
|
||||
});
|
||||
|
||||
const mouseEvents: MouseEventsCall[] = [];
|
||||
const clearedLayers: string[] = [];
|
||||
const mainWindow = {
|
||||
isDestroyed: () => false,
|
||||
isVisible: () => true,
|
||||
isFocused: () => true,
|
||||
getBounds: () => ({ x: 0, y: 0, width: 1920, height: 1080 }),
|
||||
setShape: () => {},
|
||||
setIgnoreMouseEvents: (ignore: boolean, options?: { forward?: boolean }) => {
|
||||
mouseEvents.push({ ignore, options });
|
||||
},
|
||||
} as unknown as BrowserWindow;
|
||||
const noop = () => {};
|
||||
const deps: VisibleOverlayInteractionRuntimeDeps = {
|
||||
screen: {
|
||||
getCursorScreenPoint: () => ({ x: 5, y: 5 }),
|
||||
screenToDipPoint: (point) => point,
|
||||
},
|
||||
overlayManager: {
|
||||
getMainWindow: () => mainWindow,
|
||||
getVisibleOverlayVisible: () => true,
|
||||
},
|
||||
overlayContentMeasurementStore: {
|
||||
clear: (layer) => {
|
||||
clearedLayers.push(layer);
|
||||
},
|
||||
getLatestByLayer: () => null,
|
||||
},
|
||||
logger: { info: noop, warn: noop, debug: noop },
|
||||
updateVisibleOverlayVisibility: noop,
|
||||
getModalInputExclusive: () => false,
|
||||
getStatsOverlayVisible: () => false,
|
||||
setStatsOverlayVisible: noop,
|
||||
getWindowTracker: () => null,
|
||||
setWindowTracker: noop,
|
||||
setTrackerNotReadyWarningShown: noop,
|
||||
getMpvSocketPath: () => '/tmp/subminer-interaction-test.sock',
|
||||
getBackendOverride: () => null,
|
||||
getInitialArgs: () => null,
|
||||
getOverlayRuntimeInitialized: () => true,
|
||||
getLinuxVisibleOverlayWindowMode: () => 'managed',
|
||||
setLinuxVisibleOverlayOwnerBindingKey: noop,
|
||||
bindVisibleOverlayToTrackedX11Window: noop,
|
||||
updateVisibleOverlayBounds: noop,
|
||||
refreshCurrentSubtitle: noop,
|
||||
getOverlayWindows: () => [mainWindow],
|
||||
syncOverlayShortcuts: noop,
|
||||
resetLastOverlayWindowGeometry: noop,
|
||||
enforceOverlayLayerOrder: noop,
|
||||
getOverlayForegroundSeparateWindows: () => [],
|
||||
};
|
||||
const runtime = createVisibleOverlayInteractionRuntime(deps);
|
||||
return { runtime, mouseEvents, clearedLayers };
|
||||
}
|
||||
|
||||
test('resetting visible overlay input clears the visible content measurement', (t) => {
|
||||
const { runtime, clearedLayers } = setup(t, 'darwin');
|
||||
|
||||
runtime.resetVisibleOverlayInputState();
|
||||
|
||||
assert.deepEqual(clearedLayers, ['visible']);
|
||||
});
|
||||
|
||||
// With no subtitle under the cursor the poll wants passthrough. An input reset leaves the
|
||||
// window's real state unknown, so the next poll must reapply it even though the desired state
|
||||
// matches the remembered one. Hiding resets all input; showing resets only the startup primer.
|
||||
for (const reset of [
|
||||
'resetVisibleOverlayInputState',
|
||||
'resetLinuxVisibleOverlayStartupInputPrimer',
|
||||
] as const) {
|
||||
test(`the Linux pointer poll reapplies passive passthrough after ${reset}`, (t) => {
|
||||
const { runtime, mouseEvents } = setup(t, 'linux');
|
||||
const passthrough: MouseEventsCall = { ignore: true, options: { forward: true } };
|
||||
|
||||
runtime.tickLinuxOverlayPointerInteractionNow();
|
||||
runtime.tickLinuxOverlayPointerInteractionNow();
|
||||
assert.deepEqual(mouseEvents, [passthrough]);
|
||||
|
||||
runtime[reset]();
|
||||
runtime.tickLinuxOverlayPointerInteractionNow();
|
||||
runtime.tickLinuxOverlayPointerInteractionNow();
|
||||
assert.deepEqual(mouseEvents, [passthrough, passthrough]);
|
||||
});
|
||||
}
|
||||
|
||||
test('the Linux startup input grace makes the overlay interactive on the next poll', (t) => {
|
||||
const { runtime, mouseEvents } = setup(t, 'linux');
|
||||
runtime.tickLinuxOverlayPointerInteractionNow();
|
||||
|
||||
runtime.startLinuxVisibleOverlayStartupInputGrace();
|
||||
runtime.tickLinuxOverlayPointerInteractionNow();
|
||||
|
||||
assert.deepEqual(mouseEvents.at(-1), { ignore: false, options: undefined });
|
||||
assert.equal(runtime.getVisibleOverlayInteractionActive(), true);
|
||||
});
|
||||
|
||||
test('the Linux startup input grace reasserts input on an overlay that is already interactive', (t) => {
|
||||
const { runtime, mouseEvents } = setup(t, 'linux');
|
||||
const interactive: MouseEventsCall = { ignore: false, options: undefined };
|
||||
runtime.setLinuxOverlayInteractiveHint(true);
|
||||
runtime.tickLinuxOverlayPointerInteractionNow();
|
||||
runtime.tickLinuxOverlayPointerInteractionNow();
|
||||
assert.deepEqual(mouseEvents, [interactive]);
|
||||
|
||||
runtime.startLinuxVisibleOverlayStartupInputGrace();
|
||||
runtime.tickLinuxOverlayPointerInteractionNow();
|
||||
|
||||
assert.deepEqual(mouseEvents, [interactive, interactive]);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type BrowserWindow, screen } from 'electron';
|
||||
import type { BrowserWindow, Screen } from 'electron';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { startOverlayWindowTracker as startOverlayWindowTrackerCore } from '../../core/services';
|
||||
import { applyOverlayClickThrough } from '../../core/services/overlay-click-through';
|
||||
@@ -36,6 +36,8 @@ import { hasLiveSeparateWindow } from './settings-window-z-order';
|
||||
import { tickWindowsOverlayPointerInteraction } from './windows-overlay-pointer-interaction';
|
||||
|
||||
export interface VisibleOverlayInteractionRuntimeDeps {
|
||||
/** Injected so this module loads without Electron (and under `bun test`). */
|
||||
screen: Pick<Screen, 'getCursorScreenPoint' | 'screenToDipPoint'>;
|
||||
overlayManager: {
|
||||
getMainWindow: () => BrowserWindow | null;
|
||||
getVisibleOverlayVisible: () => boolean;
|
||||
@@ -289,7 +291,7 @@ export function createVisibleOverlayInteractionRuntime(deps: VisibleOverlayInter
|
||||
return null;
|
||||
}
|
||||
return createWindowTrackerCore(override, targetMpvSocketPath, (point) =>
|
||||
screen.screenToDipPoint(point),
|
||||
deps.screen.screenToDipPoint(point),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -597,7 +599,7 @@ export function createVisibleOverlayInteractionRuntime(deps: VisibleOverlayInter
|
||||
const windowsOverlayPointerInteractionDeps = {
|
||||
getVisibleOverlayVisible: () => overlayManager.getVisibleOverlayVisible(),
|
||||
getMainWindow: () => overlayManager.getMainWindow(),
|
||||
getCursorScreenPoint: () => screen.getCursorScreenPoint(),
|
||||
getCursorScreenPoint: () => deps.screen.getCursorScreenPoint(),
|
||||
getSubtitleMeasurement: () => overlayContentMeasurementStore.getLatestByLayer('visible'),
|
||||
shouldSuspend: shouldSuspendWindowsOverlayPointerInteraction,
|
||||
getInteractionActive: () => windowsOverlayPointerInteractionActive,
|
||||
@@ -617,7 +619,7 @@ export function createVisibleOverlayInteractionRuntime(deps: VisibleOverlayInter
|
||||
ensureWindowsVisibleOverlayForegroundPollLoop();
|
||||
|
||||
const linuxX11CursorPointReader = createLinuxX11CursorPointReader({
|
||||
screenToDipPoint: (point) => screen.screenToDipPoint(point),
|
||||
screenToDipPoint: (point) => deps.screen.screenToDipPoint(point),
|
||||
});
|
||||
|
||||
function getLinuxOverlayPointerMeasurement() {
|
||||
@@ -805,7 +807,7 @@ export function createVisibleOverlayInteractionRuntime(deps: VisibleOverlayInter
|
||||
getVisibleOverlayVisible: () => overlayManager.getVisibleOverlayVisible(),
|
||||
getMainWindow: () => overlayManager.getMainWindow(),
|
||||
getCursorScreenPoint: () =>
|
||||
linuxX11CursorPointReader.getCursorScreenPoint(screen.getCursorScreenPoint()),
|
||||
linuxX11CursorPointReader.getCursorScreenPoint(deps.screen.getCursorScreenPoint()),
|
||||
getSubtitleMeasurement: getLinuxOverlayPointerMeasurement,
|
||||
getRendererInteractiveHint: () =>
|
||||
linuxOverlayInteractiveHint || hasLinuxVisibleOverlayStartupInputGrace(),
|
||||
|
||||
Reference in new issue
Block a user