KeyboardPane.java

package ui.virtualKeyboard;

import javafx.css.PseudoClass;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import libsidplay.components.keyboard.KeyTableEntry;

import java.util.EnumMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/** Native controls keep their hit targets attached to their rendered keycaps. */
public final class KeyboardPane extends VBox {
    private static final PseudoClass LATCHED = PseudoClass.getPseudoClass("latched");
    private static final PseudoClass HELD = PseudoClass.getPseudoClass("held");
    private final Map<KeyTableEntry, Button> buttons = new EnumMap<>(KeyTableEntry.class);
    private final Map<KeyTableEntry, Label> marks = new EnumMap<>(KeyTableEntry.class);
    private final Label status = new Label();
    private final Button releaseAll = new Button();
    private KeyboardInput input;
    private ResourceBundle bundle;

    public KeyboardPane() {
        getStyleClass().add("virtual-keyboard");
        getStylesheets().add(KeyboardPane.class.getResource("Keyboard.css").toExternalForm());
        setPrefWidth(960);
        setMinWidth(240);
    }

    public void configure(ResourceBundle bundle, Consumer<KeyTableEntry> press,
                          Consumer<KeyTableEntry> release, Consumer<KeyTableEntry> type) {
        if (input != null) input.releaseAll();
        this.bundle = bundle;
        buttons.clear();
        marks.clear();
        input = new KeyboardInput(press, release, type, this::updateState);
        VBox housing = new VBox(24);
        housing.getStyleClass().add("keyboard-case");
        housing.setMinWidth(900);
        Label brand = new Label("C=  commodore");
        Region rainbow = new Region();
        rainbow.getStyleClass().add("keyboard-rainbow");
        Label number = new Label("64");
        HBox badge = new HBox(10, brand, rainbow, number);
        badge.setAlignment(Pos.CENTER_LEFT);
        badge.getStyleClass().add("keyboard-badge");
        Region spring = new Region();
        HBox.setHgrow(spring, Priority.ALWAYS);
        Label powerCaption = new Label("POWER");
        Region powerLed = new Region();
        powerLed.getStyleClass().add("keyboard-power-led");
        HBox power = new HBox(8, powerCaption, powerLed);
        power.setAlignment(Pos.CENTER);
        power.getStyleClass().add("keyboard-power");
        HBox header = new HBox(badge, spring, power);
        header.setAlignment(Pos.CENTER_LEFT);
        header.getStyleClass().add("keyboard-brand");

        GridPane main = new GridPane();
        main.setHgap(4);
        main.setVgap(4);
        main.setMinWidth(764);
        for (int i = 0; i < 32; i++) {
            ColumnConstraints column = new ColumnConstraints();
            column.setPercentWidth(100.0 / 32);
            main.getColumnConstraints().add(column);
        }
        for (int row = 0; row < KeyboardLayout.ROWS.size(); row++) {
            RowConstraints constraints = new RowConstraints(52, 52, Double.MAX_VALUE);
            constraints.setVgrow(Priority.ALWAYS);
            main.getRowConstraints().add(constraints);
            int column = row == 4 ? 6 : 0;
            for (KeyboardLayout.Key key : KeyboardLayout.ROWS.get(row)) {
                main.add(createKey(key, false), column, row, key.span(), 1);
                column += key.span();
            }
        }
        VBox functions = new VBox(4);
        functions.setMinWidth(64);
        functions.setPrefWidth(64);
        for (KeyboardLayout.Key key : KeyboardLayout.FUNCTIONS) {
            Button button = createKey(key, true);
            VBox.setVgrow(button, Priority.ALWAYS);
            functions.getChildren().add(button);
        }
        Region spaceRow = new Region();
        spaceRow.setMinHeight(52);
        spaceRow.setPrefHeight(52);
        VBox.setVgrow(spaceRow, Priority.ALWAYS);
        functions.getChildren().add(spaceRow);
        HBox bed = new HBox(24, main, functions);
        HBox.setHgrow(main, Priority.ALWAYS);
        VBox.setVgrow(bed, Priority.ALWAYS);
        housing.getChildren().addAll(header, bed);
        ScrollPane scroll = new ScrollPane(housing);
        scroll.setFitToWidth(true);
        scroll.setFitToHeight(true);
        scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scroll.getStyleClass().add("keyboard-scroll");
        scroll.setMinHeight(USE_PREF_SIZE);
        VBox.setVgrow(scroll, Priority.ALWAYS);

        status.setWrapText(true);
        status.setMaxWidth(Double.MAX_VALUE);
        status.setMinWidth(0);
        status.setAccessibleRole(javafx.scene.AccessibleRole.TEXT);
        HBox.setHgrow(status, Priority.ALWAYS);
        releaseAll.setText(bundle.getString("RELEASE_ALL"));
        releaseAll.setOnAction(event -> input.releaseAll());
        releaseAll.getStyleClass().add("keyboard-release-all");
        HBox strip = new HBox(12, status, releaseAll);
        strip.setAlignment(Pos.CENTER_LEFT);
        strip.getStyleClass().add("keyboard-status");
        Label help = new Label(bundle.getString("LEGEND_MOUSE_LEFT") + " " + bundle.getString("LEGEND_MOUSE_RIGHT")
            + " " + bundle.getString("LEGEND_SHIFT_LOCK"));
        help.setWrapText(true);
        help.getStyleClass().add("keyboard-help");
        getChildren().setAll(scroll, strip, help);
        updateState();
    }

