Keyboard.java

/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation. For the full
 * license text, see http://www.gnu.org/licenses/gpl.html.
 */
package libsidplay.components.keyboard;

import java.util.HashSet;
import java.util.Set;

/**
 * <pre>
 * Implements the C64's keyboard.<br>
 * <br>
 * For documentation on the C64 keyboard handling, see
 * <a href=
 * 'http://www.zimmers.net/anonftp/pub/cbm/c64/programming/documents/keymatrix.txt'>http://www.zimmers.net/anonftp/pub/cbm/c64/programming/documents/keymatrix.txt</a> or
 * <a href=
 * 'http://www.zimmers.net/anonftp/pub/cbm/magazines/transactor/v5i5/p039.jpg'>http://www.zimmers.net/anonftp/pub/cbm/magazines/transactor/v5i5/p039.jpg</a>.
 * </pre>
 *
 * @author Jörg Jahnke (joergjahnke@users.sourceforge.net)
 */
public abstract class Keyboard {
    private final Set<KeyTableEntry> keysDown = new HashSet<>();

    /**
     * Reset the keyboard
     */
    public synchronized void reset() {
        keysDown.clear();
    }

    /**
     * Handle a pressed key
     *
     * @param ktEntry key that was pressed
     */
    public synchronized void keyPressed(final KeyTableEntry ktEntry) {
        keysDown.add(ktEntry);
    }

    /**
     * Get currently pressed keys
     *
     * @return which keys are currently pressed?
     */
    public synchronized Set<KeyTableEntry> getKeysDown() {
        return keysDown;
    }

    /**
     * Handle a released key
     *
     * @param ktEntry key to release
     */
    public synchronized void keyReleased(final KeyTableEntry ktEntry) {
        keysDown.remove(ktEntry);
    }

    /**
     * Get the keyboard contribution to PRA when the other lines are inputs.
     * For CIA1 use the pin-aware overload to distinguish inputs from high outputs.
     *
     * @param selected PRB pin levels, active low
     * @return keyboard contribution to PRA
     */
    public byte readColumn(final byte selected) {
        return readColumn((byte) 0xff, selected, (byte) 0);
    }

    /**
     * Read the PA side of the keyboard matrix, including indirect connections.
     * A high PRB output suppresses indirect reverse-scan paths in its connected
     * component; a PRB input with a pull-up does not. Direct contacts still work.
     *
     * @param paPins effective PA levels, including joystick inputs
     * @param pbPins effective PB levels, including joystick inputs
     * @param pbOutputHighMask PRB bits actively driven high (PRB AND DDRB)
     * @return keyboard contribution to PRA, to be ANDed with its pin/output mask
     */
    public synchronized byte readColumn(final byte paPins, final byte pbPins,
                                        final byte pbOutputHighMask) {
        final long matrix = matrixConnections();
        int lowRows = connectedLines(matrix, ~paPins & 0xff, 0) & 0xff;

        for (int column = 0; column < 8; column++) {
            final int bit = 1 << column;
            if ((pbPins & bit) == 0) {
                final int connected = connectedLines(matrix, 0, bit);
                if (((connected >>> 8) & pbOutputHighMask) != 0) {
                    lowRows |= directlyConnectedRows(matrix, bit);
                } else {
                    lowRows |= connected & 0xff;
                }
            }
        }
        return (byte) ~lowRows;
    }

    /**
     * Compatibility overload: all low PA pins are treated as actively driven;
     * the remaining PB pins are inputs. CIA1 uses the full pin-aware overload.
     *
     * @param selected PA pin levels, active low
     * @param thresholdMask PB bits actively driven high
     * @return keyboard contribution to PRB
     */
    public byte readRow(final byte selected, final byte thresholdMask) {
        return readRow(selected, (byte) 0xff, (byte) ~selected, thresholdMask);
    }

