/*
 * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.InputMethodEvent;
import javafx.scene.input.InputMethodTextRun;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class KeyEventViewer extends Application {

    public static void main(String[] args) {
        Application.launch(KeyEventViewer.class, args);
    }

    private final TextField typing = new TextField();
    private final TextArea logArea = new TextArea("");

    @Override
    public void start(Stage stage) {
        logArea.setEditable(false);
        logArea.setStyle("-fx-font-family: \"Monospaced\"");

        Button clearButton = new Button("Clear");
        clearButton.setOnAction(e -> clearAll());

        HBox topLine = new HBox(typing, clearButton);
        HBox.setHgrow(typing, Priority.ALWAYS);
        topLine.setSpacing(5);

        VBox root = new VBox();
        root.setPadding(new Insets(5));
        root.setSpacing(5);
        VBox.setVgrow(logArea, Priority.ALWAYS);
        root.getChildren().addAll(topLine, logArea);

        typing.addEventFilter(KeyEvent.KEY_PRESSED, this::pressedEvent);
        typing.addEventFilter(KeyEvent.KEY_RELEASED, this::releasedEvent);
        typing.addEventFilter(KeyEvent.KEY_TYPED, this::typedEvent);
        typing.addEventFilter(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, this::inputMethodTextChangedEvent);

        Scene scene = new Scene(root, 640, 640);
        stage.setScene(scene);
        stage.setTitle("Key Event Viewer");
        stage.show();

        Platform.runLater(typing::requestFocus);
    }

    private void clearAll()
    {
        typing.setText("");
        logArea.setText("");
        Platform.runLater(typing::requestFocus);
    }

    private String toPrintable(String s) {
        if (s == null) {
            return "null";
        }
        else if (s.isEmpty()) {
            return "empty";
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isISOControl(c) || Character.isWhitespace(c)) {
                sb.append(String.format("U+%04X", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    private void addToLog(String str) {
        logArea.appendText(str + "\n");
    }

    private void pressedEvent(KeyEvent e) {
        addToLog(" Pressed: " + e.getCode().getName());
        if (e.getCode() == KeyCode.TAB) {
            e.consume();
        }
    }

    private void releasedEvent(KeyEvent e) {
        addToLog("Released: " + e.getCode().getName());
    }

    private void typedEvent(KeyEvent e) {
        String characters = e.getCharacter();
        addToLog("   Typed: " + toPrintable(characters));
    }

    private void inputMethodTextChangedEvent(InputMethodEvent e) {
    	if (!e.getCommitted().isEmpty()) {
    		addToLog("  Commit: " + e.getCommitted());
    	}
        if (!e.getComposed().isEmpty()) {
            String composedText = "";
            for (InputMethodTextRun run : e.getComposed()) {
                composedText += run.getText();
            }
    	    addToLog("Composed: " + composedText);
    	}
    }
}
