From 374e783f68674139307f29d978234039b1a831e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:06:15 +0000 Subject: [PATCH 1/4] Raise core module test coverage from 11% to 93% - Add tests for KeyboardPane, KeyboardRegion (layout parser), KeyButtonEventHandler, key buttons, timelines, MultiKeyPopup, KeyBoardPopup and its builders, FXRobotHandler and FXOK - Add FxTestSupport: starts the JavaFX toolkit once and skips FX tests when no display is available instead of hanging until timeout - Fix crash on empty keyLabelStyle/keyIconStyle attributes, which aborted parsing of the rest of the layout - Add JaCoCo coverage report (target/site/jacoco) - CI: run tests under xvfb, upload surefire reports from all modules and the coverage report Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVKTE7YjM5Y9LLQ8NcRuzC --- .github/workflows/ci.yml | 13 +- fx-onscreen-keyboard/pom.xml | 5 + .../keyboard/control/KeyboardRegion.java | 2 + .../org/comtel2000/keyboard/FXOKTest.java | 88 +++ .../keyboard/control/FxTestSupport.java | 141 +++++ .../keyboard/control/KeyBoardPopupTest.java | 333 +++++++++++ .../control/KeyButtonEventHandlerTest.java | 247 ++++++++ .../keyboard/control/KeyButtonTest.java | 180 ++---- .../keyboard/control/KeyButtonsTest.java | 275 +++++++++ .../keyboard/control/KeyboardPaneTest.java | 525 ++++++++++++++++++ .../keyboard/control/KeyboardRegionTest.java | 217 ++++++++ .../keyboard/control/MultiKeyPopupTest.java | 116 ++++ .../keyboard/control/TimelinesTest.java | 124 +++++ .../keyboard/robot/FXRobotHandlerTest.java | 160 ++++++ .../keyboard/robot/RecordingRobot.java | 37 ++ .../keyboard/xml/XmlHelperTest.java | 57 ++ .../resources/xml/region/kb-empty-style.xml | 7 + .../test/resources/xml/region/kb-features.xml | 20 + .../test/resources/xml/region/kb-invalid.xml | 8 + pom.xml | 26 + 20 files changed, 2459 insertions(+), 122 deletions(-) create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/FXOKTest.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/FxTestSupport.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyBoardPopupTest.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonEventHandlerTest.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonsTest.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyboardPaneTest.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyboardRegionTest.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/MultiKeyPopupTest.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/TimelinesTest.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/robot/FXRobotHandlerTest.java create mode 100644 fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/robot/RecordingRobot.java create mode 100644 fx-onscreen-keyboard/src/test/resources/xml/region/kb-empty-style.xml create mode 100644 fx-onscreen-keyboard/src/test/resources/xml/region/kb-features.xml create mode 100644 fx-onscreen-keyboard/src/test/resources/xml/region/kb-invalid.xml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cf444911..3a90cfee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,10 +26,17 @@ jobs: java-package: jdk+fx # optional (jdk, jre, jdk+fx or jre+fx) - defaults to jdk cache: maven - name: Build with Maven - run: mvn -B test --file pom.xml + # JavaFX tests need a display; xvfb is preinstalled on ubuntu runners + run: xvfb-run -a mvn -B test --file pom.xml - name: Upload test logs on failure if: failure() uses: actions/upload-artifact@v4 with: - name: test-logs - path: target/surefire-reports/** + name: test-logs-jdk${{ matrix.java-version }} + path: '**/target/surefire-reports/**' + - name: Upload coverage report + if: matrix.java-version == 17 + uses: actions/upload-artifact@v4 + with: + name: coverage-report + path: '**/target/site/jacoco/**' diff --git a/fx-onscreen-keyboard/pom.xml b/fx-onscreen-keyboard/pom.xml index 723a36eb..5482cdd7 100644 --- a/fx-onscreen-keyboard/pom.xml +++ b/fx-onscreen-keyboard/pom.xml @@ -24,6 +24,11 @@ junit-jupiter-engine test + + org.junit.jupiter + junit-jupiter-params + test + org.slf4j slf4j-api diff --git a/fx-onscreen-keyboard/src/main/java/org/comtel2000/keyboard/control/KeyboardRegion.java b/fx-onscreen-keyboard/src/main/java/org/comtel2000/keyboard/control/KeyboardRegion.java index d370294b..58d3c391 100644 --- a/fx-onscreen-keyboard/src/main/java/org/comtel2000/keyboard/control/KeyboardRegion.java +++ b/fx-onscreen-keyboard/src/main/java/org/comtel2000/keyboard/control/KeyboardRegion.java @@ -154,6 +154,7 @@ private void build(URL layout) { button.getStyleClass().add("sticky-style"); } readAttribute(reader, ATTR_KEY_LABEL_STYLE) + .filter(s -> !s.isEmpty()) .ifPresent( s -> { if (s.charAt(0) == '.') { @@ -184,6 +185,7 @@ private void build(URL layout) { } readAttribute(reader, ATTR_KEY_ICON_STYLE) + .filter(s -> !s.isEmpty()) .ifPresent( s -> { if (s.charAt(0) == '.') { diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/FXOKTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/FXOKTest.java new file mode 100644 index 00000000..8a12ba16 --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/FXOKTest.java @@ -0,0 +1,88 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard; + +import static org.comtel2000.keyboard.control.FxTestSupport.runFx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Map; +import javafx.scene.control.TextField; +import javafx.scene.layout.HBox; +import org.comtel2000.keyboard.control.FxTestSupport; +import org.comtel2000.keyboard.control.KeyBoardPopup; +import org.comtel2000.keyboard.control.KeyBoardPopup.Visibility; +import org.comtel2000.keyboard.control.KeyboardPane; +import org.comtel2000.keyboard.control.VkProperties; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class FXOKTest { + + @BeforeAll + static void initToolkit() { + FxTestSupport.startToolkit(); + } + + @AfterEach + void reset() { + FXOK.registerPopup(null); + } + + @Test + void vkPropertiesFromNode() { + runFx( + () -> { + var field = new TextField(); + field.getProperties().put(VkProperties.VK_TYPE, VkProperties.VK_TYPE_NUMERIC); + field.getProperties().put(VkProperties.VK_LOCALE, VkProperties.VK_LOCALE_DE); + field.getProperties().put("other", "ignored"); + assertEquals( + Map.of( + VkProperties.VK_TYPE, VkProperties.VK_TYPE_NUMERIC, + VkProperties.VK_LOCALE, VkProperties.VK_LOCALE_DE), + FXOK.getVkProperties(field)); + }); + } + + @Test + void vkPropertiesFromParent() { + runFx( + () -> { + var field = new TextField(); + var parent = new HBox(field); + parent.getProperties().put(VkProperties.VK_STATE, VkProperties.VK_STATE_DISABLED); + parent.getProperties().put("x", 1); + assertEquals( + Map.of(VkProperties.VK_STATE, VkProperties.VK_STATE_DISABLED), + FXOK.getVkProperties(field)); + }); + } + + @Test + void noVkProperties() { + runFx( + () -> { + assertTrue(FXOK.getVkProperties(new TextField()).isEmpty()); + assertTrue( + FXOK.getVkProperties(new HBox(new TextField()).getChildren().get(0)).isEmpty()); + }); + } + + @Test + void registerPopup() { + runFx( + () -> { + assertNull(FXOK.getPopup()); + // without popup this is a no-op + FXOK.setVisible(Visibility.SHOW, new TextField()); + + var popup = new KeyBoardPopup(new KeyboardPane()); + FXOK.registerPopup(popup); + assertSame(popup, FXOK.getPopup()); + FXOK.setVisible(Visibility.HIDE, new TextField()); + }); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/FxTestSupport.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/FxTestSupport.java new file mode 100644 index 00000000..45b452de --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/FxTestSupport.java @@ -0,0 +1,141 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.control; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import javafx.application.Platform; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Assumptions; + +/** + * Starts the JavaFX toolkit once for all tests and runs code on the FX application thread. + * + *

