RasterTimelineView.java

package ui.vic;

import javafx.collections.FXCollections;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import libsidutils.debug.InspectionTimeline;
import libsidutils.debug.InspectionTimeline.Change;

import java.io.File;
import java.nio.file.Files;
import java.util.ResourceBundle;
import java.util.function.Consumer;
import java.util.function.IntConsumer;

/**
 * Presents a detached change log. Selecting history never reads or rewinds the emulator.
 */
final class RasterTimelineView extends VBox {
    private final ResourceBundle bundle;
    private final Button record, cancel, clear, save;
    private final Label status = new Label(), metadata = new Label(), detail = new Label();
    private final Canvas chart = new Canvas(960, 292);
    private final ListView<Change> events = new ListView<>();
    private final VBox history;
    private InspectionTimeline timeline;
    private int selectedSprite;
    private boolean running, paused;

    RasterTimelineView(ResourceBundle bundle, Consumer<String> command, IntConsumer selectSprite) {
        super(10);
        this.bundle = bundle;
        record = button("RECORD", "recordTimeline", () -> command.accept("RECORD_TIMELINE"));
        cancel = button("CANCEL", "cancelTimeline", () -> command.accept("CANCEL_TIMELINE"));
        clear = button("CLEAR", "clearTimeline", () -> command.accept("CLEAR_TIMELINE"));
        save = button("SAVE", "saveTimeline", this::save);
        status.setId("timelineStatus");
        chart.setId("rasterTimeline");
        events.setId("timelineEvents");
        events.setPrefHeight(115);
        events.setCellFactory(view -> new ListCell<>() {
            @Override
            protected void updateItem(Change event, boolean empty) {
                super.updateItem(event, empty);
                setText(empty || event == null ? null : position(event) + " · " + field(event.field())
                        + " " + hex(event.previous(), 2) + " → " + hex(event.value(), 2));
            }
        });
        events.getSelectionModel().selectedItemProperty().addListener((observable, previous, selected) -> paint());
        Button start = button("START", "timelineStart", () -> events.getSelectionModel().clearSelection());
        detail.setWrapText(true);
        detail.setStyle("-fx-font-family: monospace; -fx-font-size: 12px;");
        Pane picture = new Pane(chart);
        picture.setPrefHeight(292);
        widthProperty().addListener((observable, previous, width) -> {
            chart.setWidth(Math.max(360, Math.min(960, width.doubleValue())));
            paint();
        });
        chart.setOnMouseClicked(mouse -> {
            if (timeline == null || timeline.initial().length == 0) return;
            int sprite = (int) ((mouse.getY() - 32) / 26);
            if (mouse.getY() < 32 || sprite > 8) return;
            if (sprite < 8) {
                selectedSprite = sprite;
                selectSprite.accept(sprite);
            }
            double tick = Math.max(0, Math.min(timeline.durationTicks(),
                    (mouse.getX() - 62) / (chart.getWidth() - 80) * total()));
            int closest = -1;
            double distance = tick;
            for (int i = 0; i < timeline.events().size(); i++) {
                Change change = timeline.events().get(i);
                if (sprite < 8 && (InspectionTimeline.spriteMask(change) & (1 << sprite)) == 0) continue;
                double delta = Math.abs(change.tick() - tick);
                if (delta < distance) {
                    closest = i;
                    distance = delta;
                }
            }
            events.getSelectionModel().select(closest);
            if (closest >= 0) events.scrollTo(closest);
            paint();
        });
        history = new VBox(8, metadata, picture, start, events, detail, help("HISTORYHELP"));
        getChildren().addAll(new FlowPane(8, 8, record, cancel, clear, save, status), help("HELP"), history);
        setTimeline(null);
    }

    private String text(String key) {
        return bundle.getString("TIMELINE" + (key.isEmpty() ? "" : "_" + key));
    }

    private Button button(String key, String id, Runnable action) {
        Button button = new Button(text(key));
        button.setId(id);
        button.setOnAction(event -> action.run());
        return button;
    }

    private Label help(String key) {
        Label label = new Label(text(key));
        label.setWrapText(true);
        label.setStyle("-fx-font-size: 11px;");
        return label;
    }

    void setPlayback(boolean running, boolean paused) {
        this.running = running;
        this.paused = paused;
        updateButtons();
    }

    void setTimeline(InspectionTimeline timeline) {
        if (this.timeline == timeline && timeline != null) return;
        this.timeline = timeline;
        events.setItems(FXCollections.observableArrayList(timeline == null ? java.util.List.of() : timeline.events()));
        events.getSelectionModel().clearSelection();
        boolean available = timeline != null && timeline.initial().length != 0;
        history.setVisible(available);
        history.setManaged(available);
        status.setText(text(timeline == null ? "OFF" : timeline.status()));
        if (available)
            metadata.setText(timeline.chip() + " · t=" + timeline.startTime() + " · " + timeline.rasterLines()
                    + " " + text("RASTERS") + " · " + timeline.events().size() + " " + text("CHANGES"));
        updateButtons();
        paint();
    }

    void setSelectedSprite(int sprite) {
        if (selectedSprite == sprite) return;
        selectedSprite = sprite;
        paint();
    }

    private void updateButtons() {
        boolean busy = timeline != null && timeline.recording();
        record.setDisable(!running || paused || busy);
        cancel.setVisible(busy);
        cancel.setManaged(busy);
        clear.setDisable(timeline == null || busy);
        save.setDisable(timeline == null || timeline.initial().length == 0);
    }

