Files
LenoreSlateandClaude Opus 5.5 fb85b5e90e fix(input-mapper): show the range and built-in value of each setting
The input settings editor listed only the setting names, with every
field blank. Nothing told the user which values are accepted or what
AnyPS5 uses when a field is left blank, so the only feedback was the
error after typing an out-of-range value.

Each setting now shows its accepted range and its built-in value under
the field, linked to it with aria-describedby. The built-in label reuses
the existing translated "builtin" string, so no locale needs new keys.
The range is isolated from the text direction so it reads the same in
right-to-left locales. A test checks the built-in values against the
native InputSettings defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AI-assisted: yes
2026-11-25 22:54:29 +01:00

543 lines
34 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {actions, actionsForInput, chordButtons, defaults, emulatorActions, inputFilename, mouseValues, padButtons, typesForAction} from '../mapping.js';
import {exportableKeys, keyNames} from '../keys.js';
import {captureKey} from '../capture.js';
import {parseIni, serialize, settings, validate, validateSettings} from '../validation.js';
const binding = (action, type = 'KEY', value = 'F') => ({action, type, value});
test('exports the shared name or the exact title profile name', () => {
assert.equal(inputFilename(''), 'anyps5-input.ini');
assert.equal(inputFilename('PPSA29802'), 'anyps5-input.PPSA29802.ini');
assert.equal(inputFilename('Demo-01_a'), 'anyps5-input.Demo-01_a.ini');
});
test('title names use the native length limit and reject invalid filename characters', () => {
const source = readFileSync(new URL('../../../core/libs/prx/libScePad/include/InputMapping.hpp', import.meta.url), 'utf8');
const [, limit] = source.match(/MaxTitleIdLength = (\d+);/u);
const longestId = 'A'.repeat(Number(limit));
assert.equal(inputFilename(longestId), `anyps5-input.${longestId}.ini`);
for (const invalid of [`${longestId}A`, '../PPSA29802', 'foo\\bar', 'with space', ' ', 'C:demo', 'Títle', 'PPSA29802\n', null]) {
assert.equal(inputFilename(invalid), undefined);
}
});
test('search finds exact built-in keyboard and full input bindings', () => {
assert.deepEqual(actionsForInput(' f7 ', []), new Set(['ToggleMouse']));
assert.deepEqual(actionsForInput('F', []), new Set(['RightStickLeft']));
assert.deepEqual(actionsForInput('KEY:Left Alt', []), new Set(['R1']));
assert.deepEqual(actionsForInput('mouse:left', []), new Set(['Square']));
assert.deepEqual(actionsForInput('wheel:up', []), new Set(['Up']));
assert.deepEqual(actionsForInput(' ', []), new Set());
});
test('search uses configured alternatives in place of built-ins', () => {
const {entries} = parseIni('Square = KEY:J\nCross = KEY:Return\nCross = MOUSE:Left\nScreenshot = PAD:L1+R1\n');
assert.deepEqual(actionsForInput('j', entries), new Set(['Square']));
assert.deepEqual(actionsForInput('MOUSE:Left', entries), new Set(['Cross']));
assert.deepEqual(actionsForInput('Return', entries), new Set(['Cross']));
assert.deepEqual(actionsForInput('Space', entries), new Set());
assert.deepEqual(actionsForInput('PAD:L1+R1', entries), new Set(['Screenshot']));
assert.deepEqual(actionsForInput('J', [...entries, binding('Options', 'KEY', 'J')]), new Set(['Square', 'Options']));
assert.deepEqual(actionsForInput('F7', [...entries, binding('ToggleMouse', 'KEY', '')]), new Set());
assert.deepEqual(actionsForInput('PAD:R1+L1', entries), new Set(['Screenshot']));
});
test('action names and pad button categories agree with the current native parser', () => {
const source = readFileSync(new URL('../../../core/libs/prx/libSceVideoOut/src/InputMapping.cpp', import.meta.url), 'utf8');
const definitions = [...source.matchAll(/InputAction\{"(\w+)", Pad::InputControl::(\w+),/gu)];
assert.deepEqual([...actions].sort(), definitions.map(match => match[1]).sort());
assert.deepEqual([...padButtons].sort(), definitions.filter(match => match[2] === 'Button').map(match => match[1]).sort());
assert.match(source, /SDL_GetScancodeFromName\(keyName\.c_str\(\)\)/u);
const keyboardOnly = [...source.matchAll(/if \(action\.control == Pad::InputControl::(\w+)\) \{\s*throw std::runtime_error\("\w+ can only use a keyboard key"\);/gu)].map(match => match[1]);
assert.deepEqual(actions.filter(action => !typesForAction(action).includes('MOUSE')).sort(), keyboardOnly.sort());
const chordActions = source.match(/bool isEmulatorAction[\s\S]*?return true;/u)[0];
assert.deepEqual(actions.filter(action => typesForAction(action).includes('PAD')).sort(),
[...chordActions.matchAll(/case Pad::InputControl::(\w+):/gu)].map(match => match[1]).sort());
const chordNames = source.match(/Pad::PadButton parsePadButton[\s\S]*?throw/u)[0];
assert.deepEqual([...chordButtons].sort(), [...chordNames.matchAll(/normalized == "(\w+)"/gu)].map(match => match[1].toUpperCase()).sort().map(name => chordButtons.find(button => button.toUpperCase() === name)));
assert.match(source, /if \(action\.control != Pad::InputControl::Button\)/u);
});
test('built-in conflict catalogue agrees with the current native bindings', () => {
const source = readFileSync(new URL('../../../core/libs/prx/libScePad/include/InputMapping.hpp', import.meta.url), 'utf8');
const special = {RETURN: 'Return', SPACE: 'Space', ESCAPE: 'Escape', BACKSPACE: 'Backspace', TAB: 'Tab', UP: 'Up', RIGHT: 'Right', DOWN: 'Down', LEFT: 'Left', LALT: 'Left Alt', RALT: 'Right Alt', LSHIFT: 'Left Shift', RSHIFT: 'Right Shift', LCTRL: 'Left Ctrl', RCTRL: 'Right Ctrl'};
const native = Object.fromEntries(actions.map(action => [action, []]));
for (const match of source.matchAll(/InputBinding\{SDL_SCANCODE_(\w+), MouseButton::(\w+), InputControl::(\w+)(?:, PadButton::(\w+))?(?:, (-?\d+))?\}/gu)) {
const [, key, mouse, control, button, wheel] = match;
const action = control === 'Button' ? button : control;
const value = key !== 'UNKNOWN' ? `KEY:${special[key] || key}` : mouse !== 'None' ? `MOUSE:${mouse}` : `WHEEL:${wheel === '1' ? 'Up' : 'Down'}`;
native[action].push(value);
}
assert.deepEqual(native, defaults);
});
test('setting names and order agree with the current native parser', () => {
const source = readFileSync(new URL('../../../core/libs/prx/libSceVideoOut/src/InputMapping.cpp', import.meta.url), 'utf8');
const definitions = [...source.matchAll(/InputSettingName\{"(\w+)", InputSetting::\w+\}/gu)].map(match => match[1]);
assert.match(source, /if \(upper\(actionName\) == "TOGGLEACTIONS"\) \{/u);
assert.deepEqual(settings.map(setting => setting.name), [...definitions, 'ToggleActions']);
assert.equal(new Set(definitions).size, definitions.length);
});
test('setting hints show the built-in values of the native settings', () => {
const source = readFileSync(new URL('../../../core/libs/prx/libScePad/include/InputMapping.hpp', import.meta.url), 'utf8');
const constants = Object.fromEntries([...source.matchAll(/inline constexpr \w+ (\w+) = ([\d.]+);/gu)].map(match => [match[1], match[2]]));
const fields = source.match(/struct InputSettings \{([^}]*)\}/u)[1];
const native = {};
for (const [, field, value] of fields.matchAll(/(?:int|double) (\w+) = (\w[\w.]*);/gu)) {
native[field[0].toUpperCase() + field.slice(1).replace(/Percent$/u, '')] = Number(constants[value] ?? value);
}
native.MouseStickTarget = /bool mouseControlsRightStick = true;/u.test(fields) ? 'Right' : 'Left';
const builtin = Object.fromEntries(settings.filter(setting => setting.builtin !== undefined).map(setting => [setting.name, setting.name === 'MouseStickTarget' ? setting.builtin : Number(setting.builtin)]));
assert.deepEqual(builtin, native);
});
test('ToggleActions values follow the current native list parser', () => {
const source = readFileSync(new URL('../../../core/libs/prx/libSceVideoOut/src/InputMapping.cpp', import.meta.url), 'utf8');
const parser = source.match(/std::uint32_t parseToggleActions[\s\S]*?return mask;/u)[0];
assert.match(parser, /value\.find\(',', start\)/u);
assert.match(parser, /if \(part\.empty\(\)\) throw/u);
assert.match(parser, /findAction\(part\)/u);
assert.match(parser, /if \(action->control != Pad::InputControl::Button\)/u);
});
test('ToggleActions from the documented example imports and round trips', () => {
const imported = parseIni('ToggleActions = R2, L1\nR2 = KEY:Z\n');
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.entries, [binding('R2', 'KEY', 'Z')]);
assert.deepEqual(imported.settings, [{name: 'ToggleActions', value: 'R2, L1'}]);
assert.equal(serialize(imported.entries, imported.settings), 'R2 = KEY:Z\nToggleActions = R2, L1\n');
});
test('ToggleActions accepts every pad button in any case and repeated names', () => {
assert.deepEqual(validateSettings([{name: 'ToggleActions', value: [...padButtons].join(',')}]).errors, []);
const imported = parseIni('toggleactions = r2 ,cross, R2\n');
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.settings, [{name: 'ToggleActions', value: 'r2 ,cross, R2'}]);
});
test('ToggleActions refuses empty names, unknown actions and actions that are not pad buttons', () => {
const cases = {
'ToggleActions =': 'ToggleActions has an empty action name.',
'ToggleActions = R2,': 'ToggleActions has an empty action name.',
'ToggleActions = R2,,L1': 'ToggleActions has an empty action name.',
'ToggleActions = R2, Jump': "ToggleActions: unknown action 'Jump'.",
'ToggleActions = TouchPad': "ToggleActions: unknown action 'TouchPad'.",
'ToggleActions = leftstickup': "ToggleActions only lists pad buttons, not 'LeftStickUp'.",
'ToggleActions = R2, ToggleFullscreen': "ToggleActions only lists pad buttons, not 'ToggleFullscreen'."
};
for (const [line, message] of Object.entries(cases)) {
const result = parseIni(line);
assert.deepEqual(result.errors, [{line: 1, message}], line);
assert.deepEqual(result.settings, [], line);
assert.throws(() => serialize([], [{name: 'ToggleActions', value: line.slice(line.indexOf('=') + 1)}]), {message}, line);
}
const repeated = parseIni('ToggleActions = R2\nToggleActions = L1\n');
assert.deepEqual(repeated.errors, [{line: 2, message: 'ToggleActions is set more than once.'}]);
assert.deepEqual(repeated.settings, [{name: 'ToggleActions', value: 'R2'}]);
});
test('settings from a documented configuration import and round trip', () => {
const source = '\uFEFF# tuned\r\nCross = KEY:Return\r\nLeftStickDeadzone = 12\r\nMouseSensitivity = 2.50\r\nStickModifierScale = 0.4\r\nTriggerRampMs = 250\r\n';
const imported = parseIni(source);
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.entries, [binding('Cross', 'KEY', 'Return')]);
assert.deepEqual(imported.settings, [
{name: 'LeftStickDeadzone', value: '12'},
{name: 'MouseSensitivity', value: '2.50'},
{name: 'StickModifierScale', value: '0.4'},
{name: 'TriggerRampMs', value: '250'}
]);
assert.equal(serialize(imported.entries, imported.settings),
'Cross = KEY:Return\nLeftStickDeadzone = 12\nMouseSensitivity = 2.50\nStickModifierScale = 0.4\nTriggerRampMs = 250\n');
assert.equal(serialize(imported.entries), 'Cross = KEY:Return\n');
});
test('settings-only files import without bindings', () => {
const imported = parseIni('MouseCurve = 1.3\nMouseDecayMs = 33\n');
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.entries, []);
assert.equal(serialize(imported.entries, imported.settings), 'MouseCurve = 1.3\nMouseDecayMs = 33\n');
});
test('controller remaps survive editing and exporting an imported INI', () => {
const source = '\uFEFFSDLButton: A = circle\r\nCross = KEY:Return\r\nsdlbutton : b = cross\r\nSDLButton:back = none ; disabled\r\nMouseStickTarget = Left\r\n';
const imported = parseIni(source);
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.controllerRemaps, [
{button: 'a', destination: 'Circle'}, {button: 'b', destination: 'Cross'}, {button: 'back', destination: 'None'}
]);
const edited = [binding('Square', 'KEY', 'J'), ...imported.entries];
const exported = serialize(edited, imported.settings, imported.controllerRemaps);
assert.equal(exported, 'Cross = KEY:Return\nSquare = KEY:J\nMouseStickTarget = Left\nSDLButton:a = Circle\nSDLButton:b = Cross\nSDLButton:back = None\n');
assert.deepEqual(parseIni(exported).controllerRemaps, imported.controllerRemaps);
});
test('controller-only files keep guide, paddles, touchpad and shared destinations', () => {
const source = 'SDLButton:guide = TouchPad\nSDLButton:paddle4 = R2\nSDLButton:touchpad = TouchPad\n';
const imported = parseIni(source);
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.entries, []);
assert.equal(serialize(imported.entries, imported.settings, imported.controllerRemaps), source);
});
test('unknown, malformed and duplicate controller remaps report their line', () => {
const source = 'SDLButton:a = Cross\nSDLButton:A = Circle\nSDLButton:leftx = Cross\nSDLButton:b = Cross+Circle\nSDLButton:x = ToggleFullscreen\nSDLButton:y =\nSDLButton: = None\n';
const imported = parseIni(source);
assert.deepEqual(imported.errors, [
{line: 2, message: 'SDLButton:a is set more than once.'},
{line: 3, message: "Unknown SDL controller button 'leftx'."},
{line: 4, message: 'SDLButton:b: expected a PlayStation button or None.'},
{line: 5, message: 'SDLButton:x: expected a PlayStation button or None.'},
{line: 6, message: 'SDLButton:y: expected a PlayStation button or None.'},
{line: 7, message: "Unknown SDL controller button ''."}
]);
assert.deepEqual(imported.controllerRemaps, [{button: 'a', destination: 'Cross'}]);
assert.throws(() => serialize([], [], [{button: 'leftx', destination: 'Cross'}]), /Unknown SDL controller button/);
assert.throws(() => serialize([], [], [{button: 'a', destination: 'Cross+Circle'}]), /expected a PlayStation button or None/);
assert.throws(() => serialize([], [], [{button: 'a', destination: 'Cross'}, {button: 'A', destination: 'None'}]), /set more than once/);
});
test('binding errors name the action without the spaces around it', () => {
assert.deepEqual(parseIni('Cross = KEY:\n Cross = PAD:x\nFoo bar = KEY:A\n').errors, [
{line: 1, message: 'Cross: Unknown or empty KEY value.'},
{line: 2, message: 'Cross: Cross cannot use PAD.'},
{line: 3, message: 'Foo bar: Unknown or empty action.'}
]);
});
test('setting names canonicalize like the native parser', () => {
const imported = parseIni('leftstickdeadzone = 8\nMOUSESENSITIVITY = 1e0\n');
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.settings, [{name: 'LeftStickDeadzone', value: '8'}, {name: 'MouseSensitivity', value: '1e0'}]);
});
test('the mouse stick target accepts the native LEFT and RIGHT spellings', () => {
const imported = parseIni('MouseStickTarget = Left\n');
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.settings, [{name: 'MouseStickTarget', value: 'Left'}]);
assert.equal(serialize(imported.entries, imported.settings), 'MouseStickTarget = Left\n');
assert.deepEqual(validateSettings([{name: 'MouseStickTarget', value: 'RIGHT'}]).settings, [{name: 'MouseStickTarget', value: 'RIGHT'}]);
assert.equal(validateSettings([{name: 'MouseStickTarget', value: 'Both'}]).errors[0].message, 'MouseStickTarget must be LEFT or RIGHT.');
assert.equal(validateSettings([{name: 'MouseStickTarget', value: '1'}]).errors[0].message, 'MouseStickTarget must be LEFT or RIGHT.');
});
test('a signed zero deadzone imports like the native parser', () => {
const imported = parseIni('LeftStickDeadzone = -0\nRightStickDeadzone = -00\n');
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.settings, [{name: 'LeftStickDeadzone', value: '-0'}, {name: 'RightStickDeadzone', value: '-00'}]);
assert.equal(serialize(imported.entries, imported.settings), 'LeftStickDeadzone = -0\nRightStickDeadzone = -00\n');
});
test('out-of-range and malformed setting values report their line', () => {
const cases = {
'LeftStickDeadzone = 91': 'LeftStickDeadzone must be a whole percentage from 0 to 90.',
'LeftStickDeadzone = 12.5': 'LeftStickDeadzone must be a whole percentage from 0 to 90.',
'LeftStickDeadzone = +12': 'LeftStickDeadzone must be a whole percentage from 0 to 90.',
'LeftStickDeadzone = -1': 'LeftStickDeadzone must be a whole percentage from 0 to 90.',
'MouseSensitivity = 0': 'MouseSensitivity must be a number greater than 0 and at most 10.',
'MouseSensitivity = 10.1': 'MouseSensitivity must be a number greater than 0 and at most 10.',
'MouseSensitivity = abc': 'MouseSensitivity must be a number greater than 0 and at most 10.',
'MouseSensitivity = 1e999': 'MouseSensitivity must be a number greater than 0 and at most 10.',
'MouseSensitivity = 0x1': 'MouseSensitivity must be a number greater than 0 and at most 10.',
'MouseSensitivity = +2.5': 'MouseSensitivity must be a number greater than 0 and at most 10.',
'MouseCurve = 0.1': 'MouseCurve must be a number from 0.2 to 5.',
'MouseDecayMs = 0': 'MouseDecayMs must be a number from 1 to 1000.',
'StickModifierScale = 1.1': 'StickModifierScale must be a number from 0.05 to 1.'
};
for (const [line, message] of Object.entries(cases)) {
const result = parseIni(line);
assert.deepEqual(result.errors, [{line: 1, message}], line);
assert.deepEqual(result.settings, [], line);
}
for (const line of ['MouseSensitivity = 10', 'MouseCurve = 1e0', 'MouseDeadzoneOffset = 0', 'KeyboardRampMs = 2000', 'LeftStickDeadzone = 0', 'RightStickDeadzone = 90']) {
assert.deepEqual(parseIni(line).errors, [], line);
}
});
test('setting values that underflow to zero are refused like the native parser', () => {
for (const value of ['1e-400', '-1e-400', '0.5E-400', '.1e-999', '10e-401']) {
const message = 'MouseSmoothingMs must be a number from 0 to 500.';
assert.deepEqual(parseIni(`MouseSmoothingMs = ${value}`), {entries: [], settings: [], controllerRemaps: [], errors: [{line: 1, message}], warnings: []}, value);
assert.deepEqual(validateSettings([{name: 'MouseSmoothingMs', value}]), {errors: [{index: 0, message}], settings: []}, value);
assert.throws(() => serialize([], [{name: 'MouseSmoothingMs', value}]), {message}, value);
}
for (const value of ['0', '0.0', '-0', '0e5', '0.e-400', '00.00E+400', '1e-320']) {
assert.deepEqual(parseIni(`MouseSmoothingMs = ${value}`).settings, [{name: 'MouseSmoothingMs', value}], value);
assert.equal(serialize([], [{name: 'MouseDeadzoneOffset', value}]), `MouseDeadzoneOffset = ${value}\n`, value);
}
});
test('a setting set more than once is refused like the native parser', () => {
const result = parseIni('Cross = KEY:F\nMouseSensitivity = 1\nMouseSensitivity = 2\n');
assert.deepEqual(result.errors, [{line: 3, message: 'MouseSensitivity is set more than once.'}]);
assert.deepEqual(result.settings, [{name: 'MouseSensitivity', value: '1'}]);
});
test('names fold case and trim spaces in ASCII only, like the native parser', () => {
const lines = [
'Trıangle = KEY:A',
'ſquare = KEY:A',
'Cross = KEY:ſpace',
'Cross = MıDDLE:Left',
' Cross = KEY:A',
'Cross = KEY:A ',
'Cross = KEY:A',
'MouseSensitivity = 2 ',
'MouseStickTarget = RıGHT',
'ToggleActions = Cross, Circle',
'SDLButton:a = Cross',
'SDLButton:a = Croſſ'
];
for (const line of lines) {
const result = parseIni(line);
assert.equal(result.errors.length, 1, line);
assert.deepEqual([result.entries, result.settings, result.controllerRemaps], [[], [], []], line);
}
assert.equal(validate([binding('Trıangle', 'KEY', 'A')]).errors.length, 1);
assert.equal(validateSettings([{name: 'MouseSensitivity', value: '2 '}]).errors.length, 1);
const imported = parseIni('\tTRIANGLE\v=\fkey: a\r\nmousesensitivity =\v2\f\n');
assert.deepEqual(imported.errors, []);
assert.deepEqual(imported.entries, [binding('Triangle', 'KEY', 'A')]);
assert.deepEqual(imported.settings, [{name: 'MouseSensitivity', value: '2'}]);
});
test('serialize refuses invalid settings it is handed', () => {
for (const configuration of [[{name: 'MouseSensitivity', value: '0'}], [{name: 'MadeUp', value: '1'}], [{name: 'MouseCurve', value: '9'}], [{name: 'MouseCurve', value: '1'}, {name: 'MouseCurve', value: '2'}], null]) {
assert.throws(() => serialize([], configuration));
assert.ok(validateSettings(configuration).errors.length >= 1);
}
assert.deepEqual(validateSettings([{name: 'mousecurve', value: ' 2 '}]), {errors: [], settings: [{name: 'MouseCurve', value: '2'}]});
});
test('every action serializes with a supported key', () => {
const input = actions.map(action => binding(action));
assert.equal(serialize(input), actions.map(action => `${action} = KEY:F\n`).join(''));
});
test('multiple inputs are alternatives and omitted actions stay omitted', () => {
assert.equal(serialize([binding('Cross'), binding('Cross', 'KEY', 'Space')]), 'Cross = KEY:F\nCross = KEY:Space\n');
assert.equal(serialize([]), '');
assert.equal(serialize([binding('R2', 'MOUSE', 'Right')]), 'R2 = MOUSE:Right\n');
});
test('case and whitespace normalize; duplicate bindings warn and serialize once', () => {
const input = [binding(' cross ', ' key ', ' f '), binding('Cross')];
assert.equal(serialize(input), 'Cross = KEY:F\n');
assert.equal(validate(input).warnings.filter(warning => warning.message.includes('duplicate')).length, 1);
});
test('invalid and incomplete bindings block export', () => {
for (const input of [binding('Unknown'), binding('Cross', 'GAMEPAD'), binding('Cross', 'KEY', 'Enter'), binding('Cross', 'KEY', 'KeyF'), binding('Cross', 'KEY', ''), binding('Cross', 'KEY', 'F\nR2 = MOUSE:Left'), null, {}]) {
assert.ok(validate([input]).errors.length);
assert.throws(() => serialize([input]));
}
assert.ok(validate({}).errors.length);
});
test('all exportable SDL names validate and unsafe comment names are rejected', () => {
for (const key of exportableKeys) assert.equal(validate([binding('Cross', 'KEY', key)]).errors.length, 0, key);
for (const key of [';', '#', 'Keypad #']) assert.ok(validate([binding('Cross', 'KEY', key)]).errors.length, key);
assert.equal(new Set(keyNames).size, keyNames.length);
});
test('mouse values and action restrictions match the current INI format', () => {
for (const action of actions) {
for (const value of mouseValues) {
assert.equal(validate([binding(action, 'MOUSE', value)]).errors.length === 0, !['ToggleFullscreen', 'ToggleBorderless', 'TogglePerformanceOverlay', 'Screenshot', 'ShowPadStatus', 'VolumeUp', 'VolumeDown', 'ToggleMute', 'ReloadInputMapping'].includes(action));
}
}
assert.ok(validate([binding('Cross', 'MOUSE', 'Button1')]).errors.length);
});
test('wheel directions only map to pad buttons', () => {
for (const action of actions) {
for (const value of ['Up', 'Down', 'Left', 'Right']) {
assert.equal(validate([binding(action, 'WHEEL', value)]).errors.length === 0, padButtons.has(action));
}
assert.deepEqual(typesForAction(action).includes('WHEEL'), padButtons.has(action));
}
assert.ok(validate([binding('Cross', 'WHEEL', 'Sideways')]).errors.length);
});
test('new utility actions import and round trip without accepting unsupported sources', () => {
const source = 'StickModifier = MOUSE:X2\nShake = MOUSE:Left\nTogglePerformanceOverlay = KEY:F9\nScreenshot = KEY:F8\nShowPadStatus = KEY:F4\n';
const imported = parseIni(source);
assert.deepEqual(imported.errors, []);
assert.equal(serialize(imported.entries), source);
for (const action of ['StickModifier', 'Shake', 'TogglePerformanceOverlay', 'Screenshot', 'ShowPadStatus']) {
assert.ok(validate([binding(action, 'WHEEL', 'Up')]).errors.length);
}
for (const action of ['TogglePerformanceOverlay', 'Screenshot', 'ShowPadStatus']) {
assert.deepEqual(parseIni(`${action} = MOUSE:Left`).errors.map(error => error.line), [1]);
}
});
test('ShowPadStatus is an emulator action with an F9 default that conflicts like any built-in', () => {
assert.deepEqual(defaults.ShowPadStatus, ['KEY:F9']);
assert.deepEqual(typesForAction('ShowPadStatus'), ['KEY', 'PAD']);
assert.equal(serialize([binding('ShowPadStatus', 'KEY', 'F4')]), 'ShowPadStatus = KEY:F4\n');
assert.equal(serialize([binding(' showpadstatus ', 'key', 'f9')]), 'ShowPadStatus = KEY:F9\n');
for (const [type, value] of [['MOUSE', 'Left'], ['MOUSE', 'X2'], ['WHEEL', 'Up'], ['WHEEL', 'Down']]) {
assert.ok(validate([binding('ShowPadStatus', type, value)]).errors.length, `${type}:${value}`);
}
assert.equal(validate([binding('ShowPadStatus', 'KEY', 'F4')]).warnings.length, 0);
const shared = validate([binding('TogglePerformanceOverlay', 'KEY', 'F9')]);
assert.ok(shared.warnings.some(warning => warning.message.includes('TogglePerformanceOverlay and ShowPadStatus (built-in)')));
assert.equal(validate([binding('TogglePerformanceOverlay', 'KEY', 'F9'), binding('ShowPadStatus', 'KEY', 'F4')]).warnings.length, 0);
assert.ok(Object.values(defaults).flat().filter(source => source === 'KEY:F9').length === 1);
});
test('updated built-in inputs warn until their owning action is overridden', () => {
for (const [action, type, value] of [['L2', 'KEY', 'R'], ['L2', 'MOUSE', 'X1'], ['ToggleMouse', 'KEY', 'F7'], ['Shake', 'KEY', 'X'], ['Screenshot', 'KEY', 'F12'], ['TogglePerformanceOverlay', 'KEY', 'F10'], ['ShowPadStatus', 'KEY', 'F9']]) {
const input = binding('Cross', type, value);
assert.ok(validate([input]).warnings.some(warning => warning.message.includes(`${action} (built-in)`)));
assert.equal(validate([input, binding(action, 'KEY', 'J')]).warnings.length, 0);
}
});
test('conflicts warn without blocking, including omitted built-in actions', () => {
const input = [binding('Cross'), binding('Square')];
const result = validate(input);
assert.equal(result.errors.length, 0);
assert.ok(result.warnings.some(warning => warning.message.includes('Cross and Square and RightStickLeft (built-in)')));
assert.doesNotThrow(() => serialize(input));
const overridden = validate([binding('Cross'), binding('RightStickLeft', 'KEY', 'J')]);
assert.equal(overridden.warnings.length, 0);
});
test('serialization is deterministic in action order and preserves alternative order', () => {
const input = [binding('ToggleMouse', 'MOUSE', 'X1'), binding('Cross', 'KEY', 'Space'), binding('Cross')];
assert.equal(serialize(input), 'Cross = KEY:Space\nCross = KEY:F\nToggleMouse = MOUSE:X1\n');
assert.deepEqual(input, [binding('ToggleMouse', 'MOUSE', 'X1'), binding('Cross', 'KEY', 'Space'), binding('Cross')]);
});
test('import supports BOM, CRLF, inline comments, extra equals and colons in key names', () => {
const result = parseIni('\uFEFF# config\r\n cross = key : space ; note\r\nCross=KEY:Space\r\nR2=mouse:right\r\nL1=KEY:=\r\nL2=KEY:Keypad :\r\n');
assert.deepEqual(result.errors, []);
assert.equal(result.warnings.length, 1);
assert.deepEqual(result.entries, [binding('Cross', 'KEY', 'Space'), binding('R2', 'MOUSE', 'Right'), binding('L1', 'KEY', '='), binding('L2', 'KEY', 'Keypad :')]);
});
test('import rejects sections, unsupported extensions and malformed lines with line numbers', () => {
const result = parseIni('[Bindings]\nCross=NONE\nCross=KEY:4\nToggleFullscreen=MOUSE:Left\nLeftStickUp=WHEEL:Up\nCross=KEY:;\nCross=KEY:KeyF\nCross=KEY:\n');
assert.deepEqual(result.errors.map(error => error.line), [1, 2, 4, 5, 6, 7, 8]);
assert.deepEqual(result.entries, [binding('Cross', 'KEY', '4')]);
assert.throws(() => parseIni(null), TypeError);
});
test('round trip is stable for every safe key and supported mouse/wheel source', () => {
const input = [...exportableKeys.map(value => binding('Cross', 'KEY', value)), ...mouseValues.map(value => binding('Square', 'MOUSE', value)), binding('R2', 'WHEEL', 'Down')];
const text = serialize(input);
const imported = parseIni(text);
assert.equal(imported.errors.length, 0);
assert.equal(serialize(imported.entries), text);
});
test('capture maps physical positions and distinguishes modifiers and keypad', () => {
const cases = {KeyA: 'A', Digit1: '1', Enter: 'Return', NumpadEnter: 'Keypad Enter', Numpad1: 'Keypad 1', ControlLeft: 'Left Ctrl', AltRight: 'Right Alt', ArrowUp: 'Up', F24: 'F24', Equal: '=', Backslash: '\\'};
for (const [code, value] of Object.entries(cases)) assert.deepEqual(captureKey({code, key: 'ignored'}), {value});
assert.equal(captureKey({code: 'KeyQ', key: 'a'}).value, 'Q');
});
test('captured media and browser keys round trip through INI bindings', () => {
const keys = {
MediaTrackNext: 'AudioNext', MediaTrackPrevious: 'AudioPrev', MediaStop: 'AudioStop',
MediaPlayPause: 'AudioPlay', MediaSelect: 'MediaSelect',
AudioVolumeMute: 'Mute', AudioVolumeUp: 'VolumeUp', AudioVolumeDown: 'VolumeDown',
BrowserSearch: 'AC Search', BrowserHome: 'AC Home', BrowserBack: 'AC Back',
BrowserForward: 'AC Forward', BrowserStop: 'AC Stop', BrowserRefresh: 'AC Refresh',
BrowserFavorites: 'AC Bookmarks'
};
for (const [code, value] of Object.entries(keys)) {
const captured = captureKey({code, key: 'ignored'});
assert.deepEqual(captured, {value}, code);
const ini = serialize([binding('Cross', 'KEY', captured.value)]);
assert.deepEqual(parseIni(ini).entries, [binding('Cross', 'KEY', value)], code);
}
});
test('capture maps additional letters, digits, numpad, function and special keys', () => {
const cases = {
KeyB: 'B', KeyC: 'C', KeyD: 'D', KeyE: 'E', KeyF: 'F', KeyG: 'G', KeyH: 'H', KeyI: 'I',
KeyJ: 'J', KeyK: 'K', KeyL: 'L', KeyM: 'M', KeyN: 'N', KeyO: 'O', KeyP: 'P',
KeyR: 'R', KeyS: 'S', KeyT: 'T', KeyU: 'U', KeyV: 'V', KeyW: 'W', KeyX: 'X',
KeyY: 'Y', KeyZ: 'Z',
Digit0: '0', Digit2: '2', Digit3: '3', Digit4: '4', Digit5: '5', Digit6: '6',
Digit7: '7', Digit8: '8', Digit9: '9',
Numpad0: 'Keypad 0', Numpad2: 'Keypad 2', Numpad3: 'Keypad 3', Numpad4: 'Keypad 4',
Numpad5: 'Keypad 5', Numpad6: 'Keypad 6', Numpad7: 'Keypad 7', Numpad8: 'Keypad 8',
Numpad9: 'Keypad 9',
F1: 'F1', F2: 'F2', F3: 'F3', F4: 'F4', F5: 'F5', F6: 'F6', F7: 'F7', F8: 'F8',
F9: 'F9', F10: 'F10', F11: 'F11', F12: 'F12', F13: 'F13', F14: 'F14', F15: 'F15',
F16: 'F16', F17: 'F17', F18: 'F18', F19: 'F19', F20: 'F20', F21: 'F21', F22: 'F22',
F23: 'F23',
Minus: '-', BracketLeft: '[', BracketRight: ']', Quote: "'", Backquote: '`',
Comma: ',', Period: '.', Slash: '/',
CapsLock: 'CapsLock', PrintScreen: 'PrintScreen', ScrollLock: 'ScrollLock', Pause: 'Pause',
Insert: 'Insert', Home: 'Home', PageUp: 'PageUp', Delete: 'Delete', End: 'End', PageDown: 'PageDown',
ArrowRight: 'Right', ArrowLeft: 'Left', ArrowDown: 'Down',
NumLock: 'Numlock',
NumpadDivide: 'Keypad /', NumpadMultiply: 'Keypad *', NumpadSubtract: 'Keypad -',
NumpadAdd: 'Keypad +', NumpadDecimal: 'Keypad .', NumpadEqual: 'Keypad =', NumpadComma: 'Keypad ,',
ContextMenu: 'Application',
ControlRight: 'Right Ctrl', ShiftLeft: 'Left Shift', ShiftRight: 'Right Shift',
AltLeft: 'Left Alt', MetaLeft: 'Left GUI', MetaRight: 'Right GUI',
};
for (const [code, value] of Object.entries(cases)) assert.deepEqual(captureKey({code, key: 'ignored'}), {value}, code);
});
test('capture rejects out-of-range function keys and numpad keys', () => {
assert.match(captureKey({code: 'F25'}).error, /This physical key cannot be captured/);
assert.match(captureKey({code: 'Numpad10'}).error, /This physical key cannot be captured/);
});
test('capture rejects missing identifiers, composition and unsafe punctuation', () => {
for (const event of [{code: 'Unidentified'}, {key: 'a'}, {code: 'IntlBackslash'}, {code: 'Semicolon'}, {code: 'KeyA', isComposing: true}, {code: 'Quote', key: 'Dead'}, {code: 'KeyA', key: 'Process'}]) {
assert.ok(captureKey(event).error);
}
});
test('extended keypad editing and memory keys capture and round trip', () => {
const keys = {
NumpadBackspace: 'Keypad Backspace', NumpadClear: 'Keypad Clear',
NumpadClearEntry: 'Keypad ClearEntry', NumpadParenLeft: 'Keypad (', NumpadParenRight: 'Keypad )',
NumpadMemoryAdd: 'Keypad MemAdd', NumpadMemoryClear: 'Keypad MemClear',
NumpadMemoryRecall: 'Keypad MemRecall', NumpadMemoryStore: 'Keypad MemStore',
NumpadMemorySubtract: 'Keypad MemSubtract'
};
for (const [code, value] of Object.entries(keys)) {
const captured = captureKey({code, key: 'ignored'});
assert.deepEqual(captured, {value}, code);
const source = serialize([binding('Cross', 'KEY', captured.value)]);
assert.equal(source, `Cross = KEY:${value}\n`);
assert.deepEqual(parseIni(source).entries, [binding('Cross', 'KEY', value)]);
}
assert.deepEqual(captureKey({code: 'Backspace'}), {value: 'Backspace'});
assert.deepEqual(captureKey({code: 'NumLock'}), {value: 'Numlock'});
});
test('PAD chords for emulator actions import, normalize and export like the native parser reads them', () => {
const result = parseIni('Screenshot = PAD:L1+R1\nToggleFullscreen = pad: r1 + options \nVolumeUp = PAD:TouchPad\n');
assert.deepEqual(result.errors, []);
assert.deepEqual(result.entries, [binding('Screenshot', 'PAD', 'L1+R1'), binding('ToggleFullscreen', 'PAD', 'R1+Options'),
binding('VolumeUp', 'PAD', 'TouchPad')]);
assert.equal(serialize(result.entries), 'ToggleFullscreen = PAD:R1+Options\nScreenshot = PAD:L1+R1\nVolumeUp = PAD:TouchPad\n');
for (const action of emulatorActions) assert.deepEqual(validate([binding(action, 'PAD', 'Options+Cross')]).errors, []);
for (const source of ['Cross = PAD:L1', 'RightStickUp = PAD:L1', 'ToggleMouse = PAD:L1', 'Screenshot = PAD:', 'Screenshot = PAD:L1+',
'Screenshot = PAD:L1++R1', 'Screenshot = PAD:L4', 'Screenshot = PAD:Share']) {
assert.deepEqual(parseIni(source).errors.map(error => error.line), [1], source);
}
});
test('PAD chords with the same buttons are one binding, as the native parser compares button masks', () => {
const result = parseIni('Screenshot = PAD:L1+R1\nScreenshot = PAD:R1+L1+l1\n');
assert.deepEqual(result.entries, [binding('Screenshot', 'PAD', 'L1+R1')]);
assert.equal(result.warnings.length, 1);
assert.match(validate([binding('Screenshot', 'PAD', 'L1+R1'), binding('VolumeUp', 'PAD', 'R1+L1')]).warnings[0].message,
/^PAD:L1\+R1 controls Screenshot and VolumeUp\.$/u);
});