If the toolkit cannot be started (for example no display is available), the calling test is + * skipped instead of hanging until it times out. + */ +public final class FxTestSupport { + + private static final long TIMEOUT_SECONDS = 10; + + private static volatile Boolean toolkitAvailable; + + private FxTestSupport() {} + + /** Functional interface for test code that may throw. */ + @FunctionalInterface + public interface FxAction { + T call() throws Exception; + } + + /** Functional interface for test code without a result that may throw. */ + @FunctionalInterface + public interface FxRunnable { + void run() throws Exception; + } + + /** Start the JavaFX toolkit or skip the calling test if this is not possible. */ + public static synchronized void startToolkit() { + if (toolkitAvailable == null) { + toolkitAvailable = tryStartToolkit(); + if (toolkitAvailable) { + // closing the last test stage must not shut down the toolkit for the following tests + Platform.setImplicitExit(false); + } + } + Assumptions.assumeTrue(toolkitAvailable, "JavaFX toolkit not available (no display?)"); + } + + private static boolean tryStartToolkit() { + var started = new CountDownLatch(1); + try { + Platform.startup(started::countDown); + } catch (IllegalStateException e) { + // toolkit already running + return true; + } catch (RuntimeException | Error e) { + System.err.println("JavaFX toolkit could not be started: " + e); + return false; + } + try { + return started.await(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + /** Run {@code action} on the FX application thread and return its result. */ + public static T callFx(FxAction action) { + startToolkit(); + if (Platform.isFxApplicationThread()) { + try { + return action.call(); + } catch (Exception e) { + return Assertions.fail(e); + } + } + var latch = new CountDownLatch(1); + var result = new AtomicReference(); + var error = new AtomicReference(); + Platform.runLater( + () -> { + try { + result.set(action.call()); + } catch (Throwable t) { + error.set(t); + } finally { + latch.countDown(); + } + }); + try { + Assertions.assertTrue( + latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS), "FX action did not finish in time"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + Assertions.fail(e); + } + var t = error.get(); + if (t instanceof Error err) { + throw err; + } + if (t instanceof RuntimeException re) { + throw re; + } + if (t != null) { + Assertions.fail(t); + } + return result.get(); + } + + /** Run {@code action} on the FX application thread and wait until it is done. */ + public static void runFx(FxRunnable action) { + callFx( + () -> { + action.run(); + return null; + }); + } + + /** Wait until all events queued on the FX application thread so far have been processed. */ + public static void waitForFxEvents() { + runFx(() -> {}); + } + + /** Poll {@code condition} on the FX thread until it is true or the timeout is reached. */ + public static boolean waitFor(FxAction condition, long timeoutMillis) { + long end = System.currentTimeMillis() + timeoutMillis; + while (System.currentTimeMillis() < end) { + if (Boolean.TRUE.equals(callFx(condition))) { + return true; + } + try { + Thread.sleep(20); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + return Boolean.TRUE.equals(callFx(condition)); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyBoardPopupTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyBoardPopupTest.java new file mode 100644 index 00000000..acae8752 --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyBoardPopupTest.java @@ -0,0 +1,333 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.control; + +import static org.comtel2000.keyboard.control.FxTestSupport.callFx; +import static org.comtel2000.keyboard.control.FxTestSupport.runFx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; +import javafx.event.Event; +import javafx.scene.Scene; +import javafx.scene.control.Button; +import javafx.scene.control.ComboBox; +import javafx.scene.control.TextField; +import javafx.scene.input.MouseButton; +import javafx.scene.input.MouseEvent; +import javafx.scene.layout.VBox; +import javafx.stage.Stage; +import javafx.stage.WindowEvent; +import org.comtel2000.keyboard.control.KeyBoardPopup.Visibility; +import org.comtel2000.keyboard.robot.RecordingRobot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class KeyBoardPopupTest { + + private Stage stage; + private TextField field; + private Button button; + private KeyBoardPopup popup; + + @BeforeAll + static void initToolkit() { + FxTestSupport.startToolkit(); + } + + @BeforeEach + void setUp() { + runFx( + () -> { + field = new TextField(); + button = new Button("b"); + stage = new Stage(); + stage.setScene(new Scene(new VBox(field, button), 300, 200)); + stage.setX(50); + stage.setY(50); + stage.show(); + popup = + KeyBoardPopupBuilder.create() + .initLocale(Locale.ENGLISH) + .addIRobot(new RecordingRobot()) + .build(); + }); + } + + @AfterEach + void tearDown() { + runFx( + () -> { + popup.hide(); + stage.close(); + }); + } + + private boolean showing() { + return callFx(popup::isShowing); + } + + private void waitHidden() { + assertTrue(FxTestSupport.waitFor(() -> !popup.isShowing(), 3000), "popup did not hide"); + } + + @Test + void builderAppliesSettings() { + runFx( + () -> { + var robot = new RecordingRobot(); + var closed = new AtomicInteger(); + var p = + KeyBoardPopupBuilder.create() + .initLocale(Locale.GERMAN) + .initScale(1.5) + .layer(DefaultLayer.NUMBLOCK) + .layerPath(null) + .style("-fx-font-size: 10;") + .offset(12) + .addIRobot(robot) + .onKeyboardCloseButton(e -> closed.incrementAndGet()) + .build(); + var kb = p.getKeyBoard(); + assertEquals(Locale.GERMAN, kb.getActiveLocale()); + assertEquals(1.5, kb.getScale()); + assertEquals(DefaultLayer.NUMBLOCK, kb.getLayer()); + assertEquals("-fx-font-size: 10;", kb.getStyle()); + assertEquals(12, p.getOffset()); + assertSame(robot, kb.getRobotHandler().get(0)); + assertTrue(p.getContent().contains(kb)); + }); + } + + @Test + void keyBoardBuilder() { + runFx( + () -> { + var b = KeyBoardBuilder.create(); + b.initLocale(Locale.ENGLISH); + b.layer(DefaultLayer.DEFAULT); + b.layerPath(null); + b.style("-fx-background-color: red;"); + b.initScale(1.0); + b.addIRobot(new RecordingRobot()); + var kb = b.build(); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + }); + } + + @Test + void offsetProperty() { + runFx( + () -> { + assertEquals(5, popup.getOffset()); + popup.setOffset(7); + assertEquals(7, popup.offsetProperty().get()); + popup.setOffset(8); + assertEquals(8, popup.getOffset()); + }); + } + + @Test + void requiresKeyboardAndScene() { + runFx( + () -> { + assertThrows(NullPointerException.class, () -> new KeyBoardPopup(null)); + assertThrows(NullPointerException.class, () -> popup.registerScene(null)); + assertTrue(KeyBoardPopup.getUserAgentStyleSheet().endsWith("KeyboardTextInputSkin.css")); + assertNotNull(popup.getFocusChangeListener()); + assertNotNull(popup.getDoubleClickEventFilter()); + }); + } + + @Test + void showBelowTextFieldAndHide() { + runFx(() -> popup.setVisible(Visibility.SHOW, field)); + assertTrue(showing()); + runFx( + () -> { + assertTrue(popup.isVisible()); + var bounds = field.localToScreen(field.getBoundsInLocal()); + assertEquals(bounds.getMinX(), popup.getX(), 1.0); + assertEquals(bounds.getMaxY() + popup.getOffset(), popup.getY(), 1.0); + assertEquals(KeyboardType.TEXT, popup.getKeyBoard().getActiveType()); + }); + + runFx(() -> popup.setVisible(false)); + waitHidden(); + } + + @Test + void hideWhenNotShowingIsNoOp() { + runFx(() -> popup.setVisible(Visibility.HIDE, field)); + assertFalse(showing()); + } + + @Test + void positionOnlyDoesNotOpen() { + runFx(() -> popup.setVisible(Visibility.POS, field)); + assertFalse(showing()); + } + + @Test + void vkPropertiesSelectLayoutAndLocale() { + runFx( + () -> { + field.getProperties().put(VkProperties.VK_TYPE, VkProperties.VK_TYPE_NUMERIC); + field.getProperties().put(VkProperties.VK_LOCALE, VkProperties.VK_LOCALE_DE); + popup.setVisible(Visibility.SHOW, field); + assertEquals(Locale.GERMAN, popup.getKeyBoard().getActiveLocale()); + }); + assertTrue(showing()); + } + + @Test + void vkTypeIsApplied() { + runFx( + () -> { + field.getProperties().put(VkProperties.VK_TYPE, VkProperties.VK_TYPE_NUMERIC); + popup.setVisible(Visibility.SHOW, field); + assertEquals(KeyboardType.NUMERIC, popup.getKeyBoard().getActiveType()); + }); + } + + @Test + void vkStateOffHidesKeyboard() { + runFx(() -> popup.setVisible(Visibility.SHOW, field)); + assertTrue(showing()); + runFx( + () -> { + field.getProperties().put(VkProperties.VK_STATE, VkProperties.VK_STATE_DISABLED); + popup.setVisible(Visibility.SHOW, field); + }); + waitHidden(); + } + + @Test + void showWithoutTextNodeUsesRegisteredScene() { + runFx( + () -> { + popup.registerScene(stage.getScene()); + assertSame(stage.getScene(), popup.getRegisteredScene()); + popup.setVisible(true); + }); + assertTrue(showing()); + runFx(() -> assertSame(stage, popup.getOwnerWindow())); + } + + @Test + void focusListenerShowsAndHides() { + runFx( + () -> { + button.requestFocus(); + popup.addFocusListener(stage.getScene()); + field.requestFocus(); + }); + assertTrue(FxTestSupport.waitFor(popup::isShowing, 3000)); + runFx(button::requestFocus); + waitHidden(); + } + + @Test + void focusListenerFindsNestedTextField() { + runFx( + () -> { + var combo = new ComboBox(); + combo.setEditable(true); + ((VBox) stage.getScene().getRoot()).getChildren().add(combo); + combo.applyCss(); + popup.getFocusChangeListener().changed(null, null, combo); + }); + assertTrue(showing()); + } + + @Test + void focusListenerDoNotOpen() { + runFx( + () -> { + button.requestFocus(); + popup.addFocusListener(stage.getScene(), true); + field.requestFocus(); + }); + FxTestSupport.waitForFxEvents(); + assertFalse(showing()); + } + + @Test + void doubleClickOpensKeyboard() { + runFx( + () -> { + popup.addDoubleClickEventFilter(stage); + field.requestFocus(); + popup.getDoubleClickEventFilter().handle(click(stage, 1)); + }); + assertFalse(showing(), "single click does nothing"); + runFx(() -> popup.getDoubleClickEventFilter().handle(click(stage, 2))); + assertTrue(showing()); + } + + @Test + void globalListenersAreAddedToNewWindows() { + var other = callFx(Stage::new); + var otherField = callFx(TextField::new); + runFx( + () -> { + popup.addGlobalFocusListener(); + popup.addGlobalDoubleClickEventFilter(); + other.setScene(new Scene(new VBox(otherField), 100, 100)); + other.show(); + otherField.requestFocus(); + }); + assertTrue(FxTestSupport.waitFor(popup::isShowing, 3000)); + runFx(other::close); + } + + @Test + void defaultCloseButtonHidesPopup() { + runFx(() -> popup.setVisible(Visibility.SHOW, field)); + assertTrue(showing()); + runFx(() -> popup.getKeyBoard().fireCloseEvent(new Event(Event.ANY))); + waitHidden(); + } + + @Test + void defaultCloseHandlerFiresWindowCloseRequest() { + runFx( + () -> { + var requests = new AtomicInteger(); + button.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, e -> requests.incrementAndGet()); + KeyBoardPopup.DEFAULT_CLOSE_HANDLER.handle(new Event(button, button, Event.ANY)); + KeyBoardPopup.DEFAULT_CLOSE_HANDLER.handle(new Event("no node", null, Event.ANY)); + assertEquals(1, requests.get()); + }); + } + + private static MouseEvent click(Stage source, int clickCount) { + return new MouseEvent( + source, + source, + MouseEvent.MOUSE_CLICKED, + 0, + 0, + 0, + 0, + MouseButton.PRIMARY, + clickCount, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + null); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonEventHandlerTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonEventHandlerTest.java new file mode 100644 index 00000000..d21815b0 --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonEventHandlerTest.java @@ -0,0 +1,247 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.control; + +import static org.comtel2000.keyboard.control.FxTestSupport.runFx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.awt.event.KeyEvent; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicReference; +import javafx.animation.Animation; +import javafx.event.Event; +import javafx.scene.Scene; +import javafx.stage.Stage; +import org.comtel2000.keyboard.event.KeyButtonEvent; +import org.comtel2000.keyboard.robot.RecordingRobot; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class KeyButtonEventHandlerTest { + + private RecordingRobot robot; + private KeyboardPane kb; + + @BeforeAll + static void initToolkit() { + FxTestSupport.startToolkit(); + } + + @BeforeEach + void setUp() { + robot = new RecordingRobot(); + kb = FxTestSupport.callFx(() -> KeyboardPaneTest.loadedKeyboard(Locale.ENGLISH, robot)); + } + + private void press(int keyCode) { + press(keyCode, null, null); + } + + private void press(int keyCode, String text, String keyText) { + var button = new ShortPressKeyButton(); + button.setKeyCode(keyCode); + button.setText(text); + button.setKeyText(keyText); + var event = new KeyButtonEvent(button, KeyButtonEvent.SHORT_PRESSED); + kb.handle(event); + assertTrue(event.isConsumed()); + } + + @Test + void printableKeyIsSent() { + runFx( + () -> { + press('a'); + assertEquals("a", robot.text()); + assertFalse(robot.last().ctrl()); + }); + } + + @Test + void keyOutputTextIsSentCharByChar() { + runFx( + () -> { + press('w', "www", "www."); + assertEquals("www.", robot.text()); + }); + } + + @Test + void unknownNegativeKeyIsSentWithCtrl() { + runFx( + () -> { + press(-99); + assertEquals(1, robot.sent().size()); + assertTrue(robot.last().ctrl()); + }); + } + + @Test + void controlModeSendsCtrlFlag() { + runFx( + () -> { + press(StandardKeyCode.CTRL_DOWN); + assertTrue(kb.isControl()); + assertEquals(KeyboardType.CTRL, kb.getActiveType()); + press('c'); + assertTrue(robot.last().ctrl()); + + press(StandardKeyCode.CTRL_DOWN); + assertFalse(kb.isControl()); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + }); + } + + @Test + void shiftAndSymbolToggleLayout() { + runFx( + () -> { + press(StandardKeyCode.SHIFT_DOWN); + assertEquals(KeyboardType.TEXT_SHIFT, kb.getActiveType()); + press(StandardKeyCode.SYMBOL_DOWN); + assertEquals(KeyboardType.SYMBOL_SHIFT, kb.getActiveType()); + press(StandardKeyCode.SHIFT_DOWN); + assertEquals(KeyboardType.SYMBOL, kb.getActiveType()); + press(StandardKeyCode.SYMBOL_DOWN); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + }); + } + + @Test + void shiftIsReleasedAfterKeyWithoutCapsLock() { + runFx( + () -> { + press(StandardKeyCode.CAPS_LOCK); + assertFalse(kb.isCapsLock()); + press(StandardKeyCode.SHIFT_DOWN); + assertTrue(kb.isShift()); + press('A'); + assertFalse(kb.isShift()); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + }); + } + + @Test + void shiftStaysWithCapsLock() { + runFx( + () -> { + assertTrue(kb.isCapsLock()); + press(StandardKeyCode.SHIFT_DOWN); + press('A'); + press('B'); + assertTrue(kb.isShift()); + assertEquals("AB", robot.text()); + }); + } + + @Test + void typeKeysSwitchLayout() { + runFx( + () -> { + press(StandardKeyCode.NUMERIC_TYPE); + assertEquals(KeyboardType.NUMERIC, kb.getActiveType()); + press(StandardKeyCode.EMAIL_TYPE); + assertEquals(KeyboardType.EMAIL, kb.getActiveType()); + press(StandardKeyCode.URL_TYPE); + assertEquals(KeyboardType.URL, kb.getActiveType()); + }); + } + + @Test + void localeSwitchKey() { + runFx( + () -> { + press(StandardKeyCode.LOCALE_SWITCH, "DE", null); + assertEquals(Locale.GERMAN, kb.getActiveLocale()); + press(StandardKeyCode.LOCALE_SWITCH, "EN", null); + assertEquals(Locale.ENGLISH, kb.getActiveLocale()); + }); + } + + @ParameterizedTest + @CsvSource({ + "-4, " + KeyEvent.VK_TAB, + "-5, " + KeyEvent.VK_BACK_SPACE, + "-8, " + KeyEvent.VK_DELETE, + "-9, " + KeyEvent.VK_ENTER, + "-10, " + KeyEvent.VK_UP, + "-11, " + KeyEvent.VK_DOWN, + "-12, " + KeyEvent.VK_LEFT, + "-13, " + KeyEvent.VK_RIGHT, + "-14, " + KeyEvent.VK_Z, + "-15, " + KeyEvent.VK_Y, + "-20, " + KeyEvent.VK_HOME, + "-21, " + KeyEvent.VK_END, + "-22, " + KeyEvent.VK_PAGE_UP, + "-23, " + KeyEvent.VK_PAGE_DOWN, + "-24, " + KeyEvent.VK_HELP, + "-112, " + KeyEvent.VK_F1, + "-117, " + KeyEvent.VK_F6, + "-123, " + KeyEvent.VK_F12 + }) + void specialKeysAreSentAsControlKeys(int keyCode, int expected) { + runFx( + () -> { + press(keyCode); + assertEquals(1, robot.sent().size()); + assertEquals((char) expected, robot.last().ch()); + assertTrue(robot.last().ctrl()); + }); + } + + @Test + void nonShortPressedEventsStopTimelines() { + runFx( + () -> { + var button = new RepeatableKeyButton(); + kb.timelines().longPressDelayTimeline(button, e -> {}).playFromStart(); + kb.handle(new KeyButtonEvent(button, KeyButtonEvent.LONG_PRESSED)); + assertEquals( + Animation.Status.STOPPED, kb.timelines().longPressDelayTimeline().getStatus()); + assertTrue(robot.sent().isEmpty()); + }); + } + + @Test + void closeKeyCallsCloseHandler() { + var closed = new AtomicReference(); + runFx( + () -> { + kb.setOnKeyboardCloseButton(closed::set); + press(StandardKeyCode.CLOSE); + }); + assertTrue(FxTestSupport.waitFor(() -> closed.get() != null, 2000)); + } + + @Test + void closeKeyWithoutHandlerRequestsWindowClose() { + var stage = FxTestSupport.callFx(Stage::new); + var closeRequested = new AtomicReference(false); + runFx( + () -> { + stage.setScene(new Scene(kb)); + kb.addEventHandler( + javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST, e -> closeRequested.set(true)); + press(StandardKeyCode.CLOSE); + }); + assertTrue(FxTestSupport.waitFor(closeRequested::get, 2000)); + } + + @Test + void printScreenHidesWindowTemporarily() { + var stage = FxTestSupport.callFx(Stage::new); + runFx( + () -> { + stage.setScene(new Scene(kb)); + stage.setOpacity(0.8); + press(StandardKeyCode.PRINTSCREEN); + assertEquals(0.0, stage.getOpacity()); + assertEquals((char) KeyEvent.VK_PRINTSCREEN, robot.last().ch()); + }); + assertTrue(FxTestSupport.waitFor(() -> stage.getOpacity() > 0.79, 5000)); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonTest.java index 1feeb91f..62dd58fc 100644 --- a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonTest.java +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonTest.java @@ -4,138 +4,80 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import javafx.animation.Animation; -import javafx.application.Platform; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; -import org.junit.jupiter.api.AssertionFailureBuilder; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; -import org.junit.jupiter.api.condition.DisabledOnJre; -import org.junit.jupiter.api.condition.JRE; -import org.junit.jupiter.api.condition.OS; -@DisabledOnJre(JRE.JAVA_25) // until monocle install is fixed class KeyButtonTest { @BeforeAll - static void initToolkit() throws Exception { - if (!OS.WINDOWS.isCurrentOs()) { - // Ensure headless property is set early in CI via JAVA_TOOL_OPTIONS; this is - // just in case. - System.setProperty("java.awt.headless", System.getProperty("java.awt.headless", "true")); - System.setProperty("prism.order", "sw"); - System.setProperty("prism.forceGPU", "false"); - - // Monocle platform is not available on all systems (e.g., Linux with JDK 25) - // Only set it if the Glass factory class is available - try { - Class.forName("com.sun.glass.ui.monocle.MonoclePlatformFactory"); - System.setProperty("glass.platform", "Monocle"); - System.setProperty("monocle.platform", "Headless"); - } catch (ClassNotFoundException ex) { - // Monocle not available, use default glass implementation - System.err.println("Monocle platform not available, using default glass implementation"); - } - } - // Initialize JavaFX toolkit (safe if already started) - try { - Platform.startup( - () -> { - /* no-op */ - }); - } catch (IllegalStateException ex) { - // toolkit already started - } catch (RuntimeException ex) { - // Handle glass platform initialization failures in JDK 25+ - // This can occur when the glass platform factory is not properly initialized - System.err.println("Warning: Failed to initialize JavaFX toolkit: " + ex.getMessage()); - ex.printStackTrace(); - } + static void initToolkit() { + FxTestSupport.startToolkit(); } @Test - @Timeout(value = 20, unit = TimeUnit.SECONDS) - void previousTimelineStoppedWhenNewPressed() throws Exception { - var latch = new CountDownLatch(1); - var exception = new AtomicReference(); - Platform.runLater( + void previousTimelineStoppedWhenNewPressed() { + FxTestSupport.runFx( () -> { - try { - KeyboardPane keyboard = new KeyboardPane(); - - var b1 = new RepeatableKeyButton(); - var b2 = new RepeatableKeyButton(); - var b3 = new ShortPressKeyButton(); - - b1.setTimelines(keyboard.timelines()); - b2.setTimelines(keyboard.timelines()); - b3.setTimelines(keyboard.timelines()); - - var h1 = b1.getOnMousePressed(); - var h2 = b2.getOnMousePressed(); - var h3 = b3.getOnMousePressed(); - - // Build a basic primary mouse event - var press = - new MouseEvent( - MouseEvent.MOUSE_PRESSED, - 0, - 0, - 0, - 0, - MouseButton.PRIMARY, - 1, - false, - false, - false, - false, - true, - false, - false, - false, - false, - false, - null); - // Press first button - h1.handle(press); - - // After pressing b1 its buttonDelay should be running - assertEquals( - Animation.Status.RUNNING, - keyboard.timelines().longPressDelayTimeline().getStatus()); - assertTrue(keyboard.timelines().longPressDelayTimeline().isOwner(b1)); - - // Press second button; this should stop timeline on b1 and starts on b2 - h2.handle(press); - // switch owner - assertTrue(keyboard.timelines().longPressDelayTimeline().isOwner(b2)); - - // Press third button; this should stop all timelines - h3.handle(press); - - // After pressing short press button all timelines should be stopped - assertEquals( - Animation.Status.STOPPED, - keyboard.timelines().longPressDelayTimeline().getStatus()); - assertEquals( - Animation.Status.STOPPED, - keyboard.timelines().repeatableButtonTimeline().getStatus()); - - } catch (Throwable th) { - exception.set(th); - } finally { - latch.countDown(); - } + KeyboardPane keyboard = new KeyboardPane(); + + var b1 = new RepeatableKeyButton(); + var b2 = new RepeatableKeyButton(); + var b3 = new ShortPressKeyButton(); + + b1.setTimelines(keyboard.timelines()); + b2.setTimelines(keyboard.timelines()); + b3.setTimelines(keyboard.timelines()); + + var h1 = b1.getOnMousePressed(); + var h2 = b2.getOnMousePressed(); + var h3 = b3.getOnMousePressed(); + + // Build a basic primary mouse event + var press = + new MouseEvent( + MouseEvent.MOUSE_PRESSED, + 0, + 0, + 0, + 0, + MouseButton.PRIMARY, + 1, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + null); + // Press first button + h1.handle(press); + + // After pressing b1 its buttonDelay should be running + assertEquals( + Animation.Status.RUNNING, keyboard.timelines().longPressDelayTimeline().getStatus()); + assertTrue(keyboard.timelines().longPressDelayTimeline().isOwner(b1)); + + // Press second button; this should stop timeline on b1 and starts on b2 + h2.handle(press); + // switch owner + assertTrue(keyboard.timelines().longPressDelayTimeline().isOwner(b2)); + + // Press third button; this should stop all timelines + h3.handle(press); + + // After pressing short press button all timelines should be stopped + assertEquals( + Animation.Status.STOPPED, keyboard.timelines().longPressDelayTimeline().getStatus()); + assertEquals( + Animation.Status.STOPPED, + keyboard.timelines().repeatableButtonTimeline().getStatus()); }); - - assertTrue(latch.await(2, TimeUnit.SECONDS)); - if (exception.get() != null) { - AssertionFailureBuilder.assertionFailure().cause(exception.get()).buildAndThrow(); - } } } diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonsTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonsTest.java new file mode 100644 index 00000000..c46fca05 --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyButtonsTest.java @@ -0,0 +1,275 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.control; + +import static org.comtel2000.keyboard.control.FxTestSupport.runFx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import javafx.animation.Animation.Status; +import javafx.event.EventType; +import javafx.scene.input.MouseButton; +import javafx.scene.input.MouseEvent; +import javafx.scene.layout.Pane; +import org.comtel2000.keyboard.event.KeyButtonEvent; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class KeyButtonsTest { + + @BeforeAll + static void initToolkit() { + FxTestSupport.startToolkit(); + } + + static MouseEvent mouse(EventType type, MouseButton button) { + return new MouseEvent( + type, + 0, + 0, + 0, + 0, + button, + 1, + false, + false, + false, + false, + button == MouseButton.PRIMARY, + false, + button == MouseButton.SECONDARY, + false, + false, + false, + null); + } + + /** Records short and long presses of a button. */ + static final class Presses { + final AtomicInteger shortPresses = new AtomicInteger(); + final AtomicInteger longPresses = new AtomicInteger(); + + Presses(KeyButton button) { + button.setOnShortPressed(e -> shortPresses.incrementAndGet()); + button.setOnLongPressed(e -> longPresses.incrementAndGet()); + } + } + + @Test + void keyButtonDefaults() { + runFx( + () -> { + var b = new ShortPressKeyButton(); + assertTrue(b.getStyleClass().contains("key-button")); + assertNull(b.getOnShortPressed()); + assertNull(b.getOnLongPressed()); + assertFalse(b.isMovable()); + assertFalse(b.isSticky()); + assertFalse(b.isRepeatable()); + assertNull(b.getKeyText()); + + assertSame(b, b.onShortPressedProperty().getBean()); + assertEquals("onShortPressed", b.onShortPressedProperty().getName()); + assertSame(b, b.onLongPressedProperty().getBean()); + assertEquals("onLongPressed", b.onLongPressedProperty().getName()); + + b.setMovable(true); + b.setSticky(true); + b.setKeyCode(42); + b.setKeyText("x"); + assertTrue(b.isMovable()); + assertTrue(b.isSticky()); + assertEquals(42, b.getKeyCode()); + assertEquals("x", b.getKeyText()); + + // no-op for simple buttons + b.addExtKeyCode(new Timelines(), 1, "1"); + }); + } + + @Test + void keyButtonEventsReachHandlers() { + runFx( + () -> { + var b = new ShortPressKeyButton(); + var presses = new Presses(b); + b.fireShortPressed(); + b.fireLongPressed(); + assertEquals(1, presses.shortPresses.get()); + assertEquals(1, presses.longPresses.get()); + assertNotNull(new KeyButtonEvent(b, KeyButtonEvent.ANY).toString()); + assertEquals(KeyButtonEvent.ANY, new KeyButtonEvent(KeyButtonEvent.ANY).getEventType()); + }); + } + + @Test + void shortPressButtonFiresOnPrimaryPressOnly() { + runFx( + () -> { + var timelines = new Timelines(); + var b = new ShortPressKeyButton(); + b.setTimelines(timelines); + var presses = new Presses(b); + + timelines.repeatableButtonTimeline(new Pane(), e -> {}).playFromStart(); + b.getOnMousePressed().handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.SECONDARY)); + assertEquals(0, presses.shortPresses.get()); + assertEquals(Status.STOPPED, timelines.repeatableButtonTimeline().getStatus()); + + b.getOnMousePressed().handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.PRIMARY)); + assertEquals(1, presses.shortPresses.get()); + }); + } + + @Test + void repeatableButtonFiresOnPressAndRepeats() { + runFx( + () -> { + var timelines = new Timelines(); + var b = new RepeatableKeyButton(); + b.setTimelines(timelines); + var presses = new Presses(b); + assertTrue(b.isRepeatable()); + assertTrue(b.getStyleClass().contains("repeatable-button")); + + b.getOnMousePressed().handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.SECONDARY)); + assertEquals(0, presses.shortPresses.get()); + + b.getOnMousePressed().handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.PRIMARY)); + assertEquals(1, presses.shortPresses.get()); + assertEquals(Status.RUNNING, timelines.longPressDelayTimeline().getStatus()); + + // long press delay elapsed: repeat starts + b.onLongPressedEvent(timelines); + assertEquals(2, presses.shortPresses.get()); + assertEquals(Status.RUNNING, timelines.repeatableButtonTimeline().getStatus()); + timelines.repeatableButtonTimeline().handle(null); + assertEquals(3, presses.shortPresses.get()); + + b.getOnMouseReleased().handle(mouse(MouseEvent.MOUSE_RELEASED, MouseButton.PRIMARY)); + assertEquals(Status.STOPPED, timelines.longPressDelayTimeline().getStatus()); + assertEquals(Status.STOPPED, timelines.repeatableButtonTimeline().getStatus()); + assertEquals(3, presses.shortPresses.get()); + }); + } + + @Test + void movableRepeatableButtonFiresOnRelease() { + runFx( + () -> { + var timelines = new Timelines(); + var b = new RepeatableKeyButton(); + b.setMovable(true); + b.setTimelines(timelines); + var presses = new Presses(b); + + b.getOnMousePressed().handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.PRIMARY)); + assertEquals(0, presses.shortPresses.get()); + b.getOnMouseReleased().handle(mouse(MouseEvent.MOUSE_RELEASED, MouseButton.PRIMARY)); + assertEquals(1, presses.shortPresses.get()); + + // dragging (moving the keyboard) cancels the key press + b.getOnMousePressed().handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.PRIMARY)); + b.getOnDragDetected().handle(mouse(MouseEvent.DRAG_DETECTED, MouseButton.PRIMARY)); + assertEquals(Status.STOPPED, timelines.longPressDelayTimeline().getStatus()); + b.getOnMouseReleased().handle(mouse(MouseEvent.MOUSE_RELEASED, MouseButton.PRIMARY)); + assertEquals(1, presses.shortPresses.get()); + }); + } + + @Test + void multiKeyButtonShortClick() { + runFx( + () -> { + var timelines = new Timelines(); + var parent = new Pane(); + var b = new MultiKeyButton(parent, List.of()); + b.setTimelines(timelines); + var presses = new Presses(b); + assertTrue(b.getStyleClass().contains("multi-button")); + + b.getOnMousePressed().handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.SECONDARY)); + assertEquals(Status.STOPPED, timelines.longPressDelayTimeline().getStatus()); + + b.getOnMousePressed().handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.PRIMARY)); + assertEquals(Status.RUNNING, timelines.longPressDelayTimeline().getStatus()); + b.getOnMouseClicked().handle(mouse(MouseEvent.MOUSE_CLICKED, MouseButton.PRIMARY)); + assertEquals(1, presses.shortPresses.get()); + assertEquals(0, presses.longPresses.get()); + assertEquals(Status.STOPPED, timelines.longPressDelayTimeline().getStatus()); + + // click after the delay elapsed is not a short press + b.getOnMouseClicked().handle(mouse(MouseEvent.MOUSE_CLICKED, MouseButton.PRIMARY)); + assertEquals(1, presses.shortPresses.get()); + }); + } + + @Test + void multiKeyButtonDragIsLongPress() { + runFx( + () -> { + var timelines = new Timelines(); + var b = new MultiKeyButton(new Pane(), List.of()); + b.setTimelines(timelines); + var presses = new Presses(b); + + b.getOnDragDetected().handle(mouse(MouseEvent.DRAG_DETECTED, MouseButton.PRIMARY)); + assertEquals(0, presses.longPresses.get(), "no press in progress"); + + b.getOnMousePressed().handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.PRIMARY)); + b.getOnDragDetected().handle(mouse(MouseEvent.DRAG_DETECTED, MouseButton.PRIMARY)); + assertEquals(1, presses.longPresses.get()); + assertEquals(0, presses.shortPresses.get()); + assertEquals(Status.STOPPED, timelines.longPressDelayTimeline().getStatus()); + }); + } + + @Test + void multiKeyButtonExtraKeysShareShortPressHandler() { + runFx( + () -> { + var timelines = new Timelines(); + var parent = new Pane(); + var b = new MultiKeyButton(parent, List.of("style.css")); + b.setTimelines(timelines); + b.setPrefSize(40, 30); + var pressed = new ArrayList(); + b.setOnShortPressed(e -> pressed.add(((KeyButton) e.getSource()).getKeyCode())); + + b.addExtKeyCode(timelines, 228, "ä"); + b.addExtKeyCode(timelines, 229, "å"); + assertNotNull(b.getOnLongPressed(), "context popup is opened by long press"); + + // the extra buttons live in the popup; press them via their mouse handler + var popup = popupOf(b); + assertEquals(List.of("style.css"), popup.getStylesheets()); + var extra = KeyboardPaneTest.keyButtons(popup.getContent().get(0)); + assertEquals(2, extra.size()); + assertEquals("ä", extra.get(0).getText()); + assertEquals(40, extra.get(0).getPrefWidth()); + assertFalse(extra.get(0).isFocusTraversable()); + extra + .get(1) + .getOnMousePressed() + .handle(mouse(MouseEvent.MOUSE_PRESSED, MouseButton.PRIMARY)); + assertEquals(List.of(229), pressed); + + // hiding the popup re-enables the parent + parent.setDisable(true); + popup.getOnHidden().handle(null); + assertFalse(parent.isDisable()); + }); + } + + private static MultiKeyPopup popupOf(MultiKeyButton button) throws Exception { + var field = MultiKeyButton.class.getDeclaredField("context"); + field.setAccessible(true); + return (MultiKeyPopup) field.get(button); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyboardPaneTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyboardPaneTest.java new file mode 100644 index 00000000..0380307b --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyboardPaneTest.java @@ -0,0 +1,525 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.control; + +import static org.comtel2000.keyboard.control.FxTestSupport.runFx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import javafx.scene.Node; +import javafx.scene.Parent; +import javafx.scene.input.ScrollEvent; +import javafx.scene.input.ZoomEvent; +import javafx.scene.layout.Region; +import org.comtel2000.keyboard.robot.FXRobotHandler; +import org.comtel2000.keyboard.robot.RecordingRobot; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class KeyboardPaneTest { + + @BeforeAll + static void initToolkit() { + FxTestSupport.startToolkit(); + } + + static KeyboardPane loadedKeyboard(Locale locale, RecordingRobot robot) throws Exception { + var kb = new KeyboardPane(); + kb.setLocale(locale); + kb.addRobotHandler(robot); + kb.load(); + return kb; + } + + static List keyButtons(Node node) { + var result = new ArrayList(); + collect(node, result); + return result; + } + + private static void collect(Node node, List result) { + if (node instanceof KeyButton kb) { + result.add(kb); + } + if (node instanceof Parent p) { + for (var child : p.getChildrenUnmodifiable()) { + collect(child, result); + } + } + } + + static Region activeRegion(KeyboardPane kb) { + assertEquals(1, kb.getChildrenUnmodifiable().size()); + return (Region) kb.getChildrenUnmodifiable().get(0); + } + + @Test + void defaultProperties() { + runFx( + () -> { + var kb = new KeyboardPane(); + assertTrue(kb.getStyleClass().contains("key-background")); + assertFalse(kb.isFocusTraversable()); + assertTrue(kb.isCacheLayout()); + assertFalse(kb.isSymbol()); + assertFalse(kb.isShift()); + assertFalse(kb.isControl()); + assertTrue(kb.isSpaceKeyMove()); + assertTrue(kb.isCapsLock()); + assertEquals(0.2d, kb.getScaleOffset()); + assertEquals(1.0d, kb.getScale()); + assertEquals(0.7d, kb.getMinScale()); + assertEquals(5.0d, kb.getMaxScale()); + assertEquals(DefaultLayer.DEFAULT, kb.getLayer()); + assertNull(kb.getLayerPath()); + assertEquals(Locale.getDefault(), kb.getLocale()); + assertNull(kb.getActiveLocale()); + assertNull(kb.getActiveType()); + assertTrue(kb.getRobotHandler().isEmpty()); + assertTrue(kb.getKeyBoardStyle().endsWith("KeyboardButtonStyle.css")); + assertEquals(kb.getKeyBoardStyle(), kb.getUserAgentStylesheet()); + }); + } + + @Test + void plainValuesAreCopiedIntoLazyProperties() { + runFx( + () -> { + var kb = new KeyboardPane(); + kb.setCacheLayout(false); + kb.setSymbol(true); + kb.setShift(true); + kb.setControl(true); + kb.setSpaceKeyMove(false); + kb.setCapsLock(false); + kb.setScaleOffset(0.5); + kb.setScale(2.0); + kb.setMinScale(0.5); + kb.setMaxScale(3.0); + kb.setLayer(DefaultLayer.NUMBLOCK); + kb.setLayerPath(Path.of("x")); + kb.setLocale(Locale.GERMAN); + kb.setActiveLocale(Locale.FRENCH); + kb.setActiveType(KeyboardType.CTRL); + kb.setKeyBoardStyle("my.css"); + + assertFalse(kb.cacheLayoutProperty().get()); + assertTrue(kb.symbolProperty().get()); + assertTrue(kb.shiftProperty().get()); + assertTrue(kb.controlProperty().get()); + assertFalse(kb.spaceKeyMoveProperty().get()); + assertFalse(kb.capsLockProperty().get()); + assertEquals(0.5, kb.scaleOffsetProperty().get()); + assertEquals(2.0, kb.scaleProperty().get()); + assertEquals(2.0, kb.getScaleX()); + assertEquals(2.0, kb.getScaleY()); + assertEquals(0.5, kb.minScaleProperty().get()); + assertEquals(3.0, kb.maxScaleProperty().get()); + assertEquals(DefaultLayer.NUMBLOCK, kb.layerProperty().get()); + assertEquals(Path.of("x"), kb.layerPathProperty().get()); + assertEquals(Locale.GERMAN, kb.localeProperty().get()); + assertEquals(Locale.FRENCH, kb.activeLocaleProperty().get()); + assertEquals(KeyboardType.CTRL, kb.activeTypeProperty().get()); + assertEquals("my.css", kb.keyBoardStyleProperty().get()); + + // properties are created once + assertSame(kb.scaleProperty(), kb.scaleProperty()); + }); + } + + @Test + void settersWriteThroughToProperties() { + runFx( + () -> { + var kb = new KeyboardPane(); + kb.cacheLayoutProperty(); + kb.symbolProperty(); + kb.shiftProperty(); + kb.controlProperty(); + kb.spaceKeyMoveProperty(); + kb.capsLockProperty(); + kb.scaleOffsetProperty(); + kb.scaleProperty(); + kb.minScaleProperty(); + kb.maxScaleProperty(); + kb.layerProperty(); + kb.layerPathProperty(); + kb.localeProperty(); + kb.activeLocaleProperty(); + kb.activeTypeProperty(); + kb.keyBoardStyleProperty(); + + kb.setCacheLayout(false); + kb.setSymbol(true); + kb.setShift(true); + kb.setControl(true); + kb.setSpaceKeyMove(false); + kb.setCapsLock(false); + kb.setScaleOffset(0.3); + kb.setScale(1.5); + kb.setMinScale(0.4); + kb.setMaxScale(4.0); + kb.setLayer(DefaultLayer.NUMBLOCK); + kb.setLayerPath(Path.of("y")); + kb.setLocale(Locale.ITALIAN); + kb.setActiveLocale(Locale.GERMAN); + kb.setActiveType(KeyboardType.NUMERIC); + kb.setKeyBoardStyle("other.css"); + + assertFalse(kb.isCacheLayout()); + assertTrue(kb.isSymbol()); + assertTrue(kb.isShift()); + assertTrue(kb.isControl()); + assertFalse(kb.isSpaceKeyMove()); + assertFalse(kb.isCapsLock()); + assertEquals(0.3, kb.getScaleOffset()); + assertEquals(1.5, kb.getScale()); + assertEquals(1.5, kb.getScaleX(), "scale listener updates the node scale"); + assertEquals(0.4, kb.getMinScale()); + assertEquals(4.0, kb.getMaxScale()); + assertEquals(DefaultLayer.NUMBLOCK, kb.getLayer()); + assertEquals(Path.of("y"), kb.getLayerPath()); + assertEquals(Locale.ITALIAN, kb.getLocale()); + assertEquals(Locale.GERMAN, kb.getActiveLocale()); + assertEquals(KeyboardType.NUMERIC, kb.getActiveType()); + assertEquals("other.css", kb.getKeyBoardStyle()); + }); + } + + @Test + void loadBuildsTextLayoutAndDefaultRobot() { + runFx( + () -> { + var kb = new KeyboardPane(); + kb.setLocale(Locale.ENGLISH); + kb.load(); + + assertEquals(1, kb.getRobotHandler().size()); + assertTrue(kb.getRobotHandler().get(0) instanceof FXRobotHandler); + assertTrue(kb.getStylesheets().contains(kb.getKeyBoardStyle())); + assertEquals(Locale.ENGLISH, kb.getActiveLocale()); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + assertTrue(activeRegion(kb) instanceof KeyboardRegion); + assertEquals(37, keyButtons(activeRegion(kb)).size(), "38 keys minus one placeholder"); + }); + } + + @Test + void loadAppliesInitialScale() { + runFx( + () -> { + var kb = new KeyboardPane(); + kb.setLocale(Locale.ENGLISH); + kb.addRobotHandler(new RecordingRobot()); + kb.setScale(1.5); + kb.load(); + assertEquals(1.5, kb.getScaleX()); + assertEquals(1.5, kb.getScaleY()); + }); + } + + @Test + void availableLocalesOfEmbeddedLayers() { + runFx( + () -> { + var kb = loadedKeyboard(Locale.ENGLISH, new RecordingRobot()); + var locales = kb.getAvailableLocales(); + assertTrue(locales.containsKey(Locale.ENGLISH)); + assertTrue(locales.containsKey(Locale.GERMAN)); + assertTrue(locales.containsKey(new Locale("es"))); + assertTrue(locales.containsKey(new Locale("ru"))); + assertNotNull(kb.getLayerPath(), "embedded directory is resolved to a path"); + assertSame(locales, kb.getAvailableLocales(), "locales are cached"); + }); + } + + @Test + void unknownLocaleFallsBackToEnglish() { + runFx( + () -> { + var kb = loadedKeyboard(Locale.JAPANESE, new RecordingRobot()); + assertEquals(Locale.ENGLISH, kb.getActiveLocale()); + }); + } + + @Test + void countryLocaleUsesLanguageLayout() { + runFx( + () -> { + var kb = loadedKeyboard(Locale.GERMANY, new RecordingRobot()); + assertEquals(Locale.GERMAN, kb.getActiveLocale()); + }); + } + + @Test + void switchLocaleReplacesLayout() { + runFx( + () -> { + var kb = loadedKeyboard(Locale.ENGLISH, new RecordingRobot()); + var english = activeRegion(kb); + + kb.switchLocale(Locale.GERMAN); + assertEquals(Locale.GERMAN, kb.getActiveLocale()); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + assertNotSame(english, activeRegion(kb)); + assertTrue( + keyButtons(activeRegion(kb)).stream().anyMatch(b -> "STRG".equals(b.getText())), + "german layout has a STRG key"); + + var german = activeRegion(kb); + kb.switchLocale(Locale.GERMAN); + assertSame(german, activeRegion(kb), "same locale is a no-op"); + + kb.resetLocale(); + assertEquals(Locale.ENGLISH, kb.getActiveLocale()); + assertSame(english, activeRegion(kb), "layouts are cached"); + }); + } + + @Test + void keyboardTypeFromString() { + runFx( + () -> { + var kb = loadedKeyboard(Locale.ENGLISH, new RecordingRobot()); + kb.setKeyboardType("numeric"); + assertEquals(KeyboardType.NUMERIC, kb.getActiveType()); + kb.setKeyboardType((String) null); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + kb.setKeyboardType("ctrl"); + assertEquals(KeyboardType.CTRL, kb.getActiveType()); + kb.setKeyboardType(""); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + kb.setKeyboardType("symbol"); + kb.setKeyboardType("no-such-type"); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + }); + } + + @Test + void keyboardTypeFromModifiers() { + runFx( + () -> { + var kb = loadedKeyboard(Locale.ENGLISH, new RecordingRobot()); + + kb.setKeyboardType(false, true, false); + assertEquals(KeyboardType.TEXT_SHIFT, kb.getActiveType()); + assertTrue(kb.isShift()); + assertFalse(kb.isSymbol()); + + kb.setKeyboardType(false, false, true); + assertEquals(KeyboardType.SYMBOL, kb.getActiveType()); + assertTrue(kb.isSymbol()); + assertFalse(kb.isShift()); + + kb.setKeyboardType(false, true, true); + assertEquals(KeyboardType.SYMBOL_SHIFT, kb.getActiveType()); + assertTrue(kb.isSymbol()); + assertTrue(kb.isShift()); + + kb.setKeyboardType(true, true, true); + assertEquals(KeyboardType.CTRL, kb.getActiveType()); + assertTrue(kb.isControl()); + assertFalse(kb.isShift()); + assertFalse(kb.isSymbol()); + + kb.setKeyboardType(false, false, false); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + assertFalse(kb.isControl()); + }); + } + + @Test + void everyKeyboardTypeHasARegion() { + runFx( + () -> { + var kb = loadedKeyboard(Locale.ENGLISH, new RecordingRobot()); + for (var type : KeyboardType.values()) { + kb.setKeyboardType(type); + assertEquals(type, kb.getActiveType()); + assertFalse(keyButtons(activeRegion(kb)).isEmpty(), type + " has keys"); + } + // email and url layouts do not exist and fall back to the text layout + kb.setKeyboardType(KeyboardType.TEXT); + var text = activeRegion(kb); + kb.setKeyboardType(KeyboardType.EMAIL); + assertSame(text, activeRegion(kb)); + kb.setKeyboardType(KeyboardType.URL); + assertSame(text, activeRegion(kb)); + }); + } + + @Test + void switchLayerLoadsNumblockLayout() { + runFx( + () -> { + var kb = loadedKeyboard(Locale.ENGLISH, new RecordingRobot()); + int defaultKeys = keyButtons(activeRegion(kb)).size(); + + kb.switchLayer(DefaultLayer.NUMBLOCK); + assertEquals(DefaultLayer.NUMBLOCK, kb.getLayer()); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + assertTrue(keyButtons(activeRegion(kb)).size() > defaultKeys); + + var numblock = activeRegion(kb); + kb.switchLayer(DefaultLayer.NUMBLOCK); + assertSame(numblock, activeRegion(kb), "same layer is a no-op"); + }); + } + + @Test + void customLayerPath() throws URISyntaxException { + var path = Path.of(KeyboardPaneTest.class.getResource("/xml/default").toURI()); + runFx( + () -> { + var kb = new KeyboardPane(); + kb.setLayerPath(path); + kb.setLocale(Locale.ENGLISH); + kb.addRobotHandler(new RecordingRobot()); + kb.load(); + var locales = kb.getAvailableLocales(); + assertEquals(path.toString(), locales.get(Locale.ENGLISH)); + assertTrue(locales.containsKey(Locale.GERMAN)); + assertTrue(locales.containsKey(new Locale("ru"))); + assertEquals(KeyboardType.TEXT, kb.getActiveType()); + + // ru has no numeric layout and falls back to the english one + kb.switchLocale(new Locale("ru")); + kb.setKeyboardType(KeyboardType.NUMERIC); + assertFalse(keyButtons(activeRegion(kb)).isEmpty()); + }); + } + + @Test + void layoutCache() { + runFx( + () -> { + var kb = new KeyboardPane(); + var url = KeyboardPane.class.getResource("layer/default/kb-layout.xml"); + assertSame(kb.getKeyboardPane(url), kb.getKeyboardPane(url)); + kb.setCacheLayout(false); + assertNotSame(kb.getKeyboardPane(url), kb.getKeyboardPane(url)); + }); + } + + @Test + void sendToComponentForwardsToAllRobots() { + runFx( + () -> { + var r1 = new RecordingRobot(); + var r2 = new RecordingRobot(); + var kb = new KeyboardPane(); + kb.addRobotHandler(r1); + kb.addRobotHandler(r2); + assertThrows(UnsupportedOperationException.class, () -> kb.getRobotHandler().add(r1)); + + kb.sendToComponent('x', false); + assertEquals("x", r1.text()); + assertEquals("x", r2.text()); + + kb.removeRobotHandler(r2); + kb.sendToComponent('y', true); + assertEquals("xy", r1.text()); + assertTrue(r1.last().ctrl()); + assertEquals("x", r2.text()); + + kb.removeRobotHandler(r1); + kb.sendToComponent('z', false); // logs an error, must not fail + }); + } + + @Test + void ctrlPlusMinusChangesScale() { + runFx( + () -> { + var robot = new RecordingRobot(); + var kb = new KeyboardPane(); + kb.addRobotHandler(robot); + + kb.sendToComponent('+', true); + assertEquals(1.2, kb.getScale(), 1e-9); + kb.sendToComponent('-', true); + kb.sendToComponent('-', true); + assertEquals(0.8, kb.getScale(), 1e-9); + kb.sendToComponent('-', true); + assertEquals(0.8, kb.getScale(), 1e-9, "min scale is respected"); + + kb.setScale(4.9); + kb.sendToComponent('+', true); + assertEquals(4.9, kb.getScale(), 1e-9, "max scale is respected"); + assertTrue(robot.sent().isEmpty(), "scale keys are not forwarded"); + + kb.sendToComponent('+', false); + assertEquals("+", robot.text(), "without ctrl the key is forwarded"); + }); + } + + @Test + void scrollAndZoomChangeScale() { + runFx( + () -> { + var kb = loadedKeyboard(Locale.ENGLISH, new RecordingRobot()); + kb.getOnScroll().handle(scroll(10)); + assertEquals(1.2, kb.getScale(), 1e-9); + kb.getOnScroll().handle(scroll(-10)); + assertEquals(1.0, kb.getScale(), 1e-9); + + kb.getOnZoom().handle(zoom(2.0)); + assertEquals(2.0, kb.getScale(), 1e-9); + kb.getOnZoom().handle(zoom(10.0)); + assertEquals(2.0, kb.getScale(), 1e-9, "zoom beyond max scale is ignored"); + }); + } + + private static ScrollEvent scroll(double deltaY) { + return new ScrollEvent( + ScrollEvent.SCROLL, + 0, + 0, + 0, + 0, + false, + false, + false, + false, + false, + false, + 0, + deltaY, + 0, + deltaY, + ScrollEvent.HorizontalTextScrollUnits.NONE, + 0, + ScrollEvent.VerticalTextScrollUnits.NONE, + 0, + 0, + null); + } + + private static ZoomEvent zoom(double totalFactor) { + return new ZoomEvent( + ZoomEvent.ZOOM, + 0, + 0, + 0, + 0, + false, + false, + false, + false, + false, + false, + totalFactor, + totalFactor, + null); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyboardRegionTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyboardRegionTest.java new file mode 100644 index 00000000..43fab73b --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyboardRegionTest.java @@ -0,0 +1,217 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.control; + +import static org.comtel2000.keyboard.control.FxTestSupport.runFx; +import static org.comtel2000.keyboard.control.KeyboardPaneTest.keyButtons; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URL; +import java.util.List; +import java.util.Locale; +import javafx.geometry.HPos; +import javafx.geometry.Pos; +import javafx.geometry.VPos; +import javafx.scene.control.ContentDisplay; +import javafx.scene.control.Label; +import javafx.scene.layout.GridPane; +import org.comtel2000.keyboard.event.KeyButtonEvent; +import org.comtel2000.keyboard.robot.RecordingRobot; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class KeyboardRegionTest { + + @BeforeAll + static void initToolkit() { + FxTestSupport.startToolkit(); + } + + private static URL layout(String name) { + return KeyboardRegionTest.class.getResource("/xml/region/" + name); + } + + private static KeyButton byCode(List buttons, int code) { + return buttons.stream().filter(b -> b.getKeyCode() == code).findFirst().orElseThrow(); + } + + @Test + void parsesKeyboardAttributes() { + runFx( + () -> { + var kb = new KeyboardPane(); + var region = new KeyboardRegion(kb, layout("kb-features.xml")); + assertEquals(Pos.CENTER, region.getAlignment()); + assertEquals(4, region.getVgap()); + assertTrue(region.getStyleClass().contains("key-background-row")); + + var rows = region.getChildren(); + assertEquals(2, rows.size()); + var firstRow = (GridPane) rows.get(0); + assertEquals(3, firstRow.getHgap()); + assertEquals(7, firstRow.getChildren().size(), "placeholder + 6 keys"); + assertEquals(10, firstRow.getColumnConstraints().get(0).getPrefWidth()); + assertEquals(30, firstRow.getRowConstraints().get(0).getPrefHeight()); + assertNull(firstRow.getRowConstraints().get(0).getValignment()); + + var secondRow = (GridPane) rows.get(1); + assertEquals(VPos.BOTTOM, secondRow.getRowConstraints().get(0).getValignment()); + }); + } + + @Test + void createsButtonTypesFromAttributes() { + runFx( + () -> { + var kb = new KeyboardPane(); + kb.setLocale(Locale.ENGLISH); + var region = new KeyboardRegion(kb, layout("kb-features.xml")); + var buttons = keyButtons(region); + assertEquals(12, buttons.size()); + + var multi = byCode(buttons, 97); + assertInstanceOf(MultiKeyButton.class, multi); + assertEquals("a", multi.getText()); + + var hex = byCode(buttons, 0x62); + assertInstanceOf(ShortPressKeyButton.class, hex); + assertEquals(Pos.BASELINE_LEFT, hex.getAlignment()); + + var noLabel = byCode(buttons, 99); + assertEquals("c", noLabel.getText(), "label defaults to the key code char"); + assertEquals(Pos.BASELINE_RIGHT, noLabel.getAlignment()); + + var outputText = byCode(buttons, 100); + assertEquals("dot.", outputText.getKeyText()); + assertEquals(Pos.BASELINE_CENTER, outputText.getAlignment()); + + var backspace = byCode(buttons, StandardKeyCode.BACK_SPACE); + assertInstanceOf(RepeatableKeyButton.class, backspace); + assertTrue(backspace.isRepeatable()); + assertTrue(backspace.getStyleClass().contains("font-fxkeyboard")); + assertTrue(backspace.getStyleClass().contains("small-style")); + assertNull(backspace.getOnLongPressed(), "repeatable delete keys repeat instead"); + + var delete = byCode(buttons, StandardKeyCode.DELETE); + assertFalse(delete.getOnLongPressed() == null, "delete gets a long press handler"); + + var shift = byCode(buttons, StandardKeyCode.SHIFT_DOWN); + assertTrue(shift.isSticky()); + assertTrue(shift.getStyleClass().contains("sticky-style")); + + var space = byCode(buttons, 32); + assertTrue(space.isMovable()); + assertTrue(space.getStyleClass().contains("movable-style")); + assertTrue(space.getOnMouseDragged() != null); + + var locale = byCode(buttons, StandardKeyCode.LOCALE_SWITCH); + assertInstanceOf(MultiKeyButton.class, locale); + + var close = byCode(buttons, StandardKeyCode.CLOSE); + var icon = assertInstanceOf(Label.class, close.getGraphic()); + assertTrue(icon.getStyleClass().contains("icon-close")); + assertEquals(ContentDisplay.CENTER, close.getContentDisplay()); + + var missingImage = byCode(buttons, StandardKeyCode.ENTER); + assertNull(missingImage.getGraphic()); + + var ctrl = byCode(buttons, StandardKeyCode.CTRL_DOWN); + assertEquals( + List.of("button", "key-button"), + ctrl.getStyleClass(), + "styles without a leading '.' are ignored"); + + for (var b : buttons) { + assertFalse(b.isFocusTraversable()); + assertTrue(b.isPickOnBounds()); + assertEquals(kb, b.getOnShortPressed()); + } + }); + } + + @Test + void columnAlignmentFollowsEdgeFlags() { + runFx( + () -> { + var region = new KeyboardRegion(new KeyboardPane(), layout("kb-features.xml")); + var row = (GridPane) region.getChildren().get(0); + var cc = row.getColumnConstraints(); + assertEquals(HPos.CENTER, cc.get(1).getHalignment()); + assertEquals(HPos.LEFT, cc.get(2).getHalignment()); + assertEquals(HPos.RIGHT, cc.get(3).getHalignment()); + assertEquals(HPos.CENTER, cc.get(4).getHalignment()); + }); + } + + @Test + void deleteLongPressSendsSelectAllAndDelete() { + runFx( + () -> { + var robot = new RecordingRobot(); + var kb = new KeyboardPane(); + kb.addRobotHandler(robot); + var region = new KeyboardRegion(kb, layout("kb-features.xml")); + var delete = byCode(keyButtons(region), StandardKeyCode.DELETE); + delete.fireEvent(new KeyButtonEvent(delete, KeyButtonEvent.LONG_PRESSED)); + assertEquals(2, robot.sent().size()); + assertEquals('a', robot.sent().get(0).ch()); + assertTrue(robot.sent().get(0).ctrl()); + assertEquals((char) java.awt.event.KeyEvent.VK_DELETE, robot.sent().get(1).ch()); + }); + } + + @Test + void emptyStyleAttributesAreIgnored() { + runFx( + () -> { + var region = new KeyboardRegion(new KeyboardPane(), layout("kb-empty-style.xml")); + var buttons = keyButtons(region); + assertEquals(2, buttons.size(), "an empty style must not abort the layout"); + assertEquals("a", buttons.get(0).getText()); + assertNull(buttons.get(0).getGraphic()); + }); + } + + @Test + void invalidKeyCodeStopsParsingWithoutException() { + runFx( + () -> { + var region = new KeyboardRegion(new KeyboardPane(), layout("kb-invalid.xml")); + var buttons = keyButtons(region); + assertEquals(1, buttons.size(), "parsing stops at the invalid key"); + assertEquals("a", buttons.get(0).getText()); + }); + } + + @Test + void allEmbeddedLayoutsParse() throws Exception { + var base = KeyboardPane.class.getResource("layer"); + try (var files = java.nio.file.Files.walk(java.nio.file.Path.of(base.toURI()))) { + var layouts = + files + .filter(p -> p.getFileName().toString().endsWith(".xml")) + .map( + p -> { + try { + return p.toUri().toURL(); + } catch (java.net.MalformedURLException e) { + throw new IllegalStateException(e); + } + }) + .toList(); + assertFalse(layouts.isEmpty()); + runFx( + () -> { + var kb = new KeyboardPane(); + kb.setLocale(Locale.ENGLISH); + for (var url : layouts) { + var region = new KeyboardRegion(kb, url); + assertFalse(keyButtons(region).isEmpty(), "no keys in " + url); + } + }); + } + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/MultiKeyPopupTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/MultiKeyPopupTest.java new file mode 100644 index 00000000..d37f8834 --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/MultiKeyPopupTest.java @@ -0,0 +1,116 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.control; + +import static org.comtel2000.keyboard.control.FxTestSupport.runFx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.atomic.AtomicInteger; +import javafx.event.ActionEvent; +import javafx.scene.Scene; +import javafx.scene.control.Button; +import javafx.scene.control.Menu; +import javafx.scene.layout.StackPane; +import javafx.scene.layout.TilePane; +import javafx.stage.Stage; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class MultiKeyPopupTest { + + private Stage stage; + + @BeforeAll + static void initToolkit() { + FxTestSupport.startToolkit(); + } + + @AfterEach + void closeStage() { + if (stage != null) { + runFx(stage::close); + } + } + + private static TilePane pane(MultiKeyPopup popup) { + return (TilePane) popup.getContent().get(0); + } + + @Test + void layoutGrowsWithButtons() { + runFx( + () -> { + var popup = new MultiKeyPopup(); + var pane = pane(popup); + assertTrue(pane.getStyleClass().contains(MultiKeyPopup.DEFAULT_STYLE_CLASS)); + assertTrue(popup.isAutoHide()); + assertTrue(popup.isAutoFix()); + + int[][] expected = { + {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {3, 2}, {4, 2}, {4, 2}, {5, 2}, {5, 2} + }; + for (int i = 0; i < expected.length; i++) { + var button = new Button(String.valueOf(i)); + button.setFocusTraversable(true); + popup.addButton(button); + assertFalse(button.isFocusTraversable()); + assertEquals(expected[i][0], pane.getPrefColumns(), "columns for " + (i + 1)); + assertEquals(expected[i][1], pane.getPrefRows(), "rows for " + (i + 1)); + } + + popup.setPaneStyle("-fx-background-color: red;"); + assertEquals("-fx-background-color: red;", pane.getStyle()); + }); + } + + @Test + void onActionProperty() { + runFx( + () -> { + var popup = new MultiKeyPopup(); + var count = new AtomicInteger(); + popup.setOnAction(e -> count.incrementAndGet()); + assertSame(popup.onActionProperty().get(), popup.getOnAction()); + popup.fireEvent(new ActionEvent()); + assertEquals(1, count.get()); + }); + } + + @Test + void showAndHide() { + runFx( + () -> { + var popup = new MultiKeyPopup(); + var events = new AtomicInteger(); + popup.addEventHandler(Menu.ON_SHOWING, e -> events.incrementAndGet()); + popup.addEventHandler(Menu.ON_HIDDEN, e -> events.incrementAndGet()); + + popup.show(null, 1.0); + assertEquals(0, events.get()); + popup.hide(); // not showing: no events + assertEquals(0, events.get()); + + var anchor = new Button("x"); + stage = new Stage(); + stage.setScene(new Scene(new StackPane(anchor), 200, 200)); + stage.show(); + + popup.show(anchor, 1.0); + assertEquals(1, events.get(), "no buttons: nothing to show"); + assertFalse(popup.isShowing()); + + var button = new Button("a"); + popup.addButton(button); + popup.show(anchor, 1.5); + assertTrue(popup.isShowing()); + assertEquals(1.5, pane(popup).getScaleX()); + + button.fire(); // buttons close the popup + assertFalse(popup.isShowing()); + assertEquals(3, events.get()); + }); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/TimelinesTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/TimelinesTest.java new file mode 100644 index 00000000..25af98fb --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/TimelinesTest.java @@ -0,0 +1,124 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.control; + +import static org.comtel2000.keyboard.control.FxTestSupport.runFx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.atomic.AtomicInteger; +import javafx.animation.Animation.Status; +import javafx.event.ActionEvent; +import javafx.scene.layout.Pane; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class TimelinesTest { + + @BeforeAll + static void initToolkit() { + FxTestSupport.startToolkit(); + } + + @Test + void timelinesAreCreatedLazilyAndReused() { + runFx( + () -> { + var t = new Timelines(); + // stopping before creation must not fail + t.stop(); + assertSame(t.longPressDelayTimeline(), t.longPressDelayTimeline()); + assertSame(t.repeatableButtonTimeline(), t.repeatableButtonTimeline()); + assertTrue(t.longPressDelayTimeline() instanceof LongPressDelayTimeline); + assertTrue(t.repeatableButtonTimeline() instanceof RepeatableButtonTimeline); + assertTrue(t.longPressDelayTimeline().isEnabled()); + assertTrue(t.repeatableButtonTimeline().isEnabled()); + }); + } + + @Test + void ownerChangeStopsRunningTimeline() { + runFx( + () -> { + var t = new Timelines(); + var n1 = new Pane(); + var n2 = new Pane(); + var timeline = t.longPressDelayTimeline(n1, e -> {}); + assertTrue(timeline.isOwner(n1)); + assertFalse(timeline.isOwner(n2)); + assertFalse(timeline.isOwner(null)); + + timeline.playFromStart(); + assertEquals(Status.RUNNING, timeline.getStatus()); + assertTrue(timeline.getCurrentRate() > 0); + + // same owner keeps running + t.longPressDelayTimeline(n1, e -> {}); + assertEquals(Status.RUNNING, timeline.getStatus()); + + t.longPressDelayTimeline(n2, e -> {}); + assertEquals(Status.STOPPED, timeline.getStatus()); + assertTrue(timeline.isOwner(n2)); + }); + } + + @Test + void stopStopsBothTimelines() { + runFx( + () -> { + var t = new Timelines(); + var node = new Pane(); + t.longPressDelayTimeline(node, e -> {}).playFromStart(); + t.repeatableButtonTimeline(node, e -> {}).playFromStart(); + t.stop(); + assertEquals(Status.STOPPED, t.longPressDelayTimeline().getStatus()); + assertEquals(Status.STOPPED, t.repeatableButtonTimeline().getStatus()); + + t.repeatableButtonTimeline().playFromStart(); + t.stopLongPressDelayTimeline(); + assertEquals(Status.RUNNING, t.repeatableButtonTimeline().getStatus()); + t.stopRepeatableButtonTimeline(); + assertEquals(Status.STOPPED, t.repeatableButtonTimeline().getStatus()); + }); + } + + @Test + void handlerIsCalled() { + runFx( + () -> { + var count = new AtomicInteger(); + var timeline = + new Timelines().repeatableButtonTimeline(new Pane(), e -> count.incrementAndGet()); + timeline.handle(new ActionEvent()); + assertEquals(1, count.get()); + }); + } + + @Test + void handlerIsOptional() { + runFx(() -> new LongPressDelayTimeline().handle(new ActionEvent())); + } + + @Test + void longPressDelayFiresAfterDelay() { + var count = new AtomicInteger(); + runFx( + () -> + new Timelines() + .longPressDelayTimeline(new Pane(), e -> count.incrementAndGet()) + .playFromStart()); + assertTrue(FxTestSupport.waitFor(() -> count.get() == 1, 3000)); + } + + @Test + void timelineWithoutDelayIsDisabled() { + runFx( + () -> { + var noDelay = new ButtonTimeline(0) {}; + assertFalse(noDelay.isEnabled()); + var nanDelay = new ButtonTimeline(Double.NaN) {}; + assertFalse(nanDelay.isEnabled()); + }); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/robot/FXRobotHandlerTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/robot/FXRobotHandlerTest.java new file mode 100644 index 00000000..8bb86730 --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/robot/FXRobotHandlerTest.java @@ -0,0 +1,160 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.robot; + +import static org.comtel2000.keyboard.control.FxTestSupport.runFx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.awt.event.KeyEvent; +import java.util.ArrayList; +import java.util.List; +import javafx.scene.Scene; +import javafx.scene.control.TextField; +import javafx.scene.input.KeyCode; +import javafx.scene.layout.VBox; +import javafx.stage.Popup; +import javafx.stage.Stage; +import org.comtel2000.keyboard.control.FxTestSupport; +import org.comtel2000.keyboard.control.KeyboardPane; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class FXRobotHandlerTest { + + private Stage stage; + private TextField field; + private KeyboardPane keyboard; + private final List events = new ArrayList<>(); + private final FXRobotHandler robot = new FXRobotHandler(); + + @BeforeAll + static void initToolkit() { + FxTestSupport.startToolkit(); + } + + @BeforeEach + void setUp() { + runFx( + () -> { + field = new TextField(); + field.addEventFilter(javafx.scene.input.KeyEvent.ANY, events::add); + keyboard = new KeyboardPane(); + stage = new Stage(); + stage.setScene(new Scene(new VBox(field, keyboard), 300, 200)); + stage.show(); + field.requestFocus(); + }); + } + + @AfterEach + void tearDown() { + runFx(stage::close); + } + + private void send(char ch, boolean ctrl) { + runFx(() -> robot.sendToComponent(keyboard, ch, ctrl)); + // the robot posts the key events with Platform.runLater + FxTestSupport.waitForFxEvents(); + } + + @Test + void typedCharactersReachFocusedTextField() { + send('h', false); + send('i', false); + runFx(() -> assertEquals("hi", field.getText())); + assertEquals(6, events.size(), "pressed, typed and released per char"); + } + + @Test + void controlKeysAreMappedToKeyCodes() { + send('a', false); + send('b', false); + send((char) KeyEvent.VK_BACK_SPACE, true); + runFx(() -> assertEquals("a", field.getText())); + send((char) KeyEvent.VK_LEFT, true); + runFx(() -> assertEquals(0, field.getCaretPosition())); + send((char) KeyEvent.VK_DELETE, true); + runFx(() -> assertEquals("", field.getText())); + } + + @Test + void allSpecialKeysAreFiredAsPressedAndReleased() { + char[] keys = { + KeyEvent.VK_ENTER, KeyEvent.VK_ESCAPE, KeyEvent.VK_SPACE, KeyEvent.VK_TAB, + KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_RIGHT, KeyEvent.VK_HOME, + KeyEvent.VK_END, KeyEvent.VK_PAGE_UP, KeyEvent.VK_PAGE_DOWN, KeyEvent.VK_HELP, + KeyEvent.VK_PRINTSCREEN, KeyEvent.VK_F1, KeyEvent.VK_F2, KeyEvent.VK_F3, + KeyEvent.VK_F4, KeyEvent.VK_F5, KeyEvent.VK_F6, KeyEvent.VK_F7, + KeyEvent.VK_F8, KeyEvent.VK_F9, KeyEvent.VK_F10, KeyEvent.VK_F11, + KeyEvent.VK_F12 + }; + KeyCode[] expected = { + KeyCode.ENTER, KeyCode.ESCAPE, KeyCode.SPACE, KeyCode.TAB, + KeyCode.UP, KeyCode.DOWN, KeyCode.RIGHT, KeyCode.HOME, + KeyCode.END, KeyCode.PAGE_UP, KeyCode.PAGE_DOWN, KeyCode.HELP, + KeyCode.PRINTSCREEN, KeyCode.F1, KeyCode.F2, KeyCode.F3, + KeyCode.F4, KeyCode.F5, KeyCode.F6, KeyCode.F7, + KeyCode.F8, KeyCode.F9, KeyCode.F10, KeyCode.F11, + KeyCode.F12 + }; + for (int i = 0; i < keys.length; i++) { + events.clear(); + send(keys[i], true); + // TAB may move the focus away from the field; restore it + runFx(field::requestFocus); + assertTrue(events.size() >= 1, "no event for " + expected[i]); + assertEquals(expected[i], events.get(0).getCode()); + assertEquals(javafx.scene.input.KeyEvent.KEY_PRESSED, events.get(0).getEventType()); + } + } + + @Test + void ctrlLetterIsSentAsShortcut() { + send('a', true); + assertEquals(2, events.size(), "pressed and released"); + var pressed = events.get(0); + assertEquals(KeyCode.A, pressed.getCode()); + assertTrue(pressed.isShortcutDown()); + } + + @Test + void ctrlWithUnknownKeyCodeIsTyped() { + send('€', true); + assertEquals(3, events.size()); + assertEquals(KeyCode.UNDEFINED, events.get(0).getCode()); + } + + @Test + void keyboardInPopupSendsToOwnerScene() { + var popup = FxTestSupport.callFx(Popup::new); + runFx( + () -> { + var popupKeyboard = new KeyboardPane(); + popup.getContent().add(popupKeyboard); + popup.show(stage); + field.requestFocus(); + robot.sendToComponent(popupKeyboard, 'x', false); + }); + FxTestSupport.waitForFxEvents(); + runFx( + () -> { + assertEquals("x", field.getText()); + popup.hide(); + }); + } + + @Test + void noFocusOwnerIsIgnored() { + runFx( + () -> { + var other = new Stage(); + var kb = new KeyboardPane(); + other.setScene(new Scene(kb)); + robot.sendToComponent(kb, 'x', false); + }); + FxTestSupport.waitForFxEvents(); + assertTrue(events.isEmpty()); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/robot/RecordingRobot.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/robot/RecordingRobot.java new file mode 100644 index 00000000..c5a73cd2 --- /dev/null +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/robot/RecordingRobot.java @@ -0,0 +1,37 @@ +/* Copyright (c) 2025-2000 comtel2000 (BSD 3-Clause) */ +package org.comtel2000.keyboard.robot; + +import java.util.ArrayList; +import java.util.List; + +/** {@link IRobot} that records every key sent by the keyboard. */ +public class RecordingRobot implements IRobot { + + /** A single key sent to the robot. */ + public record Sent(char ch, boolean ctrl) {} + + private final List sent = new ArrayList<>(); + + @Override + public void sendToComponent(Object kb, char ch, boolean ctrl) { + sent.add(new Sent(ch, ctrl)); + } + + public List sent() { + return sent; + } + + public String text() { + var sb = new StringBuilder(); + sent.forEach(s -> sb.append(s.ch())); + return sb.toString(); + } + + public Sent last() { + return sent.isEmpty() ? null : sent.get(sent.size() - 1); + } + + public void clear() { + sent.clear(); + } +} diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/xml/XmlHelperTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/xml/XmlHelperTest.java index e4f95d69..af8c6884 100644 --- a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/xml/XmlHelperTest.java +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/xml/XmlHelperTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; +import java.io.StringReader; import java.net.URL; import javax.xml.stream.*; import org.junit.jupiter.api.Test; @@ -79,4 +80,60 @@ void readBooleanAttribute() throws XMLStreamException, FactoryConfigurationError } } } + + private static XMLStreamReader keyboard(String attributes) throws XMLStreamException { + XMLStreamReader reader = + XMLInputFactory.newInstance() + .createXMLStreamReader(new StringReader("")); + reader.next(); + return reader; + } + + @Test + void readDoubleAttribute() throws XMLStreamException { + XMLStreamReader reader = keyboard("keyWidth=\"40.5\" keyHeight=\"x\" verticalGap=\"\""); + assertEquals(40.5, XmlHelper.readDoubleAttribute(reader, XmlHelper.ATTR_KEY_WIDTH).orElse(-1d)); + assertTrue(XmlHelper.readDoubleAttribute(reader, XmlHelper.ATTR_KEY_HEIGHT).isEmpty()); + assertTrue(XmlHelper.readDoubleAttribute(reader, "missing").isEmpty()); + + assertEquals(40.5, XmlHelper.readDoubleAttribute(reader, XmlHelper.ATTR_KEY_WIDTH, 1d)); + assertEquals(1d, XmlHelper.readDoubleAttribute(reader, XmlHelper.ATTR_KEY_HEIGHT, 1d)); + assertEquals(1d, XmlHelper.readDoubleAttribute(reader, XmlHelper.ATTR_V_GAP, 1d)); + assertEquals(1d, XmlHelper.readDoubleAttribute(reader, "missing", 1d)); + } + + @Test + void invalidIntAttributesUseDefault() throws XMLStreamException { + XMLStreamReader reader = keyboard("keyWidth=\"4.5\" keyHeight=\"abc\""); + assertTrue(XmlHelper.readIntAttribute(reader, XmlHelper.ATTR_KEY_WIDTH).isEmpty()); + assertTrue(XmlHelper.readIntAttribute(reader, XmlHelper.ATTR_KEY_HEIGHT).isEmpty()); + assertEquals(7, XmlHelper.readIntAttribute(reader, XmlHelper.ATTR_KEY_WIDTH, 7)); + assertEquals(7, XmlHelper.readIntAttribute(reader, XmlHelper.ATTR_KEY_HEIGHT, 7)); + } + + @Test + void booleanAttributeValues() throws XMLStreamException { + XMLStreamReader reader = keyboard("sticky=\"TRUE\" movable=\"yes\" repeatable=\"false\""); + assertTrue(XmlHelper.readBooleanAttribute(reader, XmlHelper.ATTR_STICKY, false)); + assertFalse(XmlHelper.readBooleanAttribute(reader, XmlHelper.ATTR_MOVABLE, true)); + assertFalse(XmlHelper.readBooleanAttribute(reader, XmlHelper.ATTR_REPEATABLE, true)); + assertTrue(XmlHelper.readBooleanAttribute(reader, "missing", true)); + } + + @Test + void parseIntSupportsHex() { + assertEquals(98, XmlHelper.parseInt("98")); + assertEquals(-5, XmlHelper.parseInt("-5")); + assertEquals(0x62, XmlHelper.parseInt("0x62")); + assertEquals(0x20AC, XmlHelper.parseInt("0x20AC")); + assertThrows(NumberFormatException.class, () -> XmlHelper.parseInt("x")); + } + + @Test + void closeIgnoresNullAndClosedReaders() throws XMLStreamException { + XmlHelper.close(null); + XMLStreamReader reader = keyboard(""); + XmlHelper.close(reader); + XmlHelper.close(reader); + } } diff --git a/fx-onscreen-keyboard/src/test/resources/xml/region/kb-empty-style.xml b/fx-onscreen-keyboard/src/test/resources/xml/region/kb-empty-style.xml new file mode 100644 index 00000000..f4df7ac1 --- /dev/null +++ b/fx-onscreen-keyboard/src/test/resources/xml/region/kb-empty-style.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/fx-onscreen-keyboard/src/test/resources/xml/region/kb-features.xml b/fx-onscreen-keyboard/src/test/resources/xml/region/kb-features.xml new file mode 100644 index 00000000..55ccd1dd --- /dev/null +++ b/fx-onscreen-keyboard/src/test/resources/xml/region/kb-features.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/fx-onscreen-keyboard/src/test/resources/xml/region/kb-invalid.xml b/fx-onscreen-keyboard/src/test/resources/xml/region/kb-invalid.xml new file mode 100644 index 00000000..4858937e --- /dev/null +++ b/fx-onscreen-keyboard/src/test/resources/xml/region/kb-invalid.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/pom.xml b/pom.xml index 70cbde5b..c9c2060d 100644 --- a/pom.xml +++ b/pom.xml @@ -61,6 +61,12 @@ ${junit.version} test + + org.junit.jupiter + junit-jupiter-params + ${junit.version} + test + org.slf4j slf4j-api @@ -155,6 +161,26 @@ com.diffplug.spotless spotless-maven-plugin + + org.jacoco + jacoco-maven-plugin + 0.8.14 + + + prepare-agent + + prepare-agent + + + + report + test + + report + + + + From 879dadaa30709b8647135d1e3ef71d66ceea9467 Mon Sep 17 00:00:00 2001 From: sunny Date: Wed, 18 Nov 2026 20:51:44 +0000 Subject: [PATCH 2/4] Add Claude Code project context (AGENTS.md, .claude agents, docs and skills) Mirrors the eclipse-milo .claude layout: CLAUDE.md imports AGENTS.md, a maven-command-runner agent, focused docs for tests, conventions, docs and keyboard layouts, plus an add-keyboard-layout skill. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVKTE7jdB7EUYDA7qUT95U --- .claude/agents/maven-command-runner.md | 248 ++++++++++++++++++++ .claude/docs/documentation-guidelines.md | 112 +++++++++ .claude/docs/java-coding-conventions.md | 76 ++++++ .claude/docs/keyboard-layouts.md | 75 ++++++ .claude/docs/running-tests.md | 84 +++++++ .claude/docs/test-guidelines.md | 71 ++++++ .claude/skills/add-keyboard-layout/SKILL.md | 64 +++++ AGENTS.md | 79 +++++++ CLAUDE.md | 1 + 9 files changed, 810 insertions(+) create mode 100644 .claude/agents/maven-command-runner.md create mode 100644 .claude/docs/documentation-guidelines.md create mode 100644 .claude/docs/java-coding-conventions.md create mode 100644 .claude/docs/keyboard-layouts.md create mode 100644 .claude/docs/running-tests.md create mode 100644 .claude/docs/test-guidelines.md create mode 100644 .claude/skills/add-keyboard-layout/SKILL.md create mode 100644 AGENTS.md create mode 100644 CLAUDE.md diff --git a/.claude/agents/maven-command-runner.md b/.claude/agents/maven-command-runner.md new file mode 100644 index 00000000..d36cfb47 --- /dev/null +++ b/.claude/agents/maven-command-runner.md @@ -0,0 +1,248 @@ +--- +name: maven-command-runner +description: Runs Maven commands with output captured to a unique per-run log file. Use this agent to execute Maven goals (compile, test, package, etc.) and get quick success/failure feedback. If the build fails, it will automatically analyze the output and report the issues. This agent ONLY runs commands and reports results - it never modifies code. +tools: Bash, Read, Grep, Glob, LS +model: sonnet +--- + +You are a specialist at running Maven commands and reporting results. Your job is to execute Maven goals, capture output, and provide clear success/failure feedback with detailed analysis when builds fail. + +## CRITICAL: Report Only – Never Fix + +**You are a READ-ONLY agent.** Your sole purpose is to: + +1. Run the requested Maven command +2. Analyze the output +3. Report results back to the calling agent + +**You must NEVER:** + +- Attempt to fix compilation errors +- Modify any source code files +- Edit test files +- Make any changes to resolve failures +- Re-run commands hoping for different results +- Enter a loop trying to resolve issues + +The only files you create are your own log files. When a build fails, your job is DONE after reporting the failure details. The calling agent will decide how to proceed. Simply report what failed and return control immediately. + +## Core Rules + +- Run Maven as `mvn -q -B` (quiet, batch mode). The project targets Java 17; any JDK 17, 21 or 25 works. +- Drop `-q` only when the caller asks for verbose output. +- Before running any test command, read `.claude/docs/running-tests.md` and follow its module targeting and test selection guidance. +- If the caller asks for several Maven commands, run them in order, one run per command, and stop at the first failure unless the caller asks you to continue. +- Other agents may be running Maven in other worktrees at the same time. Only read the log files you created in this run. Never glob, list, or search a temp directory for logs. + +## Log Files + +Each Maven command gets its own log under the system temp directory, named by `mktemp`: + +- `mktemp` creates a new file with a random suffix, so two runs never share a path, even in parallel worktrees. +- The log stays outside `target/`, so `mvn clean` can't delete it mid-build. +- The temp directory is writable in sandboxed sessions. + +`mktemp` prints a path such as `/var/folders/.../T/maven-compile.a1B2c3`. Call it `RUN`. One command uses three files: + +- `RUN` is an empty marker whose modification time is the start of the run. +- `RUN.log` holds all Maven output. +- `RUN.exit` holds Maven's exit code. The command writes it only after Maven exits. + +## Command Pattern + +Every Maven command takes two Bash calls. + +**Call 1: create the run path.** Replace `` with a short name such as `compile`, `test`, `verify`, or `spotless-apply`. + +```bash +d="${TMPDIR:-/tmp}"; mktemp "${d%/}/maven-.XXXXXX" +``` + +**Call 2: run Maven.** Paste the path from call 1 in place of ``. Replace `` with the Maven goals, flags, and properties. Pass `timeout: 600000` (10 minutes, the maximum) to the Bash tool. Do not set `run_in_background`. + +```bash +run='' +mvn -q -B >"$run.log" 2>&1; rc=$? +echo "$rc" >"$run.exit" +echo "EXIT $rc $run.log" +``` + +Keep the variable name `rc`. `status` is read-only in zsh. + +The `EXIT ` line is the result. Exit code 0 means success. Any other code means failure. + +## Long Builds + +A command that runs longer than the Bash timeout is moved to the background by the harness, and you get a task id instead of the `EXIT` line. Maven keeps running. Wait for `RUN.exit` with this bounded loop, again with `timeout: 600000`: + +```bash +run='' +i=0; while [ ! -f "$run.exit" ] && [ "$i" -lt 108 ]; do sleep 5; i=$((i+1)); done +if [ -f "$run.exit" ]; then echo "EXIT $(cat "$run.exit") $run.log"; else echo "RUNNING $run.log"; fi +``` + +- The loop ends within 9 minutes. If it prints `RUNNING`, run it again. Stop after 6 rounds (about 1 hour) and report that Maven is still running, with the log path. Do not report success or failure in that case. +- If a completion notification for the task arrives, still read the exit code from `RUN.exit`. +- Never use `tail -f`, and never poll for a file other than `RUN.exit`. Those waits never end. + +## Reading Results + +Read the log only after `RUN.exit` exists. Before that, Maven is still writing it. + +Test output can make a log several MB, which is too large for the Read tool. Never read a whole log. Check its size, then grep for the lines that matter: + +```bash +run='' +wc -c <"$run.log" +grep -c -E '^\[ERROR\]|Tests run:|BUILD (SUCCESS|FAILURE)' "$run.log" +grep -n -m 100 -E '^\[ERROR\]|Tests run:|BUILD (SUCCESS|FAILURE)' "$run.log" +``` + +- `-m 100` caps the matches, so the output stays small. +- The `grep -c` line counts all matches. If there are more than 100, also print the last `[ERROR]` + lines, where Maven summarizes the failed goal: `grep -n -E '^\[ERROR\]' "$run.log" | tail -n 40`. + Piping `grep` is fine here because the result comes from `RUN.exit`. +- For context around a match, use the Read tool with `offset` and `limit` (at most 200 lines). +- With `-q`, a passing build prints few or no lines, so an empty grep, which exits 1, is normal after exit code 0. + +For test counts, read the surefire and failsafe reports in this worktree. Filter them with `-newer "$run"` so reports left over from earlier runs don't count: + +```bash +run='' +find . -path '*/target/surefire-reports/*.txt' -newer "$run" -exec grep -h 'Tests run:' {} + +find . -path '*/target/failsafe-reports/*.txt' -newer "$run" -exec grep -h 'Tests run:' {} + +``` + +Use relative paths from the current directory, which is your worktree. Never read reports or logs from another worktree. + +## Common Commands + +These are the `` for call 2. + +| Task | Goals | +|-----------------------|----------------------------------------------------------------------------------------------------| +| Format code | `spotless:apply` | +| Compile | `clean compile` | +| Compile one module | `-pl fx-onscreen-keyboard-swing -am compile` | +| Run one test class | `-pl fx-onscreen-keyboard test -Dtest=ClassName` | +| Test a dependent | `-pl fx-onscreen-keyboard-swing -am test -Dtest=ClassName -Dsurefire.failIfNoSpecifiedTests=false` | +| Package without tests | `package -DskipTests` | +| Full build with tests | `clean verify` | +| Full stack trace | add `-e` | + +`fx-onscreen-keyboard-swing` and `fx-onscreen-keyboard-samples` depend on `fx-onscreen-keyboard`, +so a build of either one alone needs `-am` unless the core module is already installed. With +`-am`, `-Dsurefire.failIfNoSpecifiedTests=false` keeps upstream modules without a matching test +from failing the build. + +## Failure Analysis + +When the exit code is not 0: + +- Grep the log as shown above. +- Identify the failure type: + - **Compilation errors**: `[ERROR]` lines with file paths and line numbers + - **Test failures**: test class names, method names, and assertion messages + - **Dependency issues**: resolution failures or missing artifacts + - **Configuration problems**: plugin or POM errors +- Extract only the relevant lines, with file:line references when Maven reports them. + +## Output Format + +Report success only when `RUN.exit` contains 0. Quote the `EXIT` line as evidence. + +### For Successful Builds: +``` +Maven build succeeded. +- Command: mvn -q -B +- Exit code: 0 +- Tests: [counts from the reports, if tests ran] +- Log: .log +``` + +### For Failed Builds: +``` +Maven build failed. +- Command: mvn -q -B +- Exit code: + +## Error Summary +[Brief description of what failed] + +## Details +[Specific error messages with file:line references] + +## Log +.log +``` + +### For Builds Still Running After the Wait Limit: +``` +Maven build still running after about 1 hour. No result yet. +- Command: mvn -q -B +- Log: .log +- Exit code will appear in: .exit +``` + +## Example Failure Analysis + +When a compilation fails, report like this: +``` +Maven build failed. +- Command: mvn -q -B -pl fx-onscreen-keyboard -am compile +- Exit code: 1 + +## Error Summary +Compilation error in 2 files. + +## Details +- `src/main/java/org/comtel2000/keyboard/control/KeyboardPane.java:42` - cannot find symbol: method bar() +- `src/main/java/org/comtel2000/keyboard/control/KeyButton.java:15` - incompatible types: String cannot be converted to int + +## Log +/var/folders/.../T/maven-compile.a1B2c3.log +``` + +When tests fail, report like this: +``` +Maven build failed. +- Command: mvn -q -B -pl fx-onscreen-keyboard test -Dtest=XmlHelperTest +- Exit code: 1 + +## Error Summary +2 test failures in XmlHelperTest. + +## Details +- `readIntAttribute` - expected: <40> but was: <-1> +- `readAttribute` - NullPointerException at XmlHelperTest.java:18 + +## Log +/var/folders/.../T/maven-test.d4E5f6.log +``` + +## What NOT to Do + +- **NEVER attempt to fix code** – You are a reporting agent only +- **NEVER modify source files** – No edits, no writes, no fixes +- **NEVER retry hoping for success** – Run once, report, and return +- **NEVER enter a fix-and-retry loop** – This is the most critical rule +- **NEVER report success without exit code 0 from `RUN.exit`** +- Don't run Maven without capturing output to a new `mktemp` path +- Don't use fixed log names such as `/tmp/maven_test.log` +- Don't read logs or reports that another run or worktree created +- Don't read a log before `RUN.exit` exists, and don't read a whole log +- Don't use `tail -f` or unbounded wait loops +- Don't pipe Maven through `head`, `tail`, or `grep`. The pipe hides Maven's exit code. +- Don't include the entire build output in your response (summarize instead) +- Don't guess at errors – grep the actual log + +## When to Return + +Return to the calling agent immediately after: + +- A successful build (report success) +- A failed build (report failure details) +- A build still running after the wait limit (report the log path) +- Any error running the command + +Do NOT continue working after reporting results. Your task is complete once you've provided the build status and any relevant error details. diff --git a/.claude/docs/documentation-guidelines.md b/.claude/docs/documentation-guidelines.md new file mode 100644 index 00000000..4f52befb --- /dev/null +++ b/.claude/docs/documentation-guidelines.md @@ -0,0 +1,112 @@ +# Documentation Guidelines + +## General + +Documentation comments should help someone **reading the code** understand what something is, how +to use it, and, at package level, how related APIs fit together. Class and method documentation +should stay caller-focused; use package-level documentation for broader onboarding context. Avoid +references to plans, tasks, or decisions that led to the current implementation. + +### Class-Level Documentation + +State **what** the class is and **when** you'd use it. If it has a non-obvious lifecycle or +usage pattern, describe that. + +**Include:** +- What the class represents or does (one or two sentences) +- How a caller interacts with it, if non-obvious +- Important constraints (thread-safety, lifecycle, ownership) +- Collaborating APIs or runtime boundaries a caller must coordinate with +- For public API classes: a short code example if usage isn't obvious from the signature + +**Omit:** +- How it works internally ("uses a ConcurrentHashMap to…", "delegates to…") +- Design rationale ("we chose this approach because…") +- References to plans, tasks, or implementation history + +### Method/Function-Level Documentation + +State **what** the method or constructor does from the caller's perspective. + +**Include:** +- What it does and what it returns, when applicable +- Parameter semantics when the name alone isn't enough +- Notable caller-visible behavior: side effects, threading (FX thread or not), exceptions, or nullability contracts +- Observable handoffs to related APIs, services, or lifecycle state when they affect correct use +- For public API methods and constructors: a short code example when the call has + non-obvious usage patterns, required call sequences, or interacts with other API surfaces in + ways the signature doesn't convey + +**Omit:** +- Step-by-step description of the implementation +- Internal algorithms or data structures used +- Assumptions that are only meaningful to someone editing the method body + +### Code Examples + +When a class, constructor, or method is part of the public API, consider +whether a code example would help a user understand how to use it. Good candidates for examples: + +- Builder patterns or multistep construction +- Methods that participate in a larger call sequence +- Non-obvious parameter combinations or return value interpretation + +Keep examples minimal — show the common case, not every option. If the usage is clear from the +signature and parameter names alone, skip the example. + +### Package-Level Documentation + +Prefer adding `package-info.java` files to Java packages whose purpose, data flow, runtime +boundaries, or collaboration model is not obvious from the class names alone. These files are useful +even when the package is not annotated with `@NullMarked`; package annotations are a bonus, not the +only reason to create package-level documentation. + +Package documentation should be high-level, explanatory, and onboarding-focused. It is allowed to be +more verbose than class or method documentation because its job is to help a developer build the +mental model they need before reading or changing several related classes. + +**Include:** +- What responsibility the package owns, in concrete product/runtime terms +- How the most important types fit together and where callers enter the package +- Key data flows, lifecycle phases, validation layers, threading expectations, or ownership rules +- Boundaries with other packages, the Swing bridge, robots, or the JavaFX runtime +- Important invariants the package maintains across multiple classes +- Extension guidance: what belongs in the package, what should stay elsewhere, and which layer has + final authority when responsibilities are split + +**Omit:** +- Generated boilerplate such as "provides classes for..." +- A flat inventory of every class in the package +- Method-by-method API reference that belongs on the individual classes or methods +- Implementation trivia that only matters inside one method body +- Historical notes about tasks, tickets, abandoned alternatives, or why a change was originally made + +Good package docs often use short sections such as "Data flow", "Lifecycle", "Runtime boundaries", +"Validation", "Ownership", or "Extension points". Name important classes when that helps explain +the architecture, but describe their roles and relationships rather than restating their signatures. + +### Rule of Thumb + +If a sentence only is useful to someone **modifying the implementation**, it belongs in a +code comment inside the body, not in the documentation comment. Documentation comments are for +**callers**. + +## Javadoc Guidelines + +Apply the general documentation guidelines to Java APIs, with the Java-specific guidance below. + +### Method/Constructor-Level Javadoc + +For Java methods and constructors, be explicit about checked exceptions, caller-visible runtime +exceptions, and nullability contracts when they are not obvious from the signature. + +### Javadoc Tag Formatting + +Descriptions for Javadoc block tags such as `@param`, `@return`, and `@throws` must begin with a +lowercase letter and end with a period. + +### Code Examples in Javadoc + +Use Java syntax in examples. Include constructors in example consideration when construction is +part of the public API and usage is not obvious from the signature. + diff --git a/.claude/docs/java-coding-conventions.md b/.claude/docs/java-coding-conventions.md new file mode 100644 index 00000000..9d791580 --- /dev/null +++ b/.claude/docs/java-coding-conventions.md @@ -0,0 +1,76 @@ +# Java Coding Conventions + +## Formatting + +Formatting is owned by Spotless with google-java-format (2-space indent, 100-column limit). Every +Java file starts with the license header: + +```java +/* Copyright (c) 2025 comtel2000 (BSD 3-Clause) */ +``` + +Run `mvn -q -B spotless:apply` after editing. Don't hand-format or reflow code the formatter +would change anyway. + +## Variables and Types + +Use `var` for local variables only when the type is obvious from the right-hand side. When in +doubt, write the explicit type. + +**Obvious from the right-hand side:** + +- Constructor calls with concrete types: `new KeyboardPane()`, `new ArrayList()` +- Literals and `List.of(...)` / `Map.of(...)` with literals +- Standard library methods with obvious return types: `isEmpty()`, `size()`, `toString()` + +```java +// Good: type is clear +var keyboard = new KeyboardPane(); +var latch = new CountDownLatch(1); + +// Good: explicit type when the call doesn't say it +Region pane = keyboard.getKeyboardPane(url); +Map locales = keyboard.getAvailableLocales(); + +// Avoid +var result = load(); // what type? +``` + +## Imports + +Import classes and use simple names. Use a fully qualified name only to resolve a clash, such as +`java.awt.event.KeyEvent` next to `javafx.scene.input.KeyEvent`. Avoid wildcard imports in main +code. + +## JavaFX + +- Touch the scene graph only on the JavaFX Application Thread. Use `Platform.runLater(...)` from + other threads. +- Follow the existing lazy property pattern in `KeyboardPane`: a plain field holds the value until + the `xxxProperty()` accessor is first called, then the property object takes over. Keep + `getXxx()`, `setXxx(...)` and `xxxProperty()` together and final. +- Style through the CSS in `KeyboardButtonStyle.css` and style classes, not inline `setStyle`. +- Swing code in `fx-onscreen-keyboard-swing` must touch Swing components on the EDT + (`SwingUtilities.invokeLater`) and JavaFX nodes on the FX thread. Don't block one thread on the + other. + +## Modules (JPMS) + +Each module has a `module-info.java`. When you add a package that callers need, export it there. +When you add a dependency, add the matching `requires`. Resource folders read through +`Class.getResource` from another module must be in an opened or same-module package. + +## Logging + +Use SLF4J (`LoggerFactory.getLogger(Foo.class)`) with `{}` placeholders. Don't use +`System.out` or `printStackTrace` in main code. + +## Documentation + +- Document public API with Javadoc. See `documentation-guidelines.md`. +- Javadoc tag descriptions begin with a lowercase letter and end with a period. + +## Other + +For anything not covered here, follow established Java best practice. The code base targets +Java 17 and must also build and test on JDK 21 and 25. diff --git a/.claude/docs/keyboard-layouts.md b/.claude/docs/keyboard-layouts.md new file mode 100644 index 00000000..9c18bd20 --- /dev/null +++ b/.claude/docs/keyboard-layouts.md @@ -0,0 +1,75 @@ +# Keyboard Layouts + +Layouts are XML files validated by +`fx-onscreen-keyboard/src/main/resources/org/comtel2000/keyboard/control/layer/kb-layout.xsd`. + +## Where layouts live + +``` +layer/ + default/ DefaultLayer.DEFAULT (English is the folder root) + kb-layout*.xml + de/ es/ ru/ one folder per language, named by ISO 639 language code + numblock/ DefaultLayer.NUMBLOCK (same layout set plus a number block) + kb-layout*.xml + de/ es/ ru/ +``` + +`KeyboardLocales` lists the language folders under the active layer and maps each to a `Locale`. +The layer root itself is `Locale.ENGLISH`. Callers can point `KeyboardPane.setLayerPath(...)` at a +folder on disk with the same structure to use their own layouts. + +## One file per keyboard type + +`LayoutLocaleSwitcher` loads these files from the locale folder: + +| File | `KeyboardType` | +|-----------------------------|----------------| +| `kb-layout.xml` | `TEXT` | +| `kb-layout-shift.xml` | `TEXT_SHIFT` | +| `kb-layout-sym.xml` | `SYMBOL` | +| `kb-layout-sym-shift.xml` | `SYMBOL_SHIFT` | +| `kb-layout-ctrl.xml` | `CTRL` | +| `kb-layout-numeric.xml` | `NUMERIC` | +| `kb-layout-email.xml` | `EMAIL` | +| `kb-layout-url.xml` | `URL` | + +A file missing from a locale folder falls back to the English file in the layer root. A type with +no file at all falls back to `TEXT` (or `SYMBOL` for `NUMERIC`). So a language folder only needs +the files that differ from English, but in practice each language ships the five text, shift, +symbol, symbol-shift and ctrl files. + +## XML structure + +```xml + + + + + + + + +``` + +- `codes`: comma-separated code points. The first is the key; the rest are offered in the long-press + popup (`MultiKeyButton`). An empty `codes` is a spacer. +- Negative codes are the special keys in `StandardKeyCode` (for example `-1` shift, `-2` symbol, + `-5` backspace, `-7` locale switch, `-9` enter). Add new special keys there, not as magic numbers. +- `keyLabel` is the text shown. `keyOutputText` overrides the text that is typed. +- `keyLabelStyle` / `keyIconStyle` refer to classes in `KeyboardButtonStyle.css`; + `.font-fxkeyboard` uses the glyphs in `FontKeyboardFX.ttf`. +- `keyWidth` on a key overrides the keyboard default. `repeatable`, `sticky` and `movable` are + booleans. +- The locale switch key (`-7`) lists every available locale in its popup automatically. + +## Checklist when changing layouts + +- Keep the same file set in `default/` and `numblock/` so both layers support the + language. +- Keep row widths consistent between a layout and its shift / symbol variants so the keyboard does + not jump in size when the user switches. +- Save files as UTF-8 with LF line endings. +- Validate each file against `kb-layout.xsd`, for example + `xmllint --noout --schema .../layer/kb-layout.xsd .../layer/default//*.xml`. +- If a screenshot in `doc/` or the README feature list changes, update it. diff --git a/.claude/docs/running-tests.md b/.claude/docs/running-tests.md new file mode 100644 index 00000000..f9e022b3 --- /dev/null +++ b/.claude/docs/running-tests.md @@ -0,0 +1,84 @@ +# Running Tests + +This is a multi-module project. Target the module with `-pl` so a `-Dtest` filter is not applied +to every module. + +All tests currently live in `fx-onscreen-keyboard/src/test/java`. Test layout XML files live in +`fx-onscreen-keyboard/src/test/resources/xml/`. + +## Running Specific Tests + +**Run a specific test class:** + +```bash +mvn -q -B -pl fx-onscreen-keyboard test -Dtest=XmlHelperTest +``` + +**Run a specific test method:** + +```bash +mvn -q -B -pl fx-onscreen-keyboard test -Dtest=XmlHelperTest#readAttribute +``` + +**Run tests matching a pattern:** + +```bash +mvn -q -B -pl fx-onscreen-keyboard test -Dtest='Key*Test' +``` + +## Module Targeting Flags + +- **`-pl `**: build/test only the given module(s) +- **`-am`** (also-make): also build the modules the `-pl` target depends on +- **`-amd`** (also-make-dependents): also build the modules that depend on the `-pl` target + +### When to use each + +**`-pl` alone**: the change and the tests are in the same module. + +```bash +mvn -q -B -pl fx-onscreen-keyboard test -Dtest=ClassName +``` + +**`-pl ... -am`**: the change is in `fx-onscreen-keyboard` and the tests are in +`fx-onscreen-keyboard-swing`. This rebuilds the core module so tests run against the latest code: + +```bash +mvn -q -B -pl fx-onscreen-keyboard-swing -am test -Dtest=ClassName -Dsurefire.failIfNoSpecifiedTests=false +``` + +**`-pl ... -amd`**: the change is in the core module and you want everything that depends on it +to compile and test: + +```bash +mvn -q -B -pl fx-onscreen-keyboard -amd test +``` + +### Rule of thumb + +If the code you changed and the tests you run are in **different modules**, add `-am`. Without it +the tests run against a stale core jar from your local repository. + +## JavaFX Tests and Headless Mode + +Tests that create JavaFX nodes need the JavaFX toolkit. CI runs on Linux without a display, so: + +- Surefire sets `java.awt.headless=true` (root `pom.xml`). +- `KeyButtonTest` shows the pattern: in `@BeforeAll`, set `prism.order=sw`, use the Monocle + headless platform when its classes are on the class path, then call `Platform.startup(...)` and + ignore `IllegalStateException` if the toolkit is already running. +- Run JavaFX code inside `Platform.runLater(...)` and wait with a `CountDownLatch` and a + `@Timeout`, rethrowing any captured exception on the test thread. +- `KeyButtonTest` is disabled on JDK 25 (`@DisabledOnJre(JRE.JAVA_25)`) until Monocle works there. + Follow the same pattern for new toolkit tests rather than letting CI hang. + +Prefer tests that need no toolkit at all, such as XML parsing through `XmlHelper` or pure logic, +when the behavior allows it. + +## Run All Tests + +```bash +mvn -q -B clean verify +``` + +`verify` also runs `spotless:check`. Run `mvn -q -B spotless:apply` first if formatting fails. diff --git a/.claude/docs/test-guidelines.md b/.claude/docs/test-guidelines.md new file mode 100644 index 00000000..52dda822 --- /dev/null +++ b/.claude/docs/test-guidelines.md @@ -0,0 +1,71 @@ +# Test Guidelines + +## Every test must justify its existence + +A test earns its place by verifying a **behavior that matters**: something that could break in a +way a user of the keyboard would notice, such as a wrong character typed, a layout that fails to +load, a key that keeps repeating, or a popup in the wrong place. If you can't say what would go +wrong if the test were deleted, the test probably shouldn't exist. + +## Name the WHAT, comment the WHY + +Name test methods as camelCase sentences that describe the behavior. Put a `//` comment above the +test to explain *why* it matters when the name alone doesn't. + +```java +// Holding one repeatable key and then pressing another must not leave the +// first key repeating, or the user gets a stream of unwanted characters. +@Test +void previousTimelineStoppedWhenNewPressed() { + ... +} +``` + +```java +// Locales without their own file for a keyboard type fall back to the +// English layout instead of showing an empty keyboard. +@Test +void missingLocaleLayoutFallsBackToDefault() { + ... +} +``` + +Skip the comment when the name already says it, as in `readIntAttributeReturnsDefaultForMissingName`. + +## What makes a good test + +**Good tests challenge the code.** They verify: + +- **Behavioral contracts**: shift then a letter key produces the upper-case character +- **Layout parsing**: XML attributes map to key size, codes, popup characters and styles +- **Fallbacks**: an unknown locale or a missing layout file resolves to the default layout +- **Timing**: long press opens the popup, repeatable keys stop on release +- **Error handling**: malformed XML or an invalid key code fails clearly instead of silently + +## What makes a weak test + +**Weak tests run code without testing a decision.** Watch for: + +- **Getter/setter echo tests**: setting a property and asserting it reads back. Only worth it when + the setter has logic. +- **Exhaustive repetition**: if two layouts go through the same parser path, one test covers it. +- **Testing JavaFX itself**: don't test that a `Button` shows its text. +- **Sleep-based timing**: use latches, timeline control, or `@Timeout`, not `Thread.sleep`. + +## Test structure + +- **One behavior per test.** A failing test name should tell you what broke. +- **No logic in tests.** Avoid `if`, `for`, `switch` or `try/catch` in test bodies, except the + `Platform.runLater` capture pattern described in `running-tests.md`. +- **Arrange / Act / Assert.** +- **Use helpers for test data.** Put test layout XML in + `fx-onscreen-keyboard/src/test/resources/xml/` and share loader helpers instead of repeating + stream setup. + +## Conventions + +- JUnit Jupiter (`org.junit.jupiter.api`). Use `assertThrows(...)` for exceptions. +- Prefer `assertEquals(expected, actual)` over `assertTrue(a == b)`. +- Give toolkit tests a `@Timeout` so a stuck FX thread fails the test instead of hanging CI. +- Group related tests with `@Nested` classes named after the behavior area (`LocaleFallback`, + `RepeatKeys`), not after the method under test. diff --git a/.claude/skills/add-keyboard-layout/SKILL.md b/.claude/skills/add-keyboard-layout/SKILL.md new file mode 100644 index 00000000..d205e5c8 --- /dev/null +++ b/.claude/skills/add-keyboard-layout/SKILL.md @@ -0,0 +1,64 @@ +--- +name: add-keyboard-layout +description: Use when adding a new language (locale) layout to the FXOK on-screen keyboard, or adding a missing keyboard type file (shift, symbol, ctrl, numeric, email, url) to an existing language. +--- + +# Add a keyboard layout + +Read `.claude/docs/keyboard-layouts.md` first. It explains the folder structure, the file per +keyboard type, the fallback rules and the XML attributes. + +## Steps + +1. **Pick the language code.** Use the ISO 639 language code in lower case (`fr`, `it`, `pl`). + The folder name becomes the `Locale` and the label on the locale switch popup. + +2. **Start from the closest existing layout.** Copy the five files from the most similar language + in `layer/default/` (English root for Latin QWERTY, `de/` for QWERTZ, `ru/` for Cyrillic): + + ```bash + base=fx-onscreen-keyboard/src/main/resources/org/comtel2000/keyboard/control/layer + mkdir -p "$base/default/" + cp "$base/default/de/"kb-layout*.xml "$base/default//" + ``` + +3. **Edit the keys.** For each letter set `codes` to the Unicode code point (decimal) and + `keyLabel` to the character. Put accented variants after the first code so they show in the + long-press popup, for example `codes="101,233,232,234,235" keyLabel="e"`. Shift files use the + upper-case code points. Set the locale switch key label (`codes="-7"`) to the language code in + upper case. + +4. **Keep widths aligned.** Each row should add up to the same width as the matching row in the + other files of the language, and close to the source layout, so switching shift or symbol does + not resize the keyboard. + +5. **Repeat for the number block layer.** Create `layer/numblock//` the same way, starting + from the numblock files of the source language, and apply the same key changes. The number + block columns stay as they are. + +6. **Validate the XML.** + + ```bash + xmllint --noout --schema "$base/kb-layout.xsd" "$base"/default//*.xml "$base"/numblock//*.xml + ``` + + If `xmllint` is not installed, parse the files with a short `XmlHelper`-based test or a Java + `SchemaFactory` check instead. + +7. **Add a test when behavior is new.** A new language alone needs no Java test. If you added a + new special key or attribute, add a test in `fx-onscreen-keyboard/src/test/java` following + `.claude/docs/test-guidelines.md`. + +8. **Verify.** Use the `maven-command-runner` agent to run `mvn -q -B clean verify`. + +9. **Document.** Mention the new language in the README features or in the PR description. If you + can run the sample (`StandAloneApp` in `fx-onscreen-keyboard-samples`) with a display, take a + screenshot for `doc/layout_.png`; otherwise say the layout was not checked visually. + +## Common mistakes + +- Using hexadecimal code points. `codes` is decimal. +- Adding the language to `default/` but not `numblock/`, so it disappears when the number block + layer is used. +- Forgetting the shift file. The keyboard then falls back to the English shift layout. +- Saving with CRLF line endings. `.gitattributes` expects LF. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..c587fc29 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,79 @@ +# Project Context + +**Tech Stack:** Java 17, OpenJFX 17, Maven multi-module, JUnit Jupiter, SLF4J + +FXOK (fx-experience) is a JavaFX virtual on-screen keyboard for touch screens. Key layouts are +defined in XML, so new languages and keyboard types are added as resources rather than code. + +**Modules:** + +- **fx-onscreen-keyboard**: core JavaFX component (`KeyboardPane`, popup, key buttons, robots, XML + layouts). JPMS module `fx.onscreen.keyboard`. +- **fx-onscreen-keyboard-swing**: Swing integration (`KeyBoardWindow`, text component UIs, AWT + robot handlers). +- **fx-onscreen-keyboard-samples**: demo applications for JavaFX and Swing. Not a library. + +## Key Entry Points + +- Keyboard pane: `fx-onscreen-keyboard/src/main/java/org/comtel2000/keyboard/control/KeyboardPane.java` +- Popup builder: `fx-onscreen-keyboard/src/main/java/org/comtel2000/keyboard/control/KeyBoardPopupBuilder.java` +- Special key codes: `fx-onscreen-keyboard/src/main/java/org/comtel2000/keyboard/control/StandardKeyCode.java` +- Layout XML and schema: `fx-onscreen-keyboard/src/main/resources/org/comtel2000/keyboard/control/layer/` +- Swing window: `fx-onscreen-keyboard-swing/src/main/java/org/comtel2000/swing/control/KeyBoardWindowBuilder.java` +- Samples: `fx-onscreen-keyboard-samples/src/main/java/org/comtel2000/samples/` + +## Building and Testing + +The default branch is `dev`. CI (`.github/workflows/ci.yml`) runs `mvn -B test` on JDK 17, 21 and +25 (Liberica `jdk+fx`). + +| Command | Purpose | +|--------------------------------------------|-------------------------------------------------| +| `mvn -q -B clean compile` | Compile without tests | +| `mvn -q -B test` | Run all unit tests (what CI runs) | +| `mvn -q -B clean verify` | Full build with tests and the Spotless check | +| `mvn -q -B spotless:apply` | Fix formatting (google-java-format + header) | +| `mvn -q -B install -DskipTests` | Install modules locally (needed to run samples) | + +Spotless enforces google-java-format and the license header +`/* Copyright (c) $YEAR comtel2000 (BSD 3-Clause) */` on every Java file. Run `spotless:apply` +instead of formatting by hand. + +Before running any tests, read `.claude/docs/running-tests.md` for module targeting and the +JavaFX headless setup, and `.claude/docs/test-guidelines.md` for test quality expectations. + +## Keyboard Layouts + +Before adding or changing a layout XML, a locale, or a key code, read +`.claude/docs/keyboard-layouts.md`. The `add-keyboard-layout` skill walks through adding a new +language. + +## Documentation + +Before adding or updating Javadoc, read `.claude/docs/documentation-guidelines.md`. Keep class and +method docs caller-focused. + +## Additional Resources + +- Running tests: `.claude/docs/running-tests.md` +- Test quality: `.claude/docs/test-guidelines.md` +- Java conventions: `.claude/docs/java-coding-conventions.md` +- Keyboard layouts: `.claude/docs/keyboard-layouts.md` +- Documentation: `.claude/docs/documentation-guidelines.md` + +## Verification + +Use these steps to verify any completed work. Implementation plans should include them as success +criteria. + +1. **Format, compile and test** using the `maven-command-runner` agent: + - `mvn -q -B spotless:apply` - format code + - `mvn -q -B clean verify` - compile, test and check formatting +2. For UI changes, say that the change was not checked visually unless a sample app was run. + +Before committing, ensure all verification steps pass. + +--- + +> **Build Rule:** Use the `maven-command-runner` agent (`.claude/agents/maven-command-runner.md`) +> for Maven commands, so long build output stays out of the main conversation. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md From 8bca0a19012c47b0790b9f1328cf9ca201253dfa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:33:34 +0000 Subject: [PATCH 3/4] Document xvfb, FxTestSupport and JaCoCo in agent docs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVKTE7YjM5Y9LLQ8NcRuzC --- .claude/docs/running-tests.md | 34 ++++++++++++++++++++++++--------- .claude/docs/test-guidelines.md | 8 +++++--- AGENTS.md | 7 +++++-- 3 files changed, 35 insertions(+), 14 deletions(-) diff --git a/.claude/docs/running-tests.md b/.claude/docs/running-tests.md index f9e022b3..019fd957 100644 --- a/.claude/docs/running-tests.md +++ b/.claude/docs/running-tests.md @@ -61,16 +61,26 @@ the tests run against a stale core jar from your local repository. ## JavaFX Tests and Headless Mode -Tests that create JavaFX nodes need the JavaFX toolkit. CI runs on Linux without a display, so: +Tests that create JavaFX nodes, stages or timelines need the JavaFX toolkit, and the toolkit needs +a display. + +- Use `FxTestSupport` (`fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/`). + Call `FxTestSupport.startToolkit()` in `@BeforeAll`; it starts the toolkit once, disables + implicit exit (so closing a test stage does not stop the toolkit), and **skips** the test class + when no display is available instead of hanging. +- Run FX code with `FxTestSupport.runFx(...)` or `callFx(...)`. They run on the FX thread, wait at + most 10 seconds and rethrow assertion failures on the test thread. `waitForFxEvents()` flushes + work queued with `Platform.runLater`; `waitFor(condition, millis)` polls for async results such + as fade animations. +- On Linux without a display, run the tests under Xvfb, as CI does: -- Surefire sets `java.awt.headless=true` (root `pom.xml`). -- `KeyButtonTest` shows the pattern: in `@BeforeAll`, set `prism.order=sw`, use the Monocle - headless platform when its classes are on the class path, then call `Platform.startup(...)` and - ignore `IllegalStateException` if the toolkit is already running. -- Run JavaFX code inside `Platform.runLater(...)` and wait with a `CountDownLatch` and a - `@Timeout`, rethrowing any captured exception on the test thread. -- `KeyButtonTest` is disabled on JDK 25 (`@DisabledOnJre(JRE.JAVA_25)`) until Monocle works there. - Follow the same pattern for new toolkit tests rather than letting CI hang. +```bash +xvfb-run -a mvn -q -B test +``` + + Without `xvfb-run` the FX test classes are reported as skipped and only toolkit-free tests run. +- `RecordingRobot` (`src/test/java/org/comtel2000/keyboard/robot/`) records keys sent by a + `KeyboardPane`; add it with `addRobotHandler` to assert typed characters without a real window. Prefer tests that need no toolkit at all, such as XML parsing through `XmlHelper` or pure logic, when the behavior allows it. @@ -82,3 +92,9 @@ mvn -q -B clean verify ``` `verify` also runs `spotless:check`. Run `mvn -q -B spotless:apply` first if formatting fails. + +## Coverage + +JaCoCo runs with every `test` build. The report for the core module is written to +`fx-onscreen-keyboard/target/site/jacoco/index.html` (CSV in `jacoco.csv`). CI uploads it as the +`coverage-report` artifact from the JDK 17 job. diff --git a/.claude/docs/test-guidelines.md b/.claude/docs/test-guidelines.md index 52dda822..d8f15447 100644 --- a/.claude/docs/test-guidelines.md +++ b/.claude/docs/test-guidelines.md @@ -50,13 +50,14 @@ Skip the comment when the name already says it, as in `readIntAttributeReturnsDe the setter has logic. - **Exhaustive repetition**: if two layouts go through the same parser path, one test covers it. - **Testing JavaFX itself**: don't test that a `Button` shows its text. -- **Sleep-based timing**: use latches, timeline control, or `@Timeout`, not `Thread.sleep`. +- **Sleep-based timing**: use `FxTestSupport.waitFor`, timeline control, or latches, not + `Thread.sleep`. ## Test structure - **One behavior per test.** A failing test name should tell you what broke. - **No logic in tests.** Avoid `if`, `for`, `switch` or `try/catch` in test bodies, except the - `Platform.runLater` capture pattern described in `running-tests.md`. + `FxTestSupport` helpers described in `running-tests.md`. - **Arrange / Act / Assert.** - **Use helpers for test data.** Put test layout XML in `fx-onscreen-keyboard/src/test/resources/xml/` and share loader helpers instead of repeating @@ -66,6 +67,7 @@ Skip the comment when the name already says it, as in `readIntAttributeReturnsDe - JUnit Jupiter (`org.junit.jupiter.api`). Use `assertThrows(...)` for exceptions. - Prefer `assertEquals(expected, actual)` over `assertTrue(a == b)`. -- Give toolkit tests a `@Timeout` so a stuck FX thread fails the test instead of hanging CI. +- Run toolkit code through `FxTestSupport.runFx`/`callFx`, which time out after 10 seconds, so a + stuck FX thread fails the test instead of hanging CI. - Group related tests with `@Nested` classes named after the behavior area (`LocaleFallback`, `RepeatKeys`), not after the method under test. diff --git a/AGENTS.md b/AGENTS.md index c587fc29..12ef7272 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,8 +24,9 @@ defined in XML, so new languages and keyboard types are added as resources rathe ## Building and Testing -The default branch is `dev`. CI (`.github/workflows/ci.yml`) runs `mvn -B test` on JDK 17, 21 and -25 (Liberica `jdk+fx`). +The default branch is `dev`. CI (`.github/workflows/ci.yml`) runs `xvfb-run -a mvn -B test` on +JDK 17, 21 and 25 (Liberica `jdk+fx`). JavaFX tests need a display: on Linux without one, prefix +test commands with `xvfb-run -a`, otherwise the FX test classes are skipped. | Command | Purpose | |--------------------------------------------|-------------------------------------------------| @@ -35,6 +36,8 @@ The default branch is `dev`. CI (`.github/workflows/ci.yml`) runs `mvn -B test` | `mvn -q -B spotless:apply` | Fix formatting (google-java-format + header) | | `mvn -q -B install -DskipTests` | Install modules locally (needed to run samples) | +`test` also writes a JaCoCo coverage report to `fx-onscreen-keyboard/target/site/jacoco/`. + Spotless enforces google-java-format and the license header `/* Copyright (c) $YEAR comtel2000 (BSD 3-Clause) */` on every Java file. Run `spotless:apply` instead of formatting by hand. From 6c00c6c96b0d32886e14d8db913a8736ffbe891b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:38:51 +0000 Subject: [PATCH 4/4] Allow focus-ring offset in popup position test On CI the text field bounds include the 1.4px focus ring while the popup lands on the whole pixel, so compare with a 2px tolerance. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GVKTE7YjM5Y9LLQ8NcRuzC --- .../org/comtel2000/keyboard/control/KeyBoardPopupTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyBoardPopupTest.java b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyBoardPopupTest.java index acae8752..567a3a87 100644 --- a/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyBoardPopupTest.java +++ b/fx-onscreen-keyboard/src/test/java/org/comtel2000/keyboard/control/KeyBoardPopupTest.java @@ -153,8 +153,10 @@ void showBelowTextFieldAndHide() { () -> { assertTrue(popup.isVisible()); var bounds = field.localToScreen(field.getBoundsInLocal()); - assertEquals(bounds.getMinX(), popup.getX(), 1.0); - assertEquals(bounds.getMaxY() + popup.getOffset(), popup.getY(), 1.0); + // the bounds include the focus ring (-1.4px), which is drawn only on a focused field, + // and window managers may round the popup position to whole pixels + assertEquals(bounds.getMinX(), popup.getX(), 2.0); + assertEquals(bounds.getMaxY() + popup.getOffset(), popup.getY(), 2.0); assertEquals(KeyboardType.TEXT, popup.getKeyBoard().getActiveType()); });