    private Button createKey(KeyboardLayout.Key key, boolean function) {
        Button button = new Button();
        button.setId("key-" + key.id().name());
        button.setUserData(key.id());
        button.setAccessibleText(keyName(key.id()));
        button.getStyleClass().add("keyboard-key");
        button.setMinHeight(52);
        button.setPrefHeight(52);
        button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
        GridPane.setHgrow(button, Priority.ALWAYS);
        GridPane.setVgrow(button, Priority.ALWAYS);
        Label primary = new Label(key.label());
        primary.getStyleClass().add(key.label().length() > 2 ? "keyboard-key-word" : "keyboard-key-primary");
        Label secondary = new Label(key.shifted());
        secondary.getStyleClass().add("keyboard-key-secondary");
        VBox caption = new VBox(1);
        caption.setAlignment(Pos.CENTER);
        if (key.shifted().isEmpty()) caption.getChildren().add(primary);
        else caption.getChildren().addAll(function ? primary : secondary, function ? secondary : primary);
        Label mark = new Label("●");
        mark.getStyleClass().add("keyboard-latch-mark");
        mark.setMouseTransparent(true);
        marks.put(key.id(), mark);
        StackPane graphic = new StackPane(caption, mark);
        StackPane.setAlignment(mark, Pos.TOP_LEFT);
        graphic.setMouseTransparent(true);
        graphic.setMaxWidth(Double.MAX_VALUE);
        button.setGraphic(graphic);
        button.setOnAction(event -> {
            if (key.id() == KeyTableEntry.SHIFT_LOCK) input.toggle(key.id());
            else input.tap(key.id());
        });
        button.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
            if (event.getButton() == MouseButton.PRIMARY) {
                button.requestFocus();
                if (key.id() != KeyTableEntry.SHIFT_LOCK && key.id() != KeyTableEntry.RESTORE)
                    input.hold(key.id(), button);
            }
            event.consume(); // Keep Button's automatic action from duplicating mouse input.
        });
        button.addEventFilter(MouseEvent.MOUSE_RELEASED, event -> {
            if (event.getButton() == MouseButton.PRIMARY) {
                if (key.id() == KeyTableEntry.SHIFT_LOCK || key.id() == KeyTableEntry.RESTORE) {
                    if (button.contains(event.getX(), event.getY())) button.fire();
                } else input.release(key.id(), button);
            } else if (event.getButton() == MouseButton.SECONDARY && button.contains(event.getX(), event.getY())) {
                input.toggle(key.id());
            }
            event.consume();
        });
        button.setOnContextMenuRequested(event -> event.consume());
        buttons.put(key.id(), button);
        return button;
    }

    private String keyName(KeyTableEntry key) {
        return switch (key) {
            case SHIFT_LEFT -> bundle.getString("SHIFT_LEFT");
            case SHIFT_RIGHT -> bundle.getString("SHIFT_RIGHT");
            default -> key.name().replace('_', ' ');
        };
    }

    private void updateState() {
        if (input == null) return;
        buttons.forEach((key, button) -> {
            button.pseudoClassStateChanged(LATCHED, input.isLatched(key));
            button.pseudoClassStateChanged(HELD, input.isHeld(key));
            marks.get(key).setVisible(input.isLatched(key));
        });
        String names = input.latched().stream().sorted().map(this::keyName).collect(Collectors.joining(" + "));
        status.setText(names.isEmpty() ? bundle.getString("NO_LATCHED_KEYS") : bundle.getString("LATCHED") + ": " + names);
        releaseAll.setDisable(!input.isDown());
    }

    public void releaseMomentary() { if (input != null) input.releaseMomentary(); }
    public void releaseAll() { if (input != null) input.releaseAll(); }
}