    /**
     * Read the PB side of the matrix, including multi-key and same-port paths.
     * Keep actively-high PB outputs high unless their component has two distinct
     * actively-low PA outputs, or a selected SHIFT_LOCK contact. This is a digital
     * approximation of port contention, not a resistor-network simulation.
     *
     * @param paPins effective PA levels, including joystick inputs
     * @param pbPins effective PB levels, including joystick inputs
     * @param paOutputLowMask PRA bits actively driven low (DDRA AND NOT PRA)
     * @param pbOutputHighMask PRB bits actively driven high (DDRB AND PRB)
     * @return keyboard contribution to PRB, to be ANDed with its pin/output mask
     */
    public synchronized byte readRow(final byte paPins, final byte pbPins,
                                     final byte paOutputLowMask, final byte pbOutputHighMask) {
        final long matrix = matrixConnections();
        int lowColumns = connectedLines(matrix, 0, ~pbPins & 0xff) >>> 8;
        int retainedHigh = pbOutputHighMask & 0xff;
        final boolean shiftLock = keysDown.contains(KeyTableEntry.SHIFT_LOCK);

        for (int row = 0; row < 8; row++) {
            final int bit = 1 << row;
            if ((paPins & bit) == 0) {
                final int connected = connectedLines(matrix, bit, 0);
                final int columns = connected >>> 8;
                lowColumns |= columns;

                if ((paOutputLowMask & bit) != 0 && (columns & retainedHigh) != 0) {
                    final int lowOutputs = connected & paOutputLowMask & 0xff;
                    final boolean multipleLowOutputs = (lowOutputs & (lowOutputs - 1)) != 0;
                    if (multipleLowOutputs || shiftLock && row == KeyTableEntry.SHIFT_LOCK.getRow()) {
                        retainedHigh &= ~columns;
                    }
                }
            }
        }
        return (byte) (~lowColumns | retainedHigh);
    }

    /**
     * Get the keyboard contribution to PRB with no opposing PB outputs.
     *
     * @param selected PA pin levels, active low
     * @return keyboard contribution to PRB
     */
    public byte readRow(final byte selected) {
        return readRow(selected, (byte) 0);
    }

    /**
     * Snapshot the physical contacts into one bit per matrix position.
     * Caller holds this keyboard's monitor. No cached state can retain a released
     * ghost key; RESTORE is not a matrix contact and aliases share one bit.
     */
    private long matrixConnections() {
        long matrix = 0;
        for (final KeyTableEntry key : keysDown) {
            final int row = key.getRow();
            final int column = key.getCol();
            if (row >= 0 && row < 8 && column >= 0 && column < 8) {
                matrix |= 1L << (row * 8 + column);
            }
        }
        return matrix;
    }

    /** Return PA rows directly wired to any of the selected PB columns. */
    private static int directlyConnectedRows(final long matrix, final int columns) {
        int rows = 0;
        for (int row = 0; row < 8; row++) {
            if (((matrix >>> (row * 8)) & columns) != 0) {
                rows |= 1 << row;
            }
        }
        return rows;
    }

    /**
     * Reachability over the eight PA and eight PB nodes. Low byte: rows; high
     * byte: columns. Each pass only adds nodes, so the loop always terminates.
     * All scratch state is local; reads never add phantom entries to keysDown.
     */
    private static int connectedLines(final long matrix, int rows, int columns) {
        int previous;
        do {
            previous = rows | (columns << 8);
            for (int row = 0; row < 8; row++) {
                final int rowColumns = (int) (matrix >>> (row * 8)) & 0xff;
                if ((rows & (1 << row)) != 0) {
                    columns |= rowColumns;
                }
                if ((columns & rowColumns) != 0) {
                    rows |= 1 << row;
                }
            }
        } while (previous != (rows | (columns << 8)));
        return rows | (columns << 8);
    }

    /**
     * Restore a key pressed by a user
     */
    public abstract void restore();
}