All files / src/web analogue-inputs.js

71.87% Statements 46/64
59.45% Branches 22/37
62.5% Functions 5/8
72.41% Lines 42/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132            1x                 9x 9x   9x   9x 9x         9x   9x 9x 3x 3x 3x 3x     3x     3x   1x     1x 1x           3x   9x 27x           6x   6x 24x       6x 2x 2x 2x   4x       6x 4x 3x   1x         1x         2x                                     2x 1x 1x     1x 1x                     1x 1x        
import { GamepadSource } from "../gamepad-source.js";
import { MicrophoneInput } from "./microphone-input.js";
import { MouseJoystickSource } from "../mouse-joystick-source.js";
import { calculateMouseCoordinates } from "../mouse-coordinates.js";
import { toast } from "./toast.js";
 
const AdcChannelCount = 4;
 
/**
 * What feeds the analogue port and the touchscreen: the gamepad, the mouse
 * acting as a joystick, and the microphone, with the mouse on the monitor
 * routed to whichever of them wants it.
 */
export class AnalogueInputs {
    constructor({ processor, screenCanvas, getGamepads, settings, audioHandler }) {
        this.processor = processor;
        this.settings = settings;
 
        this.gamepadSource = new GamepadSource(getGamepads);
        // Create MicrophoneInput but don't enable by default
        this.microphoneInput = new MicrophoneInput();
        this.microphoneInput.setErrorCallback((message) => {
            toast(`${message} The microphone channel has been turned off.`, { title: "Microphone" });
        });
 
        // Create MouseJoystickSource but don't enable by default
        this.mouseJoystickSource = new MouseJoystickSource(screenCanvas);
 
        const cubMonitor = document.getElementById("cub-monitor");
        const onCubMouseEvent = (evt) => {
            audioHandler.tryResume();
            Iif (document.activeElement !== document.body) document.activeElement.blur();
            const screenRect = screenCanvas.getBoundingClientRect();
            const { x, y } = calculateMouseCoordinates(evt, screenRect);
 
            // Handle touchscreen
            Eif (processor.touchScreen) processor.touchScreen.onMouse(x, y, evt.buttons);
 
            // Handle mouse joystick if enabled
            if (settings.mouseJoystickEnabled && this.mouseJoystickSource.isEnabled()) {
                // Use the API methods instead of direct manipulation
                this.mouseJoystickSource.onMouseMove(x, y);
 
                // Handle button events
                if (evt.type === "mousedown" && evt.button === 0) {
                    this.mouseJoystickSource.onMouseDown(0);
                } else Eif (evt.type === "mouseup" && evt.button === 0) {
                    this.mouseJoystickSource.onMouseUp(0);
                }
            }
 
            evt.preventDefault();
        };
        for (const eventType of ["mousemove", "mousedown", "mouseup"]) {
            cubMonitor.addEventListener(eventType, onCubMouseEvent);
        }
    }
 
    /** Helper to manage ADC source configuration */
    updateAdcSources(mouseJoystickEnabled, microphoneChannel) {
        const { processor } = this;
        // Default all channels to the gamepad source.
        for (let ch = 0; ch < AdcChannelCount; ch++) {
            processor.adconverter.setChannelSource(ch, this.gamepadSource);
        }
 
        // Apply mouse joystick if enabled (takes priority on channels 0 & 1)
        if (mouseJoystickEnabled) {
            processor.adconverter.setChannelSource(0, this.mouseJoystickSource);
            processor.adconverter.setChannelSource(1, this.mouseJoystickSource);
            this.mouseJoystickSource.setVia(processor.sysvia);
        } else {
            this.mouseJoystickSource.setVia(null);
        }
 
        // Apply microphone if configured (can override any channel)
        if (microphoneChannel === undefined) return;
        if (Number.isInteger(microphoneChannel) && microphoneChannel >= 0 && microphoneChannel < AdcChannelCount) {
            processor.adconverter.setChannelSource(microphoneChannel, this.microphoneInput);
        } else {
            toast(
                `There is no analogue channel ${microphoneChannel}; channels are 0 to 3. ` +
                    `The microphone channel has been turned off.`,
                { title: "Microphone" },
            );
            this.clearMicrophoneChannel();
        }
    }
 
    clearMicrophoneChannel() {
        this.settings.set({ microphoneChannel: undefined });
    }
 
    async ensureMicrophoneRunning() {
        const { microphoneInput } = this;
        if (microphoneInput.audioContext && microphoneInput.audioContext.state !== "running") {
            try {
                await microphoneInput.audioContext.resume();
                console.log("Microphone: Audio context resumed, new state:", microphoneInput.audioContext.state);
            } catch (err) {
                console.error("Microphone: Error resuming audio context:", err);
                return false;
            }
        }
        return true;
    }
 
    async setupMicrophone() {
        // The channel can have been turned off between the request and now.
        if (this.settings.microphoneChannel === undefined) return;
        const micPermissionStatus = document.getElementById("micPermissionStatus");
        micPermissionStatus.textContent = "Requesting microphone access...";
 
        // Try to initialise the microphone
        const success = await this.microphoneInput.initialise();
        Iif (success) {
            // Note: Channel assignment is handled by updateAdcSources()
            micPermissionStatus.textContent = "Microphone connected successfully";
            await this.ensureMicrophoneRunning();
 
            // Try starting audio context from user gesture
            const tryAgain = async () => {
                if (await this.ensureMicrophoneRunning()) document.removeEventListener("click", tryAgain);
            };
            document.addEventListener("click", tryAgain);
        } else {
            micPermissionStatus.textContent = `Error: ${this.microphoneInput.getErrorMessage() || "Unknown error"}`;
            this.clearMicrophoneChannel();
        }
    }
}