    private int total() {
        return timeline.cyclesPerLine() * timeline.rasterLines() * 2;
    }

    private double x(int tick) {
        return 62 + tick * (chart.getWidth() - 80) / total();
    }

    private void paint() {
        if (timeline == null || timeline.initial().length == 0) return;
        var graphics = chart.getGraphicsContext2D();
        graphics.setFill(Color.web("#0d171f"));
        graphics.fillRect(0, 0, chart.getWidth(), chart.getHeight());
        graphics.setFont(Font.font("Monospaced", 12));
        for (int raster = 0; raster < timeline.rasterLines(); raster += 50) {
            double x = x(raster * timeline.cyclesPerLine() * 2);
            graphics.setStroke(Color.web("#465763"));
            graphics.strokeLine(x, 26, x, 268);
            graphics.setFill(Color.web("#cad7df"));
            graphics.fillText(Integer.toString(raster), x, 17);
        }
        for (int sprite = 0; sprite < 9; sprite++) {
            double y = 32 + sprite * 26;
            graphics.setFill(Color.web(sprite == selectedSprite ? "#f4b37f" : "#cad7df"));
            graphics.fillText(sprite < 8 ? "#" + sprite : "VIC", 7, y + 15);
            if (sprite < 8) for (boolean dma : new boolean[]{false, true}) {
                graphics.setFill(Color.web(dma ? "#75cec8" : "#35566a"));
                for (var span : timeline.spans(sprite, dma))
                    graphics.fillRect(x(span.start()), y + (dma ? 7 : 3), x(span.end()) - x(span.start()), dma ? 7 : 15);
            }
            graphics.setStroke(Color.web("#f4b37f"));
            int previousX = -1;
            for (Change event : timeline.events()) {
                if (sprite == 8 ? event.field() >= 64 && event.field() != InspectionTimeline.BANK
                        : (InspectionTimeline.spriteMask(event) & (1 << sprite)) == 0) continue;
                int px = (int) x(event.tick());
                if (px != previousX) graphics.strokeLine(px, y + 1, px, y + 20);
                previousX = px;
            }
        }
        if (timeline.durationTicks() < total()) {
            graphics.setFill(Color.web("#8595a544"));
            graphics.fillRect(x(timeline.durationTicks()), 26, x(total()) - x(timeline.durationTicks()), 242);
        }
        Change event = events.getSelectionModel().getSelectedItem();
        graphics.setStroke(Color.WHITE);
        graphics.strokeLine(x(event == null ? 0 : event.tick()), 26, x(event == null ? 0 : event.tick()), 268);
        graphics.setFill(Color.web("#cad7df"));
        graphics.fillText(text("LEGEND"), 62, 286);
        int[] state = timeline.stateAt(event == null ? 0 : event.tick());
        int bit = 1 << selectedSprite;
        detail.setText((event == null ? text("START") + " · 0:" + timeline.startCycle() + " PHI1"
                : position(event) + " · " + field(event.field()) + " " + hex(event.previous(), 2) + " → " + hex(event.value(), 2))
                + "\n" + String.format(text("RECORDEDSPRITE"), selectedSprite)
                + " · X " + (state[selectedSprite * 2] + ((state[0x10] & bit) != 0 ? 256 : 0))
                + " · Y " + state[selectedSprite * 2 + 1] + " · " + text("ENABLED") + " " + yes(state[0x15] & bit)
                + " · DMA " + yes(state[InspectionTimeline.DMA] & bit) + "\n"
                + bundle.getString("BANK") + " " + hex(state[InspectionTimeline.BANK], 4)
                + " · " + text("POINTER") + " " + hex(state[InspectionTimeline.POINTERS + selectedSprite], 2)
                + " · " + bundle.getString("MULTICOLOR") + " " + yes(state[0x1c] & bit)
                + " · X×" + ((state[0x1d] & bit) != 0 ? 2 : 1) + " / Y×" + ((state[0x17] & bit) != 0 ? 2 : 1));
    }

    private String yes(int value) {
        return value != 0 ? "1" : "0";
    }

    private String position(Change event) {
        return bundle.getString("RASTER") + " " + event.raster() + " · " + bundle.getString("CYCLE") + " "
                + event.cycle() + " · " + event.phase();
    }

    private String field(int field) {
        return field < 64 ? hex(0xd000 + field, 4) : field == InspectionTimeline.DMA ? "DMA"
                : field == InspectionTimeline.BANK ? bundle.getString("BANK") : bundle.getString("SPRITE") + " #" + (field - InspectionTimeline.POINTERS) + " " + text("POINTER");
    }

    private static String hex(int value, int digits) {
        return value < 0 ? "?" : "$" + String.format("%0" + digits + "X", value);
    }

    private void save() {
        if (timeline == null) return;
        FileChooser chooser = new FileChooser();
        chooser.setTitle(text("SAVE"));
        chooser.setInitialFileName("vic-timeline-" + timeline.chip() + "-" + timeline.startTime() + ".json");
        chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON", "*.json"));
        File file = chooser.showSaveDialog(getScene().getWindow());
        if (file != null) try {
            Files.writeString(file.toPath(), timeline.toJson());
        } catch (Exception failure) {
            status.setText(failure.getMessage());
        }
    }
}