--- old/./build.gradle 2015-09-11 21:22:37.173288195 -0400 +++ new/./build.gradle 2015-09-11 21:22:37.021288197 -0400 @@ -1562,7 +1562,7 @@ test { def cssDir = file("$buildDir/classes/main/javafx") - jvmArgs "-Djava.ext.dirs=", "-Djavafx.toolkit=com.sun.javafx.pgstub.StubToolkit", + jvmArgs "-Djava.ext.dirs=", "-Djavafx.toolkit=test.com.sun.javafx.pgstub.StubToolkit", "-DCSS_META_DATA_TEST_DIR=$cssDir" enableAssertions = true testLogging.exceptionFormat = "full" @@ -1623,7 +1623,7 @@ test { def cssDir = file("$buildDir/classes/main/javafx") - jvmArgs "-Djavafx.toolkit=com.sun.javafx.pgstub.StubToolkit", + jvmArgs "-Djavafx.toolkit=test.com.sun.javafx.pgstub.StubToolkit", "-DCSS_META_DATA_TEST_DIR=$cssDir" } @@ -1694,7 +1694,7 @@ // StubToolkit is not *really* needed here, but because some code inadvertently invokes performance // tracker and this attempts to fire up the toolkit and this looks for native libraries and fails, // we have to use the stub toolkit for now. - jvmArgs "-Djavafx.toolkit=com.sun.javafx.pgstub.StubToolkit" + jvmArgs "-Djavafx.toolkit=test.com.sun.javafx.pgstub.StubToolkit" classpath += files("$JDK_HOME/jre/lib/ext/nashorn.jar") } } --- old/modules/controls/src/test/java/com/sun/javafx/scene/control/LabeledImplTest.java 2015-09-11 21:22:37.837288188 -0400 +++ new/modules/controls/src/test/java/com/sun/javafx/scene/control/LabeledImplTest.java 2015-09-11 21:22:37.701288189 -0400 @@ -25,9 +25,9 @@ package com.sun.javafx.scene.control; -import com.sun.javafx.pgstub.StubImageLoaderFactory; -import com.sun.javafx.pgstub.StubPlatformImageInfo; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubImageLoaderFactory; +import test.com.sun.javafx.pgstub.StubPlatformImageInfo; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.scene.control.LabeledImpl; import com.sun.javafx.scene.control.skin.FXVK; import com.sun.javafx.tk.Toolkit; --- old/modules/controls/src/test/java/com/sun/javafx/scene/control/infrastructure/KeyModifier.java 2015-09-11 21:22:38.469288180 -0400 +++ new/modules/controls/src/test/java/com/sun/javafx/scene/control/infrastructure/KeyModifier.java 2015-09-11 21:22:38.333288182 -0400 @@ -26,7 +26,7 @@ package com.sun.javafx.scene.control.infrastructure; import com.sun.javafx.util.Utils; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.scene.input.KeyCode; --- old/modules/controls/src/test/java/javafx/scene/chart/ChartTestBase.java 2015-09-11 21:22:39.153288173 -0400 +++ new/modules/controls/src/test/java/javafx/scene/chart/ChartTestBase.java 2015-09-11 21:22:39.017288174 -0400 @@ -32,7 +32,7 @@ import org.junit.Before; import org.junit.Test; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.collections.ObservableList; --- old/modules/controls/src/test/java/javafx/scene/chart/StackedBarChartTest.java 2015-09-11 21:22:39.861288165 -0400 +++ new/modules/controls/src/test/java/javafx/scene/chart/StackedBarChartTest.java 2015-09-11 21:22:39.725288166 -0400 @@ -30,7 +30,7 @@ import static org.junit.Assert.assertEquals; import javafx.collections.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import java.util.Arrays; --- old/modules/controls/src/test/java/javafx/scene/chart/XYChartTest.java 2015-09-11 21:22:40.553288157 -0400 +++ new/modules/controls/src/test/java/javafx/scene/chart/XYChartTest.java 2015-09-11 21:22:40.353288159 -0400 @@ -34,6 +34,7 @@ import javafx.css.StyleableProperty; import javafx.css.CssParser; import javafx.scene.Node; +import javafx.scene.ParentShim; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; @@ -121,7 +122,7 @@ axis.setPrefWidth(400); pulse(); StackPane layout = new StackPane(); - layout.getChildren().addAll(axis); + ParentShim.getChildren(layout).addAll(axis); pulse(); setTestScene(new Scene(layout)); setTestStage(new Stage()); --- old/modules/controls/src/test/java/javafx/scene/control/AccordionTest.java 2015-09-11 21:22:41.177288150 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/AccordionTest.java 2015-09-11 21:22:41.041288152 -0400 @@ -26,7 +26,6 @@ package javafx.scene.control; import com.sun.javafx.application.PlatformImpl; -import com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.scene.control.infrastructure.ControlTestUtils; import com.sun.javafx.scene.control.infrastructure.KeyEventFirer; import com.sun.javafx.tk.Toolkit; @@ -41,6 +40,7 @@ import org.junit.Test; import static org.junit.Assert.*; +import test.com.sun.javafx.pgstub.StubToolkit; /** */ --- old/modules/controls/src/test/java/javafx/scene/control/ButtonTest.java 2015-09-11 21:22:41.905288142 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/ButtonTest.java 2015-09-11 21:22:41.725288144 -0400 @@ -42,7 +42,7 @@ import javafx.stage.Stage; import javafx.stage.WindowEvent; import java.util.List; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.scene.control.infrastructure.ContextMenuEventFirer; import com.sun.javafx.scene.control.infrastructure.KeyEventFirer; import com.sun.javafx.scene.control.infrastructure.MouseEventFirer; --- old/modules/controls/src/test/java/javafx/scene/control/CheckMenuItemTest.java 2015-09-11 21:22:42.605288134 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/CheckMenuItemTest.java 2015-09-11 21:22:42.413288136 -0400 @@ -27,7 +27,7 @@ import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.beans.property.SimpleBooleanProperty; import javafx.scene.Node; --- old/modules/controls/src/test/java/javafx/scene/control/ChoiceBoxTest.java 2015-09-11 21:22:43.237288127 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/ChoiceBoxTest.java 2015-09-11 21:22:43.101288128 -0400 @@ -25,7 +25,7 @@ package javafx.scene.control; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.assertPseudoClassDoesNotExist; --- old/modules/controls/src/test/java/javafx/scene/control/ColorPickerTest.java 2015-09-11 21:22:43.933288119 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/ColorPickerTest.java 2015-09-11 21:22:43.797288121 -0400 @@ -34,7 +34,7 @@ import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.scene.control.infrastructure.KeyEventFirer; import com.sun.javafx.scene.control.infrastructure.MouseEventFirer; import com.sun.javafx.scene.control.infrastructure.MouseEventGenerator; --- old/modules/controls/src/test/java/javafx/scene/control/CustomMenuItemTest.java 2015-09-11 21:22:44.601288112 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/CustomMenuItemTest.java 2015-09-11 21:22:44.401288114 -0400 @@ -32,7 +32,7 @@ import javafx.scene.Node; import javafx.scene.shape.Rectangle; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import org.junit.Before; import org.junit.Ignore; --- old/modules/controls/src/test/java/javafx/scene/control/MenuBarTest.java 2015-09-11 21:22:45.289288104 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/MenuBarTest.java 2015-09-11 21:22:45.077288106 -0400 @@ -42,7 +42,7 @@ import org.junit.Before; import org.junit.Test; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.scene.control.infrastructure.KeyEventFirer; import com.sun.javafx.scene.control.infrastructure.MouseEventGenerator; import com.sun.javafx.scene.control.ContextMenuContent; --- old/modules/controls/src/test/java/javafx/scene/control/MiscellaneousTests.java 2015-09-11 21:22:45.897288097 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/MiscellaneousTests.java 2015-09-11 21:22:45.761288099 -0400 @@ -25,7 +25,7 @@ package javafx.scene.control; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.geometry.Bounds; import javafx.scene.Group; --- old/modules/controls/src/test/java/javafx/scene/control/PaginationTest.java 2015-09-11 21:22:46.665288088 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/PaginationTest.java 2015-09-11 21:22:46.481288090 -0400 @@ -50,7 +50,7 @@ import org.junit.Ignore; import org.junit.Test; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.scene.control.infrastructure.KeyEventFirer; import com.sun.javafx.scene.control.infrastructure.MouseEventGenerator; import com.sun.javafx.tk.Toolkit; --- old/modules/controls/src/test/java/javafx/scene/control/RadioMenuItemTest.java 2015-09-11 21:22:47.393288080 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/RadioMenuItemTest.java 2015-09-11 21:22:47.205288082 -0400 @@ -27,7 +27,7 @@ import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; --- old/modules/controls/src/test/java/javafx/scene/control/ScrollBarTest.java 2015-09-11 21:22:48.053288073 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/ScrollBarTest.java 2015-09-11 21:22:47.917288074 -0400 @@ -29,7 +29,7 @@ import javafx.css.CssMetaData; import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; --- old/modules/controls/src/test/java/javafx/scene/control/ScrollPaneTest.java 2015-09-11 21:22:48.721288065 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/ScrollPaneTest.java 2015-09-11 21:22:48.585288067 -0400 @@ -28,7 +28,7 @@ import javafx.css.CssMetaData; import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; --- old/modules/controls/src/test/java/javafx/scene/control/SeparatorMenuItemTest.java 2015-09-11 21:22:49.425288057 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/SeparatorMenuItemTest.java 2015-09-11 21:22:49.289288059 -0400 @@ -27,7 +27,7 @@ import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.geometry.Orientation; import javafx.scene.Node; --- old/modules/controls/src/test/java/javafx/scene/control/SliderTest.java 2015-09-11 21:22:50.093288050 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/SliderTest.java 2015-09-11 21:22:49.957288051 -0400 @@ -29,7 +29,7 @@ import javafx.css.ParsedValue; import javafx.css.CssMetaData; import javafx.css.CssParser; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.css.StyleableProperty; import javafx.scene.Parent; --- old/modules/controls/src/test/java/javafx/scene/control/SplitPaneTest.java 2015-09-11 21:22:50.753288042 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/SplitPaneTest.java 2015-09-11 21:22:50.617288044 -0400 @@ -29,7 +29,7 @@ import javafx.css.CssMetaData; import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import javafx.scene.control.skin.SplitPaneSkin; import com.sun.javafx.tk.Toolkit; import javafx.application.Platform; --- old/modules/controls/src/test/java/javafx/scene/control/TabPaneTest.java 2015-09-11 21:22:51.417288035 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/TabPaneTest.java 2015-09-11 21:22:51.277288037 -0400 @@ -61,7 +61,7 @@ import org.junit.Ignore; import org.junit.Test; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.scene.control.infrastructure.KeyEventFirer; import com.sun.javafx.scene.control.infrastructure.MouseEventGenerator; import javafx.scene.control.skin.TabPaneSkin; --- old/modules/controls/src/test/java/javafx/scene/control/TabTest.java 2015-09-11 21:22:52.133288027 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/TabTest.java 2015-09-11 21:22:51.933288029 -0400 @@ -29,7 +29,7 @@ import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; --- old/modules/controls/src/test/java/javafx/scene/control/TitledPaneTest.java 2015-09-11 21:22:52.901288018 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/TitledPaneTest.java 2015-09-11 21:22:52.689288021 -0400 @@ -51,7 +51,7 @@ import org.junit.Before; import org.junit.Test; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.scene.control.infrastructure.KeyEventFirer; import com.sun.javafx.scene.control.infrastructure.MouseEventGenerator; import javafx.scene.control.skin.TitledPaneSkin; --- old/modules/controls/src/test/java/javafx/scene/control/ToggleButtonTest.java 2015-09-11 21:22:53.589288011 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/ToggleButtonTest.java 2015-09-11 21:22:53.449288012 -0400 @@ -30,7 +30,7 @@ import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.event.ActionEvent; import javafx.event.Event; --- old/modules/controls/src/test/java/javafx/scene/control/ToggleGroupTest.java 2015-09-11 21:22:54.237288003 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/ToggleGroupTest.java 2015-09-11 21:22:54.097288005 -0400 @@ -26,7 +26,7 @@ package javafx.scene.control; import com.sun.javafx.event.EventUtil; -import com.sun.javafx.pgstub.StubScene; +import test.com.sun.javafx.pgstub.StubScene; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; --- old/modules/controls/src/test/java/javafx/scene/control/ToolbarTest.java 2015-09-11 21:22:54.837287997 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/ToolbarTest.java 2015-09-11 21:22:54.705287998 -0400 @@ -28,7 +28,7 @@ import javafx.css.CssMetaData; import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import javafx.scene.control.skin.ToolBarSkin; import com.sun.javafx.tk.Toolkit; import java.util.ArrayList; --- old/modules/controls/src/test/java/javafx/scene/control/TooltipTest.java 2015-09-11 21:22:55.453287990 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/TooltipTest.java 2015-09-11 21:22:55.317287991 -0400 @@ -28,7 +28,7 @@ import javafx.css.CssMetaData; import static com.sun.javafx.scene.control.infrastructure.ControlTestUtils.*; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; --- old/modules/controls/src/test/java/javafx/scene/control/skin/ColorPickerSkinTest.java 2015-09-11 21:22:56.149287982 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/skin/ColorPickerSkinTest.java 2015-09-11 21:22:56.013287983 -0400 @@ -25,7 +25,7 @@ package javafx.scene.control.skin; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.scene.control.infrastructure.KeyEventFirer; import com.sun.javafx.scene.control.infrastructure.MouseEventFirer; import com.sun.javafx.scene.control.infrastructure.MouseEventGenerator; --- old/modules/controls/src/test/java/javafx/scene/control/skin/MenuBarSkinTest.java 2015-09-11 21:22:56.905287973 -0400 +++ new/modules/controls/src/test/java/javafx/scene/control/skin/MenuBarSkinTest.java 2015-09-11 21:22:56.697287976 -0400 @@ -28,7 +28,7 @@ import static org.junit.Assert.assertEquals; import com.sun.javafx.menu.MenuBase; -import com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit; import com.sun.javafx.tk.Toolkit; import javafx.beans.value.ObservableValue; import javafx.geometry.Insets; --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/css/BitSetShim.java 2015-09-11 21:22:57.381287968 -0400 @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.javafx.css; + +import java.util.Collection; +import java.util.Iterator; + +public class BitSetShim { + + public static boolean add(BitSet s, Object t) { + return s.add(t); + } + + public static boolean addAll(BitSet s, Collection c) { + return s.addAll(c); + } + + public static boolean contains(BitSet s, Object o) { + return s.contains(o); + } + + public static boolean containsAll(BitSet s, Collection c) { + return s.containsAll(c); + } + + public static boolean equals(BitSet s, Object obj) { + return s.equals(obj); + } + + public static long[] getBits(BitSet s) { + return s.getBits(); + } + + public static boolean isEmpty(BitSet s) { + return s.isEmpty(); + } + + public static Iterator iterator(BitSet s) { + return s.iterator(); + } + + public static boolean remove(BitSet s, Object o) { + return s.remove(o); + } + + public static boolean retainAll(BitSet s, Collection c) { + return s.retainAll(c); + } + + public static int size(BitSet s) { + return s.size(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/css/PseudoClassStateShim.java 2015-09-11 21:22:58.213287959 -0400 @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.javafx.css; + +import java.util.List; +import java.util.Map; +import javafx.css.PseudoClass; + +public class PseudoClassStateShim { + + public static final Map pseudoClassMap = PseudoClassState.pseudoClassMap; + + public static final List pseudoClasses = PseudoClassState.pseudoClasses; + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/css/StyleManagerShim.java 2015-09-11 21:22:58.809287952 -0400 @@ -0,0 +1,206 @@ +package com.sun.javafx.css; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import javafx.css.PseudoClass; +import javafx.css.Styleable; +import javafx.css.Stylesheet; +import javafx.scene.Node; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.SubScene; + + + +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +public class StyleManagerShim { + + private final StyleManager sm; + + private StyleManagerShim(StyleManager sm) { + this.sm = sm; + } + + public static StyleManagerShim getInstance() { + return new StyleManagerShim(StyleManager.getInstance()); + + } + + public boolean isCacheContainerNull( + Styleable styleable, SubScene subScene) { + StyleManager.CacheContainer cc = sm.getCacheContainer(styleable, subScene); + return cc == null; + } + + public void cacheContainerMap_clear() { + sm.cacheContainerMap.clear(); + } + + public int platformUserAgentStylesheetContainers_indexOf(String fname) { + return indexOf(sm.platformUserAgentStylesheetContainers, fname); + } + + public int userAgentStylesheetContainers_indexOf(String fname) { + return indexOf(sm.userAgentStylesheetContainers, fname); + } + + private int indexOf(List list, String fname) { + for (int n = 0, nMax = list.size(); n < nMax; n++) { + StyleManager.StylesheetContainer container = list.get(n); + if (fname.equals(container.fname)) { + return n; + } + } + + return -1; + } + + public int userAgentStylesheetContainers_size() { + return sm.userAgentStylesheetContainers.size(); + } + + public void userAgentStylesheetContainers_clear() { + sm.userAgentStylesheetContainers.clear(); + } + + public boolean userAgentStylesheetContainers_isEmpty() { + return sm.userAgentStylesheetContainers.isEmpty(); + } + + public void platformUserAgentStylesheetContainers_clear() { + sm.platformUserAgentStylesheetContainers.clear(); + } + + public int platformUserAgentStylesheetContainers_size() { + return sm.platformUserAgentStylesheetContainers.size(); + } + + public String platformUserAgentStylesheetContainers_getfname(int dex) { + return sm.platformUserAgentStylesheetContainers.get(dex).fname; + } + + public void stylesheetContainerMap_clear() { + sm.stylesheetContainerMap.clear(); + } + + public boolean get_hasDefaultUserAgentStylesheet() { + return sm.hasDefaultUserAgentStylesheet; + } + + public void set_hasDefaultUserAgentStylesheet(boolean value) { + sm.hasDefaultUserAgentStylesheet = value; + } + + public void setDefaultUserAgentStylesheet(String fname) { + sm.setDefaultUserAgentStylesheet(fname); + } + + public void setDefaultUserAgentStylesheet(Scene scene, String url) { + sm.setDefaultUserAgentStylesheet(scene, url); + } + + public void setDefaultUserAgentStylesheet(Stylesheet ua_stylesheet) { + sm.setDefaultUserAgentStylesheet(ua_stylesheet); + } + + public void setUserAgentStylesheets(List urls) { + sm.setUserAgentStylesheets(urls); + } + + public void addUserAgentStylesheet(String fname) { + sm.addUserAgentStylesheet(fname); + } + + public void addUserAgentStylesheet(Scene scene, String url) { + sm.addUserAgentStylesheet(scene, url); + } + + public void addUserAgentStylesheet(Scene scene, Stylesheet ua_stylesheet) { + sm.addUserAgentStylesheet(scene, ua_stylesheet); + } + + public void forget(final Scene scene) { + sm.forget(scene); + } + + public void forget(final Parent parent) { + sm.forget(parent); + } + + public void forget(final SubScene subScene) { + sm.forget(subScene); + } + + public StyleMap findMatchingStyles(Node node, SubScene subScene, Set[] triggerStates) { + return sm.findMatchingStyles(node, subScene, triggerStates); + } + + public boolean stylesheetContainerMap_containsKey(String k) { + return sm.stylesheetContainerMap.containsKey(k); + } + + public StylesheetContainer stylesheetContainerMap_get(String k) { + return new StylesheetContainer( + sm.stylesheetContainerMap.get(k)); + } + + public static class StylesheetContainer { + + private final StyleManager.StylesheetContainer sc; + + StylesheetContainer(StyleManager.StylesheetContainer sc) { + this.sc = sc; + } + + public String get_fname() { + return sc.fname; + } + + public int parentUsers_list_size() { + return sc.parentUsers.list.size(); + } + + public boolean parentUsers_contains(Parent k) { + return sc.parentUsers.contains(k); + } + + public StyleManagerShim.RefList get_parentUsers() { + return new RefList(sc.parentUsers); + } + } + + static class RefList { + private StyleManager.RefList ref; + + RefList(StyleManager.RefList ref) { + this.ref = ref; + } + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/css/parser/TokenShim.java 2015-09-11 21:22:59.481287944 -0400 @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.javafx.css.parser; + +import static com.sun.javafx.css.parser.Token.EOF; + +public class TokenShim { + + public static final int EOF = Token.EOF; + public static final int INVALID = Token.INVALID; + public static final int SKIP = Token.SKIP; + + public final static TokenShim EOF_TOKEN = new TokenShim(Token.EOF_TOKEN); + public final static TokenShim INVALID_TOKEN = new TokenShim(Token.INVALID_TOKEN); + public final static TokenShim SKIP_TOKEN = new TokenShim(Token.SKIP_TOKEN); + + private final Token token; + + public TokenShim(int type, String text, int line, int offset) { + token = new Token(type, text, line, offset); + } + + public TokenShim(int type, String text) { + token = new Token(type, text); + } + + public TokenShim(Token t) { + token = t; + } + + public int getType() { + return token.getType(); + } + + public int getLine() { + return token.getLine(); + } + + public int getOffset() { + return token.getOffset(); + } + + public String getText() { + return token.getText(); + } + + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/iio/bmp/BMPImageLoaderShim.java 2015-09-11 21:23:00.153287937 -0400 @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.iio.bmp; + +public class BMPImageLoaderShim { + + public static boolean checkDisjointMasks(int m1, int m2, int m3) { + return BMPImageLoader.checkDisjointMasks(m1, m2, m3); + } + + public static boolean isPow2Minus1(int i) { + return BMPImageLoader.isPow2Minus1(i); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/scene/transform/TransformUtilsShim.java 2015-09-11 21:23:00.813287929 -0400 @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.scene.transform; + +import com.sun.javafx.scene.transform.TransformUtils.ImmutableTransform; +import javafx.scene.transform.Transform; + +public class TransformUtilsShim { + + public static Transform getImmutableTransform(Transform transform) { + return new TransformUtils.ImmutableTransform(transform); + } + + public static Transform getImmutableTransform( + double mxx, double mxy, double mxz, double tx, + double myx, double myy, double myz, double ty, + double mzx, double mzy, double mzz, double tz) { + return new TransformUtils.ImmutableTransform( + mxx, mxy, mxz, tx, + myx, myy, myz, ty, + mzx, mzy, mzz, tz); + } + + public static int getImmutableState2d(Transform t) { + return ((TransformUtils.ImmutableTransform) t).getState2d(); + } + + public static int getImmutableState3d(Transform t) { + return ((TransformUtils.ImmutableTransform) t).getState3d(); + } + + public static class ImmutableTransformShim extends ImmutableTransform { + + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/scene/traversal/ContainerTabOrderShim.java 2015-09-11 21:23:01.617287920 -0400 @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.scene.traversal; + +public class ContainerTabOrderShim extends ContainerTabOrder { + + public ContainerTabOrderShim () { + super(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/scene/traversal/TopMostTraversalEngineShim.java 2015-09-11 21:23:02.293287913 -0400 @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.scene.traversal; + +public abstract class TopMostTraversalEngineShim extends TopMostTraversalEngine { + + public TopMostTraversalEngineShim(Algorithm algorithm) { + super(algorithm); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/sg/prism/CacheFilterShim.java 2015-09-11 21:23:03.109287904 -0400 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; +import javafx.scene.CacheHint; + +public class CacheFilterShim { + + public static boolean isScaleHint(CacheFilter cf) { + return cf.isScaleHint(); + } + + public static final boolean isRotateHint(CacheFilter cf) { + return cf.isRotateHint(); + } + + public static BaseBounds computeDirtyBounds( + CacheFilter cf, + BaseBounds region, BaseTransform tx, GeneralTransform3D pvTx) { + return cf.computeDirtyBounds(region, tx, pvTx); + } + + public static CacheFilter getCacheFilter(NGNode node, CacheHint cacheHint) { + return new CacheFilter(node, cacheHint); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGCircleShim.java 2015-09-11 21:23:03.921287894 -0400 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.DirtyRegionPool; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; + +public class NGCircleShim extends NGCircle { + + @Override + public int accumulateGroupDirtyRegion( + final RectBounds clip, + final RectBounds dirtyRegionTemp, + final DirtyRegionPool regionPool, + DirtyRegionContainer dirtyRegionContainer, + final BaseTransform tx, + final GeneralTransform3D pvTx) { + return super.accumulateGroupDirtyRegion(clip, dirtyRegionTemp, + regionPool, dirtyRegionContainer, tx, pvTx); + } + + @Override + public int accumulateNodeDirtyRegion(final RectBounds clip, + final RectBounds dirtyRegionTemp, + final DirtyRegionContainer dirtyRegionContainer, + final BaseTransform tx, + final GeneralTransform3D pvTx) { + return super.accumulateNodeDirtyRegion(clip, dirtyRegionTemp, + dirtyRegionContainer, tx, pvTx); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGGroupShim.java 2015-09-11 21:23:04.733287885 -0400 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.DirtyRegionPool; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; + +public class NGGroupShim extends NGGroup { + + @Override + public int accumulateGroupDirtyRegion( + final RectBounds clip, + final RectBounds dirtyRegionTemp, + final DirtyRegionPool regionPool, + DirtyRegionContainer dirtyRegionContainer, + final BaseTransform tx, + final GeneralTransform3D pvTx) { + return super.accumulateGroupDirtyRegion(clip, dirtyRegionTemp, + regionPool, dirtyRegionContainer, tx, pvTx); + } + + @Override + public int accumulateNodeDirtyRegion(final RectBounds clip, + final RectBounds dirtyRegionTemp, + final DirtyRegionContainer dirtyRegionContainer, + final BaseTransform tx, + final GeneralTransform3D pvTx) { + return super.accumulateNodeDirtyRegion(clip, dirtyRegionTemp, + dirtyRegionContainer, tx, pvTx); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGNodeShim.java 2015-09-11 21:23:05.481287877 -0400 @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.DirtyRegionPool; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; + +public abstract class NGNodeShim extends NGNode { + + @Override + public boolean hasOpaqueRegion() { + return super.hasOpaqueRegion(); + + } + + //-------------------------------------------- + + public static void clearDirty(NGNode node) { + node.clearDirty(); + } + + public static RectBounds computeOpaqueRegion(NGNode node, RectBounds opaqueRegion) { + return node.computeOpaqueRegion(opaqueRegion); + } + + public static int cullingBits(NGNode node) { + return node.cullingBits; + } + + public static boolean childDirty(NGNode node) { + return node.childDirty; + } + + public static NGNode.DirtyFlag dirty(NGNode node) { + return node.dirty; + } + + public static boolean isOpaqueRegionInvalid(NGNode node) { + return node.isOpaqueRegionInvalid(); + } + + public static void markCullRegions( + NGNode node, + DirtyRegionContainer drc, + int cullingRegionsBitsOfParent, + BaseTransform tx, + GeneralTransform3D pvTx) { + node.markCullRegions(drc, cullingRegionsBitsOfParent, tx, pvTx); + } + + public static void set_dirty(NGNode node, NGNode.DirtyFlag flag) { + node.dirty = flag; + } + + public static void set_childDirty(NGNode node, boolean flag) { + node.childDirty = flag; + } + + public static boolean supportsOpaqueRegions(NGNode node) { + return node.supportsOpaqueRegions(); + } + + public static boolean hasOpaqueRegion(NGNode node) { + return node.hasOpaqueRegion(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGRectangleShim.java 2015-09-11 21:23:06.229287868 -0400 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.DirtyRegionPool; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; + +public class NGRectangleShim extends NGRectangle { + + @Override + public int accumulateGroupDirtyRegion( + final RectBounds clip, + final RectBounds dirtyRegionTemp, + final DirtyRegionPool regionPool, + DirtyRegionContainer dirtyRegionContainer, + final BaseTransform tx, + final GeneralTransform3D pvTx) { + return super.accumulateGroupDirtyRegion(clip, dirtyRegionTemp, + regionPool, dirtyRegionContainer, tx, pvTx); + } + + @Override + public int accumulateNodeDirtyRegion(final RectBounds clip, + final RectBounds dirtyRegionTemp, + final DirtyRegionContainer dirtyRegionContainer, + final BaseTransform tx, + final GeneralTransform3D pvTx) { + return super.accumulateNodeDirtyRegion(clip, dirtyRegionTemp, + dirtyRegionContainer, tx, pvTx); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGRegionShim.java 2015-09-11 21:23:06.957287860 -0400 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.DirtyRegionPool; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; + +public class NGRegionShim extends NGRegion { + + @Override + public int accumulateGroupDirtyRegion( + final RectBounds clip, + final RectBounds dirtyRegionTemp, + final DirtyRegionPool regionPool, + DirtyRegionContainer dirtyRegionContainer, + final BaseTransform tx, + final GeneralTransform3D pvTx) { + return super.accumulateGroupDirtyRegion(clip, dirtyRegionTemp, + regionPool, dirtyRegionContainer, tx, pvTx); + } + + @Override + public int accumulateNodeDirtyRegion(final RectBounds clip, + final RectBounds dirtyRegionTemp, + final DirtyRegionContainer dirtyRegionContainer, + final BaseTransform tx, + final GeneralTransform3D pvTx) { + return super.accumulateNodeDirtyRegion(clip, dirtyRegionTemp, + dirtyRegionContainer, tx, pvTx); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGTriangleMeshShim.java 2015-09-11 21:23:07.689287852 -0400 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.sg.prism; + +public class NGTriangleMeshShim extends NGTriangleMesh { + + @Override + public int[] test_getFaceSmoothingGroups() { + return super.test_getFaceSmoothingGroups(); + } + + @Override + public int[] test_getFaces() { + return super.test_getFaces(); + } + + @Override + public float[] test_getPoints() { + return super.test_getPoints(); + } + + @Override + public float[] test_getNormals() { + return super.test_getNormals(); + } + + @Override + public float[] test_getTexCoords() { + return super.test_getTexCoords(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/tk/quantum/WindowStageShim.java 2015-09-11 21:23:08.437287844 -0400 @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.tk.quantum; + +import com.sun.prism.Image; + +public class WindowStageShim { + + public static Image findBestImage(java.util.List icons, int width, int height) { + return WindowStage.findBestImage(icons, width, height); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/javafx/util/WeakReferenceQueueShim.java 2015-09-11 21:23:09.117287836 -0400 @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.javafx.util; + +public class WeakReferenceQueueShim { + + public static int size(WeakReferenceQueue q) { + return q.size; + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/prism/BasicStrokeShim.java 2015-09-11 21:23:09.909287827 -0400 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.prism; + +public class BasicStrokeShim { + + public static int join(BasicStroke bs) { + return bs.join; + } + + public static void set_join(BasicStroke bs, int join) { + bs.join = join; + } + + public static int cap(BasicStroke bs) { + return bs.cap; + } + + public static void set_cap(BasicStroke bs, int cap) { + bs.cap = cap; + } + + public static float width(BasicStroke bs) { + return bs.width; + } + + public static void set_width(BasicStroke bs, float width) { + bs.width = width; + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/prism/impl/shape/NativePiscesRasterizerShim.java 2015-09-11 21:23:10.653287819 -0400 @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.prism.impl.shape; + +public class NativePiscesRasterizerShim { + + public static void produceFillAlphas(float coords[], byte commands[], int nsegs, boolean nonzero, + double mxx, double mxy, double mxt, + double myx, double myy, double myt, + int bounds[], byte mask[]) { + NativePiscesRasterizer.produceFillAlphas( + coords, commands, nsegs, nonzero, + mxx, mxy, mxt, + myx, myy, myt, + bounds, mask); + } + + public static void produceStrokeAlphas(float coords[], byte commands[], int nsegs, + float lw, int cap, int join, float mlimit, + float dashes[], float dashoff, + double mxx, double mxy, double mxt, + double myx, double myy, double myt, + int bounds[], byte mask[]) { + NativePiscesRasterizer.produceStrokeAlphas( + coords, commands, nsegs, + lw, cap, join, mlimit, + dashes, dashoff, + mxx, mxy, mxt, + myx, myy, myt, + bounds, mask); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/scenario/animation/AbstractMasterTimerShim.java 2015-09-11 21:23:11.413287810 -0400 @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.scenario.animation; + +public class AbstractMasterTimerShim { + + public static boolean isPaused(AbstractMasterTimer amt) { + return amt.isPaused(); + } + + public static long getTotalPausedTime(AbstractMasterTimer amt) { + return amt.getTotalPausedTime(); + } + + public static long getStartPauseTime(AbstractMasterTimer amt) { + return amt.getStartPauseTime(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/scenario/animation/shared/ClipInterpolatorShim.java 2015-09-11 21:23:12.153287802 -0400 @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.scenario.animation.shared; + +import javafx.animation.KeyFrame; + +public class ClipInterpolatorShim { + + + public static ClipInterpolator setKeyFrames(ClipInterpolator clip, + KeyFrame[] keyFrames, long[] keyFrameTicks) { + return clip.setKeyFrames(keyFrames, keyFrameTicks); + } + + public static void validate(ClipInterpolator clip, boolean forceSync) { + clip.validate(forceSync); + } + + public static void interpolate(ClipInterpolator clip,long ticks) { + clip.interpolate(ticks); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/scenario/animation/shared/FiniteClipEnvelopeShim.java 2015-09-11 21:23:13.013287792 -0400 @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.scenario.animation.shared; + +import javafx.animation.Animation; + +public class FiniteClipEnvelopeShim extends FiniteClipEnvelope { + + public FiniteClipEnvelopeShim(Animation animation) { + super(animation); + + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/scenario/animation/shared/GeneralClipInterpolatorShim.java 2015-09-11 21:23:13.697287785 -0400 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.scenario.animation.shared; + +import javafx.animation.KeyFrame; + +public class GeneralClipInterpolatorShim extends GeneralClipInterpolator { + + public GeneralClipInterpolatorShim(KeyFrame[] keyFrames, long[] keyFrameTicks) { + super(keyFrames, keyFrameTicks); + } + + + @Override + public ClipInterpolator setKeyFrames( + KeyFrame[] keyFrames, long[] keyFrameTicks) { + return super.setKeyFrames(keyFrames, keyFrameTicks); + } + + @Override + public void validate(boolean forceSync) { + super.validate(forceSync); + } + + @Override + public void interpolate(long ticks) { + super.interpolate(ticks); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/scenario/animation/shared/InfiniteClipEnvelopeShim.java 2015-09-11 21:23:14.349287777 -0400 @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.scenario.animation.shared; + +import javafx.animation.Animation; + +public class InfiniteClipEnvelopeShim extends InfiniteClipEnvelope { + + public InfiniteClipEnvelopeShim(Animation animation) { + super(animation); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/scenario/animation/shared/SimpleClipInterpolatorShim.java 2015-09-11 21:23:15.017287770 -0400 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.scenario.animation.shared; + +import javafx.animation.KeyFrame; + +public class SimpleClipInterpolatorShim extends SimpleClipInterpolator { + + public SimpleClipInterpolatorShim(KeyFrame startKeyFrame, KeyFrame endKeyFrame, long ticks) { + super(startKeyFrame, endKeyFrame, ticks); + } + + public SimpleClipInterpolatorShim(KeyFrame endKeyFrame, long ticks) { + super(endKeyFrame, ticks); + } + + @Override + public ClipInterpolator setKeyFrames( + KeyFrame[] keyFrames, long[] keyFrameTicks) { + return super.setKeyFrames(keyFrames, keyFrameTicks); + } + + @Override + public void validate(boolean forceSync) { + super.validate(forceSync); + } + + @Override + public void interpolate(long ticks) { + super.interpolate(ticks); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/com/sun/scenario/animation/shared/SingleLoopClipEnvelopeShim.java 2015-09-11 21:23:15.685287762 -0400 @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.scenario.animation.shared; + +import javafx.animation.Animation; + +public class SingleLoopClipEnvelopeShim extends SingleLoopClipEnvelope { + + public SingleLoopClipEnvelopeShim(Animation animation) { + super(animation); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/animation/AnimationShim.java 2015-09-11 21:23:16.505287753 -0400 @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.animation; + +import com.sun.scenario.animation.AbstractMasterTimer; +import com.sun.scenario.animation.shared.ClipEnvelope; +import com.sun.scenario.animation.shared.PulseReceiver; +import javafx.util.Duration; + +public abstract class AnimationShim extends Animation { + + public AnimationShim() { + super(); + } + + public AnimationShim(AbstractMasterTimer timer) { + super(timer); + } + + public AnimationShim(AbstractMasterTimer timer, ClipEnvelope clipEnvelope, int resolution) { + super(timer, clipEnvelope, resolution); + } + + public ClipEnvelope get_clipEnvelope() { + return clipEnvelope; + } + + @Override + public void impl_pause() { + super.impl_pause(); + } + + @Override + public void impl_start(boolean forceSync) { + super.impl_start(forceSync); + } + + @Override + public void impl_setCurrentRate(double currentRate) { + super.impl_setCurrentRate(currentRate); + } + + @Override + public void impl_setCurrentTicks(long ticks) { + super.impl_setCurrentTicks(ticks); + } + + @Override + public boolean impl_startable(boolean forceSync) { + return super.impl_startable(forceSync); + } + + @Override + public void impl_stop() { + super.impl_stop(); + } + + @Override + public void impl_sync(boolean forceSync) { + super.impl_sync(forceSync); + } + + @Override + public void impl_timePulse(long elapsedTime) { + super.impl_timePulse(elapsedTime); + } + + @Override + public void pauseReceiver() { + super.pauseReceiver(); + } + + @Override + public void resumeReceiver() { + super.resumeReceiver(); + } + + public void shim_setCycleDuration(Duration value) { + setCycleDuration(value); + } + + @Override + public void startReceiver(long delay) { + super.startReceiver(delay); + } + + public PulseReceiver shim_pulseReceiver() { + return pulseReceiver; + } + + public void shim_impl_finished() { + impl_finished(); + } + + @Override + abstract public void impl_playTo(long currentTicks, long cycleTicks); + + @Override + abstract public void impl_jumpTo(long currentTicks, long cycleTicks, boolean forceJump); + + //------------------------------- + + public static void impl_finished(Animation a) { + a.impl_finished(); + } + + public static void impl_start(Animation a, boolean forceSync) { + a.impl_start(forceSync); + } + + public static boolean impl_startable(Animation a, boolean forceSync) { + return a.impl_startable(forceSync); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/animation/ParallelTransitionShim.java 2015-09-11 21:23:17.165287746 -0400 @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.animation; + +import com.sun.scenario.animation.AbstractMasterTimer; + +public class ParallelTransitionShim { + + public static ParallelTransition getParallelTransition( + AbstractMasterTimer timer) { + return new ParallelTransition(timer); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/animation/SequentialTransitionShim.java 2015-09-11 21:23:17.957287737 -0400 @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.animation; + +import com.sun.scenario.animation.AbstractMasterTimer; + +public class SequentialTransitionShim { + + public static SequentialTransition getSequentialTransition(AbstractMasterTimer timer) { + return new SequentialTransition(timer); + + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/animation/TimelineShim.java 2015-09-11 21:23:18.781287727 -0400 @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.animation; + +import com.sun.scenario.animation.AbstractMasterTimer; +import com.sun.scenario.animation.shared.TimelineClipCore; + +public class TimelineShim { + + public static TimelineClipCore getClipCore(Timeline timeline) { + return timeline.clipCore; + } + + public static Timeline getTimeline( AbstractMasterTimer timer) { + return new Timeline(timer); + } + + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/animation/TransitionShim.java 2015-09-11 21:23:19.529287719 -0400 @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.animation; + +import com.sun.scenario.animation.AbstractMasterTimer; +import javafx.scene.Node; + +public abstract class TransitionShim extends Transition { + + protected TransitionShim() { + super(); + } + + protected TransitionShim(double targetFramerate) { + super(targetFramerate); + } + + protected TransitionShim(AbstractMasterTimer timer) { + super(timer); + } + + @Override + public void impl_pause() { + super.impl_pause(); + } + + @Override + public void impl_sync(boolean forceSync) { + super.impl_sync(forceSync); + } + + @Override + public void impl_jumpTo(long currentTicks, long cycleTicks, boolean forceJump) { + super.impl_jumpTo(currentTicks, cycleTicks, forceJump); + } + + public void shim_impl_finished() { + super.impl_finished(); + } + + @Override + public Node getParentTargetNode() { + return super.getParentTargetNode(); + } + + @Override + public void impl_start(boolean forceSync) { + super.impl_start(forceSync); + } + + @Override + public boolean impl_startable(boolean forceSync) { + return super.impl_startable(forceSync); + } + + @Override + public void impl_playTo(long currentTicks, long cycleTicks) { + super.impl_playTo(currentTicks, cycleTicks); + } + + @Override + public Interpolator getCachedInterpolator() { + return super.getCachedInterpolator(); + } + + ///// statics + + public static void interpolate(Transition t, double frac) { + t.interpolate(frac); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/concurrent/ScheduledServiceShim.java 2015-09-11 21:23:20.269287711 -0400 @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.concurrent; + +import java.util.TimerTask; +import javafx.util.Duration; + +public abstract class ScheduledServiceShim extends ScheduledService { + + public static void setCumulativePeriod(ScheduledService ss, + Duration value) { + ss.setCumulativePeriod(value); + } + + //------------------------------------------- + + @Override + public void checkThread() { + super.checkThread(); + } + + @Override + public void schedule(TimerTask task, long delay) { + super.schedule(task, delay); + } + + @Override public void executeTask(final Task task) { + super.executeTask(task); + } + + @Override + public long clock() { + return super.clock(); + } + + @Override + public boolean isFxApplicationThread() { + return super.isFxApplicationThread(); + } + + @Override + public boolean isFreshStart() { + return super.isFreshStart(); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/concurrent/ServiceShim.java 2015-09-11 21:23:20.893287704 -0400 @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.concurrent; + +import javafx.event.Event; +import javafx.event.EventHandler; +import javafx.event.EventType; + +public abstract class ServiceShim extends Service { + + public static void fireEvent(Service s, Event event) { + s.fireEvent(event); + } + + public static void setEventHandler(Service s, + final EventType eventType, + final EventHandler eventHandler) { + s.setEventHandler(eventType, eventHandler); + } + + //----------------------------------- + + @Override + public void runLater(Runnable r) { + super.runLater(r); + } + + @Override + public boolean isFxApplicationThread() { + return super.isFxApplicationThread(); + } + + @Override + public void checkThread() { + super.checkThread(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/concurrent/TaskShim.java 2015-09-11 21:23:21.625287695 -0400 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.concurrent; + +import javafx.event.Event; +import javafx.event.EventHandler; +import javafx.event.EventType; + +public abstract class TaskShim extends Task { + + public static void setEventHandler( + Task t, + final EventType eventType, + final EventHandler eventHandler) { + t.setEventHandler(eventType, eventHandler); + } + + //------------------------------------------------------------- + + @Override + public boolean isFxApplicationThread() { + return super.isFxApplicationThread(); +} + + @Override + public void runLater(Runnable r) { + super.runLater(r); + } + + public void shim_setState(State value) { + super.setState(value); + } + + + @Override + public void updateTitle(String title) { + super.updateTitle(title); + } + + @Override + public void updateMessage(String message) { + super.updateMessage(message); + } + + public static void updateProgress(Task t, double workDone, double max) { + t.updateProgress(workDone, max); + } + + public static void updateProgress(Task t, long workDone, long max) { + t.updateProgress(workDone, max); + } + + @Override + public void updateProgress(double workDone, double max) { + super.updateProgress(workDone, max); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/css/CssLexerShim.java 2015-09-11 21:23:22.361287687 -0400 @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.css; + +import com.sun.javafx.css.parser.Token; +import com.sun.javafx.css.parser.TokenShim; +import java.io.Reader; + +public class CssLexerShim { + + public final static int STRING = CssLexer.STRING; + public final static int IDENT = CssLexer.IDENT; + public final static int FUNCTION = CssLexer.FUNCTION; + public final static int NUMBER = CssLexer.NUMBER; + public final static int CM = CssLexer.CM; + public final static int EMS = CssLexer.EMS; + public final static int EXS = CssLexer.EXS; + public final static int IN = CssLexer.IN; + public final static int MM = CssLexer.MM; + public final static int PC = CssLexer.PC; + public final static int PT = CssLexer.PT; + public final static int PX = CssLexer.PX; + public final static int PERCENTAGE = CssLexer.PERCENTAGE; + public final static int DEG = CssLexer.DEG; + public final static int GRAD = CssLexer.GRAD; + public final static int RAD = CssLexer.RAD; + public final static int TURN = CssLexer.TURN; + public final static int GREATER = CssLexer.GREATER; + public final static int LBRACE = CssLexer.LBRACE; + public final static int RBRACE = CssLexer.RBRACE; + public final static int SEMI = CssLexer.SEMI; + public final static int COLON = CssLexer.COLON; + public final static int SOLIDUS = CssLexer.SOLIDUS; + public final static int STAR = CssLexer.STAR; + public final static int LPAREN = CssLexer.LPAREN; + public final static int RPAREN = CssLexer.RPAREN; + public final static int COMMA = CssLexer.COMMA; + public final static int HASH = CssLexer.HASH; + public final static int DOT = CssLexer.DOT; + public final static int IMPORTANT_SYM = CssLexer.IMPORTANT_SYM; + public final static int WS = CssLexer.WS; + public final static int NL = CssLexer.NL; + public final static int FONT_FACE = CssLexer.FONT_FACE; + public final static int URL = CssLexer.URL; + public final static int IMPORT = CssLexer.IMPORT; + public final static int SECONDS = CssLexer.SECONDS; + public final static int MS = CssLexer.MS; + public final static int AT_KEYWORD = CssLexer.AT_KEYWORD; + + + CssLexer lexer; + + public CssLexerShim(CssLexer lexer) { + this.lexer = lexer; + } + + public CssLexerShim() { + this.lexer = new CssLexer(); + } + + public TokenShim nextToken() { + Token t = this.lexer.nextToken(); + return new TokenShim(t); + } + + public void setReader(Reader reader) { + lexer.setReader(reader); + } + + //------------ + + public static TokenShim nextToken(CssLexerShim l) { + Token t = l.lexer.nextToken(); + return new TokenShim(t); + } + + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/css/DeclarationShim.java 2015-09-11 21:23:23.093287679 -0400 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.css; + + +public class DeclarationShim { + + public static ParsedValue get_parsedValue(Declaration d) { + return d.parsedValue; + } + + public static String get_property(Declaration d) { + return d.property; + } + + public static Declaration getDeclaration(final String propertyName, final ParsedValue parsedValue, + final boolean important) { + return new Declaration(propertyName, parsedValue, important); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/css/RuleShim.java 2015-09-11 21:23:23.789287671 -0400 @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.css; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Set; +import javafx.scene.Node; + +public class RuleShim { + + public static List getUnobservedDeclarationList(Rule r) { + return r.getUnobservedDeclarationList(); + } + + public static List getUnobservedSelectorList(Rule r) { + return r.getUnobservedSelectorList(); + } + + public static long applies( + Rule r, + Node node, Set[] triggerStates) { + return r.applies(node, triggerStates); + } + + public static Rule readBinary( + int bssVersion, DataInputStream is, String[] strings) + throws IOException { + return Rule.readBinary(bssVersion, is, strings); + } + + public static void writeBinary( + Rule r, + DataOutputStream os, StyleConverter.StringStore stringStore) + throws IOException { + r.writeBinary(os, stringStore); + } + + public static Rule getRule(List selectors, List declarations) { + return new Rule(selectors, declarations); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/css/SelectorShim.java 2015-09-11 21:23:24.461287664 -0400 @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.css; + +public class SelectorShim { + + public static Selector getUniversalSelector() { + return Selector.getUniversalSelector(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/css/SimpleSelectorShim.java 2015-09-11 21:23:25.185287655 -0400 @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.css; + +import java.util.List; +import java.util.Set; + +public class SimpleSelectorShim { + + public static SimpleSelector getSimpleSelector( + final String name, final List styleClasses, + final List pseudoClasses, final String id) { + return new SimpleSelector(name, styleClasses, pseudoClasses, id); + } + + public static Set getPseudoClassStates(SimpleSelector ss) { + return ss.getPseudoClassStates(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/css/SizeShim.java 2015-09-11 21:23:25.965287647 -0400 @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.css; + +import javafx.scene.text.Font; + +public class SizeShim { + + public static double points(Size su, + Font font) { + return su.points(font); + } + + public static double points(Size su, + double multiplier, Font font) { + return su.pixels(multiplier, font); + } + + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/css/SizeUnitsShim.java 2015-09-11 21:23:26.789287637 -0400 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.css; + +import javafx.scene.text.Font; + +public class SizeUnitsShim { + + public static double points(SizeUnits su, + double value, double multiplier, Font font) { + return su.points(value, multiplier, font); + } + + public static double pixels(SizeUnits su, + double value, double multiplier, Font font) { + return su.pixels(value, multiplier, font); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/css/StyleablePropertyFactoryShim.java 2015-09-11 21:23:27.529287629 -0400 @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.css; + +public class StyleablePropertyFactoryShim { + + public static void clearDataForTesting(StyleablePropertyFactory spf) { + spf.clearDataForTesting(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/css/StylesheetShim.java 2015-09-11 21:23:28.257287621 -0400 @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.css; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import javafx.css.StyleConverter.StringStore; + +public class StylesheetShim extends Stylesheet { + + public StylesheetShim () { + super(); + } + + public StylesheetShim (String s) { + super(s); + } + + public final static int BINARY_CSS_VERSION = Stylesheet.BINARY_CSS_VERSION; + + public static void writeBinary(Stylesheet ss, + final DataOutputStream os, final StringStore stringStore) + throws IOException { + ss.writeBinary(os, stringStore); + } + + public static void readBinary(Stylesheet ss, + int bssVersion, DataInputStream is, String[] strings) + throws IOException { + ss.readBinary(bssVersion, is, strings); + } + + public static Stylesheet getStylesheet() { + return new Stylesheet(); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/CameraShim.java 2015-09-11 21:23:28.917287613 -0400 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene; + +import com.sun.javafx.geom.PickRay; +import com.sun.javafx.geom.Vec3d; +import com.sun.javafx.geom.transform.Affine3D; +import com.sun.javafx.geom.transform.GeneralTransform3D; + +public class CameraShim { + + public static PickRay computePickRay(Camera c, + double x, double y, PickRay pickRay) { + return c.computePickRay(x, y, pickRay); + } + + public static Vec3d computePosition(Camera c, Vec3d position) { + return c.computePosition(position); + } + + public static double getFarClipInScene(Camera c) { + return c.getFarClipInScene(); + } + + public static double getNearClipInScene(Camera c) { + return c.getNearClipInScene(); + } + + public static GeneralTransform3D getProjViewTransform(Camera c) { + return c.getProjViewTransform(); + } + + public static Affine3D getSceneToLocalTransform(Camera c) { + return c.getSceneToLocalTransform(); + } + + public static double getViewHeight(Camera c) { + return c.getViewHeight(); + } + + public static double getViewWidth(Camera c) { + return c.getViewWidth(); + } + + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/CursorShim.java 2015-09-11 21:23:29.589287606 -0400 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene; + +import com.sun.javafx.cursor.CursorFrame; + +public class CursorShim { + + public static void activate(Cursor c) { + c.activate(); + } + + public static void deactivate(Cursor c) { + c.deactivate(); + } + + public static CursorFrame getCurrentFrame(Cursor c) { + return c.getCurrentFrame(); + } + + public static Cursor getCursor(String name) { + return new Cursor(name) { + + @Override + CursorFrame getCurrentFrame() { + throw new UnsupportedOperationException("Not supported yet."); + } + }; + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/GroupShim.java 2015-09-11 21:23:30.269287598 -0400 @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene; + +public class GroupShim { + + public static void layoutChildren(Group g) { + g.layoutChildren(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/NodeShim.java 2015-09-11 21:23:30.921287591 -0400 @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene; + +import com.sun.javafx.scene.DirtyBits; +import javafx.scene.transform.Transform; + +public class NodeShim { + + public static boolean boundsChanged(Node n) { + return n.boundsChanged; + } + + public static Node getClipParent(Node n) { + return n.getClipParent(); + } + + public static Transform getCurrentLocalToSceneTransformState(Node n) { + return n.getCurrentLocalToSceneTransformState(); + } + + public static SubScene getSubScene(Node n) { + return n.getSubScene(); + } + + public static boolean hasMirroring(Node n) { + return n.hasMirroring(); + } + + public static void impl_clearDirty(Node n, DirtyBits dirtyBit) { + n.impl_clearDirty(dirtyBit); + } + + public static boolean impl_isDirty(Node n, DirtyBits dirtyBit) { + return n.impl_isDirty(dirtyBit); + } + + public static boolean isDerivedDepthTest(Node n) { + return n.isDerivedDepthTest(); + } + + public static void set_boundsChanged(Node n, boolean b) { + n.boundsChanged = b; + } + + public static void updateBounds(Node n) { + n.updateBounds(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/ParentShim.java 2015-09-11 21:23:31.673287583 -0400 @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene; + +import java.util.List; +import javafx.collections.ObservableList; + +public class ParentShim extends Parent { + + public static final int DIRTY_CHILDREN_THRESHOLD = Parent.DIRTY_CHILDREN_THRESHOLD; + + public ObservableList getChildren() { + return super.getChildren(); + } + + public static ObservableList getChildren(Parent p) { + return p.getChildren(); + } + + public static List getManagedChildren(Parent p) { + return p.getManagedChildren(); + } + + public static List test_getRemoved(Parent p) { + return p.test_getRemoved(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/SceneShim.java 2015-09-11 21:23:32.393287574 -0400 @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene; + +public class SceneShim { + + public static void focusCleanup(Scene s) { + s.focusCleanup(); + } + + public static Camera getEffectiveCamera(Scene s) { + return s.getEffectiveCamera(); + } + + public static Node test_pick(Scene s, double x, double y) { + return s.test_pick(x, y); + } + + public static void scenePulseListener_pulse(Scene s) { + s.scenePulseListener.pulse(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/SubSceneShim.java 2015-09-11 21:23:33.145287566 -0400 @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene; + +public class SubSceneShim { + + public static Camera getEffectiveCamera(SubScene ss) { + return ss.getEffectiveCamera(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/effect/EffectShim.java 2015-09-11 21:23:33.741287559 -0400 @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene.effect; + +public class EffectShim { + + public static com.sun.scenario.effect.Effect impl_getImpl(Effect effect) { + return effect.impl_getImpl(); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/effect/FloatMapShim.java 2015-09-11 21:23:34.413287552 -0400 @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene.effect; + +public class FloatMapShim { + + public static com.sun.scenario.effect.FloatMap getImpl(FloatMap map) { + return map.getImpl(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/effect/LightShim.java 2015-09-11 21:23:35.141287544 -0400 @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene.effect; + +public class LightShim { + + public static com.sun.scenario.effect.light.Light impl_getImpl(Light light) { + return light.impl_getImpl(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/image/ImageShim.java 2015-09-11 21:23:35.809287536 -0400 @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.scene.image; + +import java.io.InputStream; + +public class ImageShim extends Image { + + public ImageShim(String url, boolean background) { + super(url, background); + } + + @Override + public void dispose() { + super.dispose(); + } + + public InputStream shim_getImpl_source() { + return super.getImpl_source(); + } + + @Override + public void pixelsDirty() { + super.pixelsDirty(); + } + + public void shim_setProgress(double value) { + super.setProgress(value); + } + + //------------------------------------------- + + public static void dispose(Image image) { + image.dispose(); + } + + public static InputStream getImpl_source(Image image) { + return image.getImpl_source(); + } + + public static void pixelsDirty(Image image) { + image.pixelsDirty(); + } + + public static void setProgress(Image image, double value) { + image.setProgress(value); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/input/DragboardShim.java 2015-09-11 21:23:36.529287528 -0400 @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.scene.input; + +import com.sun.javafx.tk.TKClipboard; + +public class DragboardShim { + + public static Dragboard getDragboard(TKClipboard peer) { + return new Dragboard(peer); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/input/GestureEventShim.java 2015-09-11 21:23:37.265287520 -0400 @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package javafx.scene.input; + +import javafx.event.EventTarget; +import javafx.event.EventType; + +public class GestureEventShim { + + public static GestureEvent getGestureEvent( + final EventType eventType, + double x, double y, double screenX, double screenY, + boolean shiftDown, boolean controlDown, boolean altDown, + boolean metaDown, boolean direct, boolean inertia, + PickResult pickResult) { + return new GestureEvent(eventType, + x, y, screenX, screenY, + shiftDown, controlDown, altDown, + metaDown, direct, inertia, + pickResult); + } + + public static GestureEvent getGestureEvent( + Object source, EventTarget target, + final EventType eventType) { + return new GestureEvent(source, target, eventType); + } + + public static GestureEvent getGestureEvent( + Object source, EventTarget target, final EventType eventType, + double x, double y, double screenX, double screenY, + boolean shiftDown, boolean controlDown, boolean altDown, + boolean metaDown, boolean direct, boolean inertia, PickResult pickResult) { + + return new GestureEvent( + source, target, eventType, + x, y, screenX, screenY, + shiftDown, controlDown, altDown, + metaDown, direct, inertia, pickResult); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/layout/BackgroundShim.java 2015-09-11 21:23:38.009287511 -0400 @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene.layout; + +public class BackgroundShim { + + public static void computeOpaqueInsets(Background bg, + double width, double height, double[] trbl) { + bg.computeOpaqueInsets(width, height, trbl); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/layout/GridPaneShim.java 2015-09-11 21:23:38.685287504 -0400 @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene.layout; + +import javafx.scene.Node; + +public class GridPaneShim { + + public static void createRow(int rowIndex, int columnIndex, Node... nodes) { + GridPane.createRow(rowIndex, columnIndex, nodes); + } + + public static void createColumn(int columnIndex, int rowIndex, Node... nodes) { + GridPane.createColumn(columnIndex, rowIndex, nodes); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/layout/RegionShim.java 2015-09-11 21:23:39.433287495 -0400 @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene.layout; + +import javafx.geometry.HPos; +import javafx.geometry.Insets; +import javafx.geometry.VPos; +import javafx.scene.Node; +import javafx.scene.image.Image; + +public class RegionShim extends Region { + + public static double boundedSize(double min, double pref, double max) { + return Region.boundedSize(min, pref, max); + } + + public static void addImageListener(Region r, Image image) { + r.addImageListener(image); + } + + public static double computeChildMaxAreaHeight(Region r, + Node child, double maxBaselineComplement, Insets margin, double width) { + return r.computeChildMaxAreaHeight(child, maxBaselineComplement, margin, width); + } + + public static double computeChildMaxAreaWidth(Region r, + Node child, double baselineComplement, + Insets margin, double height, boolean fillHeight) { + return r.computeChildMaxAreaWidth(child, + baselineComplement, margin, height, fillHeight); + } + + public static double computeChildMinAreaHeight(Region r, + Node child, double minBaselineComplement, + Insets margin, double width) { + return r.computeChildMinAreaHeight(child, + minBaselineComplement, + margin, width ); + } + + public static double computeChildMinAreaWidth(Region r, + Node child, Insets margin) { + return r.computeChildMinAreaWidth(child, margin); + } + + public static double computeChildMinAreaWidth(Region r, + Node child, double baselineComplement, + Insets margin, double height, boolean fillHeight) { + return r.computeChildMinAreaWidth(child, + baselineComplement, + margin, height, fillHeight); + } + + public static double computeChildPrefAreaHeight(Region r, + Node child, Insets margin) { + return r.computeChildPrefAreaHeight(child, margin); + } + + public static double computeChildPrefAreaHeight(Region r, + Node child, double prefBaselineComplement, + Insets margin, double width) { + return r.computeChildPrefAreaHeight(child, + prefBaselineComplement, margin, width); + } + + public static double computeChildPrefAreaWidth(Region r, + Node child, Insets margin) { + return r.computeChildPrefAreaWidth(child, margin); + } + + public static double computeChildPrefAreaWidth(Region r, + Node child, double baselineComplement, Insets margin, + double height, boolean fillHeight) { + return r.computeChildPrefAreaWidth(child, baselineComplement, + margin, height, fillHeight); + } + + public static void layoutInArea(Region r, + Node child, double areaX, double areaY, + double areaWidth, double areaHeight, + double areaBaselineOffset, + HPos halignment, VPos valignment) { + r.layoutInArea(child, areaX, areaY, + areaWidth, areaHeight, areaBaselineOffset, + halignment, valignment); + } + + public static void layoutInArea(Region r, + Node child, double areaX, double areaY, + double areaWidth, double areaHeight, + double areaBaselineOffset, + Insets margin, + HPos halignment, VPos valignment) { + r.layoutInArea(child, areaX, areaY, + areaWidth, areaHeight, + areaBaselineOffset, + margin, + halignment, valignment); + } + + public static void layoutInArea(Region r, + Node child, double areaX, double areaY, + double areaWidth, double areaHeight, + double areaBaselineOffset, + Insets margin, boolean fillWidth, boolean fillHeight, + HPos halignment, VPos valignment) { + r.layoutInArea(child, areaX, areaY, + areaWidth, areaHeight, + areaBaselineOffset, + margin, fillWidth, fillHeight, + halignment, valignment); + + } + + public static void positionInArea(Region r, + Node child, double areaX, double areaY, + double areaWidth, double areaHeight, + double areaBaselineOffset, HPos halignment, + VPos valignment) { + r.positionInArea(child, areaX, areaY, + areaWidth, areaHeight, + areaBaselineOffset, halignment, + valignment); + } + + public static void removeImageListener(Region r, Image image) { + r.addImageListener(image); + } + + //---------------------------------------------------------- + + @Override public void addImageListener(Image image) { + super.addImageListener(image); + } + + @Override public void removeImageListener(Image image) { + super.removeImageListener(image); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/shape/ClosePathShim.java 2015-09-11 21:23:40.237287486 -0400 @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene.shape; + +import com.sun.javafx.sg.prism.NGPath; + +public class ClosePathShim { + + public static void addTo(ClosePath cp, NGPath pgPath) { + cp.addTo(pgPath); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/transform/AffineShim.java 2015-09-11 21:23:40.905287479 -0400 @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene.transform; + +public class AffineShim { + + public static boolean atomicChangeRuns(Affine a) { + return a.atomicChangeRuns(); + } + + public static int getState2d(Affine a) { + return a.getState2d(); + } + + public static int getState3d(Affine a) { + return a.getState3d(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/scene/transform/TransformShim.java 2015-09-11 21:23:41.729287469 -0400 @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.scene.transform; + +public class TransformShim { + + public static boolean computeIs2D(Transform t) { + return t.computeIs2D(); + } + + public static void clearInverseCache(Transform t) { + t.clearInverseCache(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/stage/StageShim.java 2015-09-11 21:23:42.533287460 -0400 @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.stage; + +public class StageShim { + + public static boolean isPrimary(Stage stage) { + return stage.isPrimary(); + } + + public static boolean isSecurityDialog(Stage stage) { + return stage.isSecurityDialog(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/javafx/stage/WindowShim.java 2015-09-11 21:23:43.205287453 -0400 @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javafx.stage; + +public class WindowShim extends Window { + + public WindowShim() { + super(); + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/BooleanTypeTest.java 2015-09-11 21:23:44.149287442 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import static org.junit.Assert.assertEquals; -import javafx.css.ParsedValue; -import javafx.scene.text.Font; - -import org.junit.Test; - -import javafx.css.converter.BooleanConverter; - - -public class BooleanTypeTest { - - public BooleanTypeTest() { - } - - /** - * Test of convert method, of class BooleanType. - */ - @Test - public void testConvert() { - //System.out.println("convert"); - Font font = null; - - ParsedValue< String,Boolean> value = new ParsedValueImpl("true", BooleanConverter.getInstance()); - Boolean expResult = Boolean.TRUE; - Boolean result = value.convert(font); - assertEquals(expResult, result); - - value = value = new ParsedValueImpl("false", BooleanConverter.getInstance()); - expResult = Boolean.FALSE; - result = value.convert(font); - assertEquals(expResult, result); - - value = new ParsedValueImpl(null, BooleanConverter.getInstance()); - expResult = Boolean.FALSE; - result = value.convert(font); - assertEquals(expResult, result); - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/BooleanTypeTest.java 2015-09-11 21:23:44.013287444 -0400 @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import com.sun.javafx.css.ParsedValueImpl; +import static org.junit.Assert.assertEquals; +import javafx.css.ParsedValue; +import javafx.scene.text.Font; + +import org.junit.Test; + +import javafx.css.converter.BooleanConverter; + + +public class BooleanTypeTest { + + public BooleanTypeTest() { + } + + /** + * Test of convert method, of class BooleanType. + */ + @Test + public void testConvert() { + //System.out.println("convert"); + Font font = null; + + ParsedValue< String,Boolean> value = new ParsedValueImpl("true", BooleanConverter.getInstance()); + Boolean expResult = Boolean.TRUE; + Boolean result = value.convert(font); + assertEquals(expResult, result); + + value = value = new ParsedValueImpl("false", BooleanConverter.getInstance()); + expResult = Boolean.FALSE; + result = value.convert(font); + assertEquals(expResult, result); + + value = new ParsedValueImpl(null, BooleanConverter.getInstance()); + expResult = Boolean.FALSE; + result = value.convert(font); + assertEquals(expResult, result); + + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/CursorTypeTest.java 2015-09-11 21:23:44.769287435 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import static org.junit.Assert.*; -import javafx.css.ParsedValue; -import javafx.scene.Cursor; -import javafx.scene.text.Font; - -import org.junit.Test; - -import javafx.css.converter.CursorConverter; - - -public class CursorTypeTest { - - public CursorTypeTest() { - } - - /** - * Test of convert method, of class CursorType. - */ - @Test - public void testConvert() { - ParsedValue value = new ParsedValueImpl("hand", CursorConverter.getInstance()); - Font font = null; - Cursor expResult = Cursor.HAND; - Cursor result = value.convert(font); - assertEquals(expResult, result); - } - - @Test - public void testConvert_with_hyphen() { - ParsedValue value = new ParsedValueImpl("open-hand", CursorConverter.getInstance()); - Font font = null; - Cursor expResult = Cursor.OPEN_HAND; - Cursor result = value.convert(font); - assertEquals(expResult, result); - } - - @Test - public void testConvert_with_Cursor_dot() { - ParsedValue value = new ParsedValueImpl("Cursor.open-hand", CursorConverter.getInstance()); - Font font = null; - Cursor expResult = Cursor.OPEN_HAND; - Cursor result = value.convert(font); - assertEquals(expResult, result); - } - - @Test - public void testConvert_with_package_name() { - ParsedValue value = new ParsedValueImpl("javafx.scene.Cursor.open-hand", CursorConverter.getInstance()); - Font font = null; - Cursor expResult = Cursor.OPEN_HAND; - Cursor result = value.convert(font); - assertEquals(expResult, result); - } - - @Test - public void testConvert_with_package_name_only() { - ParsedValue value = new ParsedValueImpl("javafx.scene.Cursor.", CursorConverter.getInstance()); - Font font = null; - Cursor expResult = Cursor.DEFAULT; - Cursor result = value.convert(font); - assertEquals(expResult, result); - } - - @Test - public void testConvert_with_empty_string() { - ParsedValue value = new ParsedValueImpl("", CursorConverter.getInstance()); - Font font = null; - Cursor expResult = Cursor.DEFAULT; - Cursor result = value.convert(font); - assertEquals(expResult, result); - } - - @Test - public void testConvert_with_null() { - ParsedValue value = new ParsedValueImpl(null, CursorConverter.getInstance()); - Font font = null; - Cursor expResult = Cursor.DEFAULT; - Cursor result = value.convert(font); - assertEquals(expResult, result); - } - - @Test - public void testConvert_with_bogus_value() { - ParsedValue value = new ParsedValueImpl("bogus", CursorConverter.getInstance()); - Font font = null; - Cursor expResult = Cursor.DEFAULT; - Cursor result = value.convert(font); - assertEquals(expResult, result); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/CursorTypeTest.java 2015-09-11 21:23:44.629287437 -0400 @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import com.sun.javafx.css.ParsedValueImpl; +import static org.junit.Assert.*; +import javafx.css.ParsedValue; +import javafx.scene.Cursor; +import javafx.scene.text.Font; + +import org.junit.Test; + +import javafx.css.converter.CursorConverter; + + +public class CursorTypeTest { + + public CursorTypeTest() { + } + + /** + * Test of convert method, of class CursorType. + */ + @Test + public void testConvert() { + ParsedValue value = new ParsedValueImpl("hand", CursorConverter.getInstance()); + Font font = null; + Cursor expResult = Cursor.HAND; + Cursor result = value.convert(font); + assertEquals(expResult, result); + } + + @Test + public void testConvert_with_hyphen() { + ParsedValue value = new ParsedValueImpl("open-hand", CursorConverter.getInstance()); + Font font = null; + Cursor expResult = Cursor.OPEN_HAND; + Cursor result = value.convert(font); + assertEquals(expResult, result); + } + + @Test + public void testConvert_with_Cursor_dot() { + ParsedValue value = new ParsedValueImpl("Cursor.open-hand", CursorConverter.getInstance()); + Font font = null; + Cursor expResult = Cursor.OPEN_HAND; + Cursor result = value.convert(font); + assertEquals(expResult, result); + } + + @Test + public void testConvert_with_package_name() { + ParsedValue value = new ParsedValueImpl("javafx.scene.Cursor.open-hand", CursorConverter.getInstance()); + Font font = null; + Cursor expResult = Cursor.OPEN_HAND; + Cursor result = value.convert(font); + assertEquals(expResult, result); + } + + @Test + public void testConvert_with_package_name_only() { + ParsedValue value = new ParsedValueImpl("javafx.scene.Cursor.", CursorConverter.getInstance()); + Font font = null; + Cursor expResult = Cursor.DEFAULT; + Cursor result = value.convert(font); + assertEquals(expResult, result); + } + + @Test + public void testConvert_with_empty_string() { + ParsedValue value = new ParsedValueImpl("", CursorConverter.getInstance()); + Font font = null; + Cursor expResult = Cursor.DEFAULT; + Cursor result = value.convert(font); + assertEquals(expResult, result); + } + + @Test + public void testConvert_with_null() { + ParsedValue value = new ParsedValueImpl(null, CursorConverter.getInstance()); + Font font = null; + Cursor expResult = Cursor.DEFAULT; + Cursor result = value.convert(font); + assertEquals(expResult, result); + } + + @Test + public void testConvert_with_bogus_value() { + ParsedValue value = new ParsedValueImpl("bogus", CursorConverter.getInstance()); + Font font = null; + Cursor expResult = Cursor.DEFAULT; + Cursor result = value.convert(font); + assertEquals(expResult, result); + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/EffectTypeTest.java 2015-09-11 21:23:45.473287427 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,184 +0,0 @@ -/* - * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import static org.junit.Assert.assertEquals; -import javafx.css.ParsedValue; -import javafx.css.Size; -import javafx.css.SizeUnits; -import javafx.scene.effect.BlurType; -import javafx.scene.effect.DropShadow; -import javafx.scene.effect.Effect; -import javafx.scene.effect.InnerShadow; -import javafx.scene.paint.Color; -import javafx.scene.text.Font; - -import org.junit.Test; - -import javafx.css.converter.EffectConverter; -import javafx.css.converter.DeriveColorConverter; - - -public class EffectTypeTest { - - public EffectTypeTest() { - } - - Size makeSize(float f) { - return new Size(f, SizeUnits.PX); - } - - InnerShadow getInnerShadow() { - return new InnerShadow(); - } - - ParsedValue getInnerShadowValue(InnerShadow is, boolean colorIsDerived) { - Size offsetX = makeSize((float) is.getOffsetX()); - Size offsetY = makeSize((float) is.getOffsetX()); - Size choke = makeSize((float) is.getChoke()); - Size radius = makeSize((float) is.getRadius()); - - ParsedValue colorVal; - - if (colorIsDerived) { - ParsedValue[] values = new ParsedValue[] { - new ParsedValueImpl(is.getColor(),null), - new ParsedValueImpl(makeSize(0.5f),null) - }; - colorVal = new ParsedValueImpl(values, DeriveColorConverter.getInstance()); - } else { - colorVal = new ParsedValueImpl(is.getColor(),null); - } - - BlurType blurType = is.getBlurType(); - - ParsedValue[] vals = new ParsedValue[] { - new ParsedValueImpl(blurType, null), - colorVal, - new ParsedValueImpl(radius, null), - new ParsedValueImpl(choke, null), - new ParsedValueImpl(offsetX, null), - new ParsedValueImpl(offsetY, null) - }; - - return new ParsedValueImpl(vals, EffectConverter.InnerShadowConverter.getInstance()); - } - - DropShadow getDropShadow() { - return new DropShadow(); - } - - ParsedValue getDropShadowValue(DropShadow ds, boolean colorIsDerived) { - Size offsetX = makeSize((float) ds.getOffsetX()); - Size offsetY = makeSize((float) ds.getOffsetX()); - Size spread = makeSize((float) ds.getSpread()); - Size radius = makeSize((float) ds.getRadius()); - - ParsedValue colorVal; - - if (colorIsDerived) { - ParsedValue[] values = new ParsedValue[] { - new ParsedValueImpl(ds.getColor(),null), - new ParsedValueImpl(makeSize(0.5f),null) - }; - colorVal = new ParsedValueImpl(values, DeriveColorConverter.getInstance()); - } else { - colorVal = new ParsedValueImpl(ds.getColor(),null); - } - - BlurType blurType = ds.getBlurType(); - - ParsedValue[] vals = new ParsedValue[] { - new ParsedValueImpl(blurType, null), - colorVal, - new ParsedValueImpl(radius, null), - new ParsedValueImpl(spread, null), - new ParsedValueImpl(offsetX, null), - new ParsedValueImpl(offsetY, null) - }; - - return new ParsedValueImpl(vals, EffectConverter.DropShadowConverter.getInstance()); - } - - void checkColor(String msg, Color c1, Color c2) { - assertEquals(msg + ".red", c1.getRed(), c2.getRed(), 0.001); - assertEquals(msg + ".blue", c1.getBlue(), c2.getBlue(), 0.001); - assertEquals(msg + ".green", c1.getGreen(), c2.getGreen(), 0.001); - assertEquals(msg + ".opacity", c1.getOpacity(), c2.getOpacity(), 0.001); - } - - void checkInnerShadow(String msg, InnerShadow o1, InnerShadow o2) { - assertEquals(msg + "innershadow.offsetX", o1.getOffsetX(), o2.getOffsetX(), 0.001); - assertEquals(msg + "innershadow.offsety", o1.getOffsetY(), o2.getOffsetY(), 0.001); - assertEquals(msg + "innershadow.choke", o1.getChoke(), o2.getChoke(), 0.001); - assertEquals(msg + "innershadow.radius", o1.getRadius(), o2.getRadius(), 0.001); - checkColor(msg + "innershadow", o1.getColor(), o2.getColor()); - assertEquals(msg + "innershadow.blurType", o1.getBlurType(), o2.getBlurType()); - } - - void checkDropShadow(String msg, DropShadow o1, DropShadow o2) { - assertEquals(msg + "DropShadow.offsetX", o1.getOffsetX(), o2.getOffsetX(), 0.001); - assertEquals(msg + "DropShadow.offsety", o1.getOffsetY(), o2.getOffsetY(), 0.001); - assertEquals(msg + "DropShadow.spread", o1.getSpread(), o2.getSpread(), 0.001); - assertEquals(msg + "DropShadow.radius", o1.getRadius(), o2.getRadius(), 0.001); - checkColor(msg + "DropShadow", o1.getColor(), o2.getColor()); - assertEquals(msg + "DropShadow.blurType", o1.getBlurType(), o2.getBlurType()); - } - - /** - * Test of convert method, of class EffectType. - */ - @Test - public void testConvert() { - //System.out.println("convert"); - InnerShadow is = getInnerShadow(); - Font font = null; - ParsedValue value = getInnerShadowValue(is, false); - Effect result = value.convert(font); - checkInnerShadow("convert[1] ", is, (InnerShadow)result); - - // Test with derived colors - value = getInnerShadowValue(is, true); - result = value.convert(font); - // derived color is 50% of is.getColor() - is.setColor(com.sun.javafx.util.Utils.deriveColor(is.getColor(), 0.5f)); - checkInnerShadow("convert[2] ", is, (InnerShadow)result); - - DropShadow ds = getDropShadow(); - value = getDropShadowValue(ds, false); - result = value.convert(font); - checkDropShadow("convert[3] ", ds, (DropShadow)result); - - // Test with derived colors - value = getDropShadowValue(ds, true); - result = value.convert(font); - // derived color is 50% of is.getColor() - ds.setColor(com.sun.javafx.util.Utils.deriveColor(ds.getColor(), 0.5f)); - checkDropShadow("convert[4] ", ds, (DropShadow)result); - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/EffectTypeTest.java 2015-09-11 21:23:45.277287430 -0400 @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import com.sun.javafx.css.ParsedValueImpl; +import static org.junit.Assert.assertEquals; +import javafx.css.ParsedValue; +import javafx.css.Size; +import javafx.css.SizeUnits; +import javafx.scene.effect.BlurType; +import javafx.scene.effect.DropShadow; +import javafx.scene.effect.Effect; +import javafx.scene.effect.InnerShadow; +import javafx.scene.paint.Color; +import javafx.scene.text.Font; + +import org.junit.Test; + +import javafx.css.converter.EffectConverter; +import javafx.css.converter.DeriveColorConverter; + + +public class EffectTypeTest { + + public EffectTypeTest() { + } + + Size makeSize(float f) { + return new Size(f, SizeUnits.PX); + } + + InnerShadow getInnerShadow() { + return new InnerShadow(); + } + + ParsedValue getInnerShadowValue(InnerShadow is, boolean colorIsDerived) { + Size offsetX = makeSize((float) is.getOffsetX()); + Size offsetY = makeSize((float) is.getOffsetX()); + Size choke = makeSize((float) is.getChoke()); + Size radius = makeSize((float) is.getRadius()); + + ParsedValue colorVal; + + if (colorIsDerived) { + ParsedValue[] values = new ParsedValue[] { + new ParsedValueImpl(is.getColor(),null), + new ParsedValueImpl(makeSize(0.5f),null) + }; + colorVal = new ParsedValueImpl(values, DeriveColorConverter.getInstance()); + } else { + colorVal = new ParsedValueImpl(is.getColor(),null); + } + + BlurType blurType = is.getBlurType(); + + ParsedValue[] vals = new ParsedValue[] { + new ParsedValueImpl(blurType, null), + colorVal, + new ParsedValueImpl(radius, null), + new ParsedValueImpl(choke, null), + new ParsedValueImpl(offsetX, null), + new ParsedValueImpl(offsetY, null) + }; + + return new ParsedValueImpl(vals, EffectConverter.InnerShadowConverter.getInstance()); + } + + DropShadow getDropShadow() { + return new DropShadow(); + } + + ParsedValue getDropShadowValue(DropShadow ds, boolean colorIsDerived) { + Size offsetX = makeSize((float) ds.getOffsetX()); + Size offsetY = makeSize((float) ds.getOffsetX()); + Size spread = makeSize((float) ds.getSpread()); + Size radius = makeSize((float) ds.getRadius()); + + ParsedValue colorVal; + + if (colorIsDerived) { + ParsedValue[] values = new ParsedValue[] { + new ParsedValueImpl(ds.getColor(),null), + new ParsedValueImpl(makeSize(0.5f),null) + }; + colorVal = new ParsedValueImpl(values, DeriveColorConverter.getInstance()); + } else { + colorVal = new ParsedValueImpl(ds.getColor(),null); + } + + BlurType blurType = ds.getBlurType(); + + ParsedValue[] vals = new ParsedValue[] { + new ParsedValueImpl(blurType, null), + colorVal, + new ParsedValueImpl(radius, null), + new ParsedValueImpl(spread, null), + new ParsedValueImpl(offsetX, null), + new ParsedValueImpl(offsetY, null) + }; + + return new ParsedValueImpl(vals, EffectConverter.DropShadowConverter.getInstance()); + } + + void checkColor(String msg, Color c1, Color c2) { + assertEquals(msg + ".red", c1.getRed(), c2.getRed(), 0.001); + assertEquals(msg + ".blue", c1.getBlue(), c2.getBlue(), 0.001); + assertEquals(msg + ".green", c1.getGreen(), c2.getGreen(), 0.001); + assertEquals(msg + ".opacity", c1.getOpacity(), c2.getOpacity(), 0.001); + } + + void checkInnerShadow(String msg, InnerShadow o1, InnerShadow o2) { + assertEquals(msg + "innershadow.offsetX", o1.getOffsetX(), o2.getOffsetX(), 0.001); + assertEquals(msg + "innershadow.offsety", o1.getOffsetY(), o2.getOffsetY(), 0.001); + assertEquals(msg + "innershadow.choke", o1.getChoke(), o2.getChoke(), 0.001); + assertEquals(msg + "innershadow.radius", o1.getRadius(), o2.getRadius(), 0.001); + checkColor(msg + "innershadow", o1.getColor(), o2.getColor()); + assertEquals(msg + "innershadow.blurType", o1.getBlurType(), o2.getBlurType()); + } + + void checkDropShadow(String msg, DropShadow o1, DropShadow o2) { + assertEquals(msg + "DropShadow.offsetX", o1.getOffsetX(), o2.getOffsetX(), 0.001); + assertEquals(msg + "DropShadow.offsety", o1.getOffsetY(), o2.getOffsetY(), 0.001); + assertEquals(msg + "DropShadow.spread", o1.getSpread(), o2.getSpread(), 0.001); + assertEquals(msg + "DropShadow.radius", o1.getRadius(), o2.getRadius(), 0.001); + checkColor(msg + "DropShadow", o1.getColor(), o2.getColor()); + assertEquals(msg + "DropShadow.blurType", o1.getBlurType(), o2.getBlurType()); + } + + /** + * Test of convert method, of class EffectType. + */ + @Test + public void testConvert() { + //System.out.println("convert"); + InnerShadow is = getInnerShadow(); + Font font = null; + ParsedValue value = getInnerShadowValue(is, false); + Effect result = value.convert(font); + checkInnerShadow("convert[1] ", is, (InnerShadow)result); + + // Test with derived colors + value = getInnerShadowValue(is, true); + result = value.convert(font); + // derived color is 50% of is.getColor() + is.setColor(com.sun.javafx.util.Utils.deriveColor(is.getColor(), 0.5f)); + checkInnerShadow("convert[2] ", is, (InnerShadow)result); + + DropShadow ds = getDropShadow(); + value = getDropShadowValue(ds, false); + result = value.convert(font); + checkDropShadow("convert[3] ", ds, (DropShadow)result); + + // Test with derived colors + value = getDropShadowValue(ds, true); + result = value.convert(font); + // derived color is 50% of is.getColor() + ds.setColor(com.sun.javafx.util.Utils.deriveColor(ds.getColor(), 0.5f)); + checkDropShadow("convert[4] ", ds, (DropShadow)result); + + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/EnumTypeTest.java 2015-09-11 21:23:46.089287420 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import javafx.css.ParsedValue; -import javafx.css.SizeUnits; -import javafx.css.StyleConverter; -import javafx.scene.text.Font; - -import org.junit.Test; - -import javafx.css.converter.EnumConverter; - - -public class EnumTypeTest { - - public EnumTypeTest() { - } - - /** - * Test of convert method, of class EnumType. - */ - @Test - public void testConvert() { - StyleConverter sizeUnitsType = new EnumConverter(SizeUnits.class); - ParsedValue value = - new ParsedValueImpl("percent", sizeUnitsType); - Font font = null; - Enum expResult = SizeUnits.PERCENT; - Enum result = value.convert(font); - assertEquals(expResult, result); - - value = new ParsedValueImpl("SizeUnits.PERCENT", sizeUnitsType); - result = value.convert(font); - assertEquals(expResult, result); - - try { - value = new ParsedValueImpl("fubar", sizeUnitsType); - result = value.convert(font); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - } - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/EnumTypeTest.java 2015-09-11 21:23:45.949287422 -0400 @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import com.sun.javafx.css.ParsedValueImpl; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import javafx.css.ParsedValue; +import javafx.css.SizeUnits; +import javafx.css.StyleConverter; +import javafx.scene.text.Font; + +import org.junit.Test; + +import javafx.css.converter.EnumConverter; + + +public class EnumTypeTest { + + public EnumTypeTest() { + } + + /** + * Test of convert method, of class EnumType. + */ + @Test + public void testConvert() { + StyleConverter sizeUnitsType = new EnumConverter(SizeUnits.class); + ParsedValue value = + new ParsedValueImpl("percent", sizeUnitsType); + Font font = null; + Enum expResult = SizeUnits.PERCENT; + Enum result = value.convert(font); + assertEquals(expResult, result); + + value = new ParsedValueImpl("SizeUnits.PERCENT", sizeUnitsType); + result = value.convert(font); + assertEquals(expResult, result); + + try { + value = new ParsedValueImpl("fubar", sizeUnitsType); + result = value.convert(font); + fail("expected IllegalArgumentException"); + } catch (IllegalArgumentException iae) { + } + + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/FontSizeTypeTest.java 2015-09-11 21:23:46.793287413 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import javafx.css.converter.SizeConverter; -import javafx.css.ParsedValue; -import javafx.css.Size; -import javafx.css.SizeUnits; -import javafx.scene.text.Font; -import static org.junit.Assert.assertEquals; -import org.junit.Test; - - -public class FontSizeTypeTest { - - public FontSizeTypeTest() { - } - - /** - * Test of convert method, of class FontSizeType. - */ - @Test - public void testConvertToPixels() { - ParsedValue size = new ParsedValueImpl(new Size(2.0f, SizeUnits.EM), null); - ParsedValue,Number> value = new ParsedValueImpl,Number>(size, SizeConverter.getInstance()); - Font font = Font.getDefault(); - double expResult = SizeUnits.EM.pixels(2, 1, font); - double result = SizeConverter.getInstance().convert(value, font).doubleValue(); - assertEquals(expResult, result, 0.01); - - size = new ParsedValueImpl(new Size(120.0f, SizeUnits.PERCENT), null); - value = new ParsedValueImpl,Number>(size, SizeConverter.getInstance()); - expResult = SizeUnits.PERCENT.pixels(120, 1, font); - result = SizeConverter.getInstance().convert(value, font).doubleValue(); - assertEquals(expResult, result, 0.01); - - size = new ParsedValueImpl(new Size(12.0f, SizeUnits.PT), null); - value = new ParsedValueImpl,Number>(size, SizeConverter.getInstance()); - expResult = SizeUnits.PT.pixels(12, 1, font); - result = SizeConverter.getInstance().convert(value, font).doubleValue(); - assertEquals(expResult, result, 0.01); - - size = new ParsedValueImpl(new Size(12.0f, SizeUnits.PX), null); - value = new ParsedValueImpl,Number>(size, SizeConverter.getInstance()); - expResult = SizeUnits.PX.pixels(12, 1, font); - result = SizeConverter.getInstance().convert(value, font).doubleValue(); - assertEquals(expResult, result, 0.01); - } - -// @Test -// public void testConvertToPoints() { -// -// Font font = Font.getDefault(); -// // font size is in pixels. convert to points -// double pointSize = font.getSize() / javafx.stage.Screen.getPrimary().getDpi() * 72; -// -// ParsedValue size = new ParsedValueImpl(new Size(2.0f, SizeUnits.EM), null); -// ParsedValue,Double> value = new ParsedValueImpl,Double>(size, StyleConverter.POINTS); -// double expResult = SizeUnits.EM.points(2, 1, font); -// double result = StyleConverter.POINTS.convert(value, font); -// assertEquals(expResult, result, 0.01); -// -// size = new ParsedValueImpl(new Size(120.0f, SizeUnits.PERCENT), null); -// value = new ParsedValueImpl,Double>(size, StyleConverter.POINTS); -// expResult = SizeUnits.PERCENT.points(120, 1, font); -// result = StyleConverter.POINTS.convert(value, font); -// assertEquals(expResult, result, 0.01); -// -// size = new ParsedValueImpl(new Size(12.0f, SizeUnits.PT), null); -// value = new ParsedValueImpl,Double>(size, StyleConverter.POINTS); -// expResult = SizeUnits.PT.points(12, 1, font); -// result = StyleConverter.POINTS.convert(value, font); -// assertEquals(expResult, result, 0.01); -// -// size = new ParsedValueImpl(new Size(12.0f, SizeUnits.PX), null); -// value = new ParsedValueImpl,Double>(size, StyleConverter.POINTS); -// expResult = SizeUnits.PX.points(12, 1, font); -// result = StyleConverter.POINTS.convert(value, font); -// assertEquals(expResult, result, 0.01); -// -// } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/FontSizeTypeTest.java 2015-09-11 21:23:46.589287415 -0400 @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import com.sun.javafx.css.ParsedValueImpl; +import javafx.css.converter.SizeConverter; +import javafx.css.ParsedValue; +import javafx.css.Size; +import javafx.css.SizeUnits; +import javafx.css.SizeUnitsShim; +import javafx.scene.text.Font; +import static org.junit.Assert.assertEquals; +import org.junit.Test; + + +public class FontSizeTypeTest { + + public FontSizeTypeTest() { + } + + /** + * Test of convert method, of class FontSizeType. + */ + @Test + public void testConvertToPixels() { + ParsedValue size = new ParsedValueImpl(new Size(2.0f, SizeUnits.EM), null); + ParsedValue,Number> value = new ParsedValueImpl,Number>(size, SizeConverter.getInstance()); + Font font = Font.getDefault(); + double expResult = SizeUnitsShim.pixels(SizeUnits.EM, 2, 1, font); + double result = SizeConverter.getInstance().convert(value, font).doubleValue(); + assertEquals(expResult, result, 0.01); + + size = new ParsedValueImpl(new Size(120.0f, SizeUnits.PERCENT), null); + value = new ParsedValueImpl,Number>(size, SizeConverter.getInstance()); + expResult = SizeUnitsShim.pixels(SizeUnits.PERCENT, 120, 1, font); + result = SizeConverter.getInstance().convert(value, font).doubleValue(); + assertEquals(expResult, result, 0.01); + + size = new ParsedValueImpl(new Size(12.0f, SizeUnits.PT), null); + value = new ParsedValueImpl,Number>(size, SizeConverter.getInstance()); + expResult = SizeUnitsShim.pixels(SizeUnits.PT, 12, 1, font); + result = SizeConverter.getInstance().convert(value, font).doubleValue(); + assertEquals(expResult, result, 0.01); + + size = new ParsedValueImpl(new Size(12.0f, SizeUnits.PX), null); + value = new ParsedValueImpl,Number>(size, SizeConverter.getInstance()); + expResult = SizeUnitsShim.pixels(SizeUnits.PX, 12, 1, font); + result = SizeConverter.getInstance().convert(value, font).doubleValue(); + assertEquals(expResult, result, 0.01); + } + +// @Test +// public void testConvertToPoints() { +// +// Font font = Font.getDefault(); +// // font size is in pixels. convert to points +// double pointSize = font.getSize() / javafx.stage.Screen.getPrimary().getDpi() * 72; +// +// ParsedValue size = new ParsedValueImpl(new Size(2.0f, SizeUnits.EM), null); +// ParsedValue,Double> value = new ParsedValueImpl,Double>(size, StyleConverter.POINTS); +// double expResult = SizeUnits.EM.points(2, 1, font); +// double result = StyleConverter.POINTS.convert(value, font); +// assertEquals(expResult, result, 0.01); +// +// size = new ParsedValueImpl(new Size(120.0f, SizeUnits.PERCENT), null); +// value = new ParsedValueImpl,Double>(size, StyleConverter.POINTS); +// expResult = SizeUnits.PERCENT.points(120, 1, font); +// result = StyleConverter.POINTS.convert(value, font); +// assertEquals(expResult, result, 0.01); +// +// size = new ParsedValueImpl(new Size(12.0f, SizeUnits.PT), null); +// value = new ParsedValueImpl,Double>(size, StyleConverter.POINTS); +// expResult = SizeUnits.PT.points(12, 1, font); +// result = StyleConverter.POINTS.convert(value, font); +// assertEquals(expResult, result, 0.01); +// +// size = new ParsedValueImpl(new Size(12.0f, SizeUnits.PX), null); +// value = new ParsedValueImpl,Double>(size, StyleConverter.POINTS); +// expResult = SizeUnits.PX.points(12, 1, font); +// result = StyleConverter.POINTS.convert(value, font); +// assertEquals(expResult, result, 0.01); +// +// } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/PseudoClassTest.java 2015-09-11 21:23:47.477287405 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,1249 +0,0 @@ -/* - * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javafx.beans.value.ChangeListener; -import javafx.collections.ObservableSet; -import javafx.collections.SetChangeListener; -import javafx.css.PseudoClass; -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.Test; - -/** - * - * @author dgrieve - */ -public class PseudoClassTest { - - public PseudoClassTest() { - } - - @Before - public void before() { - PseudoClassState.pseudoClassMap.clear(); - PseudoClassState.pseudoClasses.clear(); - } - - @Test - public void testGetState() { - String pseudoClass = "xyzzy"; - PseudoClass result = PseudoClass.getPseudoClass(pseudoClass); - assertEquals(pseudoClass, result.getPseudoClassName()); - } - - @Test - public void testCreateStatesInstance() { - PseudoClassState result = new PseudoClassState(); - assertNotNull(result); - } - - @Test - public void testGetStateThrowsIllegalArgumentExceptionWithNullArg() { - try { - PseudoClass state = PseudoClass.getPseudoClass(null); - fail(); - } catch (IllegalArgumentException exception) { - } - } - - @Test - public void testGetStateThrowsIllegalArgumentExceptionWithEmptyArg() { - try { - PseudoClass state = PseudoClass.getPseudoClass(" "); - fail(); - } catch (IllegalArgumentException exception) { - } - } - - @Test - public void testState_getPseudoClass() { - // no different than testing the getPseudoClassName method! - String pseudoClass = "xyzzy"; - PseudoClass result = PseudoClass.getPseudoClass(pseudoClass); - assertEquals(pseudoClass, result.getPseudoClassName()); - } - - @Test - public void testState_toString() { - String pseudoClass = "xyzzy"; - PseudoClass result = PseudoClass.getPseudoClass(pseudoClass); - assertEquals(pseudoClass, result.toString()); - } - - @Test - public void testPseudoClassState_add() { - String pseudoClass = "xyzzy"; - PseudoClass state = PseudoClass.getPseudoClass(pseudoClass); - PseudoClassState states = new PseudoClassState(); - states.add(state); - - List stateList = new ArrayList(); - Iterator iter = states.iterator(); - while (iter.hasNext()) { - stateList.add(iter.next()); - } - - assertTrue(stateList.contains(state)); - } - - @Test - public void testPseudoClassState_add_multipleStates() { - String[] pseudoClasses = new String[] { - "one", "two", "three", "four", "five" - }; - - PseudoClassState states = new PseudoClassState(); - - for (int n=0; n stateList = new ArrayList(); - Iterator iter = states.iterator(); - while (iter.hasNext()) { - stateList.add(iter.next()); - } - - for (int n=0; n states = new ArrayList(); - Iterator iter = aStates.iterator(); - while (iter.hasNext()) { - states.add(iter.next()); - } - - assertEquals(expected.length, states.size(), 0.000001); - - for (int n=0; n states = new ArrayList(); - Iterator iter = aStates.iterator(); - while (iter.hasNext()) { - states.add(iter.next()); - } - assertEquals(0, states.size(), 0.000001); - } - - @Test - public void testPseudoClassState_retainAll_withNullArg() { - - PseudoClassState aStates = new PseudoClassState(); - PseudoClassState bStates = null; - aStates.retainAll(bStates); - List states = new ArrayList(); - Iterator iter = aStates.iterator(); - while (iter.hasNext()) { - states.add(iter.next()); - } - assertEquals(0, states.size(), 0.000001); - - } - - @Test - public void testPseudoClassState_retainAll_disjointYieldsEmpty() { - - String[] setA = new String[] { - "zero", "one", "two", "three" - }; - - PseudoClassState aStates = new PseudoClassState(); - for(int n=0; n states = new ArrayList(); - Iterator iter = aStates.iterator(); - while (iter.hasNext()) { - states.add(iter.next()); - } - - assertEquals(expected.length, states.size(), 0.000001); - - for (int n=0; n states = new ArrayList(); - Iterator iter = aStates.iterator(); - while (iter.hasNext()) { - states.add(iter.next()); - } - - assertEquals(expected.length, states.size(), 0.000001); - - for (int n=0; n states = new ArrayList(); - Iterator iter = aStates.iterator(); - while (iter.hasNext()) { - states.add(iter.next()); - } - assertEquals(0, states.size(), 0.000001); - } - - @Test - public void testPseudoClassState_addAll_withNullArgs() { - - PseudoClassState aStates = new PseudoClassState(); - PseudoClassState bStates = null; - aStates.addAll(bStates); - List states = new ArrayList(); - Iterator iter = aStates.iterator(); - while (iter.hasNext()) { - states.add(iter.next()); - } - assertEquals(0, states.size(), 0.000001); - - } - - @Test - public void testPseudoClassState_getPseudoClasses() { - - String[] pseudoClasses = new String[] { - "zero", "one", "two", "three" - }; - List expected = new ArrayList(); - PseudoClassState states = new PseudoClassState(); - for(int n=0; n stateList = new ArrayList(); - Iterator iter = states.iterator(); - while (iter.hasNext()) { - stateList.add(iter.next()); - } - - assertTrue(expected.containsAll(stateList)); - } - - @Test - public void testPseudoClassState_toString() { - - String[] pseudoClasses = new String[] { - "zero", "one", "two", "three" - }; - - PseudoClassState states = new PseudoClassState(); - for(int n=0; n stateList = new ArrayList(); - Iterator iter = states.iterator(); - while (iter.hasNext()) { - stateList.add(iter.next()); - } - String expected = stateList.toString(); - - String result = states.toString(); - - assertEquals(expected, result); - } - - @Test public void testPseudoClassState_iterator() { - - PseudoClass[] pseudoClasses = new PseudoClass[4]; - PseudoClassState states = new PseudoClassState(); - - for (int n=0; n iter = states.iterator(); - while(iter.hasNext()) { - - iterations += 1; - assertTrue (iterations+">"+pseudoClasses.length, iterations <= pseudoClasses.length); - - PseudoClass pseudoClass = iter.next(); - assertEquals (pseudoClass, pseudoClasses[iterations-1]); - } - - assertTrue (pseudoClasses.length+"!="+iterations, pseudoClasses.length == iterations); - - } - - @Test public void testPseudoClassState_iterator_withLargeNumberOfPsuedoClasses() { - - PseudoClass[] pseudoClasses = new PseudoClass[Long.SIZE*3]; - PseudoClassState states = new PseudoClassState(); - - for (int n=0; n iter = states.iterator(); - while(iter.hasNext()) { - - iterations += 1; - assertTrue (iterations+">"+pseudoClasses.length, iterations <= pseudoClasses.length); - - PseudoClass pseudoClass = iter.next(); - assertEquals (pseudoClass, pseudoClasses[iterations-1]); - } - - assertTrue (pseudoClasses.length+"!="+iterations, pseudoClasses.length == iterations); - - } - - @Test public void testPseudoClassState_iterator_remove() { - - PseudoClass[] pseudoClasses = new PseudoClass[4]; - PseudoClassState states = new PseudoClassState(); - - for (int n=0; n iter = states.iterator(); - while(iter.hasNext()) { - - ++iterations; - - if ((iterations % 2) == 0) { - iter.remove(); - --nPseudoClasses; - assertFalse(states.contains(pseudoClasses[iterations-1])); - } - } - - assertTrue (nPseudoClasses+"!="+states.size(), nPseudoClasses == states.size()); - - } - - @Test public void testPseudoClassState_iterator_remove_withLargeNumberOfPseudoClasses() { - - PseudoClass[] pseudoClasses = new PseudoClass[Long.SIZE*3]; - PseudoClassState states = new PseudoClassState(); - - for (int n=0; n iter = states.iterator(); - while(iter.hasNext()) { - - ++iterations; - - if ((iterations % 2) == 0) { - iter.remove(); - --nPseudoClasses; - assertFalse(states.contains(pseudoClasses[iterations-1])); - } - } - - assertTrue (nPseudoClasses+"!="+states.size(), nPseudoClasses == states.size()); - - } - - int nObservations = 0; - - @Test public void testObservablePseudoClass_listener_add() { - - - final PseudoClass[] expectedObservations = new PseudoClass[] { - PseudoClass.getPseudoClass("ONE"), - PseudoClass.getPseudoClass("TWO"), - PseudoClass.getPseudoClass("THREE") - - }; - final int nObservationsExpected = expectedObservations.length; - nObservations = 0; - - ObservableSet pseudoClasses = new PseudoClassState(); - pseudoClasses.addListener((SetChangeListener.Change change) -> { - if (change.wasAdded()) { - assert (nObservations < nObservationsExpected); - PseudoClass observed = change.getElementAdded(); - assertSame(expectedObservations[nObservations], observed); - nObservations += 1; - } else { - fail(); - } - }); - - for (int n=0; n pseudoClasses = new PseudoClassState(); - for (int n=0; n change) -> { - if (change.wasRemoved()) { - assert (nObservations < nObservationsExpected); - PseudoClass observed = change.getElementRemoved(); - assertSame(expectedObservations[nObservations], observed); - nObservations += 1; - } else { - fail(); - } - }); - - for (int n=0; n pseudoClasses = new PseudoClassState(); - for (int n=0; n change) -> { - if (change.wasRemoved()) { - assert (nObservations < nObservationsExpected); - PseudoClass observed = change.getElementRemoved(); - assertSame(expectedObservations[nObservations], observed); - nObservations += 1; - } else { - fail(); - } - }); - - for (Iterator iter = pseudoClasses.iterator(); iter.hasNext();) { - iter.remove(); - }; - - assertEquals(nObservationsExpected, nObservations); - - } - - @Test public void testObservablePseudoClass_listener_addAll() { - - - final PseudoClass[] expectedObservations = new PseudoClass[] { - PseudoClass.getPseudoClass("ONE"), - PseudoClass.getPseudoClass("TWO"), - PseudoClass.getPseudoClass("THREE") - - }; - final int nObservationsExpected = expectedObservations.length; - nObservations = 0; - - Set pseudoClassesToAdd = new PseudoClassState(); - for (int n=0; n pseudoClasses = new PseudoClassState(); - pseudoClasses.addListener((SetChangeListener.Change change) -> { - if (change.wasAdded()) { - assert (nObservations < nObservationsExpected); - PseudoClass observed = change.getElementAdded(); - assertSame(expectedObservations[nObservations], observed); - nObservations += 1; - } else { - fail(); - } - }); - - pseudoClasses.addAll(pseudoClassesToAdd); - - assertEquals(nObservationsExpected, nObservations); - - } - - @Test public void testObservablePseudoClass_listener_removeAll() { - - - final PseudoClass[] pseudoClassesToRemove = new PseudoClass[] { - PseudoClass.getPseudoClass("TWO"), - PseudoClass.getPseudoClass("THREE") - - }; - - final PseudoClass[] pseudoClasses = new PseudoClass[] { - PseudoClass.getPseudoClass("ONE"), - PseudoClass.getPseudoClass("TWO"), - PseudoClass.getPseudoClass("THREE"), - PseudoClass.getPseudoClass("FOUR") - - }; - - final int nObservationsExpected = pseudoClassesToRemove.length; - nObservations = 0; - - Set other = new PseudoClassState(); - for (int n=0; n master = new PseudoClassState(); - for (int n=0; n change) -> { - if (change.wasRemoved()) { - assert (nObservations < nObservationsExpected); - PseudoClass observed = change.getElementRemoved(); - assertSame(pseudoClassesToRemove[nObservations], observed); - nObservations += 1; - } else { - fail(); - } - }); - - master.removeAll(other); - - assertEquals(nObservationsExpected, nObservations); - assertEquals(pseudoClasses.length-pseudoClassesToRemove.length, master.size()); - - } - - @Test public void testObservablePseudoClass_listener_retainAll() { - - - final PseudoClass[] pseudoClassesToRetain = new PseudoClass[] { - PseudoClass.getPseudoClass("TWO"), - PseudoClass.getPseudoClass("THREE") - - }; - - final PseudoClass[] removedPseudoClasses = new PseudoClass[] { - PseudoClass.getPseudoClass("ONE"), - PseudoClass.getPseudoClass("FOUR") - - }; - - final PseudoClass[] pseudoClasses = new PseudoClass[] { - PseudoClass.getPseudoClass("ONE"), - PseudoClass.getPseudoClass("TWO"), - PseudoClass.getPseudoClass("THREE"), - PseudoClass.getPseudoClass("FOUR") - - }; - - final int nObservationsExpected = pseudoClassesToRetain.length; - nObservations = 0; - - Set other = new PseudoClassState(); - for (int n=0; n master = new PseudoClassState(); - for (int n=0; n change) -> { - if (change.wasRemoved()) { - assert (nObservations < nObservationsExpected); - PseudoClass observed = change.getElementRemoved(); - assertSame(removedPseudoClasses[nObservations], observed); - nObservations += 1; - } else { - fail(); - } - }); - - master.retainAll(other); - - assertEquals(nObservationsExpected, nObservations); - assertEquals(pseudoClassesToRetain.length, master.size()); - - } - - @Test public void testObservablePseudoClass_listener_clear() { - - - final PseudoClass[] pseudoClasses = new PseudoClass[] { - PseudoClass.getPseudoClass("ONE"), - PseudoClass.getPseudoClass("TWO"), - PseudoClass.getPseudoClass("THREE"), - PseudoClass.getPseudoClass("FOUR") - - }; - - final int nObservationsExpected = pseudoClasses.length; - nObservations = 0; - - ObservableSet master = new PseudoClassState(); - for (int n=0; n change) -> { - if (change.wasRemoved()) { - assert (nObservations < nObservationsExpected); - PseudoClass observed = change.getElementRemoved(); - assertSame(pseudoClasses[nObservations], observed); - nObservations += 1; - } else { - fail(); - } - }); - - master.clear(); - - assertEquals(nObservationsExpected, nObservations); - assertTrue(master.isEmpty()); - - } - - @Test public void testObservablePseudoClass_listener_getSet_unmodifiable() { - - final ObservableSet master = new PseudoClassState(); - - master.addListener(new SetChangeListener() { - - @Override - public void onChanged(SetChangeListener.Change change) { - master.removeListener(this); - try { - ObservableSet set = change.getSet(); - set.add(PseudoClass.getPseudoClass("TWO")); - fail(); - } catch (UnsupportedOperationException e) { - // This is the exception we expect from an unmodifiable set - } catch (Exception other) { - fail(other.getMessage()); - } - } - }); - - master.add(PseudoClass.getPseudoClass("ONE")); - - } - - @Test public void testRetainAllOfEmptySetResultsInEmptySet() { - - final PseudoClass[] pseudoClasses = new PseudoClass[] { - PseudoClass.getPseudoClass("ONE"), - PseudoClass.getPseudoClass("TWO"), - PseudoClass.getPseudoClass("THREE"), - PseudoClass.getPseudoClass("FOUR") - - }; - - Set setA = new PseudoClassState(); - for (int n=0; n setB = new PseudoClassState(); - - assertTrue(setA.retainAll(setB)); - - assertArrayEquals(new long[0], ((PseudoClassState)setA).getBits()); - - } - - @Test public void testRemoveAllOfSameSetResultsInEmptySet() { - - final PseudoClass[] pseudoClasses = new PseudoClass[] { - PseudoClass.getPseudoClass("ONE"), - PseudoClass.getPseudoClass("TWO"), - PseudoClass.getPseudoClass("THREE"), - PseudoClass.getPseudoClass("FOUR") - - }; - - Set setA = new PseudoClassState(); - for (int n=0; n setA = new PseudoClassState(); - for (int n=0; n setA = new PseudoClassState(); - for (int n=0; n iterator = setA.iterator(); - while (iterator.hasNext()) { - iterator.remove(); - } - - assertArrayEquals(new long[0], ((PseudoClassState)setA).getBits()); - - } - - @Test public void testAddEmptyToEmptyResultsInEmptySet() { - - Set setA = new PseudoClassState(); - Set setB = new PseudoClassState(); - assertFalse(setA.addAll(setB)); - assertArrayEquals(new long[0], ((PseudoClassState)setA).getBits()); - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/PseudoClassTest.java 2015-09-11 21:23:47.285287407 -0400 @@ -0,0 +1,1250 @@ +/* + * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import com.sun.javafx.css.BitSetShim; +import com.sun.javafx.css.PseudoClassState; +import com.sun.javafx.css.PseudoClassStateShim; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javafx.collections.ObservableSet; +import javafx.collections.SetChangeListener; +import javafx.css.PseudoClass; +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; + +/** + * + * @author dgrieve + */ +public class PseudoClassTest { + + public PseudoClassTest() { + } + + @Before + public void before() { + PseudoClassStateShim.pseudoClassMap.clear(); + PseudoClassStateShim.pseudoClasses.clear(); + } + + @Test + public void testGetState() { + String pseudoClass = "xyzzy"; + PseudoClass result = PseudoClass.getPseudoClass(pseudoClass); + assertEquals(pseudoClass, result.getPseudoClassName()); + } + + @Test + public void testCreateStatesInstance() { + PseudoClassState result = new PseudoClassState(); + assertNotNull(result); + } + + @Test + public void testGetStateThrowsIllegalArgumentExceptionWithNullArg() { + try { + PseudoClass state = PseudoClass.getPseudoClass(null); + fail(); + } catch (IllegalArgumentException exception) { + } + } + + @Test + public void testGetStateThrowsIllegalArgumentExceptionWithEmptyArg() { + try { + PseudoClass state = PseudoClass.getPseudoClass(" "); + fail(); + } catch (IllegalArgumentException exception) { + } + } + + @Test + public void testState_getPseudoClass() { + // no different than testing the getPseudoClassName method! + String pseudoClass = "xyzzy"; + PseudoClass result = PseudoClass.getPseudoClass(pseudoClass); + assertEquals(pseudoClass, result.getPseudoClassName()); + } + + @Test + public void testState_toString() { + String pseudoClass = "xyzzy"; + PseudoClass result = PseudoClass.getPseudoClass(pseudoClass); + assertEquals(pseudoClass, result.toString()); + } + + @Test + public void testPseudoClassState_add() { + String pseudoClass = "xyzzy"; + PseudoClass state = PseudoClass.getPseudoClass(pseudoClass); + PseudoClassState states = new PseudoClassState(); + BitSetShim.add(states, state); + + List stateList = new ArrayList(); + Iterator iter = BitSetShim.iterator(states); + while (iter.hasNext()) { + stateList.add(iter.next()); + } + + assertTrue(stateList.contains(state)); + } + + @Test + public void testPseudoClassState_add_multipleStates() { + String[] pseudoClasses = new String[] { + "one", "two", "three", "four", "five" + }; + + PseudoClassState states = new PseudoClassState(); + + for (int n=0; n stateList = new ArrayList(); + Iterator iter = BitSetShim.iterator(states); + while (iter.hasNext()) { + stateList.add(iter.next()); + } + + for (int n=0; n states = new ArrayList(); + Iterator iter = BitSetShim.iterator(aStates); + while (iter.hasNext()) { + states.add(iter.next()); + } + + assertEquals(expected.length, states.size(), 0.000001); + + for (int n=0; n states = new ArrayList(); + Iterator iter = BitSetShim.iterator(aStates); + while (iter.hasNext()) { + states.add(iter.next()); + } + assertEquals(0, states.size(), 0.000001); + } + + @Test + public void testPseudoClassState_retainAll_withNullArg() { + + PseudoClassState aStates = new PseudoClassState(); + PseudoClassState bStates = null; + BitSetShim.retainAll(aStates, bStates); + List states = new ArrayList(); + Iterator iter = BitSetShim.iterator(aStates); + while (iter.hasNext()) { + states.add(iter.next()); + } + assertEquals(0, states.size(), 0.000001); + + } + + @Test + public void testPseudoClassState_retainAll_disjointYieldsEmpty() { + + String[] setA = new String[] { + "zero", "one", "two", "three" + }; + + PseudoClassState aStates = new PseudoClassState(); + for(int n=0; n states = new ArrayList(); + Iterator iter = BitSetShim.iterator(aStates); + while (iter.hasNext()) { + states.add(iter.next()); + } + + assertEquals(expected.length, states.size(), 0.000001); + + for (int n=0; n states = new ArrayList(); + Iterator iter = BitSetShim.iterator(aStates); + while (iter.hasNext()) { + states.add(iter.next()); + } + + assertEquals(expected.length, states.size(), 0.000001); + + for (int n=0; n states = new ArrayList(); + Iterator iter = BitSetShim.iterator(aStates); + while (iter.hasNext()) { + states.add(iter.next()); + } + assertEquals(0, states.size(), 0.000001); + } + + @Test + public void testPseudoClassState_addAll_withNullArgs() { + + PseudoClassState aStates = new PseudoClassState(); + PseudoClassState bStates = null; + BitSetShim.addAll(aStates, bStates); + List states = new ArrayList(); + Iterator iter = BitSetShim.iterator(aStates); + while (iter.hasNext()) { + states.add(iter.next()); + } + assertEquals(0, states.size(), 0.000001); + + } + + @Test + public void testPseudoClassState_getPseudoClasses() { + + String[] pseudoClasses = new String[] { + "zero", "one", "two", "three" + }; + List expected = new ArrayList(); + PseudoClassState states = new PseudoClassState(); + for(int n=0; n stateList = new ArrayList(); + Iterator iter = BitSetShim.iterator(states); + while (iter.hasNext()) { + stateList.add(iter.next()); + } + + assertTrue(expected.containsAll(stateList)); + } + + @Test + public void testPseudoClassState_toString() { + + String[] pseudoClasses = new String[] { + "zero", "one", "two", "three" + }; + + PseudoClassState states = new PseudoClassState(); + for(int n=0; n stateList = new ArrayList(); + Iterator iter = BitSetShim.iterator(states); + while (iter.hasNext()) { + stateList.add(iter.next()); + } + String expected = stateList.toString(); + + String result = states.toString(); + + assertEquals(expected, result); + } + + @Test public void testPseudoClassState_iterator() { + + PseudoClass[] pseudoClasses = new PseudoClass[4]; + PseudoClassState states = new PseudoClassState(); + + for (int n=0; n iter = BitSetShim.iterator(states); + while(iter.hasNext()) { + + iterations += 1; + assertTrue (iterations+">"+pseudoClasses.length, iterations <= pseudoClasses.length); + + PseudoClass pseudoClass = iter.next(); + assertEquals (pseudoClass, pseudoClasses[iterations-1]); + } + + assertTrue (pseudoClasses.length+"!="+iterations, pseudoClasses.length == iterations); + + } + + @Test public void testPseudoClassState_iterator_withLargeNumberOfPsuedoClasses() { + + PseudoClass[] pseudoClasses = new PseudoClass[Long.SIZE*3]; + PseudoClassState states = new PseudoClassState(); + + for (int n=0; n iter = BitSetShim.iterator(states); + while(iter.hasNext()) { + + iterations += 1; + assertTrue (iterations+">"+pseudoClasses.length, iterations <= pseudoClasses.length); + + PseudoClass pseudoClass = iter.next(); + assertEquals (pseudoClass, pseudoClasses[iterations-1]); + } + + assertTrue (pseudoClasses.length+"!="+iterations, pseudoClasses.length == iterations); + + } + + @Test public void testPseudoClassState_iterator_remove() { + + PseudoClass[] pseudoClasses = new PseudoClass[4]; + PseudoClassState states = new PseudoClassState(); + + for (int n=0; n iter = BitSetShim.iterator(states); + while(iter.hasNext()) { + + ++iterations; + + if ((iterations % 2) == 0) { + iter.remove(); + --nPseudoClasses; + assertFalse( BitSetShim.contains(states, pseudoClasses[iterations-1])); + } + } + + assertTrue (nPseudoClasses+"!="+BitSetShim.size(states), nPseudoClasses == BitSetShim.size(states)); + + } + + @Test public void testPseudoClassState_iterator_remove_withLargeNumberOfPseudoClasses() { + + PseudoClass[] pseudoClasses = new PseudoClass[Long.SIZE*3]; + PseudoClassState states = new PseudoClassState(); + + for (int n=0; n iter = BitSetShim.iterator(states); + while(iter.hasNext()) { + + ++iterations; + + if ((iterations % 2) == 0) { + iter.remove(); + --nPseudoClasses; + assertFalse( BitSetShim.contains(states, pseudoClasses[iterations-1])); + } + } + + assertTrue (nPseudoClasses+"!="+BitSetShim.size(states), nPseudoClasses == BitSetShim.size(states)); + + } + + int nObservations = 0; + + @Test public void testObservablePseudoClass_listener_add() { + + + final PseudoClass[] expectedObservations = new PseudoClass[] { + PseudoClass.getPseudoClass("ONE"), + PseudoClass.getPseudoClass("TWO"), + PseudoClass.getPseudoClass("THREE") + + }; + final int nObservationsExpected = expectedObservations.length; + nObservations = 0; + + ObservableSet pseudoClasses = new PseudoClassState(); + pseudoClasses.addListener((SetChangeListener.Change change) -> { + if (change.wasAdded()) { + assert (nObservations < nObservationsExpected); + PseudoClass observed = change.getElementAdded(); + assertSame(expectedObservations[nObservations], observed); + nObservations += 1; + } else { + fail(); + } + }); + + for (int n=0; n pseudoClasses = new PseudoClassState(); + for (int n=0; n change) -> { + if (change.wasRemoved()) { + assert (nObservations < nObservationsExpected); + PseudoClass observed = change.getElementRemoved(); + assertSame(expectedObservations[nObservations], observed); + nObservations += 1; + } else { + fail(); + } + }); + + for (int n=0; n pseudoClasses = new PseudoClassState(); + for (int n=0; n change) -> { + if (change.wasRemoved()) { + assert (nObservations < nObservationsExpected); + PseudoClass observed = change.getElementRemoved(); + assertSame(expectedObservations[nObservations], observed); + nObservations += 1; + } else { + fail(); + } + }); + + for (Iterator iter = pseudoClasses.iterator(); iter.hasNext();) { + iter.remove(); + }; + + assertEquals(nObservationsExpected, nObservations); + + } + + @Test public void testObservablePseudoClass_listener_addAll() { + + + final PseudoClass[] expectedObservations = new PseudoClass[] { + PseudoClass.getPseudoClass("ONE"), + PseudoClass.getPseudoClass("TWO"), + PseudoClass.getPseudoClass("THREE") + + }; + final int nObservationsExpected = expectedObservations.length; + nObservations = 0; + + Set pseudoClassesToAdd = new PseudoClassState(); + for (int n=0; n pseudoClasses = new PseudoClassState(); + pseudoClasses.addListener((SetChangeListener.Change change) -> { + if (change.wasAdded()) { + assert (nObservations < nObservationsExpected); + PseudoClass observed = change.getElementAdded(); + assertSame(expectedObservations[nObservations], observed); + nObservations += 1; + } else { + fail(); + } + }); + + pseudoClasses.addAll(pseudoClassesToAdd); + + assertEquals(nObservationsExpected, nObservations); + + } + + @Test public void testObservablePseudoClass_listener_removeAll() { + + + final PseudoClass[] pseudoClassesToRemove = new PseudoClass[] { + PseudoClass.getPseudoClass("TWO"), + PseudoClass.getPseudoClass("THREE") + + }; + + final PseudoClass[] pseudoClasses = new PseudoClass[] { + PseudoClass.getPseudoClass("ONE"), + PseudoClass.getPseudoClass("TWO"), + PseudoClass.getPseudoClass("THREE"), + PseudoClass.getPseudoClass("FOUR") + + }; + + final int nObservationsExpected = pseudoClassesToRemove.length; + nObservations = 0; + + Set other = new PseudoClassState(); + for (int n=0; n master = new PseudoClassState(); + for (int n=0; n change) -> { + if (change.wasRemoved()) { + assert (nObservations < nObservationsExpected); + PseudoClass observed = change.getElementRemoved(); + assertSame(pseudoClassesToRemove[nObservations], observed); + nObservations += 1; + } else { + fail(); + } + }); + + master.removeAll(other); + + assertEquals(nObservationsExpected, nObservations); + assertEquals(pseudoClasses.length-pseudoClassesToRemove.length, master.size()); + + } + + @Test public void testObservablePseudoClass_listener_retainAll() { + + + final PseudoClass[] pseudoClassesToRetain = new PseudoClass[] { + PseudoClass.getPseudoClass("TWO"), + PseudoClass.getPseudoClass("THREE") + + }; + + final PseudoClass[] removedPseudoClasses = new PseudoClass[] { + PseudoClass.getPseudoClass("ONE"), + PseudoClass.getPseudoClass("FOUR") + + }; + + final PseudoClass[] pseudoClasses = new PseudoClass[] { + PseudoClass.getPseudoClass("ONE"), + PseudoClass.getPseudoClass("TWO"), + PseudoClass.getPseudoClass("THREE"), + PseudoClass.getPseudoClass("FOUR") + + }; + + final int nObservationsExpected = pseudoClassesToRetain.length; + nObservations = 0; + + Set other = new PseudoClassState(); + for (int n=0; n master = new PseudoClassState(); + for (int n=0; n change) -> { + if (change.wasRemoved()) { + assert (nObservations < nObservationsExpected); + PseudoClass observed = change.getElementRemoved(); + assertSame(removedPseudoClasses[nObservations], observed); + nObservations += 1; + } else { + fail(); + } + }); + + master.retainAll(other); + + assertEquals(nObservationsExpected, nObservations); + assertEquals(pseudoClassesToRetain.length, master.size()); + + } + + @Test public void testObservablePseudoClass_listener_clear() { + + + final PseudoClass[] pseudoClasses = new PseudoClass[] { + PseudoClass.getPseudoClass("ONE"), + PseudoClass.getPseudoClass("TWO"), + PseudoClass.getPseudoClass("THREE"), + PseudoClass.getPseudoClass("FOUR") + + }; + + final int nObservationsExpected = pseudoClasses.length; + nObservations = 0; + + ObservableSet master = new PseudoClassState(); + for (int n=0; n change) -> { + if (change.wasRemoved()) { + assert (nObservations < nObservationsExpected); + PseudoClass observed = change.getElementRemoved(); + assertSame(pseudoClasses[nObservations], observed); + nObservations += 1; + } else { + fail(); + } + }); + + master.clear(); + + assertEquals(nObservationsExpected, nObservations); + assertTrue(master.isEmpty()); + + } + + @Test public void testObservablePseudoClass_listener_getSet_unmodifiable() { + + final ObservableSet master = new PseudoClassState(); + + master.addListener(new SetChangeListener() { + + @Override + public void onChanged(SetChangeListener.Change change) { + master.removeListener(this); + try { + ObservableSet set = change.getSet(); + set.add(PseudoClass.getPseudoClass("TWO")); + fail(); + } catch (UnsupportedOperationException e) { + // This is the exception we expect from an unmodifiable set + } catch (Exception other) { + fail(other.getMessage()); + } + } + }); + + master.add(PseudoClass.getPseudoClass("ONE")); + + } + + @Test public void testRetainAllOfEmptySetResultsInEmptySet() { + + final PseudoClass[] pseudoClasses = new PseudoClass[] { + PseudoClass.getPseudoClass("ONE"), + PseudoClass.getPseudoClass("TWO"), + PseudoClass.getPseudoClass("THREE"), + PseudoClass.getPseudoClass("FOUR") + + }; + + Set setA = new PseudoClassState(); + for (int n=0; n setB = new PseudoClassState(); + + assertTrue(setA.retainAll(setB)); + + assertArrayEquals(new long[0], BitSetShim.getBits((PseudoClassState)setA)); + } + + @Test public void testRemoveAllOfSameSetResultsInEmptySet() { + + final PseudoClass[] pseudoClasses = new PseudoClass[] { + PseudoClass.getPseudoClass("ONE"), + PseudoClass.getPseudoClass("TWO"), + PseudoClass.getPseudoClass("THREE"), + PseudoClass.getPseudoClass("FOUR") + + }; + + Set setA = new PseudoClassState(); + for (int n=0; n setA = new PseudoClassState(); + for (int n=0; n setA = new PseudoClassState(); + for (int n=0; n iterator = setA.iterator(); + while (iterator.hasNext()) { + iterator.remove(); + } + + assertArrayEquals(new long[0], BitSetShim.getBits((PseudoClassState)setA)); + + } + + @Test public void testAddEmptyToEmptyResultsInEmptySet() { + + Set setA = new PseudoClassState(); + Set setB = new PseudoClassState(); + assertFalse(setA.addAll(setB)); + assertArrayEquals(new long[0], BitSetShim.getBits((PseudoClassState)setA)); + + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/SizeTypeTest.java 2015-09-11 21:23:48.233287396 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import static org.junit.Assert.assertEquals; - -import javafx.css.ParsedValue; -import javafx.css.Size; -import javafx.css.SizeUnits; -import javafx.css.StyleConverter; -import javafx.scene.text.Font; - -import org.junit.Test; - - - -public class SizeTypeTest { - - public SizeTypeTest() { - } - - /** - * Test of convert method, of class SizeType. - */ - @Test - public void testConvert() { - //System.out.println("convert"); - Size size = new Size(2.0f, SizeUnits.EM); - ParsedValue value = new ParsedValueImpl(size,null); - Font font = null; - Size result = value.convert(font); - assertEquals(size, result); - - ParsedValue,Double> pxSize = new ParsedValueImpl(value,StyleConverter.getSizeConverter()); - Float expResult = (float) size.pixels(font); - Float pixels = (float) ((double) pxSize.convert(font)); - assertEquals(expResult, pixels); - -// ParsedValue,Double> ptSize = new ParsedValue(value,SizeConverter.POINTS); -// expResult = (float) size.points(font); -// Float points = (float) ((double) ptSize.convert(font)); -// assertEquals(expResult, points); - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/SizeTypeTest.java 2015-09-11 21:23:48.093287398 -0400 @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import com.sun.javafx.css.ParsedValueImpl; +import static org.junit.Assert.assertEquals; + +import javafx.css.ParsedValue; +import javafx.css.Size; +import javafx.css.SizeUnits; +import javafx.css.StyleConverter; +import javafx.scene.text.Font; + +import org.junit.Test; + + + +public class SizeTypeTest { + + public SizeTypeTest() { + } + + /** + * Test of convert method, of class SizeType. + */ + @Test + public void testConvert() { + //System.out.println("convert"); + Size size = new Size(2.0f, SizeUnits.EM); + ParsedValue value = new ParsedValueImpl(size,null); + Font font = null; + Size result = value.convert(font); + assertEquals(size, result); + + ParsedValue,Double> pxSize = new ParsedValueImpl(value,StyleConverter.getSizeConverter()); + Float expResult = (float) size.pixels(font); + Float pixels = (float) ((double) pxSize.convert(font)); + assertEquals(expResult, pixels); + +// ParsedValue,Double> ptSize = new ParsedValue(value,SizeConverter.POINTS); +// expResult = (float) size.points(font); +// Float points = (float) ((double) ptSize.convert(font)); +// assertEquals(expResult, points); + + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/StringTypeTest.java 2015-09-11 21:23:49.009287388 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import javafx.css.converter.StringConverter; -import javafx.css.ParsedValue; -import javafx.css.StyleConverter; -import javafx.scene.text.Font; -import org.junit.AfterClass; -import static org.junit.Assert.assertEquals; -import org.junit.BeforeClass; -import org.junit.Test; - - -public class StringTypeTest { - - public StringTypeTest() { - } - - @BeforeClass - public static void setUpClass() throws Exception { - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - /** - * Test of convert method, of class StringType. - */ - @Test - public void testConvert() { - //System.out.println("convert"); - ParsedValue value = new ParsedValueImpl("test", StyleConverter.getStringConverter()); - Font font = null; - String expResult = "test"; - String result = value.convert(font); - assertEquals(expResult, result); - - ParsedValue[] values = new ParsedValue[] { - new ParsedValueImpl("hello", StyleConverter.getStringConverter()), - new ParsedValueImpl("world", StyleConverter.getStringConverter()) - }; - - ParsedValue[], String[]> seq = - new ParsedValueImpl[], String[]>(values, StringConverter.SequenceConverter.getInstance()); - - String[] strings = seq.convert(font); - assertEquals("hello", strings[0]); - assertEquals("world", strings[1]); - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/StringTypeTest.java 2015-09-11 21:23:48.809287390 -0400 @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import com.sun.javafx.css.ParsedValueImpl; +import javafx.css.converter.StringConverter; +import javafx.css.ParsedValue; +import javafx.css.StyleConverter; +import javafx.scene.text.Font; +import org.junit.AfterClass; +import static org.junit.Assert.assertEquals; +import org.junit.BeforeClass; +import org.junit.Test; + + +public class StringTypeTest { + + public StringTypeTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + /** + * Test of convert method, of class StringType. + */ + @Test + public void testConvert() { + //System.out.println("convert"); + ParsedValue value = new ParsedValueImpl("test", StyleConverter.getStringConverter()); + Font font = null; + String expResult = "test"; + String result = value.convert(font); + assertEquals(expResult, result); + + ParsedValue[] values = new ParsedValue[] { + new ParsedValueImpl("hello", StyleConverter.getStringConverter()), + new ParsedValueImpl("world", StyleConverter.getStringConverter()) + }; + + ParsedValue[], String[]> seq = + new ParsedValueImpl[], String[]>(values, StringConverter.SequenceConverter.getInstance()); + + String[] strings = seq.convert(font); + assertEquals("hello", strings[0]); + assertEquals("world", strings[1]); + + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/StyleManagerTest.java 2015-09-11 21:23:49.649287380 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,1119 +0,0 @@ -/* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import javafx.css.CssParser; -import javafx.css.StyleOrigin; -import javafx.css.StyleableProperty; -import javafx.css.Stylesheet; -import javafx.scene.Group; -import javafx.scene.Parent; -import javafx.scene.Scene; -import javafx.scene.SubScene; -import javafx.scene.layout.Pane; -import javafx.scene.paint.Color; -import javafx.scene.paint.Paint; -import javafx.scene.shape.Rectangle; -import org.junit.Before; -import org.junit.Test; - -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.junit.Assert.*; - -/** - * - * @author dgrieve - */ -public class StyleManagerTest { - - public StyleManagerTest() { - } - - @Before - public void setUp() { - StyleManager sm = StyleManager.getInstance(); - sm.userAgentStylesheetContainers.clear(); - sm.platformUserAgentStylesheetContainers.clear(); - sm.stylesheetContainerMap.clear(); - sm.cacheContainerMap.clear(); - sm.hasDefaultUserAgentStylesheet = false; - } - - @Test - public void testMethod_getInstance() { - Scene scene = new Scene(new Group()); - StyleManager sm = StyleManager.getInstance(); - assertNotNull(sm); - } - - private static int indexOf(final List list, final String fname) { - - for (int n=0, nMax=list.size(); n> styleMap = matchingStyles.getCascadingStyles(); - - assertTrue(styleMap.containsKey("-fx-fill")); - - List styles = styleMap.get("-fx-fill"); - assertEquals(1, styles.size()); - - Object obj = styles.get(0).getParsedValue().convert(null); - assertEquals(Color.RED, obj); - } - - @Test - public void testFindMatchingStyles_defaultStyleSheet_sceneUserAgentStylesheet() { - - StyleManager sm = StyleManager.getInstance(); - sm.setDefaultUserAgentStylesheet("/com/sun/javafx/css/ua0.css"); - - Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; - Scene scene = new Scene(new Group(rect)); - scene.setUserAgentStylesheet("/com/sun/javafx/css/ua1.css"); - - StyleMap matchingStyles = sm.findMatchingStyles(rect, null, null); - Map> styleMap = matchingStyles.getCascadingStyles(); - - scene.getRoot().applyCss(); - - // scene stylesheet should totally replace default - assertFalse(styleMap.containsKey("-fx-fill")); - assertTrue(styleMap.containsKey("-fx-stroke")); - - List styles = styleMap.get("-fx-stroke"); - assertEquals(1, styles.size()); - - Object obj = styles.get(0).getParsedValue().convert(null); - assertEquals(Color.YELLOW, obj); - } - - @Test - public void testFindMatchingStyles_defaultStyleSheet_sceneUserAgentStylesheet_sceneAuthorStylesheet() { - - StyleManager sm = StyleManager.getInstance(); - sm.setDefaultUserAgentStylesheet("/com/sun/javafx/css/ua0.css"); - - Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; - Scene scene = new Scene(new Group(rect)); - scene.setUserAgentStylesheet("/com/sun/javafx/css/ua1.css"); - scene.getStylesheets().add("/com/sun/javafx/css/ua2.css"); - - StyleMap matchingStyles = sm.findMatchingStyles(rect, null, null); - Map> styleMap = matchingStyles.getCascadingStyles(); - - scene.getRoot().applyCss(); - - // ua2.css has fill - assertTrue(styleMap.containsKey("-fx-fill")); - assertTrue(styleMap.containsKey("-fx-stroke")); - - // ua1.css and ua2.css have stroke - List styles = styleMap.get("-fx-stroke"); - assertEquals(2, styles.size()); - - Object obj = styles.get(0).getParsedValue().convert(null); - assertEquals(Color.GREEN, obj); - - // ua0.css and ua2.css have fill, but we shouldn't get anything from ua0 - // since we have a scene user-agent stylesheet - styles = styleMap.get("-fx-fill"); - assertEquals(1, styles.size()); - - obj = styles.get(0).getParsedValue().convert(null); - assertEquals(Color.BLUE, obj); - } - - @Test - public void testFindMatchingStyles_defaultStyleSheet_subSceneUserAgentStylesheet() { - - StyleManager sm = StyleManager.getInstance(); - sm.setDefaultUserAgentStylesheet("/com/sun/javafx/css/ua0.css"); - - Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; - Pane subSceneRoot = new Pane(rect); - SubScene subScene = new SubScene(subSceneRoot, 100, 100); - subScene.setUserAgentStylesheet("/com/sun/javafx/css/ua1.css"); - Scene scene = new Scene(new Group(subScene)); - - StyleMap matchingStyles = sm.findMatchingStyles(rect, subScene, null); - Map> styleMap = matchingStyles.getCascadingStyles(); - - scene.getRoot().applyCss(); - - // SubScene stylesheet should totally replace default - assertFalse(styleMap.containsKey("-fx-fill")); - assertTrue(styleMap.containsKey("-fx-stroke")); - - List styles = styleMap.get("-fx-stroke"); - assertEquals(1, styles.size()); - - Object obj = styles.get(0).getParsedValue().convert(null); - assertEquals(Color.YELLOW, obj); - } - - @Test - public void testFindMatchingStyles_defaultStyleSheet_subSceneUserAgentStylesheet_parentStylesheet() { - - StyleManager sm = StyleManager.getInstance(); - sm.setDefaultUserAgentStylesheet("/com/sun/javafx/css/ua0.css"); - - Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; - Group group = new Group(rect); - group.getStylesheets().add("/com/sun/javafx/css/ua2.css"); - Pane subSceneRoot = new Pane(group); - SubScene subScene = new SubScene(subSceneRoot, 100, 100); - subScene.setUserAgentStylesheet("/com/sun/javafx/css/ua1.css"); - Scene scene = new Scene(new Group(subScene)); - - StyleMap matchingStyles = sm.findMatchingStyles(rect, subScene, null); - Map> styleMap = matchingStyles.getCascadingStyles(); - - scene.getRoot().applyCss(); - - // ua2.css has fill - assertTrue(styleMap.containsKey("-fx-fill")); - assertTrue(styleMap.containsKey("-fx-stroke")); - - // ua1.css and ua2.css have stroke - List styles = styleMap.get("-fx-stroke"); - assertEquals(2, styles.size()); - - Object obj = styles.get(0).getParsedValue().convert(null); - assertEquals(Color.GREEN, obj); - - // ua0.css and ua2.css have fill, but we shouldn't get anything from ua0 - // since we have a scene user-agent stylesheet - styles = styleMap.get("-fx-fill"); - assertEquals(1, styles.size()); - - obj = styles.get(0).getParsedValue().convert(null); - assertEquals(Color.BLUE, obj); - } - - @Test - public void testSwitchDefaultUserAgentStylesheets() { - - Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; - Group group = new Group(rect); - Pane subSceneRoot = new Pane(group); - SubScene subScene = new SubScene(subSceneRoot, 100, 100); - Scene scene = new Scene(new Group(subScene)); - - StyleManager sm = StyleManager.getInstance(); - sm.setDefaultUserAgentStylesheet("/com/sun/javafx/css/ua0.css"); - - scene.getRoot().applyCss(); - - StyleMap matchingStyles = sm.findMatchingStyles(rect, subScene, null); - Map> styleMap = matchingStyles.getCascadingStyles(); - - // ua0.css has fill - assertTrue(styleMap.containsKey("-fx-fill")); - assertFalse(styleMap.containsKey("-fx-stroke")); - - List styles = styleMap.get("-fx-fill"); - assertEquals(1, styles.size()); - - Object obj = styles.get(0).getParsedValue().convert(null); - assertEquals(Color.RED, obj); - - sm.setDefaultUserAgentStylesheet("/com/sun/javafx/css/ua1.css"); - - matchingStyles = sm.findMatchingStyles(rect, subScene, null); - styleMap = matchingStyles.getCascadingStyles(); - - // ua1.css has stroke - assertTrue(styleMap.containsKey("-fx-stroke")); - assertFalse(styleMap.containsKey("-fx-fill")); - - styles = styleMap.get("-fx-stroke"); - assertEquals(1, styles.size()); - - obj = styles.get(0).getParsedValue().convert(null); - assertEquals(Color.YELLOW, obj); - } - - @Test - public void testGetCacheContainer() { - - Rectangle rectangle = new Rectangle(); - SubScene subScene = new SubScene(null, 0, 0); - - StyleManager sm = StyleManager.getInstance(); - - // no scene, should return null - StyleManager.CacheContainer container = sm.getCacheContainer(rectangle, subScene); - - assertNull(container); - - // has scene, should return non-null - subScene.setRoot(new Group()); - Scene scene = new Scene(new Group(rectangle,subScene)); - container = sm.getCacheContainer(rectangle, subScene); - - assertNotNull(container); - - } - - @Test - public void testGetCacheContainer_styleable() { - Rectangle rectangle = new Rectangle(); - - StyleManager sm = StyleManager.getInstance(); - - // no scene, should return null - StyleManager.CacheContainer container = sm.getCacheContainer(rectangle, null); - - assertNull(container); - - // has scene, should return non-null - Scene scene = new Scene(new Group(rectangle)); - container = sm.getCacheContainer(rectangle, null); - - assertNotNull(container); - - } - - @Test - public void testGetCacheContainer_subScene() { - - SubScene subScene = new SubScene(null, 0, 0); - - StyleManager sm = StyleManager.getInstance(); - - // no scene, should return null - StyleManager.CacheContainer container = sm.getCacheContainer(null, subScene); - - assertNull(container); - - // has scene, should return non-null - subScene.setRoot(new Group()); - Scene scene = new Scene(new Group(subScene)); - container = sm.getCacheContainer(null, subScene); - - assertNotNull(container); - - } - - @Test - public void testRT_37025() { - - // - // The issue in RT-37025 was that the stylesheet container wasn't getting removed even - // though the parent had been forgotten. The StyleManager#forget(Parent) method didn't - // look to see if _any_ stylesheet container had the parent as a reference. - // - final StyleManager sm = StyleManager.getInstance(); - - // This test needs a bit more complexity to the scene-graph - Group group = null; - Pane pane = new Pane( - new Group( - new Pane( - // I want these to be a Parent, not a Node - new Group(new Pane(){{ getStyleClass().add("rect"); }}), - group = new Group(new Pane(){{ getStyleClass().add("rect"); }}) - ) - ) - ); - pane.getStylesheets().add("/com/sun/javafx/css/ua0.css"); - group.getStylesheets().add("/com/sun/javafx/css/ua1.css"); - - Group root = new Group(pane); - Scene scene = new Scene(root); - - root.applyCss(); - - assertTrue(sm.stylesheetContainerMap.containsKey("/com/sun/javafx/css/ua0.css")); - StyleManager.StylesheetContainer container = sm.stylesheetContainerMap.get("/com/sun/javafx/css/ua0.css"); - assertEquals(7, container.parentUsers.list.size()); - - assertTrue(sm.stylesheetContainerMap.containsKey("/com/sun/javafx/css/ua1.css")); - container = sm.stylesheetContainerMap.get("/com/sun/javafx/css/ua1.css"); - assertEquals(2, container.parentUsers.list.size()); - - ((Pane)group.getParent()).getChildren().remove(group); - - assertFalse(sm.stylesheetContainerMap.containsKey("/com/sun/javafx/css/ua1.css")); - assertTrue(sm.stylesheetContainerMap.containsKey("/com/sun/javafx/css/ua0.css")); - container = sm.stylesheetContainerMap.get("/com/sun/javafx/css/ua0.css"); - assertEquals(5, container.parentUsers.list.size()); - - scene.setRoot(new Group()); - assertFalse(sm.stylesheetContainerMap.containsKey("/com/sun/javafx/css/ua0.css")); - assertFalse(StyleManager.cacheContainerMap.containsKey(root)); - assertTrue(StyleManager.cacheContainerMap.containsKey(scene.getRoot())); - - } - - @Test - public void test_setUserAgentStylesheets() { - - List uaStylesheets = new ArrayList<>(); - Collections.addAll(uaStylesheets, "/com/sun/javafx/css/ua0.css", "/com/sun/javafx/css/ua1.css"); - - final StyleManager sm = StyleManager.getInstance(); - sm.setUserAgentStylesheets(uaStylesheets); - - assertEquals(2, sm.platformUserAgentStylesheetContainers.size()); - assertEquals("/com/sun/javafx/css/ua0.css", sm.platformUserAgentStylesheetContainers.get(0).fname); - assertEquals("/com/sun/javafx/css/ua1.css", sm.platformUserAgentStylesheetContainers.get(1).fname); - } - - @Test - public void test_setUserAgentStylesheets_overwrites_existing() { - - List uaStylesheets = new ArrayList<>(); - Collections.addAll(uaStylesheets, "/com/sun/javafx/css/ua0.css"); - - final StyleManager sm = StyleManager.getInstance(); - - // 1 - overwrite default user agent stylesheet - sm.platformUserAgentStylesheetContainers.clear();; - sm.setDefaultUserAgentStylesheet("/com/sun/javafx/css/ua1.css"); - assertEquals(1, sm.platformUserAgentStylesheetContainers.size()); - assertEquals("/com/sun/javafx/css/ua1.css", sm.platformUserAgentStylesheetContainers.get(0).fname); - - sm.setUserAgentStylesheets(uaStylesheets); - assertEquals(1, sm.platformUserAgentStylesheetContainers.size()); - assertEquals("/com/sun/javafx/css/ua0.css", sm.platformUserAgentStylesheetContainers.get(0).fname); - - // 2 - overwrite other user-agent stylesheets - sm.platformUserAgentStylesheetContainers.clear();; - sm.addUserAgentStylesheet("/com/sun/javafx/css/ua1.css"); - assertEquals(1, sm.platformUserAgentStylesheetContainers.size()); - - sm.setUserAgentStylesheets(uaStylesheets); - assertEquals(1, sm.platformUserAgentStylesheetContainers.size()); - assertEquals("/com/sun/javafx/css/ua0.css", sm.platformUserAgentStylesheetContainers.get(0).fname); - } - - @Test - public void testRT_38687_with_Scene() { - - Rectangle rect = new Rectangle(50,50) {{ getStyleClass().add("rect"); }}; - Scene scene = new Scene(new Group(rect)); - scene.setUserAgentStylesheet("com/sun/javafx/css/ua0.css"); - scene.getRoot().applyCss(); - - StyleableProperty fillProperty = (StyleableProperty)rect.fillProperty(); - assertEquals(StyleOrigin.USER_AGENT, fillProperty.getStyleOrigin()); - - scene.setUserAgentStylesheet("com/sun/javafx/css/ua1.css"); - scene.getRoot().applyCss(); - - assertEquals(null, fillProperty.getStyleOrigin()); - - rect.setFill(Color.GREEN); - - scene.setUserAgentStylesheet("com/sun/javafx/css/rt38637.css"); - scene.getRoot().applyCss(); - assertEquals(StyleOrigin.USER, fillProperty.getStyleOrigin()); - - } - - @Test - public void testRT_38687_with_SubScene() { - - Rectangle rect = new Rectangle(50,50) {{ getStyleClass().add("rect"); }}; - Group group = new Group(rect); - SubScene subScene = new SubScene(group, 100, 100); - subScene.setUserAgentStylesheet("com/sun/javafx/css/ua0.css"); - - Scene scene = new Scene(new Group(subScene)); - scene.getRoot().applyCss(); - - StyleableProperty fillProperty = (StyleableProperty)rect.fillProperty(); - assertEquals(StyleOrigin.USER_AGENT, fillProperty.getStyleOrigin()); - - subScene.setUserAgentStylesheet("com/sun/javafx/css/ua1.css"); - scene.getRoot().applyCss(); - - assertEquals(null, fillProperty.getStyleOrigin()); - - rect.setFill(Color.GREEN); - - subScene.setUserAgentStylesheet("com/sun/javafx/css/rt38637.css"); - scene.getRoot().applyCss(); - assertEquals(StyleOrigin.USER, fillProperty.getStyleOrigin()); - - } - - @Test - public void testConcurrentAccess() { - final int NUM_THREADS = 10; - final Thread[] bgThreads = new Thread[NUM_THREADS]; - final AtomicBoolean err = new AtomicBoolean(false); - for (int i = 0; i < NUM_THREADS; i++) { - Thread thr = new Thread(() -> { - try { - for (int j = 0; j < 1000; j++) { - Scene scene = new Scene(new Group()); - scene.setUserAgentStylesheet("com/sun/javafx/css/ua0.css"); - scene.getRoot().applyCss(); - } - } catch (RuntimeException ex) { - err.set(true); - throw ex; - } - }); - thr.setName("MyThread-" + i); - thr.setDaemon(true); - bgThreads[i] = thr; - } - - for (Thread thr : bgThreads) { - thr.start(); - } - - try { - for (Thread thr : bgThreads) { - thr.join(); - } - } catch (InterruptedException ex) { - fail("Unexpected exception waiting for threads to finish"); - } - - assertFalse("Exception during CSS processing on BG thread", err.get()); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/StyleManagerTest.java 2015-09-11 21:23:49.509287382 -0400 @@ -0,0 +1,1102 @@ +/* + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import com.sun.javafx.css.CascadingStyle; +import com.sun.javafx.css.StyleManager; +import com.sun.javafx.css.StyleManagerShim; +import com.sun.javafx.css.StyleMap; +import javafx.css.CssParser; +import javafx.css.StyleOrigin; +import javafx.css.StyleableProperty; +import javafx.css.Stylesheet; +import javafx.scene.Group; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.SubScene; +import javafx.scene.layout.Pane; +import javafx.scene.paint.Color; +import javafx.scene.paint.Paint; +import javafx.scene.shape.Rectangle; +import org.junit.Before; +import org.junit.Test; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.Assert.*; + +/** + * + * @author dgrieve + */ +public class StyleManagerTest { + + public StyleManagerTest() { + } + + @Before + public void setUp() { + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.userAgentStylesheetContainers_clear(); + sm.platformUserAgentStylesheetContainers_clear(); + sm.stylesheetContainerMap_clear(); + sm.cacheContainerMap_clear(); + sm.set_hasDefaultUserAgentStylesheet(false); + } + + @Test + public void testMethod_getInstance() { + Scene scene = new Scene(new Group()); + StyleManagerShim sm = StyleManagerShim.getInstance(); + assertNotNull(sm); + } + + @Test + public void testAddUserAgentStyleshseet_String() { + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + } + + @Test + public void testAddUserAgentStyleshseet_String_Multiple() { + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + int index = sm.platformUserAgentStylesheetContainers_indexOf( "/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(1, index); + } + + @Test + public void testAddUserAgentStyleshseet_String_Duplicate() { + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + assertTrue(sm.platformUserAgentStylesheetContainers_size() == 2); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(1, index); + + } + + @Test + public void testSetDefaultUserAgentStyleshseet_String() { + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + int index = sm.platformUserAgentStylesheetContainers_indexOf( "/test/com/sun/javafx/css/ua0.css"); + assertEquals(0, index); + } + + @Test + public void testSetUserAgentStyleshseet_String_Multiple() { + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + assertTrue(sm.platformUserAgentStylesheetContainers_size() == 2); + + int index = sm.platformUserAgentStylesheetContainers_indexOf( "/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf( "/test/com/sun/javafx/css/ua1.css"); + assertEquals(1, index); + } + + @Test + public void testSetUserAgentStyleshseet_String_Multiple2() { + StyleManagerShim sm = StyleManagerShim.getInstance(); + // same as before but set default after adding another. + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + assertEquals(2, sm.platformUserAgentStylesheetContainers_size()); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(1, index); + } + + @Test + public void testSetUserAgentStyleshseet_String_Duplicate() { + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + assertEquals(2, sm.platformUserAgentStylesheetContainers_size()); + + int index = sm.platformUserAgentStylesheetContainers_indexOf( "/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf( "/test/com/sun/javafx/css/ua1.css"); + assertEquals(1, index); + } + + @Test + public void testAddUserAgentStyleshseet_Stylesheet() { + + try { + StyleManagerShim sm = StyleManagerShim.getInstance(); + URL ua0_url = StyleManagerTest.class.getResource("ua0.css"); + Stylesheet stylesheet = new CssParser().parse(ua0_url); + sm.addUserAgentStylesheet(null,stylesheet); + + assertEquals(1, sm.platformUserAgentStylesheetContainers_size()); + + int index = sm.platformUserAgentStylesheetContainers_indexOf(ua0_url.toExternalForm()); + assertEquals(0, index); + + } catch (Exception ioe) { + fail(ioe.getMessage()); + } + + } + + @Test + public void testSetDefaultUserAgentStyleshseet_Stylesheet() { + + try { + StyleManagerShim sm = StyleManagerShim.getInstance(); + + URL ua1_url = StyleManagerTest.class.getResource("ua1.css"); + Stylesheet stylesheet = new CssParser().parse(ua1_url); + sm.addUserAgentStylesheet(null,stylesheet); + + URL ua0_url = StyleManagerTest.class.getResource("ua0.css"); + stylesheet = new CssParser().parse(ua0_url); + sm.setDefaultUserAgentStylesheet(stylesheet); + + assertEquals(2, sm.platformUserAgentStylesheetContainers_size()); + + int index = sm.platformUserAgentStylesheetContainers_indexOf(ua0_url.toExternalForm()); + assertEquals(0, index); + + index = sm.platformUserAgentStylesheetContainers_indexOf(ua1_url.toExternalForm()); + assertEquals(1, index); + + } catch (Exception ioe) { + fail(ioe.getMessage()); + } + + } + + @Test + public void testSceneUAStylesheetAdded() { + Scene scene = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + scene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(-1, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + // the Scene user-agent stylesheet is not a platform user-agent stylesheet + index = sm.platformUserAgentStylesheetContainers_indexOf( "/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + } + + @Test + public void testSubSceneUAStylesheetAdded() { + Scene scene = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + scene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(-1, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + // the Scene user-agent stylesheet is not a platform user-agent stylesheet + index = sm.platformUserAgentStylesheetContainers_indexOf( "/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + } + + @Test + public void testForgetParent() { + + Scene scene = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + sm.forget(scene.getRoot()); + + // forgetting the scene should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + } + + @Test + public void testForgetParent_withSceneUAStylesheet() { + + Scene scene = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + scene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(-1, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + sm.forget(scene.getRoot()); + + // forgetting the parent should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + // only forgetting the scene should affect the platform user-agent stylesheets + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0, index); + + } + + @Test + public void testForgetParent_withTwoScenes() { + Scene scene0 = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + scene0.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + Scene scene1 = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + scene1.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene0.getRoot().applyCss(); + scene1.getRoot().applyCss(); + + // even though there are two scenes using this stylesheet, there should only be one container. + assertEquals(1, sm.userAgentStylesheetContainers_size()); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(-1, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0, index); + + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + sm.forget(scene0.getRoot()); + + // forgetting the scene should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + // we should still have ua1.css since scene1 is still using it + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + sm.forget(scene1.getRoot()); + + // only forgetting the scene should affect the platform user-agent stylesheets + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0, index); + } + + @Test + public void testForgetParent_withParentStylesheet() { + + Scene scene = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + scene.getRoot().getStylesheets().add("/test/com/sun/javafx/css/ua1.css"); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0, index); + + assertTrue(sm.userAgentStylesheetContainers_isEmpty()); + assertTrue(sm.stylesheetContainerMap_containsKey("/test/com/sun/javafx/css/ua1.css")); + + sm.forget(scene.getRoot()); + + // forgetting the scene should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0, index); + + assertFalse(sm.stylesheetContainerMap_containsKey("/test/com/sun/javafx/css/ua1.css")); + + } + + @Test + public void testForgetParent_withMultipleParentStylesheets() { + + final Parent parent0 = new Pane(new Rectangle(){{ getStyleClass().add("rect"); }}); + parent0.getStylesheets().add("/test/com/sun/javafx/css/ua1.css"); + + final Parent parent1 = new Pane(new Rectangle(){{ getStyleClass().add("rect"); }}); + parent1.getStylesheets().add("/test/com/sun/javafx/css/ua1.css"); + + Scene scene = new Scene(new Group(parent0, parent1)); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + assertTrue(sm.userAgentStylesheetContainers_isEmpty()); + + StyleManagerShim.StylesheetContainer container = sm.stylesheetContainerMap_get("/test/com/sun/javafx/css/ua1.css"); + assertNotNull(container); + assertTrue(container.parentUsers_contains(parent0)); + assertTrue(container.parentUsers_contains(parent1)); + + sm.forget(parent0); + + assertTrue(sm.stylesheetContainerMap_containsKey("/test/com/sun/javafx/css/ua1.css")); + assertFalse(container.parentUsers_contains(parent0)); + assertTrue(container.parentUsers_contains(parent1)); + + sm.forget(parent1); + + assertFalse(sm.stylesheetContainerMap_containsKey("/test/com/sun/javafx/css/ua1.css")); + assertFalse(container.parentUsers_contains(parent0)); + assertFalse(container.parentUsers_contains(parent1)); + } + + @Test + public void testForgetScene() { + + Scene scene = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + sm.forget(scene); + + // forgetting the scene should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + } + + @Test + public void testForgetScene_withUAStylesheet() { + + Scene scene = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + scene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(-1, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + sm.forget(scene); + + // forgetting the scene should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + } + + @Test + public void testForgetScene_withTwoScenes() { + Scene scene0 = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + scene0.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + Scene scene1 = new Scene(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + scene1.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene0.getRoot().applyCss(); + scene1.getRoot().applyCss(); + + // even though there are two scenes using this stylesheet, there should only be one container. + assertEquals(1, sm.userAgentStylesheetContainers_size()); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(-1, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + sm.forget(scene0); + + // forgetting the scene should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + // we should still have ua1.css since scene1 is still using it + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + sm.forget(scene1); + + // having forgotten scene1, userAgentStylesheetContainers should be empty. + assertTrue(sm.userAgentStylesheetContainers_isEmpty()); + } + + @Test + public void testForgetSubScene() { + + Pane subSceneRoot = new Pane(new Rectangle(){{ getStyleClass().add("rect"); }}); + SubScene subScene = new SubScene(subSceneRoot, 100, 100); + Scene scene = new Scene(new Group(subScene)); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + sm.forget(subScene); + + // forgetting the scene should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + } + + @Test + public void testForgetSubScene_withUAStylesheet() { + + Pane subSceneRoot = new Pane(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + SubScene subScene = new SubScene(subSceneRoot, 100, 100); + subScene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + Scene scene = new Scene(new Group(subScene)); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(-1, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + sm.forget(subScene); + + // forgetting the scene should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + } + + @Test + public void testForgetSubScene_with_UAStylesheet_and_ParentStylesheet() { + + // make sure forget(SubScene) get's children with stylesheets + Group group = new Group(new Rectangle(){{ getStyleClass().add("rect"); }}); + group.getStylesheets().add("/test/com/sun/javafx/css/ua2.css"); + Pane subSceneRoot = new Pane(group); + SubScene subScene = new SubScene(subSceneRoot, 100, 100); + subScene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + Scene scene = new Scene(new Group(subScene)); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(-1, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + sm.forget(subScene); + + // forgetting the scene should not affect the platform user-agent stylesheets + index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0,index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1, index); + + } + + @Test + public void testChangeSubSceneStylesheet() { + + Pane subSceneRoot = new Pane(new Group(new Rectangle(){{ getStyleClass().add("rect"); }})); + SubScene subScene = new SubScene(subSceneRoot, 100, 100); + Scene scene = new Scene(new Group(subScene)); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + scene.getRoot().applyCss(); + + scene.getRoot().applyCss(); + + int index = sm.platformUserAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(0, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua0.css"); + assertEquals(-1, index); + + subScene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(0,index); + + sm.forget(subScene); + + subScene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua2.css"); + scene.getRoot().applyCss(); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua2.css"); + assertEquals(0, index); + + index = sm.userAgentStylesheetContainers_indexOf("/test/com/sun/javafx/css/ua1.css"); + assertEquals(-1,index); + + } + + @Test + public void testFindMatchingStyles_defaultStyleSheet() { + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; + Scene scene = new Scene(new Group(rect)); + + StyleMap matchingStyles = sm.findMatchingStyles(rect, null, null); + Map> styleMap = matchingStyles.getCascadingStyles(); + + assertTrue(styleMap.containsKey("-fx-fill")); + + List styles = styleMap.get("-fx-fill"); + assertEquals(1, styles.size()); + + Object obj = styles.get(0).getParsedValue().convert(null); + assertEquals(Color.RED, obj); + } + + @Test + public void testFindMatchingStyles_defaultStyleSheet_sceneUserAgentStylesheet() { + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; + Scene scene = new Scene(new Group(rect)); + scene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + StyleMap matchingStyles = sm.findMatchingStyles(rect, null, null); + Map> styleMap = matchingStyles.getCascadingStyles(); + + scene.getRoot().applyCss(); + + // scene stylesheet should totally replace default + assertFalse(styleMap.containsKey("-fx-fill")); + assertTrue(styleMap.containsKey("-fx-stroke")); + + List styles = styleMap.get("-fx-stroke"); + assertEquals(1, styles.size()); + + Object obj = styles.get(0).getParsedValue().convert(null); + assertEquals(Color.YELLOW, obj); + } + + @Test + public void testFindMatchingStyles_defaultStyleSheet_sceneUserAgentStylesheet_sceneAuthorStylesheet() { + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; + Scene scene = new Scene(new Group(rect)); + scene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + scene.getStylesheets().add("/test/com/sun/javafx/css/ua2.css"); + + StyleMap matchingStyles = sm.findMatchingStyles(rect, null, null); + Map> styleMap = matchingStyles.getCascadingStyles(); + + scene.getRoot().applyCss(); + + // ua2.css has fill + assertTrue(styleMap.containsKey("-fx-fill")); + assertTrue(styleMap.containsKey("-fx-stroke")); + + // ua1.css and ua2.css have stroke + List styles = styleMap.get("-fx-stroke"); + assertEquals(2, styles.size()); + + Object obj = styles.get(0).getParsedValue().convert(null); + assertEquals(Color.GREEN, obj); + + // ua0.css and ua2.css have fill, but we shouldn't get anything from ua0 + // since we have a scene user-agent stylesheet + styles = styleMap.get("-fx-fill"); + assertEquals(1, styles.size()); + + obj = styles.get(0).getParsedValue().convert(null); + assertEquals(Color.BLUE, obj); + } + + @Test + public void testFindMatchingStyles_defaultStyleSheet_subSceneUserAgentStylesheet() { + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; + Pane subSceneRoot = new Pane(rect); + SubScene subScene = new SubScene(subSceneRoot, 100, 100); + subScene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + Scene scene = new Scene(new Group(subScene)); + + StyleMap matchingStyles = sm.findMatchingStyles(rect, subScene, null); + Map> styleMap = matchingStyles.getCascadingStyles(); + + scene.getRoot().applyCss(); + + // SubScene stylesheet should totally replace default + assertFalse(styleMap.containsKey("-fx-fill")); + assertTrue(styleMap.containsKey("-fx-stroke")); + + List styles = styleMap.get("-fx-stroke"); + assertEquals(1, styles.size()); + + Object obj = styles.get(0).getParsedValue().convert(null); + assertEquals(Color.YELLOW, obj); + } + + @Test + public void testFindMatchingStyles_defaultStyleSheet_subSceneUserAgentStylesheet_parentStylesheet() { + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; + Group group = new Group(rect); + group.getStylesheets().add("/test/com/sun/javafx/css/ua2.css"); + Pane subSceneRoot = new Pane(group); + SubScene subScene = new SubScene(subSceneRoot, 100, 100); + subScene.setUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + Scene scene = new Scene(new Group(subScene)); + + StyleMap matchingStyles = sm.findMatchingStyles(rect, subScene, null); + Map> styleMap = matchingStyles.getCascadingStyles(); + + scene.getRoot().applyCss(); + + // ua2.css has fill + assertTrue(styleMap.containsKey("-fx-fill")); + assertTrue(styleMap.containsKey("-fx-stroke")); + + // ua1.css and ua2.css have stroke + List styles = styleMap.get("-fx-stroke"); + assertEquals(2, styles.size()); + + Object obj = styles.get(0).getParsedValue().convert(null); + assertEquals(Color.GREEN, obj); + + // ua0.css and ua2.css have fill, but we shouldn't get anything from ua0 + // since we have a scene user-agent stylesheet + styles = styleMap.get("-fx-fill"); + assertEquals(1, styles.size()); + + obj = styles.get(0).getParsedValue().convert(null); + assertEquals(Color.BLUE, obj); + } + + @Test + public void testSwitchDefaultUserAgentStylesheets() { + + Rectangle rect = new Rectangle(){{ getStyleClass().add("rect"); }}; + Group group = new Group(rect); + Pane subSceneRoot = new Pane(group); + SubScene subScene = new SubScene(subSceneRoot, 100, 100); + Scene scene = new Scene(new Group(subScene)); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua0.css"); + + scene.getRoot().applyCss(); + + StyleMap matchingStyles = sm.findMatchingStyles(rect, subScene, null); + Map> styleMap = matchingStyles.getCascadingStyles(); + + // ua0.css has fill + assertTrue(styleMap.containsKey("-fx-fill")); + assertFalse(styleMap.containsKey("-fx-stroke")); + + List styles = styleMap.get("-fx-fill"); + assertEquals(1, styles.size()); + + Object obj = styles.get(0).getParsedValue().convert(null); + assertEquals(Color.RED, obj); + + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + + matchingStyles = sm.findMatchingStyles(rect, subScene, null); + styleMap = matchingStyles.getCascadingStyles(); + + // ua1.css has stroke + assertTrue(styleMap.containsKey("-fx-stroke")); + assertFalse(styleMap.containsKey("-fx-fill")); + + styles = styleMap.get("-fx-stroke"); + assertEquals(1, styles.size()); + + obj = styles.get(0).getParsedValue().convert(null); + assertEquals(Color.YELLOW, obj); + } + + @Test + public void testGetCacheContainer() { + + Rectangle rectangle = new Rectangle(); + SubScene subScene = new SubScene(null, 0, 0); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + + // no scene, should return null + assertTrue(sm.isCacheContainerNull(rectangle, subScene)); + + // has scene, should return non-null + subScene.setRoot(new Group()); + Scene scene = new Scene(new Group(rectangle,subScene)); + + assertFalse(sm.isCacheContainerNull(rectangle, subScene)); + + } + + @Test + public void testGetCacheContainer_styleable() { + Rectangle rectangle = new Rectangle(); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + + // no scene, should return null + assertTrue(sm.isCacheContainerNull(rectangle, null)); + + // has scene, should return non-null + Scene scene = new Scene(new Group(rectangle)); + + assertFalse(sm.isCacheContainerNull(rectangle, null)); + + } + + @Test + public void testGetCacheContainer_subScene() { + + SubScene subScene = new SubScene(null, 0, 0); + + StyleManagerShim sm = StyleManagerShim.getInstance(); + + // no scene, should return null + assertTrue(sm.isCacheContainerNull(null, subScene)); + + // has scene, should return non-null + subScene.setRoot(new Group()); + Scene scene = new Scene(new Group(subScene)); + + assertFalse(sm.isCacheContainerNull(null, subScene)); + + } + + @Test + public void testRT_37025() { + + // + // The issue in RT-37025 was that the stylesheet container wasn't getting removed even + // though the parent had been forgotten. The StyleManager#forget(Parent) method didn't + // look to see if _any_ stylesheet container had the parent as a reference. + // + final StyleManagerShim sm = StyleManagerShim.getInstance(); + + // This test needs a bit more complexity to the scene-graph + Group group = null; + Pane pane = new Pane( + new Group( + new Pane( + // I want these to be a Parent, not a Node + new Group(new Pane(){{ getStyleClass().add("rect"); }}), + group = new Group(new Pane(){{ getStyleClass().add("rect"); }}) + ) + ) + ); + pane.getStylesheets().add("/test/com/sun/javafx/css/ua0.css"); + group.getStylesheets().add("/test/com/sun/javafx/css/ua1.css"); + + Group root = new Group(pane); + Scene scene = new Scene(root); + + root.applyCss(); + + assertTrue(sm.stylesheetContainerMap_containsKey("/test/com/sun/javafx/css/ua0.css")); + StyleManagerShim.StylesheetContainer container = sm.stylesheetContainerMap_get("/test/com/sun/javafx/css/ua0.css"); + assertEquals(7, container.parentUsers_list_size()); + + assertTrue(sm.stylesheetContainerMap_containsKey("/test/com/sun/javafx/css/ua1.css")); + container = sm.stylesheetContainerMap_get("/test/com/sun/javafx/css/ua1.css"); + assertEquals(2, container.parentUsers_list_size()); + + ((Pane)group.getParent()).getChildren().remove(group); + + assertFalse(sm.stylesheetContainerMap_containsKey("/test/com/sun/javafx/css/ua1.css")); + assertTrue(sm.stylesheetContainerMap_containsKey("/test/com/sun/javafx/css/ua0.css")); + container = sm.stylesheetContainerMap_get("/test/com/sun/javafx/css/ua0.css"); + assertEquals(5, container.parentUsers_list_size()); + + scene.setRoot(new Group()); + assertFalse(sm.stylesheetContainerMap_containsKey("/test/com/sun/javafx/css/ua0.css")); + assertFalse(StyleManager.cacheContainerMap.containsKey(root)); + assertTrue(StyleManager.cacheContainerMap.containsKey(scene.getRoot())); + + } + + @Test + public void test_setUserAgentStylesheets() { + + List uaStylesheets = new ArrayList<>(); + Collections.addAll(uaStylesheets, "/test/com/sun/javafx/css/ua0.css", "/test/com/sun/javafx/css/ua1.css"); + + final StyleManagerShim sm = StyleManagerShim.getInstance(); + sm.setUserAgentStylesheets(uaStylesheets); + + assertEquals(2, sm.platformUserAgentStylesheetContainers_size()); + assertEquals("/test/com/sun/javafx/css/ua0.css", sm.platformUserAgentStylesheetContainers_getfname(0)); + assertEquals("/test/com/sun/javafx/css/ua1.css", sm.platformUserAgentStylesheetContainers_getfname(1)); + } + + @Test + public void test_setUserAgentStylesheets_overwrites_existing() { + + List uaStylesheets = new ArrayList<>(); + Collections.addAll(uaStylesheets, "/test/com/sun/javafx/css/ua0.css"); + + final StyleManagerShim sm = StyleManagerShim.getInstance(); + + // 1 - overwrite default user agent stylesheet + sm.platformUserAgentStylesheetContainers_clear();; + sm.setDefaultUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + assertEquals(1, sm.platformUserAgentStylesheetContainers_size()); + assertEquals("/test/com/sun/javafx/css/ua1.css", sm.platformUserAgentStylesheetContainers_getfname(0)); + + sm.setUserAgentStylesheets(uaStylesheets); + assertEquals(1, sm.platformUserAgentStylesheetContainers_size()); + assertEquals("/test/com/sun/javafx/css/ua0.css", sm.platformUserAgentStylesheetContainers_getfname(0)); + + // 2 - overwrite other user-agent stylesheets + sm.platformUserAgentStylesheetContainers_clear();; + sm.addUserAgentStylesheet("/test/com/sun/javafx/css/ua1.css"); + assertEquals(1, sm.platformUserAgentStylesheetContainers_size()); + + sm.setUserAgentStylesheets(uaStylesheets); + assertEquals(1, sm.platformUserAgentStylesheetContainers_size()); + assertEquals("/test/com/sun/javafx/css/ua0.css", sm.platformUserAgentStylesheetContainers_getfname(0)); + } + + @Test + public void testRT_38687_with_Scene() { + + Rectangle rect = new Rectangle(50,50) {{ getStyleClass().add("rect"); }}; + Scene scene = new Scene(new Group(rect)); + scene.setUserAgentStylesheet("test/com/sun/javafx/css/ua0.css"); + scene.getRoot().applyCss(); + + StyleableProperty fillProperty = (StyleableProperty)rect.fillProperty(); + assertEquals(StyleOrigin.USER_AGENT, fillProperty.getStyleOrigin()); + + scene.setUserAgentStylesheet("test/com/sun/javafx/css/ua1.css"); + scene.getRoot().applyCss(); + + assertEquals(null, fillProperty.getStyleOrigin()); + + rect.setFill(Color.GREEN); + + scene.setUserAgentStylesheet("test/com/sun/javafx/css/rt38637.css"); + scene.getRoot().applyCss(); + assertEquals(StyleOrigin.USER, fillProperty.getStyleOrigin()); + + } + + @Test + public void testRT_38687_with_SubScene() { + + Rectangle rect = new Rectangle(50,50) {{ getStyleClass().add("rect"); }}; + Group group = new Group(rect); + SubScene subScene = new SubScene(group, 100, 100); + subScene.setUserAgentStylesheet("test/com/sun/javafx/css/ua0.css"); + + Scene scene = new Scene(new Group(subScene)); + scene.getRoot().applyCss(); + + StyleableProperty fillProperty = (StyleableProperty)rect.fillProperty(); + assertEquals(StyleOrigin.USER_AGENT, fillProperty.getStyleOrigin()); + + subScene.setUserAgentStylesheet("test/com/sun/javafx/css/ua1.css"); + scene.getRoot().applyCss(); + + assertEquals(null, fillProperty.getStyleOrigin()); + + rect.setFill(Color.GREEN); + + subScene.setUserAgentStylesheet("test/com/sun/javafx/css/rt38637.css"); + scene.getRoot().applyCss(); + assertEquals(StyleOrigin.USER, fillProperty.getStyleOrigin()); + + } + + @Test + public void testConcurrentAccess() { + final int NUM_THREADS = 10; + final Thread[] bgThreads = new Thread[NUM_THREADS]; + final AtomicBoolean err = new AtomicBoolean(false); + for (int i = 0; i < NUM_THREADS; i++) { + Thread thr = new Thread(() -> { + try { + for (int j = 0; j < 1000; j++) { + Scene scene = new Scene(new Group()); + scene.setUserAgentStylesheet("test/com/sun/javafx/css/ua0.css"); + scene.getRoot().applyCss(); + } + } catch (RuntimeException ex) { + err.set(true); + throw ex; + } + }); + thr.setName("MyThread-" + i); + thr.setDaemon(true); + bgThreads[i] = thr; + } + + for (Thread thr : bgThreads) { + thr.start(); + } + + try { + for (Thread thr : bgThreads) { + thr.join(); + } + } catch (InterruptedException ex) { + fail("Unexpected exception waiting for threads to finish"); + } + + assertFalse("Exception during CSS processing on BG thread", err.get()); + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/TestNode.java 2015-09-11 21:23:50.405287372 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import javafx.css.converter.SizeConverter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import javafx.beans.property.DoubleProperty; -import javafx.css.CssMetaData; -import javafx.css.Styleable; -import javafx.css.StyleableDoubleProperty; -import javafx.css.StyleableProperty; - -/** Test Node with styleable property but no getClassCssMetaData method */ -public class TestNode extends TestNodeBase { - - private DoubleProperty xyzzy; - private DoubleProperty xyzzyProperty() { - if (xyzzy == null) { - xyzzy = new StyleableDoubleProperty(.5) { - - @Override - public Object getBean() { - return TestNode.this; - } - - @Override - public String getName() { - return "xyzzy"; - } - - @Override - public CssMetaData getCssMetaData() { - return StyleableProperties.XYZZY; - } - - }; - } - return xyzzy; - } - - public void setXyzzy(double number) { - xyzzyProperty().set(number); - } - - public double getXyzzy() { - return (xyzzy == null ? .5 : xyzzy.get()); - } - - public TestNode() { - super(); - } - - public static class StyleableProperties { - - public static final CssMetaData XYZZY = - new CssMetaData("-fx-xyzzy", - SizeConverter.getInstance(), - .5) { - - @Override - public boolean isSettable(TestNode node) { - return node.xyzzy == null || !node.xyzzy.isBound(); - } - - @Override - public StyleableProperty getStyleableProperty(TestNode node) { - return (StyleableProperty)node.xyzzyProperty(); - } - - }; - - private static final List> STYLEABLES; - static { - final List> styleables = - new ArrayList>(TestNodeBase.getClassCssMetaData()); - styleables.add(XYZZY); - STYLEABLES = Collections.unmodifiableList(styleables); - } - } - - /** - * @return The CssMetaData associated with this class, which may include the - * CssMetaData of its super classes. - */ - public static List> getClassCssMetaData() { - return StyleableProperties.STYLEABLES; - } - - /** - * {@inheritDoc} - * - */ - - - @Override - public List> getCssMetaData() { - return getClassCssMetaData(); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/TestNode.java 2015-09-11 21:23:50.265287374 -0400 @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import javafx.css.converter.SizeConverter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javafx.beans.property.DoubleProperty; +import javafx.css.CssMetaData; +import javafx.css.Styleable; +import javafx.css.StyleableDoubleProperty; +import javafx.css.StyleableProperty; + +/** Test Node with styleable property but no getClassCssMetaData method */ +public class TestNode extends TestNodeBase { + + private DoubleProperty xyzzy; + private DoubleProperty xyzzyProperty() { + if (xyzzy == null) { + xyzzy = new StyleableDoubleProperty(.5) { + + @Override + public Object getBean() { + return TestNode.this; + } + + @Override + public String getName() { + return "xyzzy"; + } + + @Override + public CssMetaData getCssMetaData() { + return StyleableProperties.XYZZY; + } + + }; + } + return xyzzy; + } + + public void setXyzzy(double number) { + xyzzyProperty().set(number); + } + + public double getXyzzy() { + return (xyzzy == null ? .5 : xyzzy.get()); + } + + public TestNode() { + super(); + } + + public static class StyleableProperties { + + public static final CssMetaData XYZZY = + new CssMetaData("-fx-xyzzy", + SizeConverter.getInstance(), + .5) { + + @Override + public boolean isSettable(TestNode node) { + return node.xyzzy == null || !node.xyzzy.isBound(); + } + + @Override + public StyleableProperty getStyleableProperty(TestNode node) { + return (StyleableProperty)node.xyzzyProperty(); + } + + }; + + private static final List> STYLEABLES; + static { + final List> styleables = + new ArrayList>(TestNodeBase.getClassCssMetaData()); + styleables.add(XYZZY); + STYLEABLES = Collections.unmodifiableList(styleables); + } + } + + /** + * @return The CssMetaData associated with this class, which may include the + * CssMetaData of its super classes. + */ + public static List> getClassCssMetaData() { + return StyleableProperties.STYLEABLES; + } + + /** + * {@inheritDoc} + * + */ + + + @Override + public List> getCssMetaData() { + return getClassCssMetaData(); + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/TestNodeBase.java 2015-09-11 21:23:51.029287365 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,254 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import javafx.css.converter.BooleanConverter; -import javafx.css.converter.SizeConverter; -import javafx.css.converter.StringConverter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.sun.javafx.sg.prism.NGNode; -import javafx.beans.property.BooleanProperty; -import javafx.beans.property.DoubleProperty; -import javafx.beans.property.StringProperty; -import javafx.css.CssMetaData; -import javafx.css.StyleableBooleanProperty; -import javafx.css.StyleableDoubleProperty; -import javafx.css.StyleableStringProperty; -import javafx.scene.Node; - -import com.sun.javafx.geom.BaseBounds; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.javafx.jmx.MXNodeAlgorithm; -import com.sun.javafx.jmx.MXNodeAlgorithmContext; -import javafx.css.Styleable; -import javafx.css.StyleableProperty; - -/** Test Node with styleable properties and an getClassCssMetaData method */ -public class TestNodeBase extends Node { - - protected TestNodeBase() { - } - - @Override - protected boolean impl_computeContains(double d, double d1) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public BaseBounds impl_computeGeomBounds(BaseBounds bb, BaseTransform bt) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - protected NGNode impl_createPeer() { - throw new UnsupportedOperationException("Not supported yet."); - } - - private BooleanProperty test; - private BooleanProperty testProperty() { - if (test == null) { - test = new StyleableBooleanProperty(true) { - - @Override - public Object getBean() { - return TestNodeBase.this; - } - - @Override - public String getName() { - return "test"; - } - - @Override - public CssMetaData getCssMetaData() { - return TestNodeBase.StyleableProperties.TEST; - } - - }; - } - return test; - } - - public void setTest(boolean value) { - testProperty().set(value); - } - - public boolean getTest() { - return (test == null ? true : test.get()); - } - - private StringProperty string; - private StringProperty stringProperty() { - if (string == null) { - string = new StyleableStringProperty("init string") { - - @Override - public Object getBean() { - return TestNodeBase.this; - } - - @Override - public String getName() { - return "string"; - } - - @Override - public CssMetaData getCssMetaData() { - return TestNodeBase.StyleableProperties.STRING; - } - - }; - } - return string; - } - - public void setString(String value) { - stringProperty().set(value); - } - - public String getString() { - return (string == null ? "init string" : string.get()); - } - - private DoubleProperty doubleProperty; - private DoubleProperty doublePropertyProperty() { - if (doubleProperty == null) { - doubleProperty = new StyleableDoubleProperty(0) { - - @Override - public Object getBean() { - return TestNodeBase.this; - } - - @Override - public String getName() { - return "doubleProperty"; - } - - @Override - public CssMetaData getCssMetaData() { - return TestNodeBase.StyleableProperties.DOUBLE_PROPERTY; - } - - }; - } - return doubleProperty; - } - - public void setDoubleProperty(double number) { - doublePropertyProperty().set(number); - } - - public double getDoubleProperty() { - return (doubleProperty == null ? 0 : doubleProperty.get()); - } - - - public static class StyleableProperties { - public final static CssMetaData TEST = - new CssMetaData("-fx-test", - BooleanConverter.getInstance(), Boolean.TRUE) { - - @Override - public boolean isSettable(TestNodeBase n) { - return n.test == null || !n.test.isBound(); - } - - @Override - public StyleableProperty getStyleableProperty(TestNodeBase n) { - return (StyleableProperty)n.testProperty(); - } - }; - - public final static CssMetaData STRING = - new CssMetaData("-fx-string", - StringConverter.getInstance(), "init string") { - - @Override - public boolean isSettable(TestNodeBase n) { - return n.string == null || !n.string.isBound(); - } - - @Override - public StyleableProperty getStyleableProperty(TestNodeBase n) { - return (StyleableProperty)n.stringProperty(); - } - }; - - public final static CssMetaData DOUBLE_PROPERTY = - new CssMetaData("-fx-double-property", - SizeConverter.getInstance(), 0) { - - @Override - public boolean isSettable(TestNodeBase n) { - return n.doubleProperty == null || !n.doubleProperty.isBound(); - } - - @Override - public StyleableProperty getStyleableProperty(TestNodeBase n) { - return (StyleableProperty)n.doublePropertyProperty(); - } - }; - - static final List> STYLEABLES; - static { - List> list = - new ArrayList>(Node.getClassCssMetaData()); - Collections.addAll(list, - TEST, - STRING, - DOUBLE_PROPERTY - ); - STYLEABLES = Collections.unmodifiableList(list); - } - } - - /** - * {@inheritDoc} - */ - public static List> getClassCssMetaData() { - return StyleableProperties.STYLEABLES; - } - - /** - * {@inheritDoc} - * - */ - - - @Override - public List> getCssMetaData() { - return getClassCssMetaData(); - } - - @Override - public Object impl_processMXNode(MXNodeAlgorithm alg, MXNodeAlgorithmContext ctx) { - return alg.processLeafNode(this, ctx); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/css/TestNodeBase.java 2015-09-11 21:23:50.893287366 -0400 @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.css; + +import javafx.css.converter.BooleanConverter; +import javafx.css.converter.SizeConverter; +import javafx.css.converter.StringConverter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.sun.javafx.sg.prism.NGNode; +import javafx.beans.property.BooleanProperty; +import javafx.beans.property.DoubleProperty; +import javafx.beans.property.StringProperty; +import javafx.css.CssMetaData; +import javafx.css.StyleableBooleanProperty; +import javafx.css.StyleableDoubleProperty; +import javafx.css.StyleableStringProperty; +import javafx.scene.Node; + +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.jmx.MXNodeAlgorithm; +import com.sun.javafx.jmx.MXNodeAlgorithmContext; +import javafx.css.Styleable; +import javafx.css.StyleableProperty; + +/** Test Node with styleable properties and an getClassCssMetaData method */ +public class TestNodeBase extends Node { + + protected TestNodeBase() { + } + + @Override + protected boolean impl_computeContains(double d, double d1) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public BaseBounds impl_computeGeomBounds(BaseBounds bb, BaseTransform bt) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + protected NGNode impl_createPeer() { + throw new UnsupportedOperationException("Not supported yet."); + } + + private BooleanProperty test; + private BooleanProperty testProperty() { + if (test == null) { + test = new StyleableBooleanProperty(true) { + + @Override + public Object getBean() { + return TestNodeBase.this; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public CssMetaData getCssMetaData() { + return TestNodeBase.StyleableProperties.TEST; + } + + }; + } + return test; + } + + public void setTest(boolean value) { + testProperty().set(value); + } + + public boolean getTest() { + return (test == null ? true : test.get()); + } + + private StringProperty string; + private StringProperty stringProperty() { + if (string == null) { + string = new StyleableStringProperty("init string") { + + @Override + public Object getBean() { + return TestNodeBase.this; + } + + @Override + public String getName() { + return "string"; + } + + @Override + public CssMetaData getCssMetaData() { + return TestNodeBase.StyleableProperties.STRING; + } + + }; + } + return string; + } + + public void setString(String value) { + stringProperty().set(value); + } + + public String getString() { + return (string == null ? "init string" : string.get()); + } + + private DoubleProperty doubleProperty; + private DoubleProperty doublePropertyProperty() { + if (doubleProperty == null) { + doubleProperty = new StyleableDoubleProperty(0) { + + @Override + public Object getBean() { + return TestNodeBase.this; + } + + @Override + public String getName() { + return "doubleProperty"; + } + + @Override + public CssMetaData getCssMetaData() { + return TestNodeBase.StyleableProperties.DOUBLE_PROPERTY; + } + + }; + } + return doubleProperty; + } + + public void setDoubleProperty(double number) { + doublePropertyProperty().set(number); + } + + public double getDoubleProperty() { + return (doubleProperty == null ? 0 : doubleProperty.get()); + } + + + public static class StyleableProperties { + public final static CssMetaData TEST = + new CssMetaData("-fx-test", + BooleanConverter.getInstance(), Boolean.TRUE) { + + @Override + public boolean isSettable(TestNodeBase n) { + return n.test == null || !n.test.isBound(); + } + + @Override + public StyleableProperty getStyleableProperty(TestNodeBase n) { + return (StyleableProperty)n.testProperty(); + } + }; + + public final static CssMetaData STRING = + new CssMetaData("-fx-string", + StringConverter.getInstance(), "init string") { + + @Override + public boolean isSettable(TestNodeBase n) { + return n.string == null || !n.string.isBound(); + } + + @Override + public StyleableProperty getStyleableProperty(TestNodeBase n) { + return (StyleableProperty)n.stringProperty(); + } + }; + + public final static CssMetaData DOUBLE_PROPERTY = + new CssMetaData("-fx-double-property", + SizeConverter.getInstance(), 0) { + + @Override + public boolean isSettable(TestNodeBase n) { + return n.doubleProperty == null || !n.doubleProperty.isBound(); + } + + @Override + public StyleableProperty getStyleableProperty(TestNodeBase n) { + return (StyleableProperty)n.doublePropertyProperty(); + } + }; + + static final List> STYLEABLES; + static { + List> list = + new ArrayList>(Node.getClassCssMetaData()); + Collections.addAll(list, + TEST, + STRING, + DOUBLE_PROPERTY + ); + STYLEABLES = Collections.unmodifiableList(list); + } + } + + /** + * {@inheritDoc} + */ + public static List> getClassCssMetaData() { + return StyleableProperties.STYLEABLES; + } + + /** + * {@inheritDoc} + * + */ + + + @Override + public List> getCssMetaData() { + return getClassCssMetaData(); + } + + @Override + public Object impl_processMXNode(MXNodeAlgorithm alg, MXNodeAlgorithmContext ctx) { + return alg.processLeafNode(this, ctx); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/css/URLTypeTest.java 2015-09-11 21:23:51.745287357 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.css; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import javafx.css.ParsedValue; -import javafx.scene.text.Font; - -import org.junit.Test; - -import javafx.css.converter.StringConverter; -import javafx.css.converter.URLConverter; - - -public class URLTypeTest { - - public URLTypeTest() { - } - - static final String absClassName = "/com/sun/javafx/css/URLTypeTest.class"; - static final String classURL = URLTypeTest.class.getResource("URLTypeTest.class").toExternalForm(); - - final String baseURL = "http://a/b/c/d;p?q"; - - // from rfc3986, section 5 - final String[][] testPairs = new String[][] { - {"file:h" , "file:h"}, - {"g" , "http://a/b/c/g"}, - {"./g" , "http://a/b/c/g"}, - {"g/" , "http://a/b/c/g/"}, - // The following is relative to classloader root, and since it won't be found, will return null - {"/g" , null}, - // The following is relative to classloader root and will be resolved as such - {absClassName , classURL}, - {"//g" , "http://g"}, - // actual is http://a/b/c/?y - bug in java.net.URI? {"?y" , "http://a/b/c/d;p?y"}, - {"g?y" , "http://a/b/c/g?y"}, - {"#s" , "http://a/b/c/d;p?q#s"}, - {"g#s" , "http://a/b/c/g#s"}, - {"g?y#s" , "http://a/b/c/g?y#s"}, - {";x" , "http://a/b/c/;x"}, - {"g;x" , "http://a/b/c/g;x"}, - {"g;x?y#s" , "http://a/b/c/g;x?y#s"}, - // empty string causes URISyntaxException, so converter returns null {"" , "http://a/b/c/d;p?q"}, - {"", null}, // not part of the rfc test suite - converter returns null if resolving base against empty string - {"." , "http://a/b/c/"}, - {"./" , "http://a/b/c/"}, - {".." , "http://a/b/"}, - {"../" , "http://a/b/"}, - {"../g" , "http://a/b/g"}, - {"../.." , "http://a/"}, - {"../../" , "http://a/"}, - {"../../g" , "http://a/g"} - }; - - /** - * Test of convert method, of class URLType. - */ - @Test - public void testConvert() { - //System.out.println("convert"); - ParsedValue[] urls = new ParsedValue[testPairs.length]; - - for(int n=0; n(testPairs[n][0], StringConverter.getInstance()), - new ParsedValueImpl(baseURL, null) - }; - urls[n] = new ParsedValueImpl(values, URLConverter.getInstance()); - }; - - ParsedValue[],String[]> value = - new ParsedValueImpl[],String[]>(urls, URLConverter.SequenceConverter.getInstance()); - - Font font = null; - String[] result = value.convert(font); - assertEquals(testPairs.length, result.length); - for(int n=0; n[] urls = new ParsedValue[testPairs.length]; + + for(int n=0; n(testPairs[n][0], StringConverter.getInstance()), + new ParsedValueImpl(baseURL, null) + }; + urls[n] = new ParsedValueImpl(values, URLConverter.getInstance()); + }; + + ParsedValue[],String[]> value = + new ParsedValueImpl[],String[]>(urls, URLConverter.SequenceConverter.getInstance()); + + Font font = null; + String[] result = value.convert(font); + assertEquals(testPairs.length, result.length); + for(int n=0; n result = URLConverter.getInstance(); + assertNotNull(result); + } + + /** + * Test of convert method, of class URLConverter. + */ + @Test + public void testConvertWithNullBaseURL() { + + ParsedValue[] values = new ParsedValue[] { + new ParsedValueImpl("test/javafx/css/converter/some.txt", null), + new ParsedValueImpl(null,null) + }; + ParsedValueImpl value = + new ParsedValueImpl(values, URLConverter.getInstance()); + + Font font = null; + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + String expResult = cl.getResource("test/javafx/css/converter/some.txt").toExternalForm(); + String result = value.convert(font); + assertEquals(expResult, result); + } + + public void testConvertWithBaseURL() { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + String base = cl.getResource("com/..").toExternalForm(); + ParsedValue[] values = new ParsedValue[] { + new ParsedValueImpl("test/javafx/css/converter/some.txt", null), + new ParsedValueImpl(base,null) + }; + ParsedValueImpl value = + new ParsedValueImpl(values, URLConverter.getInstance()); + + Font font = null; + String expResult = cl.getResource("test/javafx/css/converter/some.txt").toExternalForm(); + String result = value.convert(font); + assertEquals(expResult, result); + } + + @Test + public void testConvertWithAbsoluteURLAndNullBaseURL() { + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + String expResult = cl.getResource("test/javafx/css/converter/some.txt").toExternalForm(); + ParsedValue[] values = new ParsedValue[] { + new ParsedValueImpl(expResult, null), + new ParsedValueImpl(null,null) + }; + ParsedValueImpl value = + new ParsedValueImpl(values, URLConverter.getInstance()); + + Font font = null; + String result = value.convert(font); + assertEquals(expResult, result); + } + + @Test + public void testConvertWithAbsoluteURLWithBaseURL() { + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + String baseURL = cl.getResource("com/..").toExternalForm(); + String expResult = cl.getResource("test/javafx/css/converter/some.txt").toExternalForm(); + ParsedValue[] values = new ParsedValue[] { + new ParsedValueImpl(expResult, null), + new ParsedValueImpl(baseURL,null) + }; + ParsedValueImpl value = + new ParsedValueImpl(values, URLConverter.getInstance()); + + Font font = null; + String result = value.convert(font); + assertEquals(expResult, result); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/font/PrismFontFactoryTest.java 2015-09-11 21:23:53.081287342 -0400 @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package test.com.sun.javafx.font; + +import com.sun.javafx.font.PrismFontFactory; +import org.junit.After; +import org.junit.AfterClass; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * + */ +public class PrismFontFactoryTest { + + public PrismFontFactoryTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + /** + * Test of getFontFactory method, of class T2KFontFactory. + */ + @Test + public void testGetFontFactory() { + PrismFontFactory expResult = null; + PrismFontFactory result = PrismFontFactory.getFontFactory(); + assertNotNull("Should never turn null", result); + expResult = PrismFontFactory.getFontFactory(); + assertEquals("Creates different instance of FontFactory", expResult, result); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/geom/BaseBoundsTest.java 2015-09-11 21:23:53.825287334 -0400 @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.geom; + +import com.sun.javafx.geom.BoxBounds; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.Rectangle; +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertEquals; + +import org.junit.Test; + +public class BaseBoundsTest { + + public @Test + void testBounds_MakeEmptyTest() { + RectBounds rectBounds = new RectBounds(10, 20, 20, 30); + assertFalse(rectBounds.isEmpty()); + rectBounds.makeEmpty(); + assertTrue(rectBounds.isEmpty()); + assertEquals(new RectBounds(), rectBounds); + + BoxBounds boxBounds = new BoxBounds(10, 20, 10, 40, 50, 20); + assertFalse(boxBounds.isEmpty()); + boxBounds.makeEmpty(); + assertTrue(boxBounds.isEmpty()); + assertEquals(new BoxBounds(), boxBounds); + } + + public @Test + void testRectangle_ZeroArea() { + RectBounds rectBounds = new RectBounds(new Rectangle()); + assertFalse(rectBounds.isEmpty()); + RectBounds rectBounds2 = new RectBounds(0, 0, 0, 0); + assertEquals(rectBounds, rectBounds2); + } + + public @Test + void testRectangle_Offset() { + // the arguments are (x, y, width, height) + Rectangle rect = new Rectangle(10, 20, 40, 50); + RectBounds rectBounds = new RectBounds(rect); + assertFalse(rectBounds.isEmpty()); + + // the arguments are (minX, minY, maxX, maxY) + RectBounds rectBounds2 = new RectBounds(10, 20, 50, 70); + assertEquals(rectBounds, rectBounds2); + } + + public @Test + void testBounds_IntersectsTest1() { + RectBounds rectBounds = new RectBounds(10, 20, 40, 50); + assertTrue(rectBounds.is2D()); + assertFalse(rectBounds.isEmpty()); + + BoxBounds boxBounds = new BoxBounds(10, 20, 0, 20, 30, 0); + assertTrue(boxBounds.is2D()); + assertTrue(boxBounds.intersects(rectBounds)); + + boxBounds = new BoxBounds(10, 20, 2, 20, 30, 2); + assertFalse(boxBounds.is2D()); + assertFalse(boxBounds.intersects(rectBounds)); + } + + public @Test + void testBounds_IntersectsTest2() { + RectBounds rectBounds = new RectBounds(10, 20, 40, 50); + assertFalse(rectBounds.isEmpty()); + + BoxBounds boxBounds = new BoxBounds(10, 20, 1, 20, 30, 1); + assertFalse(boxBounds.intersects(rectBounds)); + } + + public @Test + void testBounds_IntersectsTest3() { + BoxBounds boxBounds = new BoxBounds(10, 20, 10, 40, 50, 20); + assertFalse(boxBounds.isEmpty()); + + BoxBounds boxBounds2 = new BoxBounds(10, 20, 0, 20, 30, 5); + assertFalse(boxBounds2.intersects(boxBounds)); + } + + public @Test + void testBounds_IntersectsTest4() { + BoxBounds boxBounds = new BoxBounds(10, 20, 10, 40, 50, 20); + assertFalse(boxBounds.isEmpty()); + + BoxBounds boxBounds2 = new BoxBounds(10, 20, 0, 20, 30, 10); + assertTrue(boxBounds2.intersects(boxBounds)); + } + + public @Test + void testBounds_SetBoundsAndSortTest() { + RectBounds rectBounds = new RectBounds(); + assertTrue(rectBounds.isEmpty()); + rectBounds.setBoundsAndSort(20, 30, 10, 20); + assertFalse(rectBounds.isEmpty()); + assertEquals(new RectBounds(10, 20, 20, 30), rectBounds); + + BoxBounds boxBounds = new BoxBounds(); + assertTrue(boxBounds.isEmpty()); + boxBounds.setBoundsAndSort(40, 50, 20, 10, 20, 10); + assertFalse(boxBounds.isEmpty()); + assertEquals(new BoxBounds(10, 20, 10, 40, 50, 20), boxBounds); + } + + public @Test + void testBounds_UnionWithTest() { + RectBounds rectBounds = new RectBounds(); + assertTrue(rectBounds.isEmpty()); + RectBounds rectBounds2 = new RectBounds(0, 1, 2, 4); + rectBounds.unionWith(rectBounds2); + assertFalse(rectBounds.isEmpty()); + assertEquals(new RectBounds(0, 1, 2, 4), rectBounds); + RectBounds rectBounds3 = new RectBounds(-1, -2, 2, 3); + rectBounds.unionWith(rectBounds3); + assertEquals(new RectBounds(-1, -2, 2, 4), rectBounds); + + BoxBounds boxBounds = new BoxBounds(); + assertTrue(boxBounds.isEmpty()); + BoxBounds boxBounds2 = new BoxBounds(0, 1, 2, 2, 3, 4); + boxBounds.unionWith(boxBounds2); + assertFalse(boxBounds.isEmpty()); + assertEquals(new BoxBounds(0, 1, 2, 2, 3, 4), boxBounds); + BoxBounds boxBounds3 = new BoxBounds(-1, -2, -3, 1, 2, 3); + boxBounds.unionWith(boxBounds3); + assertEquals(new BoxBounds(-1, -2, -3, 2, 3, 4), boxBounds); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/geom/DirtyRegionContainerTest.java 2015-09-11 21:23:54.633287324 -0400 @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.geom; + +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.RectBounds; +import junit.framework.Assert; +import org.junit.Test; + +public class DirtyRegionContainerTest { + + static RectBounds[] nonIntersecting_3_Regions = new RectBounds[] { + new RectBounds(0, 0, 20, 20), + new RectBounds(25, 25, 50, 50), + new RectBounds(60, 60, 100, 100) + }; + + @Test + public void test_maxSpace() { + DirtyRegionContainer drc = new DirtyRegionContainer(10); + Assert.assertEquals(10, drc.maxSpace()); + } + + @Test + public void test_size() { + DirtyRegionContainer drc = new DirtyRegionContainer(5); + drc.deriveWithNewRegions(nonIntersecting_3_Regions); + Assert.assertEquals(3, drc.size()); + } + + @Test + public void test_deriveWithNewBounds() { + DirtyRegionContainer drc = new DirtyRegionContainer(5); + drc.deriveWithNewRegions(nonIntersecting_3_Regions); + for (int i = 0; i < drc.size(); i++) { + RectBounds rb = drc.getDirtyRegion(i); + Assert.assertEquals(nonIntersecting_3_Regions[i], rb); + } + } + + @Test + public void test_deriveWithNewBounds_null() { + DirtyRegionContainer drc = getDRC_initialized(); + drc.deriveWithNewRegions(null); + for (int i = 0; i < drc.size(); i++) { + RectBounds rb = drc.getDirtyRegion(i); + Assert.assertEquals(nonIntersecting_3_Regions[i], rb); + } + } + + @Test + public void test_deriveWithNewBounds_zero_length () { + DirtyRegionContainer drc = getDRC_initialized(); + drc.deriveWithNewRegions(new RectBounds[]{}); + for (int i = 0; i < drc.size(); i++) { + RectBounds rb = drc.getDirtyRegion(i); + Assert.assertEquals(nonIntersecting_3_Regions[i], rb); + } + } + + @Test + public void test_deriveWithNewBounds_biger_length () { + DirtyRegionContainer drc = getDRC_initialized(); + RectBounds[] arry = new RectBounds[]{ + new RectBounds(1, 1, 10, 10), + new RectBounds(15, 15, 50, 50), + new RectBounds(60, 60, 100, 100), + new RectBounds(110, 110, 200, 200) + }; + drc.deriveWithNewRegions(arry); + for (int i = 0; i < drc.size(); i++) { + RectBounds rb = drc.getDirtyRegion(i); + Assert.assertEquals(arry[i], rb); + } + } + + @Test + public void test_copy() { + DirtyRegionContainer drc = getDRC_initialized(); + DirtyRegionContainer copyDrc = drc.copy(); + Assert.assertTrue(copyDrc != drc); + Assert.assertEquals(copyDrc, drc); + } + + @Test + public void test_getDirtyRegion() { + DirtyRegionContainer drc = getDRC_initialized(); + RectBounds dr = drc.getDirtyRegion(1); + Assert.assertEquals(new RectBounds(25, 25, 50, 50), dr); + } + + @Test (expected=ArrayIndexOutOfBoundsException.class) + public void test_getDirtyRegion_AIOOBE() { + DirtyRegionContainer drc = getDRC_initialized(); + RectBounds dr = drc.getDirtyRegion(10); + Assert.fail("Expected AIOOBE"); + } + + @Test + public void test_addDirtyRegion_non_intersecting() { + DirtyRegionContainer drc = getDRC_initialized(); + RectBounds newregion = new RectBounds(150, 150, 200, 200); + drc.addDirtyRegion(newregion); + + Assert.assertEquals(4, drc.size()); + for(int i = 0; i < drc.size() - 1; i++) { + Assert.assertEquals(nonIntersecting_3_Regions[i], (drc.getDirtyRegion(i))); + } + Assert.assertEquals(drc.getDirtyRegion(drc.size() - 1), newregion); + } + + @Test + public void test_addDirtyRegion_has_space_intersect_once() { + DirtyRegionContainer drc = getDRC_initialized(); + + drc.addDirtyRegion(new RectBounds(10, 10, 22, 15)); + + Assert.assertEquals(3, drc.size()); + Assert.assertEquals(new RectBounds(60, 60, 100, 100), drc.getDirtyRegion(0)); + Assert.assertEquals(new RectBounds(25, 25, 50, 50), drc.getDirtyRegion(1)); + Assert.assertEquals(new RectBounds(0, 0, 22, 20), drc.getDirtyRegion(2)); + } + + @Test + public void test_addDirtyRegion_has_space_intersect_twice() { + DirtyRegionContainer drc = getDRC_initialized(); + + drc.addDirtyRegion(new RectBounds(10, 10, 40, 40)); + + Assert.assertEquals(2, drc.size()); + Assert.assertEquals(new RectBounds(60, 60, 100, 100), drc.getDirtyRegion(0)); + Assert.assertEquals(new RectBounds(0, 0, 50, 50), drc.getDirtyRegion(1)); + } + + @Test + public void test_addDirtyRegion_has_space_intersect_all() { + DirtyRegionContainer drc = getDRC_initialized(); + drc.addDirtyRegion(new RectBounds(10, 10, 80, 80)); + + Assert.assertEquals(1, drc.size()); + Assert.assertEquals(new RectBounds(0, 0, 100, 100), drc.getDirtyRegion(0)); + } + + @Test + public void test_addDirtyRegion_no_space_intersect_once() { + DirtyRegionContainer drc = getDRC_initialized(); + drc.addDirtyRegion(new RectBounds(120, 120, 150, 150)); + + drc.addDirtyRegion(new RectBounds(10, 10, 22, 15)); + + Assert.assertEquals(4, drc.size()); + Assert.assertEquals(new RectBounds(120, 120, 150, 150), drc.getDirtyRegion(0)); + Assert.assertEquals(new RectBounds(25, 25, 50, 50), drc.getDirtyRegion(1)); + Assert.assertEquals(new RectBounds(60, 60, 100, 100), drc.getDirtyRegion(2)); + Assert.assertEquals(new RectBounds(0, 0, 22, 20), drc.getDirtyRegion(3)); + } + + @Test + public void test_addDirtyRegion_no_space_intersect_twice() { + DirtyRegionContainer drc = getDRC_initialized(); + drc.addDirtyRegion(new RectBounds(120, 120, 150, 150)); + + drc.addDirtyRegion(new RectBounds(10, 10, 40, 40)); + + Assert.assertEquals(3, drc.size()); + Assert.assertEquals(new RectBounds(120, 120, 150, 150), drc.getDirtyRegion(0)); + Assert.assertEquals(new RectBounds(60, 60, 100, 100), drc.getDirtyRegion(1)); + Assert.assertEquals(new RectBounds(0, 0, 50, 50), drc.getDirtyRegion(2)); + } + + private DirtyRegionContainer getDRC_initialized() { + DirtyRegionContainer drc = new DirtyRegionContainer(4); + return drc.deriveWithNewRegions(nonIntersecting_3_Regions); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/geom/Path2DTest.java 2015-09-11 21:23:55.305287317 -0400 @@ -0,0 +1,594 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.geom; + +import com.sun.javafx.geom.Arc2D; +import com.sun.javafx.geom.BoxBounds; +import com.sun.javafx.geom.IllegalPathStateException; +import com.sun.javafx.geom.Path2D; +import com.sun.javafx.geom.PathIterator; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.Shape; +import com.sun.javafx.geom.transform.BaseTransform; +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertEquals; + +import org.junit.Test; + +public class Path2DTest { + void checkLine(PathIterator pi, float x1, float y1, float x2, float y2) { + float coords[] = new float[2]; + assertFalse(pi.isDone()); + assertEquals(PathIterator.SEG_MOVETO, pi.currentSegment(coords)); + assertEquals(x1, coords[0], .001); + assertEquals(y1, coords[1], .001); + assertFalse(pi.isDone()); + pi.next(); + assertFalse(pi.isDone()); + assertEquals(PathIterator.SEG_LINETO, pi.currentSegment(coords)); + assertEquals(x2, coords[0], .001); + assertEquals(y2, coords[1], .001); + assertFalse(pi.isDone()); + pi.next(); + assertTrue(pi.isDone()); + } + + void checkAndResetPaths(Path2D pref, Path2D ptest, float curx, float cury) { + checkAndResetPaths(pref, ptest, curx, cury, false); + } + + void checkAndResetPaths(Path2D pref, Path2D ptest, + float curx, float cury, + boolean verbose) + { + assertEquals(curx, pref.getCurrentX(), .001); + assertEquals(cury, pref.getCurrentY(), .001); + checkShapes(pref, ptest, verbose); + pref.reset(); + ptest.reset(); + } + + void checkShapes(Shape sref, Shape stest) { + checkShapes(sref, stest, false); + } + + void checkShapes(Shape sref, Shape stest, boolean verbose) { + checkPaths(sref.getPathIterator(BaseTransform.IDENTITY_TRANSFORM), + stest.getPathIterator(BaseTransform.IDENTITY_TRANSFORM), + verbose); + } + + void checkPaths(PathIterator piref, PathIterator pitest) { + checkPaths(piref, pitest, false); + } + + static int numcoords[]; + static { + numcoords = new int[5]; + numcoords[PathIterator.SEG_MOVETO] = 2; + numcoords[PathIterator.SEG_LINETO] = 2; + numcoords[PathIterator.SEG_QUADTO] = 4; + numcoords[PathIterator.SEG_CUBICTO] = 6; + numcoords[PathIterator.SEG_CLOSE] = 0; + } + + void checkPaths(PathIterator piref, PathIterator pitest, boolean verbose) { + float coordsref[] = new float[6]; + float coordstest[] = new float[6]; + while (!piref.isDone()) { + assertFalse(pitest.isDone()); + int typref = piref.currentSegment(coordsref); + int typtest = pitest.currentSegment(coordstest); + assertEquals(typref, typtest); + if (verbose) System.out.println("type = "+typref); + for (int i = 0; i < numcoords[typref]; i++) { + assertEquals(coordsref[i], coordstest[i], .001); + if (verbose) System.out.println("coord["+i+"] = "+coordsref[i]); + } + assertFalse(pitest.isDone()); + piref.next(); + pitest.next(); + } + assertTrue(pitest.isDone()); + } + + double angle(double ux, double uy, double vx, double vy) { + double sgn = (ux * vy - uy * vx) > 0 ? 1f : -1f; + double dot = ux * vx + uy * vy; + double ulen = Math.hypot(ux, uy); + double vlen = Math.hypot(vx, vy); + double cos = dot / (ulen * vlen); + if (cos < -1f) cos = -1f; + else if (cos > 1f) cos = 1f; + return sgn * Math.acos(cos); + } + + void checkArcTo(float x1, float y1, + float rw, float rh, float arcrad, + boolean largeArcs, boolean sweepFlag, + float x2, float y2) + { +// System.out.println("rw="+rw+", rh="+rh+", phi="+arcrad+", fA="+largeArcs+", fS="+sweepFlag+", x="+x2+", y="+y2); + // Comparing to math specified at: + // http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes + Path2D path = new Path2D(); + path.moveTo(x1, y1); + path.arcTo(rw/2f, rh/2f, arcrad, largeArcs, sweepFlag, x2, y2); + double rx = rw/2.0; + double ry = rh/2.0; + if (rx == 0 || ry == 0) { + checkLine(path.getPathIterator(BaseTransform.IDENTITY_TRANSFORM), + x1, y1, x2, y2); + return; + } + double cosphi = Math.cos(arcrad); + double sinphi = Math.sin(arcrad); + double x1p = cosphi * ((x1 - x2) / 2f) + sinphi * ((y1 - y2) / 2f); + double y1p = -sinphi * ((x1 - x2) / 2f) + cosphi * ((y1 - y2) / 2f); + double x1psq = x1p * x1p; + double y1psq = y1p * y1p; + double rxsq = rx * rx; + double rysq = ry * ry; + double delta = (x1psq / rxsq) + (y1psq / rysq); + double num = rxsq * rysq - rxsq * y1psq - rysq * x1psq; + if (delta > 1f) { + rx *= Math.sqrt(delta); + ry *= Math.sqrt(delta); + rxsq = rx * rx; + rysq = ry * ry; + // Note that repeating the num calculation can sometimes yield + // a negative answer... + num = 0; + } + double den = rxsq * y1psq + rysq * x1psq; + double sgn = (largeArcs == sweepFlag) ? -1f : 1f; + double cxp = sgn * Math.sqrt(num / den) * (rx * y1p) / ry; + double cyp = sgn * Math.sqrt(num / den) * -(ry * x1p) / rx; + double cx = cosphi * cxp - sinphi * cyp + (x1 + x2) / 2f; + double cy = sinphi * cxp + cosphi * cyp + (y1 + y2) / 2f; + double theta = angle(1, 0, + (x1p - cxp) / rx, (y1p - cyp) / ry); + double dtheta = angle((x1p - cxp) / rx, (y1p - cyp) / ry, + (-x1p - cxp) / rx, (-y1p - cyp) / ry); + theta = Math.toDegrees(theta); + dtheta = Math.toDegrees(dtheta); + if (sweepFlag && dtheta < 0) dtheta += 360; + if (!sweepFlag && dtheta > 0) dtheta -= 360; + Arc2D arc = new Arc2D((float) (cx-rx), (float) (cy-ry), + (float) (rx*2.0), (float) (ry*2.0), + (float) -theta, (float) -dtheta, Arc2D.OPEN); + BaseTransform arctx = + BaseTransform.getRotateInstance(arcrad, cx, cy); + checkPaths(arc.getPathIterator(arctx), + path.getPathIterator(BaseTransform.IDENTITY_TRANSFORM)); + } + + public @Test + void testArcTo() { + Path2D path = new Path2D(); + for (int pathdeg = 0; pathdeg <= 360; pathdeg += 15) { + double pathrad = Math.toRadians(pathdeg); + float px = (float) Math.cos(pathrad) * 50; + float py = (float) Math.sin(pathrad) * 50; + for (int arcdeg = 0; arcdeg <= 360; arcdeg += 15) { + float arcrad = (float) Math.toRadians(arcdeg); + for (int rw = 0; rw < 100; rw += 10) { + for (int rh = 0; rh < 100; rh += 10) { + checkArcTo(-px, -py, rw, rh, arcrad, false, false, px, py); + checkArcTo(-px, -py, rw, rh, arcrad, false, true, px, py); + checkArcTo(-px, -py, rw, rh, arcrad, true, false, px, py); + checkArcTo(-px, -py, rw, rh, arcrad, true, true, px, py); + } + } + } + } + RectBounds rectBounds = new RectBounds(10, 20, 20, 30); + assertFalse(rectBounds.isEmpty()); + rectBounds.makeEmpty(); + assertTrue(rectBounds.isEmpty()); + assertEquals(new RectBounds(), rectBounds); + + BoxBounds boxBounds = new BoxBounds(10, 20, 10, 40, 50, 20); + assertFalse(boxBounds.isEmpty()); + boxBounds.makeEmpty(); + assertTrue(boxBounds.isEmpty()); + assertEquals(new BoxBounds(), boxBounds); + } + + public @Test + void testEmptyPathException() { + int bad = 0; + Path2D p = new Path2D(); + try { p.lineTo(0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.quadTo(0, 0, 0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.curveTo(0, 0, 0, 0, 0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.arcTo(1, 1, 0, true, true, 1, 1); bad++; } catch (IllegalPathStateException e) {} + try { p.moveToRel(0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.lineToRel(0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.quadToRel(0, 0, 0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.curveToRel(0, 0, 0, 0, 0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.arcToRel(1, 1, 0, true, true, 1, 1); bad++; } catch (IllegalPathStateException e) {} + try { p.quadToSmooth(0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.curveToSmooth(0, 0, 0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.quadToSmoothRel(0, 0); bad++; } catch (IllegalPathStateException e) {} + try { p.curveToSmoothRel(0, 0, 0, 0); bad++; } catch (IllegalPathStateException e) {} + assertEquals(0, bad); + } + + public @Test + void testRelative() { + Path2D pabs = new Path2D(); + Path2D prel = new Path2D(); + for (int x0 = -100; x0 < 100; x0 += 50) { + for (int y0 = -100; y0 < 100; y0 += 50) { + for (int x1 = -100; x1 < 100; x1 += 50) { + for (int y1 = -100; y1 < 100; y1 += 50) { + testRelative(pabs, prel, x0, y0, x1, y1); + } + } + } + } + } + + private void testRelative(Path2D pabs, Path2D prel, + int x0, int y0, int x1, int y1) + { + // Test relative moveTo following moveTo + pabs.moveTo(x0, y0); + pabs.moveTo(x1, y1); + prel.moveTo(x0, y0); + prel.moveToRel(x1-x0, y1-y0); + checkAndResetPaths(pabs, prel, x1, y1); + + // Test relative lineTo + pabs.moveTo(x0, y0); + pabs.lineTo(x1, y1); + prel.moveTo(x0, y0); + prel.lineToRel(x1-x0, y1-y0); + checkAndResetPaths(pabs, prel, x1, y1); + + // test relative arcTo + pabs.moveTo(x0, y0); + pabs.arcTo(1, 1, 0, true, true, x1, y1); + prel.moveTo(x0, y0); + prel.arcToRel(1, 1, 0, true, true, x1-x0, y1-y0); + checkAndResetPaths(pabs, prel, x1, y1); + + // test relative paths with longer coordinate lists + for (int x2 = -100; x2 < 100; x2 += 50) { + for (int y2 = -100; y2 < 100; y2 += 50) { + testRelative(pabs, prel, x0, y0, x1, y1, x2, y2); + } + } + } + + private void testRelative(Path2D pabs, Path2D prel, + int x0, int y0, int x1, int y1, int x2, int y2) + { + // test relative quadTo + pabs.moveTo(x0, y0); + pabs.quadTo(x1, y1, x2, y2); + prel.moveTo(x0, y0); + prel.quadToRel(x1-x0, y1-y0, x2-x0, y2-y0); + checkAndResetPaths(pabs, prel, x2, y2); + + for (int x3 = -100; x3 < 100; x3 += 50) { + for (int y3 = -100; y3 < 100; y3 += 50) { + // test relative cubic curveTo + pabs.moveTo(x0, y0); + pabs.curveTo(x1, y1, x2, y2, x3, y3); + prel.moveTo(x0, y0); + prel.curveToRel(x1-x0, y1-y0, x2-x0, y2-y0, x3-x0, y3-y0); + checkAndResetPaths(pabs, prel, x3, y3); + } + } + } + + public @Test + void testSmoothCurves() { + Path2D pabs = new Path2D(); + Path2D psmooth = new Path2D(); + for (int x0 = -100; x0 < 100; x0 += 50) { + for (int y0 = -100; y0 < 100; y0 += 50) { + for (int x1 = -100; x1 < 100; x1 += 50) { + for (int y1 = -100; y1 < 100; y1 += 50) { + testSmoothCurves(pabs, psmooth, x0, y0, x1, y1); + } + } + } + } + } + + private void testSmoothCurves(Path2D pabs, Path2D psmooth, + int x0, int y0, int x1, int y1) + { + for (int xc0 = -100; xc0 < 100; xc0 += 100) { + for (int yc0 = -100; yc0 < 100; yc0 += 100) { + // test smooth quadto after lineTo + pabs.moveTo(x0, y0); + pabs.lineTo(xc0, yc0); + pabs.quadTo(xc0, yc0, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.lineTo(xc0, yc0); + psmooth.quadToSmooth(x1, y1); + checkAndResetPaths(pabs, psmooth, x1, y1); + + // test smooth relative quadTo after lineTo + pabs.moveTo(x0, y0); + pabs.lineTo(xc0, yc0); + pabs.quadTo(xc0, yc0, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.lineTo(xc0, yc0); + psmooth.quadToSmoothRel(x1-xc0, y1-yc0); + checkAndResetPaths(pabs, psmooth, x1, y1); + + for (int xc1 = -100; xc1 < 100; xc1 += 100) { + for (int yc1 = -100; yc1 < 100; yc1 += 100) { + float xc01 = (xc0 + xc1) / 2f; + float yc01 = (yc0 + yc1) / 2f; + + // test smooth quadTo after quadTo + pabs.moveTo(x0, y0); + pabs.quadTo(xc0, yc0, xc01, yc01); + pabs.quadTo(xc1, yc1, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.quadTo(xc0, yc0, xc01, yc01); + psmooth.quadToSmooth(x1, y1); + checkAndResetPaths(pabs, psmooth, x1, y1); + + // test smooth relative quadTo after quadTo + pabs.moveTo(x0, y0); + pabs.quadTo(xc0, yc0, xc01, yc01); + pabs.quadTo(xc1, yc1, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.quadTo(xc0, yc0, xc01, yc01); + psmooth.quadToSmoothRel(x1-xc01, y1-yc01); + checkAndResetPaths(pabs, psmooth, x1, y1); + + // test smooth curveTo after lineTo + pabs.moveTo(x0, y0); + pabs.lineTo(xc0, yc0); + pabs.curveTo(xc0, yc0, xc1, yc1, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.lineTo(xc0, yc0); + psmooth.curveToSmooth(xc1, yc1, x1, y1); + checkAndResetPaths(pabs, psmooth, x1, y1); + + // test smooth relative curveTo after lineTo + pabs.moveTo(x0, y0); + pabs.lineTo(xc0, yc0); + pabs.curveTo(xc0, yc0, xc1, yc1, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.lineTo(xc0, yc0); + psmooth.curveToSmoothRel(xc1-xc0, yc1-yc0, x1-xc0, y1-yc0); + checkAndResetPaths(pabs, psmooth, x1, y1); + + testSmoothCurves(pabs, psmooth, + x0, y0, x1, y1, + xc0, yc0, xc01, yc01, xc1, yc1); + } + } + } + } + } + + private void testSmoothCurves(Path2D pabs, Path2D psmooth, + int x0, int y0, int x1, int y1, + int xc0, int yc0, + float xc01, float yc01, + int xc1, int yc1) + { + for (int xc2 = -100; xc2 < 100; xc2 += 100) { + for (int yc2 = -100; yc2 < 100; yc2 += 100) { + // test smooth curveTo after quadTo + pabs.moveTo(x0, y0); + pabs.quadTo(xc0, yc0, xc01, yc01); + pabs.curveTo(xc1, yc1, xc2, yc2, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.quadTo(xc0, yc0, xc01, yc01); + psmooth.curveToSmooth(xc2, yc2, x1, y1); + checkAndResetPaths(pabs, psmooth, x1, y1); + + // test smooth relative curveTo after quadTo + pabs.moveTo(x0, y0); + pabs.quadTo(xc0, yc0, xc01, yc01); + pabs.curveTo(xc1, yc1, xc2, yc2, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.quadTo(xc0, yc0, xc01, yc01); + psmooth.curveToSmoothRel(xc2-xc01, yc2-yc01, x1-xc01, y1-yc01); + checkAndResetPaths(pabs, psmooth, x1, y1); + + float xc12 = (xc1 + xc2) / 2f; + float yc12 = (yc1 + yc2) / 2f; + + // test smooth quadTo after curveTo + pabs.moveTo(x0, y0); + pabs.curveTo(xc0, yc0, xc1, yc1, xc12, yc12); + pabs.quadTo(xc2, yc2, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.curveTo(xc0, yc0, xc1, yc1, xc12, yc12); + psmooth.quadToSmooth(x1, y1); + checkAndResetPaths(pabs, psmooth, x1, y1); + + // test smooth relative quadTo after curveTo + pabs.moveTo(x0, y0); + pabs.curveTo(xc0, yc0, xc1, yc1, xc12, yc12); + pabs.quadTo(xc2, yc2, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.curveTo(xc0, yc0, xc1, yc1, xc12, yc12); + psmooth.quadToSmoothRel(x1-xc12, y1-yc12); + checkAndResetPaths(pabs, psmooth, x1, y1); + + for (int xc3 = -100; xc3 < 100; xc3 += 100) { + for (int yc3 = -100; yc3 < 100; yc3 += 100) { + // test smooth curveTo after curveTo + pabs.moveTo(x0, y0); + pabs.curveTo(xc0, yc0, xc1, yc1, xc12, yc12); + pabs.curveTo(xc2, yc2, xc3, yc3, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.curveTo(xc0, yc0, xc1, yc1, xc12, yc12); + psmooth.curveToSmooth(xc3, yc3, x1, y1); + checkAndResetPaths(pabs, psmooth, x1, y1); + + // test smooth relative curveTo after curveTo + pabs.moveTo(x0, y0); + pabs.curveTo(xc0, yc0, xc1, yc1, xc12, yc12); + pabs.curveTo(xc2, yc2, xc3, yc3, x1, y1); + psmooth.moveTo(x0, y0); + psmooth.curveTo(xc0, yc0, xc1, yc1, xc12, yc12); + psmooth.curveToSmoothRel(xc3-xc12, yc3-yc12, x1-xc12, y1-yc12); + checkAndResetPaths(pabs, psmooth, x1, y1); + } + } + } + } + } + + public @Test + void testSVGPath() { + String svgpath = + "M 10 20 "+ + "L 20 30 "+ + "H 10 "+ + "V 20 "+ + "Q 20 30 10 20 "+ + "C 20 30 20 20 10 40 "+ + "T 10 50 "+ + "S 20 25 10 35 "+ + "A 40 60 10 0 0 15 20 "+ + "A 40 60 10 0 1 25 30 "+ + "A 40 60 10 1 0 15 10 "+ + "A 40 60 10 1 1 25 20 "+ + "Z "+ + "m 10 20 "+ + "l 20 20 "+ + "h 10 "+ + "v 20 "+ + "q 10 30 10 20 "+ + "c 10 30 10 20 10 40 "+ + "t 10 50 "+ + "s 10 25 10 35 "+ + "a 40 60 10 0 0 10 20 "+ + "a 40 60 10 0 1 10 20 "+ + "a 40 60 10 1 0 10 20 "+ + "a 40 60 10 1 1 10 20 "+ + "z"; + Path2D p2dtest = new Path2D(); + p2dtest.appendSVGPath(svgpath); + Path2D p2dref = new Path2D(); + p2dref.moveTo(10, 20); + p2dref.lineTo(20, 30); + p2dref.lineTo(10, p2dref.getCurrentY()); + p2dref.lineTo(p2dref.getCurrentX(), 20); + p2dref.quadTo(20, 30, 10, 20); + p2dref.curveTo(20, 30, 20, 20, 10, 40); + p2dref.quadToSmooth(10, 50); + p2dref.curveToSmooth(20, 25, 10, 35); + p2dref.arcTo(40, 60, (float) Math.toRadians(10), false, false, 15, 20); + p2dref.arcTo(40, 60, (float) Math.toRadians(10), false, true, 25, 30); + p2dref.arcTo(40, 60, (float) Math.toRadians(10), true, false, 15, 10); + p2dref.arcTo(40, 60, (float) Math.toRadians(10), true, true, 25, 20); + p2dref.closePath(); + p2dref.moveToRel(10, 20); + p2dref.lineToRel(20, 20); + p2dref.lineToRel(10, 0); + p2dref.lineToRel(0, 20); + p2dref.quadToRel(10, 30, 10, 20); + p2dref.curveToRel(10, 30, 10, 20, 10, 40); + p2dref.quadToSmoothRel(10, 50); + p2dref.curveToSmoothRel(10, 25, 10, 35); + p2dref.arcToRel(40, 60, (float) Math.toRadians(10), false, false, 10, 20); + p2dref.arcToRel(40, 60, (float) Math.toRadians(10), false, true, 10, 20); + p2dref.arcToRel(40, 60, (float) Math.toRadians(10), true, false, 10, 20); + p2dref.arcToRel(40, 60, (float) Math.toRadians(10), true, true, 10, 20); + p2dref.closePath(); + checkShapes(p2dref, p2dtest); + } + + public @Test + void testSVGPathWS() { + String svgpathlotsofWS = + "M 10, 20 "+ + "L 20, 30 "+ + "H 10 "+ + "V 20 "+ + "Q 20, 30 10, 20 "+ + "C 20, 30 20, 20 10, 40 "+ + "T 10, 50 "+ + "S 20, 25 10, 35 "+ + "A 40, 60 10 0 0 15, 20 "+ + "A 40, 60 10 0 1 25, 30 "+ + "A 40, 60 10 1 0 15, 10 "+ + "A 40, 60 10 1 1 25, 20 "+ + "Z "+ + "m 10, 20 "+ + "l 20, 20 "+ + "h 10 "+ + "v 20 "+ + "q 10, 30 10, 20 "+ + "c 10, 30 10, 20 10, 40 "+ + "t 10, 50 "+ + "s 10, 25 10 35 "+ + "a 40, 60 10 0 0 10, 20 "+ + "a 40, 60 10 0 1 10, 20 "+ + "a 40, 60 10 1 0 10, 20 "+ + "a 40, 60 10 1 1 10, 20 "+ + "z"; + String svgpathminWS = + "M10,20"+ + "L20,30"+ + "H10"+ + "V20"+ + "Q20,30,10,20"+ + "C20,30,20,20,10,40"+ + "T10,50"+ + "S20,25,10,35"+ + "A40,60,10,0,0,15,20"+ + "A40,60,10,0,1,25,30"+ + "A40,60,10,1,0,15,10"+ + "A40,60,10,1,1,25,20"+ + "Z"+ + "m10,20"+ + "l20,20"+ + "h10"+ + "v20"+ + "q10,30,10,20"+ + "c10,30,10,20,10,40"+ + "t10,50"+ + "s10,25,10,35"+ + "a40,60,10,0,0,10,20"+ + "a40,60,10,0,1,10,20"+ + "a40,60,10,1,0,10,20"+ + "a40,60,10,1,1,10,20"+ + "z"; + Path2D p2dref = new Path2D(); + p2dref.appendSVGPath(svgpathlotsofWS); + Path2D p2dtest = new Path2D(); + p2dtest.appendSVGPath(svgpathminWS); + checkShapes(p2dref, p2dtest); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/geom/TransformedShapeTest.java 2015-09-11 21:23:56.053287308 -0400 @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.geom; + +import com.sun.javafx.geom.Arc2D; +import com.sun.javafx.geom.CubicCurve2D; +import com.sun.javafx.geom.Ellipse2D; +import com.sun.javafx.geom.Line2D; +import com.sun.javafx.geom.Path2D; +import com.sun.javafx.geom.QuadCurve2D; +import com.sun.javafx.geom.RoundRectangle2D; +import com.sun.javafx.geom.Shape; +import com.sun.javafx.geom.TransformedShape; +import static junit.framework.Assert.assertEquals; +import com.sun.javafx.geom.transform.BaseTransform; +import org.junit.Test; + +/** + * + */ +public class TransformedShapeTest { + // Avoid integer coordinates so that float->double->float roundoff errors + // do not end up causing "failures of questionable value" + static Shape testShapes[] = { + new Arc2D(9.5f, 9.5f, 26.2f, 16.1f, 0, 270, Arc2D.PIE), + new Arc2D(9.5f, 9.5f, 26.2f, 16.1f, 0, 270, Arc2D.OPEN), + new Arc2D(9.5f, 9.5f, 26.2f, 16.1f, 0, 270, Arc2D.CHORD), + new CubicCurve2D(9.5f, 9.5f, 40.5f, 9.5f, 9.5f, 40.5f, 40.5f, 40.5f), + new Ellipse2D(9.5f, 9.5f, 21f, 16f), + new Line2D(9.5f, 9.5f, 40.5f, 40.5f), + makePath(Path2D.WIND_EVEN_ODD), + makePath(Path2D.WIND_NON_ZERO), + new QuadCurve2D(9.5f, 9.5f, 20.5f, 40.5f, 40.5f, 9.5f), + new RoundRectangle2D(9.5f, 9.5f, 21f, 16f, 5f, 5f), + }; + + static Shape makePath(int rule) { + Path2D p2d = new Path2D(rule); + p2d.moveTo(9.5f, 9.5f); + p2d.lineTo(20.5f, 9.5f); + p2d.quadTo(20.5f, 30.5f, 40.5f, 40.5f); + p2d.lineTo(9.5f, 40.5f); + p2d.curveTo(30.5f, 30.5f, 20.5f, 10.5f, 40.5f, 10.5f); + p2d.lineTo(9.5f, 20.5f); + p2d.closePath(); + return p2d; + } + + static BaseTransform testTransforms[] = { + BaseTransform.getTranslateInstance(5.125, 5.75), + BaseTransform.getRotateInstance(Math.toRadians(45), 25, 25), + BaseTransform.getScaleInstance(0.5, 0.5), + BaseTransform.getScaleInstance(1.75, 1.6), + }; + + public @Test void testTranslatedShapes() { + for (Shape s : testShapes) { + test(TransformedShape.translatedShape(s, 5.125, 8.25)); + test(TransformedShape.translatedShape(s, -5.25, 8.125)); + test(TransformedShape.translatedShape(s, 5.125, -8.25)); + test(TransformedShape.translatedShape(s, -5.25, -8.125)); + } + } + + public @Test void testTransformedShapes() { + BaseTransform combinedtx = BaseTransform.IDENTITY_TRANSFORM; + for (BaseTransform tx : testTransforms) { + test(tx); + combinedtx = combinedtx.deriveWithConcatenation(tx); + test(combinedtx); + } + } + + static void test(BaseTransform tx) { + for (Shape s : testShapes) { + test(TransformedShape.transformedShape(s, tx)); + } + } + + // Number of ulp to hunt around for a good answer for fuzzy testing + static final int FUZZY = 5; + + static void test(TransformedShape s1) { + BaseTransform tx = s1.getTransformNoClone(); + Shape raws1 = s1.getDelegateNoClone(); + Shape s2 = tx.createTransformedShape(raws1); + for (int y = 0; y < 50; y++) { + for (int x = 0; x < 50; x++) { + boolean cp1 = s1.contains(x, y); + boolean cp2 = s2.contains(x, y); + boolean cr1 = s1.contains(x, y, 1, 1); + boolean cr2 = s2.contains(x, y, 1, 1); + boolean ir1 = s1.intersects(x, y, 1, 1); + boolean ir2 = s2.intersects(x, y, 1, 1); + boolean cpfail = (cp1 != cp2); + boolean crfail = (cr1 != cr2); + boolean irfail = (ir1 != ir2); + if (cpfail || crfail || irfail) { + Float ulpx = Math.ulp(x); + Float ulpy = Math.ulp(y); + for (int i = -FUZZY; i <= +FUZZY; i++) { + float fy = y + ulpy * i; + for (int j = -FUZZY; j <= +FUZZY; j++) { + float fx = x + ulpx * j; + cpfail = cpfail && (s1.contains(fx, fy) != + s2.contains(fx, fy)); + crfail = crfail && (s1.contains(fx, fy, 1, 1) != + s2.contains(fx, fy, 1, 1)); + irfail = irfail && (s1.intersects(fx, fy, 1, 1) != + s2.intersects(fx, fy, 1, 1)); + } + } + System.err.println("testing: "+raws1+" transformed by "+tx); + if (cpfail) { assertEquals(cp2, cp1); } + else if (crfail) { assertEquals(cr2, cr1); } + else if (irfail) { assertEquals(ir2, ir1); } + else { + System.err.println("fuzzy test required for ("+x+", "+y+")"); + } + } + } + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/geom/Vec3dTest.java 2015-09-11 21:23:56.781287300 -0400 @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.geom; + +import com.sun.javafx.geom.Vec3d; +import com.sun.javafx.geom.Vec3f; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * PRELIMINARY unit tests for Vec3d. + * + * TODO: expand this to cover the entire class (RT-26882) + */ +public class Vec3dTest { + + private static double EPSILON = 1e-10; + + @Test + public void testDefaultContructor() { + Vec3d v3d = new Vec3d(); + assertEquals(0, v3d.x, 0); + assertEquals(0, v3d.y, 0); + assertEquals(0, v3d.z, 0); + } + + @Test + public void testContructor1() { + Vec3d v3d = new Vec3d(1.0, 2.0, 3.0); + assertEquals(1, v3d.x, 0); + assertEquals(2, v3d.y, 0); + assertEquals(3, v3d.z, 0); + } + + @Test + public void testContructor2() { + Vec3f v3f = new Vec3f(1f, 2f, 3f); + Vec3d v3d = new Vec3d(v3f); + assertEquals(1, v3d.x, 0); + assertEquals(2, v3d.y, 0); + assertEquals(3, v3d.z, 0); + } + + @Test + public void testLength() { + Vec3d v3d = new Vec3d(); + double len = v3d.length(); + assertEquals(0, len, 0); + + v3d = new Vec3d(1, 2, 3); + len = v3d.length(); + assertEquals(Math.sqrt(14.0), len, EPSILON); + + v3d = new Vec3d(-1, 2, 3); + len = v3d.length(); + assertEquals(Math.sqrt(14.0), len, EPSILON); + + v3d = new Vec3d(1, -0.2, -0.03); + len = v3d.length(); + assertEquals(Math.sqrt(1.0409), len, EPSILON); + + v3d = new Vec3d(-0.1, -0.2, -0.3); + len = v3d.length(); + assertEquals(Math.sqrt(0.14), len, EPSILON); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/geom/transform/BaseTransformTest.java 2015-09-11 21:23:57.533287292 -0400 @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.geom.transform; + + +import com.sun.javafx.geom.transform.Affine2D; +import com.sun.javafx.geom.transform.Affine3D; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.Identity; +import com.sun.javafx.geom.transform.Translate2D; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * This Unit Test covers BaseTransform and some of its calculations. + * TODO: cover more of BaseTransform's functionality. (RT-26882) + */ +public class BaseTransformTest { + + public void assertEqual(BaseTransform src1, BaseTransform src2) { + assertEquals(src1.getMxx(), src2.getMxx(), 0.001); + assertEquals(src1.getMxy(), src2.getMxy(), 0.001); + assertEquals(src1.getMxz(), src2.getMxz(), 0.001); + assertEquals(src1.getMyx(), src2.getMyx(), 0.001); + assertEquals(src1.getMyy(), src2.getMyy(), 0.001); + assertEquals(src1.getMyz(), src2.getMyz(), 0.001); + assertEquals(src1.getMzx(), src2.getMzx(), 0.001); + assertEquals(src1.getMzy(), src2.getMzy(), 0.001); + assertEquals(src1.getMzz(), src2.getMzz(), 0.001); + assertEquals(src1.getMxt(), src2.getMxt(), 0.001); + assertEquals(src1.getMyt(), src2.getMyt(), 0.001); + assertEquals(src1.getMzt(), src2.getMzt(), 0.001); + } + + BaseTransform getTest3DTransform() { + return new Affine3D(10, 0, 0, 2, + 0, 10, 0, 2, + 0, 0, 10, 2); + } + + BaseTransform getTest2DTransform() { + return new Affine2D(2, 0, 0, 2, 5, 5); + } + + Translate2D getTestTranslateTransform() { + return new Translate2D(8,8); + } + + @Test + public void testCompare() { + BaseTransform test1 = new Identity(); + BaseTransform test2 = new Identity(); + assertEqual(test1, test2); + } + + @Test + public void testConcatenation() { + BaseTransform test1 = new Identity(); + BaseTransform test2 = getTest3DTransform(); + BaseTransform result1 = test1.deriveWithConcatenation(test2); + assertEqual(result1, getTest3DTransform()); + } + + @Test + public void testDeriveWithPreConcatenation() { + BaseTransform test1 = new Identity(); + test1.deriveWithPreConcatenation(test1); + assertEqual(test1, BaseTransform.IDENTITY_TRANSFORM); + } + + @Test + public void testAffine3DPreConcatenation() { + Affine3D test1 = (Affine3D)getTest3DTransform(); + BaseTransform test2 = getTest2DTransform(); + BaseTransform result1 = test1.deriveWithPreConcatenation(test2); + test1 = (Affine3D)getTest3DTransform(); + test2 = getTest2DTransform(); + BaseTransform result2 = test2.deriveWithConcatenation(test1); + assertEqual(result1, result2); + } + + @Test + public void testTranslatePreConcatenation() { + Affine3D test1 = (Affine3D)getTest3DTransform(); + BaseTransform test2 = getTestTranslateTransform(); + BaseTransform result1 = test1.deriveWithPreConcatenation(test2); + test1 = (Affine3D)getTest3DTransform(); + test2 = getTestTranslateTransform(); + BaseTransform result2 = test2.deriveWithConcatenation(test1); + assertEqual(result1, result2); + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/iio/GIFLoaderTest.java 2015-09-11 21:23:58.481287281 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,413 +0,0 @@ -/* - * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.iio; - -import com.sun.javafx.iio.gif.GIFImageLoader2; -import java.awt.image.*; -import java.io.*; -import static org.junit.Assert.*; -import org.junit.Test; - - -class TestStream extends InputStream { - byte data[]; - int p = 0; - - public TestStream(byte data[]) { - this.data = data; - } - - @Override - public int read() throws IOException { - return p < data.length ? (int)data[p++] & 0xff : -1; - } -} - -public class GIFLoaderTest { - - @Test - public void testCtorNPE() { - try { - new GIFImageLoader2(null); - } catch (NullPointerException ex) { - return; // PASSED - } catch (IOException ioEx) { - fail("unexpected IOException:" + ioEx.toString()); - } - fail("expected NPE after constructor invocation with null"); - } - - - - @Test - public void testCtorReadBadHeader1() { - final byte tooShortHeaderData[] = { - 0,1,2,3,4 - }; - - try { - new GIFImageLoader2(new TestStream(tooShortHeaderData)); - } catch (EOFException ex) { - return; // PASSED - } catch (IOException ioEx) { - fail("unexpected IOException:" + ioEx.toString()); - } - fail("expected EOF exception for streams lesser then 13 bytes"); - } - - @Test - public void testCtorReadBadHeader2() { - final byte tooShortHeaderData[] = { - 'G', 'I', 'F', '8', '9', 'a', - 0, 0, 0, 0, 0, 0 - }; - - try { - new GIFImageLoader2(new TestStream(tooShortHeaderData)); - } catch (EOFException ex) { - return; // PASSED - } catch (IOException ioEx) { - fail("unexpected IOException:" + ioEx.toString()); - } - fail("expected EOF exception for streams lesser then 13 bytes"); - } - - @Test - public void testCtorReadGoodHeader() { - final byte _87HeaderData[] = { - 'G', 'I', 'F', '8', '7', 'a', - 1, 0, 1, 0, 0, 0, 0 - }; - final byte _89HeaderData[] = { - 'G', 'I', 'F', '8', '9', 'a', - 1, 0, 1, 0, 0, 0, 0 - }; - try { - new GIFImageLoader2(new TestStream(_87HeaderData)); - new GIFImageLoader2(new TestStream(_89HeaderData)); - } catch (IOException ioEx) { - ioEx.printStackTrace(System.out); - fail("unexpected IOException:" + ioEx.toString()); - - } - } - - @Test (timeout=2000) - public void testCtorReadBadExtension() { - final byte badGifData[] = { - 'G', 'I', 'F', '8', '9', 'a', - 1, 0, 1, 0, -112, 0, 0, -18, 51, 34, - 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 1, 0, - 0, 2, 2, 4, 1, 43, 48 - }; - - // Create a loader using the data containing a bad GIF extension - GIFImageLoader2 loader = null; - try { - loader = new GIFImageLoader2(new TestStream(badGifData)); - } catch (IOException ioEx) { - fail("unexpected IOException:" + ioEx.toString()); - } - assertNotNull(loader); - - // Now try to load the image; it should get an EOFException - try { - loader.load(0, 1, 1, true, true); - } catch (EOFException ex) { - return; // PASSED - } catch (IOException ioEx) { - fail("unexpected IOException:" + ioEx.toString()); - } - fail("expected EOF exception for streams with bad extension"); - } - - private void compareBGRaAndIndexed(byte dataRGBA[], byte dataIndexed[], int paletteBGRA[]) { - assertEquals(dataIndexed.length*4, dataRGBA.length); - for (int i = 0, j = 0, e = dataIndexed.length; i < e; j += 4, ++i) { - int r = dataRGBA[j+0] & 0xFF, g = dataRGBA[j+1] & 0xFF, - b = dataRGBA[j+2] & 0xFF, a = dataRGBA[j+3] & 0xFF; - int x = b + (g<<8) + (r<<16) + (a<<24); - int y = paletteBGRA[dataIndexed[i] & 0xFF]; - - if ((x != y) && (((x & 0xFF000000) != 0) || ((y & 0xFF000000) != 0))) { - fail("colors are different : JDK: " + Integer.toHexString(y) - + ", JavaFX: " + Integer.toHexString(x)); - } - } - } - - private void compareBGRaAndIndexed(byte dataRGBA[], int dataIndexed[], int paletteBGRA[]) { - assertEquals(dataIndexed.length*4, dataRGBA.length); - for (int i = 0, j = 0, e = dataIndexed.length; i < e; j += 4, ++i) { - int r = dataRGBA[j+0] & 0xFF, g = dataRGBA[j+1] & 0xFF, - b = dataRGBA[j+2] & 0xFF, a = dataRGBA[j+3] & 0xFF; - int x = b + (g<<8) + (r<<16) + (a<<24); - int y = paletteBGRA[dataIndexed[i] & 0xFF]; - if ((x != y) && (((x & 0xFF000000) != 0) || ((y & 0xFF000000) != 0))) { - fail("colors are different : JDK: " + Integer.toHexString(y) - + ", JavaFX: " + Integer.toHexString(x)); - } - } - } - - - private void compareImageFrameAndBImage(ImageFrame f, BufferedImage bimg) { - byte dataRGBA[] = (byte[])f.getImageData().array(); - assertEquals(dataRGBA.length, f.getHeight() * f.getWidth() * 4); - assertEquals(f.getImageType(), ImageStorage.ImageType.RGBA); - - assertEquals(f.getHeight(), bimg.getHeight()); - assertEquals(f.getWidth(), bimg.getWidth()); - - if (bimg.getColorModel() instanceof IndexColorModel) { - IndexColorModel idx = (IndexColorModel)bimg.getColorModel(); - int rgb[] = new int [256]; - idx.getRGBs(rgb); - Raster r = bimg.getData(); - DataBuffer db = r.getDataBuffer(); - assertTrue( db instanceof DataBufferByte); - DataBufferByte bdb = (DataBufferByte)db; - assertEquals(bdb.getNumBanks(), 1); - byte dataIndexed[] = bdb.getData(0); - int bitsPerPixel = idx.getPixelSize(); - if (bitsPerPixel == 8) { - assertEquals(dataIndexed.length, f.getHeight()*f.getWidth()); - compareBGRaAndIndexed(dataRGBA, dataIndexed, rgb); - } else { - int rgbData[] = new int[bimg.getWidth() * bimg.getHeight()]; - r.getPixels(0, 0, bimg.getWidth(), bimg.getHeight(), rgbData); - compareBGRaAndIndexed(dataRGBA, rgbData, rgb); - } - } else { - Raster r = bimg.getData(); -// System.out.println("" + r.getWidth() + "," + r.getHeight() + "," + r.getNumBands() -// + "," + r.getDataBuffer() + "," + r.getSampleModel()); - fail("Unexpected image form AWT"); - } - } - - private void testReadGIFFile(String fname) throws IOException { - InputStream i = this.getClass().getResourceAsStream(fname); - InputStream testStream = ImageTestHelper.createStutteringInputStream(i); - ImageLoader l = new GIFImageLoader2(testStream); - ImageFrame f = l.load(0, 0, 0, true, false); - InputStream i2 = this.getClass().getResourceAsStream(fname); - BufferedImage bimg = javax.imageio.ImageIO.read(i2); - - compareImageFrameAndBImage(f, bimg); - } - - @Test - public void testReadGIFFile() throws Exception { - for (String s : fileList) { - try { - testReadGIFFile(s); - } catch (Exception ex) { - System.err.println("Failure in test file " + s); - throw ex; - } - } - } - -// public static void main(String[] args) throws IOException { -// new GIFLoaderTest().testReadGIFFile(); -// } - - final static String fileList[] = { - "gif/adam_7_interlacing/basi0g01.gif", - "gif/adam_7_interlacing/basi0g02.gif", - "gif/adam_7_interlacing/basi0g04.gif", - "gif/adam_7_interlacing/basi0g08.gif", - "gif/adam_7_interlacing/basi0g16.gif", - "gif/adam_7_interlacing/basi2c08.gif", - "gif/adam_7_interlacing/basi2c16.gif", - "gif/adam_7_interlacing/basi3p01.gif", - "gif/adam_7_interlacing/basi3p02.gif", - "gif/adam_7_interlacing/basi3p04.gif", - "gif/adam_7_interlacing/basi3p08.gif", - "gif/adam_7_interlacing/basi4a08.gif", - "gif/adam_7_interlacing/basi4a16.gif", - "gif/adam_7_interlacing/basi6a08.gif", - "gif/adam_7_interlacing/basi6a16.gif", - "gif/base/basn0g01.gif", - "gif/base/basn0g02.gif", - "gif/base/basn0g04.gif", - "gif/base/basn0g08.gif", - "gif/base/basn0g16.gif", - "gif/base/basn2c08.gif", - "gif/base/basn2c16.gif", - "gif/base/basn3p01.gif", - "gif/base/basn3p02.gif", - "gif/base/basn3p04.gif", - "gif/base/basn3p08.gif", - "gif/base/basn4a08.gif", - "gif/base/basn4a16.gif", - "gif/base/basn6a08.gif", - "gif/base/basn6a16.gif", - "gif/background/bgai4a08.gif", - "gif/background/bgai4a16.gif", - "gif/background/bgan6a08.gif", - "gif/background/bgan6a16.gif", - "gif/background/bgbn4a08.gif", - "gif/background/bggn4a16.gif", - "gif/background/bgwn6a08.gif", - "gif/background/bgyn6a16.gif", - "gif/ancillary_chunks/ccwn2c08.gif", - "gif/ancillary_chunks/ccwn3p08.gif", - "gif/ancillary_chunks/cdfn2c08.gif", - "gif/ancillary_chunks/cdhn2c08.gif", - "gif/ancillary_chunks/cdsn2c08.gif", - "gif/ancillary_chunks/cdun2c08.gif", - "gif/ancillary_chunks/ch1n3p04.gif", - "gif/ancillary_chunks/ch2n3p08.gif", - "gif/ancillary_chunks/cm0n0g04.gif", - "gif/ancillary_chunks/cm7n0g04.gif", - "gif/ancillary_chunks/cm9n0g04.gif", - "gif/ancillary_chunks/cs3n2c16.gif", - "gif/ancillary_chunks/cs3n3p08.gif", - "gif/ancillary_chunks/cs5n2c08.gif", - "gif/ancillary_chunks/cs5n3p08.gif", - "gif/ancillary_chunks/cs8n2c08.gif", - "gif/ancillary_chunks/cs8n3p08.gif", - "gif/ancillary_chunks/ct0n0g04.gif", - "gif/ancillary_chunks/ct1n0g04.gif", - "gif/ancillary_chunks/cten0g04.gif", - "gif/ancillary_chunks/ctfn0g04.gif", - "gif/ancillary_chunks/ctgn0g04.gif", - "gif/ancillary_chunks/cthn0g04.gif", - "gif/ancillary_chunks/ctjn0g04.gif", - "gif/filtering/f00n0g08.gif", - "gif/filtering/f00n2c08.gif", - "gif/filtering/f01n0g08.gif", - "gif/filtering/f01n2c08.gif", - "gif/filtering/f02n0g08.gif", - "gif/filtering/f02n2c08.gif", - "gif/filtering/f03n0g08.gif", - "gif/filtering/f03n2c08.gif", - "gif/filtering/f04n0g08.gif", - "gif/filtering/f04n2c08.gif", - "gif/filtering/f99n0g04.gif", - "gif/gamma/g03n0g16.gif", - "gif/gamma/g03n2c08.gif", - "gif/gamma/g03n3p04.gif", - "gif/gamma/g04n0g16.gif", - "gif/gamma/g04n2c08.gif", - "gif/gamma/g04n3p04.gif", - "gif/gamma/g05n0g16.gif", - "gif/gamma/g05n2c08.gif", - "gif/gamma/g05n3p04.gif", - "gif/gamma/g07n0g16.gif", - "gif/gamma/g07n2c08.gif", - "gif/gamma/g07n3p04.gif", - "gif/gamma/g10n0g16.gif", - "gif/gamma/g10n2c08.gif", - "gif/gamma/g10n3p04.gif", - "gif/gamma/g25n0g16.gif", - "gif/gamma/g25n2c08.gif", - "gif/gamma/g25n3p04.gif", - "gif/chunk_ordering/oi1n0g16.gif", - "gif/chunk_ordering/oi1n2c16.gif", - "gif/chunk_ordering/oi2n0g16.gif", - "gif/chunk_ordering/oi2n2c16.gif", - "gif/chunk_ordering/oi4n0g16.gif", - "gif/chunk_ordering/oi4n2c16.gif", - "gif/chunk_ordering/oi9n0g16.gif", - "gif/chunk_ordering/oi9n2c16.gif", - "gif/add_palets/pp0n2c16.gif", - "gif/add_palets/pp0n6a08.gif", - "gif/add_palets/ps1n0g08.gif", - "gif/add_palets/ps1n2c16.gif", - "gif/add_palets/ps2n0g08.gif", - "gif/add_palets/ps2n2c16.gif", - "gif/odd_sizes/s01i3p01.gif", - "gif/odd_sizes/s01n3p01.gif", - "gif/odd_sizes/s02i3p01.gif", - "gif/odd_sizes/s02n3p01.gif", - "gif/odd_sizes/s03i3p01.gif", - "gif/odd_sizes/s03n3p01.gif", - "gif/odd_sizes/s04i3p01.gif", - "gif/odd_sizes/s04n3p01.gif", - "gif/odd_sizes/s05i3p02.gif", - "gif/odd_sizes/s05n3p02.gif", - "gif/odd_sizes/s06i3p02.gif", - "gif/odd_sizes/s06n3p02.gif", - "gif/odd_sizes/s07i3p02.gif", - "gif/odd_sizes/s07n3p02.gif", - "gif/odd_sizes/s08i3p02.gif", - "gif/odd_sizes/s08n3p02.gif", - "gif/odd_sizes/s09i3p02.gif", - "gif/odd_sizes/s09n3p02.gif", - "gif/odd_sizes/s32i3p04.gif", - "gif/odd_sizes/s32n3p04.gif", - "gif/odd_sizes/s33i3p04.gif", - "gif/odd_sizes/s33n3p04.gif", - "gif/odd_sizes/s34i3p04.gif", - "gif/odd_sizes/s34n3p04.gif", - "gif/odd_sizes/s35i3p04.gif", - "gif/odd_sizes/s35n3p04.gif", - "gif/odd_sizes/s36i3p04.gif", - "gif/odd_sizes/s36n3p04.gif", - "gif/odd_sizes/s37i3p04.gif", - "gif/odd_sizes/s37n3p04.gif", - "gif/odd_sizes/s38i3p04.gif", - "gif/odd_sizes/s38n3p04.gif", - "gif/odd_sizes/s39i3p04.gif", - "gif/odd_sizes/s39n3p04.gif", - "gif/odd_sizes/s40i3p04.gif", - "gif/odd_sizes/s40n3p04.gif", - "gif/transparency/tbbn0g04.gif", - "gif/transparency/tbbn2c16.gif", - "gif/transparency/tbbn3p08.gif", - "gif/transparency/tbgn2c16.gif", - "gif/transparency/tbgn3p08.gif", - "gif/transparency/tbrn2c08.gif", - "gif/transparency/tbwn0g16.gif", - "gif/transparency/tbwn3p08.gif", - "gif/transparency/tbyn3p08.gif", - "gif/transparency/tp0n0g08.gif", - "gif/transparency/tp0n2c08.gif", - "gif/transparency/tp0n3p08.gif", - "gif/transparency/tp1n3p08.gif", - "gif/corrupted/xc1n0g08.gif", - "gif/corrupted/xc9n2c08.gif", - "gif/corrupted/xcrn0g04.gif", - "gif/corrupted/xcsn0g01.gif", - "gif/corrupted/xd0n2c08.gif", - "gif/corrupted/xd3n2c08.gif", - "gif/corrupted/xd9n2c08.gif", - "gif/corrupted/xdtn0g01.gif", - "gif/corrupted/xhdn0g08.gif", - "gif/corrupted/xlfn0g04.gif", - "gif/corrupted/xs1n0g01.gif", - "gif/corrupted/xs2n0g01.gif", - "gif/corrupted/xs4n0g01.gif", - "gif/corrupted/xs7n0g01.gif", - "gif/zlib_compression_level/z00n2c08.gif", - "gif/zlib_compression_level/z03n2c08.gif", - "gif/zlib_compression_level/z06n2c08.gif", - "gif/zlib_compression_level/z09n2c08.gif" - }; -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/iio/GIFLoaderTest.java 2015-09-11 21:23:58.337287283 -0400 @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.iio; + +import com.sun.javafx.iio.ImageFrame; +import com.sun.javafx.iio.ImageLoader; +import com.sun.javafx.iio.ImageStorage; +import com.sun.javafx.iio.gif.GIFImageLoader2; +import java.awt.image.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + + +class TestStream extends InputStream { + byte data[]; + int p = 0; + + public TestStream(byte data[]) { + this.data = data; + } + + @Override + public int read() throws IOException { + return p < data.length ? (int)data[p++] & 0xff : -1; + } +} + +public class GIFLoaderTest { + + @Test + public void testCtorNPE() { + try { + new GIFImageLoader2(null); + } catch (NullPointerException ex) { + return; // PASSED + } catch (IOException ioEx) { + fail("unexpected IOException:" + ioEx.toString()); + } + fail("expected NPE after constructor invocation with null"); + } + + + + @Test + public void testCtorReadBadHeader1() { + final byte tooShortHeaderData[] = { + 0,1,2,3,4 + }; + + try { + new GIFImageLoader2(new TestStream(tooShortHeaderData)); + } catch (EOFException ex) { + return; // PASSED + } catch (IOException ioEx) { + fail("unexpected IOException:" + ioEx.toString()); + } + fail("expected EOF exception for streams lesser then 13 bytes"); + } + + @Test + public void testCtorReadBadHeader2() { + final byte tooShortHeaderData[] = { + 'G', 'I', 'F', '8', '9', 'a', + 0, 0, 0, 0, 0, 0 + }; + + try { + new GIFImageLoader2(new TestStream(tooShortHeaderData)); + } catch (EOFException ex) { + return; // PASSED + } catch (IOException ioEx) { + fail("unexpected IOException:" + ioEx.toString()); + } + fail("expected EOF exception for streams lesser then 13 bytes"); + } + + @Test + public void testCtorReadGoodHeader() { + final byte _87HeaderData[] = { + 'G', 'I', 'F', '8', '7', 'a', + 1, 0, 1, 0, 0, 0, 0 + }; + final byte _89HeaderData[] = { + 'G', 'I', 'F', '8', '9', 'a', + 1, 0, 1, 0, 0, 0, 0 + }; + try { + new GIFImageLoader2(new TestStream(_87HeaderData)); + new GIFImageLoader2(new TestStream(_89HeaderData)); + } catch (IOException ioEx) { + ioEx.printStackTrace(System.out); + fail("unexpected IOException:" + ioEx.toString()); + + } + } + + @Test (timeout=2000) + public void testCtorReadBadExtension() { + final byte badGifData[] = { + 'G', 'I', 'F', '8', '9', 'a', + 1, 0, 1, 0, -112, 0, 0, -18, 51, 34, + 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 2, 2, 4, 1, 43, 48 + }; + + // Create a loader using the data containing a bad GIF extension + GIFImageLoader2 loader = null; + try { + loader = new GIFImageLoader2(new TestStream(badGifData)); + } catch (IOException ioEx) { + fail("unexpected IOException:" + ioEx.toString()); + } + assertNotNull(loader); + + // Now try to load the image; it should get an EOFException + try { + loader.load(0, 1, 1, true, true); + } catch (EOFException ex) { + return; // PASSED + } catch (IOException ioEx) { + fail("unexpected IOException:" + ioEx.toString()); + } + fail("expected EOF exception for streams with bad extension"); + } + + private void compareBGRaAndIndexed(byte dataRGBA[], byte dataIndexed[], int paletteBGRA[]) { + assertEquals(dataIndexed.length*4, dataRGBA.length); + for (int i = 0, j = 0, e = dataIndexed.length; i < e; j += 4, ++i) { + int r = dataRGBA[j+0] & 0xFF, g = dataRGBA[j+1] & 0xFF, + b = dataRGBA[j+2] & 0xFF, a = dataRGBA[j+3] & 0xFF; + int x = b + (g<<8) + (r<<16) + (a<<24); + int y = paletteBGRA[dataIndexed[i] & 0xFF]; + + if ((x != y) && (((x & 0xFF000000) != 0) || ((y & 0xFF000000) != 0))) { + fail("colors are different : JDK: " + Integer.toHexString(y) + + ", JavaFX: " + Integer.toHexString(x)); + } + } + } + + private void compareBGRaAndIndexed(byte dataRGBA[], int dataIndexed[], int paletteBGRA[]) { + assertEquals(dataIndexed.length*4, dataRGBA.length); + for (int i = 0, j = 0, e = dataIndexed.length; i < e; j += 4, ++i) { + int r = dataRGBA[j+0] & 0xFF, g = dataRGBA[j+1] & 0xFF, + b = dataRGBA[j+2] & 0xFF, a = dataRGBA[j+3] & 0xFF; + int x = b + (g<<8) + (r<<16) + (a<<24); + int y = paletteBGRA[dataIndexed[i] & 0xFF]; + if ((x != y) && (((x & 0xFF000000) != 0) || ((y & 0xFF000000) != 0))) { + fail("colors are different : JDK: " + Integer.toHexString(y) + + ", JavaFX: " + Integer.toHexString(x)); + } + } + } + + + private void compareImageFrameAndBImage(ImageFrame f, BufferedImage bimg) { + byte dataRGBA[] = (byte[])f.getImageData().array(); + assertEquals(dataRGBA.length, f.getHeight() * f.getWidth() * 4); + assertEquals(f.getImageType(), ImageStorage.ImageType.RGBA); + + assertEquals(f.getHeight(), bimg.getHeight()); + assertEquals(f.getWidth(), bimg.getWidth()); + + if (bimg.getColorModel() instanceof IndexColorModel) { + IndexColorModel idx = (IndexColorModel)bimg.getColorModel(); + int rgb[] = new int [256]; + idx.getRGBs(rgb); + Raster r = bimg.getData(); + DataBuffer db = r.getDataBuffer(); + assertTrue( db instanceof DataBufferByte); + DataBufferByte bdb = (DataBufferByte)db; + assertEquals(bdb.getNumBanks(), 1); + byte dataIndexed[] = bdb.getData(0); + int bitsPerPixel = idx.getPixelSize(); + if (bitsPerPixel == 8) { + assertEquals(dataIndexed.length, f.getHeight()*f.getWidth()); + compareBGRaAndIndexed(dataRGBA, dataIndexed, rgb); + } else { + int rgbData[] = new int[bimg.getWidth() * bimg.getHeight()]; + r.getPixels(0, 0, bimg.getWidth(), bimg.getHeight(), rgbData); + compareBGRaAndIndexed(dataRGBA, rgbData, rgb); + } + } else { + Raster r = bimg.getData(); +// System.out.println("" + r.getWidth() + "," + r.getHeight() + "," + r.getNumBands() +// + "," + r.getDataBuffer() + "," + r.getSampleModel()); + fail("Unexpected image form AWT"); + } + } + + private void testReadGIFFile(String fname) throws IOException { + InputStream i = this.getClass().getResourceAsStream(fname); + InputStream testStream = ImageTestHelper.createStutteringInputStream(i); + ImageLoader l = new GIFImageLoader2(testStream); + ImageFrame f = l.load(0, 0, 0, true, false); + InputStream i2 = this.getClass().getResourceAsStream(fname); + BufferedImage bimg = javax.imageio.ImageIO.read(i2); + + compareImageFrameAndBImage(f, bimg); + } + + @Test + public void testReadGIFFile() throws Exception { + for (String s : fileList) { + try { + testReadGIFFile(s); + } catch (Exception ex) { + System.err.println("Failure in test file " + s); + throw ex; + } + } + } + +// public static void main(String[] args) throws IOException { +// new GIFLoaderTest().testReadGIFFile(); +// } + + final static String fileList[] = { + "gif/adam_7_interlacing/basi0g01.gif", + "gif/adam_7_interlacing/basi0g02.gif", + "gif/adam_7_interlacing/basi0g04.gif", + "gif/adam_7_interlacing/basi0g08.gif", + "gif/adam_7_interlacing/basi0g16.gif", + "gif/adam_7_interlacing/basi2c08.gif", + "gif/adam_7_interlacing/basi2c16.gif", + "gif/adam_7_interlacing/basi3p01.gif", + "gif/adam_7_interlacing/basi3p02.gif", + "gif/adam_7_interlacing/basi3p04.gif", + "gif/adam_7_interlacing/basi3p08.gif", + "gif/adam_7_interlacing/basi4a08.gif", + "gif/adam_7_interlacing/basi4a16.gif", + "gif/adam_7_interlacing/basi6a08.gif", + "gif/adam_7_interlacing/basi6a16.gif", + "gif/base/basn0g01.gif", + "gif/base/basn0g02.gif", + "gif/base/basn0g04.gif", + "gif/base/basn0g08.gif", + "gif/base/basn0g16.gif", + "gif/base/basn2c08.gif", + "gif/base/basn2c16.gif", + "gif/base/basn3p01.gif", + "gif/base/basn3p02.gif", + "gif/base/basn3p04.gif", + "gif/base/basn3p08.gif", + "gif/base/basn4a08.gif", + "gif/base/basn4a16.gif", + "gif/base/basn6a08.gif", + "gif/base/basn6a16.gif", + "gif/background/bgai4a08.gif", + "gif/background/bgai4a16.gif", + "gif/background/bgan6a08.gif", + "gif/background/bgan6a16.gif", + "gif/background/bgbn4a08.gif", + "gif/background/bggn4a16.gif", + "gif/background/bgwn6a08.gif", + "gif/background/bgyn6a16.gif", + "gif/ancillary_chunks/ccwn2c08.gif", + "gif/ancillary_chunks/ccwn3p08.gif", + "gif/ancillary_chunks/cdfn2c08.gif", + "gif/ancillary_chunks/cdhn2c08.gif", + "gif/ancillary_chunks/cdsn2c08.gif", + "gif/ancillary_chunks/cdun2c08.gif", + "gif/ancillary_chunks/ch1n3p04.gif", + "gif/ancillary_chunks/ch2n3p08.gif", + "gif/ancillary_chunks/cm0n0g04.gif", + "gif/ancillary_chunks/cm7n0g04.gif", + "gif/ancillary_chunks/cm9n0g04.gif", + "gif/ancillary_chunks/cs3n2c16.gif", + "gif/ancillary_chunks/cs3n3p08.gif", + "gif/ancillary_chunks/cs5n2c08.gif", + "gif/ancillary_chunks/cs5n3p08.gif", + "gif/ancillary_chunks/cs8n2c08.gif", + "gif/ancillary_chunks/cs8n3p08.gif", + "gif/ancillary_chunks/ct0n0g04.gif", + "gif/ancillary_chunks/ct1n0g04.gif", + "gif/ancillary_chunks/cten0g04.gif", + "gif/ancillary_chunks/ctfn0g04.gif", + "gif/ancillary_chunks/ctgn0g04.gif", + "gif/ancillary_chunks/cthn0g04.gif", + "gif/ancillary_chunks/ctjn0g04.gif", + "gif/filtering/f00n0g08.gif", + "gif/filtering/f00n2c08.gif", + "gif/filtering/f01n0g08.gif", + "gif/filtering/f01n2c08.gif", + "gif/filtering/f02n0g08.gif", + "gif/filtering/f02n2c08.gif", + "gif/filtering/f03n0g08.gif", + "gif/filtering/f03n2c08.gif", + "gif/filtering/f04n0g08.gif", + "gif/filtering/f04n2c08.gif", + "gif/filtering/f99n0g04.gif", + "gif/gamma/g03n0g16.gif", + "gif/gamma/g03n2c08.gif", + "gif/gamma/g03n3p04.gif", + "gif/gamma/g04n0g16.gif", + "gif/gamma/g04n2c08.gif", + "gif/gamma/g04n3p04.gif", + "gif/gamma/g05n0g16.gif", + "gif/gamma/g05n2c08.gif", + "gif/gamma/g05n3p04.gif", + "gif/gamma/g07n0g16.gif", + "gif/gamma/g07n2c08.gif", + "gif/gamma/g07n3p04.gif", + "gif/gamma/g10n0g16.gif", + "gif/gamma/g10n2c08.gif", + "gif/gamma/g10n3p04.gif", + "gif/gamma/g25n0g16.gif", + "gif/gamma/g25n2c08.gif", + "gif/gamma/g25n3p04.gif", + "gif/chunk_ordering/oi1n0g16.gif", + "gif/chunk_ordering/oi1n2c16.gif", + "gif/chunk_ordering/oi2n0g16.gif", + "gif/chunk_ordering/oi2n2c16.gif", + "gif/chunk_ordering/oi4n0g16.gif", + "gif/chunk_ordering/oi4n2c16.gif", + "gif/chunk_ordering/oi9n0g16.gif", + "gif/chunk_ordering/oi9n2c16.gif", + "gif/add_palets/pp0n2c16.gif", + "gif/add_palets/pp0n6a08.gif", + "gif/add_palets/ps1n0g08.gif", + "gif/add_palets/ps1n2c16.gif", + "gif/add_palets/ps2n0g08.gif", + "gif/add_palets/ps2n2c16.gif", + "gif/odd_sizes/s01i3p01.gif", + "gif/odd_sizes/s01n3p01.gif", + "gif/odd_sizes/s02i3p01.gif", + "gif/odd_sizes/s02n3p01.gif", + "gif/odd_sizes/s03i3p01.gif", + "gif/odd_sizes/s03n3p01.gif", + "gif/odd_sizes/s04i3p01.gif", + "gif/odd_sizes/s04n3p01.gif", + "gif/odd_sizes/s05i3p02.gif", + "gif/odd_sizes/s05n3p02.gif", + "gif/odd_sizes/s06i3p02.gif", + "gif/odd_sizes/s06n3p02.gif", + "gif/odd_sizes/s07i3p02.gif", + "gif/odd_sizes/s07n3p02.gif", + "gif/odd_sizes/s08i3p02.gif", + "gif/odd_sizes/s08n3p02.gif", + "gif/odd_sizes/s09i3p02.gif", + "gif/odd_sizes/s09n3p02.gif", + "gif/odd_sizes/s32i3p04.gif", + "gif/odd_sizes/s32n3p04.gif", + "gif/odd_sizes/s33i3p04.gif", + "gif/odd_sizes/s33n3p04.gif", + "gif/odd_sizes/s34i3p04.gif", + "gif/odd_sizes/s34n3p04.gif", + "gif/odd_sizes/s35i3p04.gif", + "gif/odd_sizes/s35n3p04.gif", + "gif/odd_sizes/s36i3p04.gif", + "gif/odd_sizes/s36n3p04.gif", + "gif/odd_sizes/s37i3p04.gif", + "gif/odd_sizes/s37n3p04.gif", + "gif/odd_sizes/s38i3p04.gif", + "gif/odd_sizes/s38n3p04.gif", + "gif/odd_sizes/s39i3p04.gif", + "gif/odd_sizes/s39n3p04.gif", + "gif/odd_sizes/s40i3p04.gif", + "gif/odd_sizes/s40n3p04.gif", + "gif/transparency/tbbn0g04.gif", + "gif/transparency/tbbn2c16.gif", + "gif/transparency/tbbn3p08.gif", + "gif/transparency/tbgn2c16.gif", + "gif/transparency/tbgn3p08.gif", + "gif/transparency/tbrn2c08.gif", + "gif/transparency/tbwn0g16.gif", + "gif/transparency/tbwn3p08.gif", + "gif/transparency/tbyn3p08.gif", + "gif/transparency/tp0n0g08.gif", + "gif/transparency/tp0n2c08.gif", + "gif/transparency/tp0n3p08.gif", + "gif/transparency/tp1n3p08.gif", + "gif/corrupted/xc1n0g08.gif", + "gif/corrupted/xc9n2c08.gif", + "gif/corrupted/xcrn0g04.gif", + "gif/corrupted/xcsn0g01.gif", + "gif/corrupted/xd0n2c08.gif", + "gif/corrupted/xd3n2c08.gif", + "gif/corrupted/xd9n2c08.gif", + "gif/corrupted/xdtn0g01.gif", + "gif/corrupted/xhdn0g08.gif", + "gif/corrupted/xlfn0g04.gif", + "gif/corrupted/xs1n0g01.gif", + "gif/corrupted/xs2n0g01.gif", + "gif/corrupted/xs4n0g01.gif", + "gif/corrupted/xs7n0g01.gif", + "gif/zlib_compression_level/z00n2c08.gif", + "gif/zlib_compression_level/z03n2c08.gif", + "gif/zlib_compression_level/z06n2c08.gif", + "gif/zlib_compression_level/z09n2c08.gif" + }; +} --- old/modules/graphics/src/test/java/com/sun/javafx/iio/ImageLoaderScalingTest.java 2015-09-11 21:23:59.269287272 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,196 +0,0 @@ -/* - * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.iio; - -import com.sun.prism.Image; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import static org.junit.Assert.*; -import org.junit.Ignore; -import org.junit.Test; - -public class ImageLoaderScalingTest { - // if true, the test will write original and scaled PNG files to the current directory - private static final boolean writeFiles = false; - - private BufferedImage createImage(int w, int h) { - BufferedImage bImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); - ImageTestHelper.drawImageRandom(bImg); - return bImg; - } - - private Image loadImage(InputStream stream, int width, int height) - throws Exception - { - ImageFrame[] imgFrames = - ImageStorage.loadAll(stream, null, width, height, false, 1.0f, false); - assertNotNull(imgFrames); - assertTrue(imgFrames.length > 0); - return Image.convertImageFrame(imgFrames[0]); - } - - private void compare(Image img, Image expectedImg) { - assertNotNull(img); - assertNotNull(expectedImg); - int w = img.getWidth(), h = img.getHeight(); - double scaleX = (double)expectedImg.getWidth() / w; - double scaleY = (double)expectedImg.getHeight() / h; - for (int y = 0; y < h; y++) { - int srcY = (int) Math.floor((y + 0.5) * scaleY); - for (int x = 0; x < w; x++) { - int srcX = (int) Math.floor((x + 0.5) * scaleX); - int expected = expectedImg.getArgb(srcX, srcY); - int actual = img.getArgb(x, y); - if (expected != actual) { - if (writeFiles) { - writeImages(img, expectedImg); - } - throw new org.junit.ComparisonFailure( - "pixel " + x + ", " + y + " does not match", - String.format("0x%08X", expected), - String.format("0x%08X", actual) - ); - } - } - } - } - - private void writeImage(Image img, String fileName) { - int w = img.getWidth(); - int h = img.getHeight(); - int pixels[] = new int[w * h]; - img.getPixels(0, 0, w, h, - javafx.scene.image.PixelFormat.getIntArgbPreInstance(), - pixels, 0, w); - BufferedImage bImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); - bImg.setRGB(0, 0, w, h, pixels, 0, w); - try { - ImageTestHelper.writeImage(bImg, fileName, "png", null); - } catch (IOException e) { - System.err.println("writeImage " + fileName + " failed: " + e); - } - } - - private void writeImages(Image img, Image expectedImg) { - int w = img.getWidth(); - int h = img.getHeight(); - writeImage(expectedImg, "out"+w+"x"+h+"Orig.png"); - writeImage(img, "out"+w+"x"+h+"Scaled.png"); - } - - private void scaleAndCompareImage(BufferedImage bImg, String format, - int width, int height) throws Exception - { - ByteArrayInputStream in = ImageTestHelper.writeImageToStream(bImg, format, null); - Image expectedImg = loadImage(in, 0, 0); - in.reset(); - Image img = loadImage(in, width, height); - compare(img, expectedImg); - } - - private void testScale(String format, int srcW, int srcH, int dstW, int dstH) throws Exception { - BufferedImage bImg = createImage(srcW, srcH); - scaleAndCompareImage(bImg, format, dstW, dstH); - } - - @Test - public void testNoScalePNG() throws Exception { - testScale("png", 100, 100, 0, 0); - testScale("png", 100, 100, 100, 100); - } - - @Test - public void testNoScaleBMP() throws Exception { - testScale("bmp", 100, 100, 0, 0); - testScale("bmp", 100, 100, 100, 100); - } - - @Test - public void testNoScaleJPG() throws Exception { - testScale("jpg", 100, 100, 0, 0); - testScale("jpg", 100, 100, 100, 100); - } - - @Test - public void testNoScaleGIF() throws Exception { - testScale("gif", 100, 100, 0, 0); - testScale("gif", 100, 100, 100, 100); - } - - @Test - public void testAllTheScalesPNG() throws Exception { - testAllTheScales("png"); - } - - @Test - public void testAllTheScalesBMP() throws Exception { - testAllTheScales("bmp"); - } - - @Ignore // libjpeg can scale the image itself and results are unpredictable - @Test - public void testAllTheScalesJPG() throws Exception { - testAllTheScales("jpg"); - } - - @Test - public void testAllTheScalesGIF() throws Exception { - testAllTheScales("gif"); - } - - public void testAllTheScales(String format) throws Exception { - BufferedImage bImg = createImage(10, 10); - for (int h = 2; h < 20; h++) { - for (int w = 2; w < 20; w++) { - scaleAndCompareImage(bImg, format, w, h); - testScale(format, w, h, 10, 10); - } - } - } - - // (62.0 / 78.0) * 78 != 62 - @Test - public void testRT20295_PNG() throws Exception { - testScale("png", 100, 62, 100, 78); - } - - @Test - public void testRT20295_BMP() throws Exception { - testScale("bmp", 100, 62, 100, 78); - } - - @Test - public void testRT20295_JPG() throws Exception { - testScale("jpg", 100, 62, 100, 78); - } - - @Test - public void testRT20295_GIF() throws Exception { - testScale("gif", 100, 62, 100, 78); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/iio/ImageLoaderScalingTest.java 2015-09-11 21:23:59.097287274 -0400 @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.iio; + +import com.sun.javafx.iio.ImageFrame; +import com.sun.javafx.iio.ImageStorage; +import com.sun.prism.Image; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import static org.junit.Assert.*; +import org.junit.Ignore; +import org.junit.Test; + +public class ImageLoaderScalingTest { + // if true, the test will write original and scaled PNG files to the current directory + private static final boolean writeFiles = false; + + private BufferedImage createImage(int w, int h) { + BufferedImage bImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + ImageTestHelper.drawImageRandom(bImg); + return bImg; + } + + private Image loadImage(InputStream stream, int width, int height) + throws Exception + { + ImageFrame[] imgFrames = + ImageStorage.loadAll(stream, null, width, height, false, 1.0f, false); + assertNotNull(imgFrames); + assertTrue(imgFrames.length > 0); + return Image.convertImageFrame(imgFrames[0]); + } + + private void compare(Image img, Image expectedImg) { + assertNotNull(img); + assertNotNull(expectedImg); + int w = img.getWidth(), h = img.getHeight(); + double scaleX = (double)expectedImg.getWidth() / w; + double scaleY = (double)expectedImg.getHeight() / h; + for (int y = 0; y < h; y++) { + int srcY = (int) Math.floor((y + 0.5) * scaleY); + for (int x = 0; x < w; x++) { + int srcX = (int) Math.floor((x + 0.5) * scaleX); + int expected = expectedImg.getArgb(srcX, srcY); + int actual = img.getArgb(x, y); + if (expected != actual) { + if (writeFiles) { + writeImages(img, expectedImg); + } + throw new org.junit.ComparisonFailure( + "pixel " + x + ", " + y + " does not match", + String.format("0x%08X", expected), + String.format("0x%08X", actual) + ); + } + } + } + } + + private void writeImage(Image img, String fileName) { + int w = img.getWidth(); + int h = img.getHeight(); + int pixels[] = new int[w * h]; + img.getPixels(0, 0, w, h, + javafx.scene.image.PixelFormat.getIntArgbPreInstance(), + pixels, 0, w); + BufferedImage bImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + bImg.setRGB(0, 0, w, h, pixels, 0, w); + try { + ImageTestHelper.writeImage(bImg, fileName, "png", null); + } catch (IOException e) { + System.err.println("writeImage " + fileName + " failed: " + e); + } + } + + private void writeImages(Image img, Image expectedImg) { + int w = img.getWidth(); + int h = img.getHeight(); + writeImage(expectedImg, "out"+w+"x"+h+"Orig.png"); + writeImage(img, "out"+w+"x"+h+"Scaled.png"); + } + + private void scaleAndCompareImage(BufferedImage bImg, String format, + int width, int height) throws Exception + { + ByteArrayInputStream in = ImageTestHelper.writeImageToStream(bImg, format, null); + Image expectedImg = loadImage(in, 0, 0); + in.reset(); + Image img = loadImage(in, width, height); + compare(img, expectedImg); + } + + private void testScale(String format, int srcW, int srcH, int dstW, int dstH) throws Exception { + BufferedImage bImg = createImage(srcW, srcH); + scaleAndCompareImage(bImg, format, dstW, dstH); + } + + @Test + public void testNoScalePNG() throws Exception { + testScale("png", 100, 100, 0, 0); + testScale("png", 100, 100, 100, 100); + } + + @Test + public void testNoScaleBMP() throws Exception { + testScale("bmp", 100, 100, 0, 0); + testScale("bmp", 100, 100, 100, 100); + } + + @Test + public void testNoScaleJPG() throws Exception { + testScale("jpg", 100, 100, 0, 0); + testScale("jpg", 100, 100, 100, 100); + } + + @Test + public void testNoScaleGIF() throws Exception { + testScale("gif", 100, 100, 0, 0); + testScale("gif", 100, 100, 100, 100); + } + + @Test + public void testAllTheScalesPNG() throws Exception { + testAllTheScales("png"); + } + + @Test + public void testAllTheScalesBMP() throws Exception { + testAllTheScales("bmp"); + } + + @Ignore // libjpeg can scale the image itself and results are unpredictable + @Test + public void testAllTheScalesJPG() throws Exception { + testAllTheScales("jpg"); + } + + @Test + public void testAllTheScalesGIF() throws Exception { + testAllTheScales("gif"); + } + + public void testAllTheScales(String format) throws Exception { + BufferedImage bImg = createImage(10, 10); + for (int h = 2; h < 20; h++) { + for (int w = 2; w < 20; w++) { + scaleAndCompareImage(bImg, format, w, h); + testScale(format, w, h, 10, 10); + } + } + } + + // (62.0 / 78.0) * 78 != 62 + @Test + public void testRT20295_PNG() throws Exception { + testScale("png", 100, 62, 100, 78); + } + + @Test + public void testRT20295_BMP() throws Exception { + testScale("bmp", 100, 62, 100, 78); + } + + @Test + public void testRT20295_JPG() throws Exception { + testScale("jpg", 100, 62, 100, 78); + } + + @Test + public void testRT20295_GIF() throws Exception { + testScale("gif", 100, 62, 100, 78); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/iio/ImageStorageTest.java 2015-09-11 21:23:59.901287265 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.iio; - -import com.sun.javafx.iio.common.ImageTools; -import static org.junit.Assert.*; -import org.junit.ComparisonFailure; -import org.junit.Test; - -public class ImageStorageTest { - private String getResourcePath(String path) { - return this.getClass().getResource(path).toString(); - } - - @Test - public void createImageFromNoExtensionURL() throws ImageStorageException { - String path = getResourcePath("testpngnoextension"); - assertNotNull(ImageStorage.loadAll(path, null, 0, 0, true, 2.0f, true)); - } - - @Test - public void testImageNames() { - String [][]imageNames = new String[][] { - { "image", "image@2x" }, - { "image.ext", "image@2x.ext" }, - { "dir/image", "dir/image@2x" }, - { "/dir.ext/image.ext", "/dir.ext/image@2x.ext" }, - { "file:image", "file:image@2x" }, - { "file:image.ext", "file:image@2x.ext" }, - { "http://test.com/image", "http://test.com/image@2x" }, - { "http://test.com/dir.ext/image", "http://test.com/dir.ext/image@2x" }, - { "http://test.com/image.ext", "http://test.com/image@2x.ext" }, - { "http://test.com/dir.ext/image.ext", "http://test.com/dir.ext/image@2x.ext" }, - }; - for (String[] names : imageNames) { - String name2x = ImageTools.getScaledImageName(names[0]); - if (name2x.equals(names[1])) continue; - throw new ComparisonFailure("Scaled image names don't match", names[1], name2x); - } - } - - @Test - public void testCompleteAnimation() throws ImageStorageException { - String path = getResourcePath("gif/animation/test3Frames.gif"); - ImageFrame[] frames = ImageStorage.loadAll(path, null, 0, 0, true, 1.0f, true); - assertEquals(frames.length, 3); - } - - @Test - public void testIncompleteAnimation() throws ImageStorageException { - String path = getResourcePath("gif/animation/test3rdFrameIncomplete.gif"); - ImageFrame[] frames = ImageStorage.loadAll(path, null, 0, 0, true, 1.0f, true); - assertEquals(frames.length, 2); - } - - @Test(expected = ImageStorageException.class) - public void testCorruptFirstFrame() throws ImageStorageException { - String path = getResourcePath("gif/animation/testBad.gif"); - ImageStorage.loadAll(path, null, 0, 0, false, 1.0f, false); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/iio/ImageStorageTest.java 2015-09-11 21:23:59.765287267 -0400 @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.iio; + +import com.sun.javafx.iio.ImageFrame; +import com.sun.javafx.iio.ImageStorage; +import com.sun.javafx.iio.ImageStorageException; +import com.sun.javafx.iio.common.ImageTools; +import static org.junit.Assert.*; +import org.junit.ComparisonFailure; +import org.junit.Test; + +public class ImageStorageTest { + private String getResourcePath(String path) { + return this.getClass().getResource(path).toString(); + } + + @Test + public void createImageFromNoExtensionURL() throws ImageStorageException { + String path = getResourcePath("testpngnoextension"); + assertNotNull(ImageStorage.loadAll(path, null, 0, 0, true, 2.0f, true)); + } + + @Test + public void testImageNames() { + String [][]imageNames = new String[][] { + { "image", "image@2x" }, + { "image.ext", "image@2x.ext" }, + { "dir/image", "dir/image@2x" }, + { "/dir.ext/image.ext", "/dir.ext/image@2x.ext" }, + { "file:image", "file:image@2x" }, + { "file:image.ext", "file:image@2x.ext" }, + { "http://test.com/image", "http://test.com/image@2x" }, + { "http://test.com/dir.ext/image", "http://test.com/dir.ext/image@2x" }, + { "http://test.com/image.ext", "http://test.com/image@2x.ext" }, + { "http://test.com/dir.ext/image.ext", "http://test.com/dir.ext/image@2x.ext" }, + }; + for (String[] names : imageNames) { + String name2x = ImageTools.getScaledImageName(names[0]); + if (name2x.equals(names[1])) continue; + throw new ComparisonFailure("Scaled image names don't match", names[1], name2x); + } + } + + @Test + public void testCompleteAnimation() throws ImageStorageException { + String path = getResourcePath("gif/animation/test3Frames.gif"); + ImageFrame[] frames = ImageStorage.loadAll(path, null, 0, 0, true, 1.0f, true); + assertEquals(frames.length, 3); + } + + @Test + public void testIncompleteAnimation() throws ImageStorageException { + String path = getResourcePath("gif/animation/test3rdFrameIncomplete.gif"); + ImageFrame[] frames = ImageStorage.loadAll(path, null, 0, 0, true, 1.0f, true); + assertEquals(frames.length, 2); + } + + @Test(expected = ImageStorageException.class) + public void testCorruptFirstFrame() throws ImageStorageException { + String path = getResourcePath("gif/animation/testBad.gif"); + ImageStorage.loadAll(path, null, 0, 0, false, 1.0f, false); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/iio/ImageStorageTest.java.DISABLED 2015-09-11 21:24:00.581287258 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,408 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.iio; - -import java.awt.Canvas; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.Graphics; -import java.awt.Image; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferByte; -import java.io.IOException; -import java.nio.ByteBuffer; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * - * @author bpb - */ -public class ImageStorageTest { - - private static final boolean WRITE_OUTPUT = false; - - private static final float MINIFY_FRACTION = 0.57F; - private static final float MAGNIFY_FRACTION = 1.47F; - - private static int rawWidth = -1; - private static int rawHeight = -1; - - public static final void main(String[] args) throws Throwable { - String input = args[0]; - String output = null; - if (args.length > 1) { - output = args[1]; - } - ImageStorageTest test = new ImageStorageTest(); - int width = 111; - int height = 97; - boolean preserveAspectRatio = true; - boolean smooth = true; - test.loadAllTest(input, output, width, height, preserveAspectRatio, smooth); - Thread.sleep(3000); - System.exit(0); - } - - public static final BufferedImage getAsBufferedImage(ImageFrame frame) { - BufferedImage image = null; - int width = frame.getWidth(); - int height = frame.getHeight(); - int scanlineStride = frame.getStride(); - ByteBuffer bbuf = (ByteBuffer) frame.getImageData(); - byte[] pixels = null; - if (bbuf.hasArray()) { - pixels = bbuf.array(); - } else { - pixels = new byte[bbuf.capacity()]; - bbuf.get(pixels); - } - switch (frame.getImageType()) { - case GRAY: { - image = new BufferedImage(width, height, - BufferedImage.TYPE_BYTE_GRAY); - DataBufferByte db = - (DataBufferByte) image.getRaster().getDataBuffer(); - byte[] data = db.getData(); - int inLine = 0; - int outLine = 0; - for (int y = 0; y < height; y++) { - System.arraycopy(pixels, inLine, data, outLine, width); - inLine += scanlineStride; - outLine += width; - } - - } - break; -// case PALETTE: -// case PALETTE_ALPHA: { -// byte[][] p = frame.getPalette(); -// IndexColorModel icm = -// frame.getImageType() == ImageType.PALETTE ? new IndexColorModel(8, p[0].length, -// p[0], p[1], p[2]) : new IndexColorModel(8, p[0].length, -// p[0], p[1], p[2], p[3]); -// image = new BufferedImage(width, height, -// BufferedImage.TYPE_BYTE_INDEXED, icm); -// DataBufferByte db = -// (DataBufferByte) image.getRaster().getDataBuffer(); -// byte[] data = db.getData(); -// int inLine = 0; -// int outLine = 0; -// for (int y = 0; y < height; y++) { -// System.arraycopy(pixels, inLine, data, outLine, width); -// inLine += scanlineStride; -// outLine += width; -// } -// } -// break; - case RGB: { - image = new BufferedImage(width, height, - BufferedImage.TYPE_3BYTE_BGR); - for (int y = 0; y < height; y++) { - int off = y * scanlineStride; - for (int x = 0; x < width; x++) { - int rgb = ((pixels[off++] & 0xff) << 16) | - ((pixels[off++] & 0xff) << 8) | - (pixels[off++] & 0xff); - image.setRGB(x, y, rgb); - } - } - } - break; - case RGBA_PRE: { - image = new BufferedImage(width, height, - BufferedImage.TYPE_INT_ARGB_PRE); - for (int y = 0; y < height; y++) { - int off = y * scanlineStride; - for (int x = 0; x < width; x++) { - byte red = pixels[off++]; - byte green = pixels[off++]; - byte blue = pixels[off++]; - byte alpha = pixels[off++]; -// float f = alpha/255.0F; -// red = (byte)((red & 0xff)/f); -// green = (byte)((green & 0xff)/f); -// blue = (byte)((blue & 0xff)/f); - int rgb = ((alpha & 0xff) << 24) | - ((red & 0xff) << 16) | - ((green & 0xff) << 8) | - (blue & 0xff); - image.setRGB(x, y, rgb); - } - } -// DataBufferByte db = -// (DataBufferByte) image.getRaster().getDataBuffer(); -// byte[] data = db.getData(); -// for (int y = 0; y < height; y++) { -// int offPrism = y * scanlineStride; -// int offImage = y * width * 4; -// for (int x = 0; x < width; x++) { -// data[offImage++] = pixels[offPrism + 3]; // A -// data[offImage++] = pixels[offPrism + 2]; // B -// data[offImage++] = pixels[offPrism + 1]; // G -// data[offImage++] = pixels[offPrism]; // R -// offPrism += 4; -// } -// } - } - break; - default: - throw new UnsupportedOperationException("Unsupported test case " + - frame.getImageType()); - } - - return image; - } - - public static void show(Image img, String label) { - final Frame f = new Frame(); - f.addWindowListener(new WindowAdapter() { - - public void windowClosing(WindowEvent e) { - f.setVisible(false); - f.dispose(); - } - }); - f.setTitle(label); - f.add(new ImageCanvas(img)); - f.pack(); - f.setVisible(true); - } - - public static class ImageCanvas extends Canvas { - - private static final long serialVersionUID = 1L; - Image image; - - public ImageCanvas(Image img) { - this.image = img; - } - - public Dimension getPreferredSize() { - return new Dimension(image.getWidth(null), image.getHeight(null)); - } - - public void paint(Graphics g) { - g.drawImage(image, 0, 0, this); - } - } - - public ImageStorageTest() { - } - - @BeforeClass - public static void setUpClass() throws Exception { - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - @Before - public void setUp() { - } - - @After - public void tearDown() { - } - - /** - * Test of loadAll method, of class ImageStorage. - */ - @Test - public void testLoadRaw() throws IOException, InterruptedException { - loadTest("testLoadRaw", "Output", 0, 0, false, false); - } - - /** - * Test of loadAll method, of class ImageStorage. - */ - @Test - public void testLoadMagnifyNoAspectRough() throws IOException, InterruptedException { - loadTest("testLoadMagnifyNoAspectRough", "Output_scaled", - (int)(MAGNIFY_FRACTION*rawHeight), (int)(MAGNIFY_FRACTION*rawWidth), - false, false); - } - - /** - * Test of loadAll method, of class ImageStorage. - */ - @Test - public void testLoadMagnifyAspectRough() throws IOException, InterruptedException { - loadTest("testLoadMagnifyAspectRough", "Output_scaled", - (int)(MAGNIFY_FRACTION*rawHeight), (int)(MAGNIFY_FRACTION*rawWidth), - true, false); - } - - /** - * Test of loadAll method, of class ImageStorage. - */ - @Test - public void testLoadMagnifyNoAspectSmooth() throws IOException, InterruptedException { - loadTest("testLoadMagnifyNoAspectSmooth", "Output_scaled", - (int)(MAGNIFY_FRACTION*rawHeight), (int)(MAGNIFY_FRACTION*rawWidth), - false, true); - } - - /** - * Test of loadAll method, of class ImageStorage. - */ - @Test - public void testLoadMagnifyAspectSmooth() throws IOException, InterruptedException { - loadTest("testLoadMagnifyAspectSmooth", "Output_scaled", - (int)(MAGNIFY_FRACTION*rawHeight), (int)(MAGNIFY_FRACTION*rawWidth), - true, true); - } - - /** - * Test of loadAll method, of class ImageStorage. - */ - @Test - public void testLoadMinifyNoAspectRough() throws IOException, InterruptedException { - loadTest("testLoadMinifyNoAspectRough", "Output_scaled", - (int)(MINIFY_FRACTION*rawHeight), (int)(MINIFY_FRACTION*rawWidth), - false, false); - } - - /** - * Test of loadAll method, of class ImageStorage. - */ - @Test - public void testLoadMinifyAspectRough() throws IOException, InterruptedException { - loadTest("testLoadMinifyAspectRough", "Output_scaled", - (int)(MINIFY_FRACTION*rawHeight), (int)(MINIFY_FRACTION*rawWidth), - true, false); - } - - /** - * Test of loadAll method, of class ImageStorage. - */ - @Test - public void testLoadMinifyNoAspectSmooth() throws IOException, InterruptedException { - loadTest("testLoadMinifyNoAspectSmooth", "Output_scaled", - (int)(MINIFY_FRACTION*rawHeight), (int)(MINIFY_FRACTION*rawWidth), - false, true); - } - - /** - * Test of loadAll method, of class ImageStorage. - */ - @Test - public void testLoadMinifyAspectSmooth() throws IOException, InterruptedException { - loadTest("testLoadMinifyAspectSmooth", "Output_scaled", - (int)(MINIFY_FRACTION*rawHeight), (int)(MINIFY_FRACTION*rawWidth), - true, true); - } - - private void loadTest(String testName, String outbasename, int width, int height, - boolean preserveAspectRatio, boolean smooth) - throws IOException, InterruptedException { - System.out.println(testName+", "+width+"x"+height+ - ", preserveAspectRatio: "+preserveAspectRatio+ - ", smooth: "+smooth); - String input = System.getProperty("image.input.url"); - String outBase = System.getProperty("user.home") + - System.getProperty("file.separator") + outbasename; - loadAllTest(input, outBase, width, height, preserveAspectRatio, smooth); - Thread.sleep(3000); - } - - private void loadAllTest(String input, String output, - int width, int height, boolean preserveAspectRatio, boolean smooth) - throws IOException { - ImageLoadListener listener = new ImageLoadListener() { - - public void imageLoadProgress(ImageLoader loader, float percentageComplete) { - if (percentageComplete == 0.0) { - System.out.println("Image loading started (" + percentageComplete + "%)."); - } else if (percentageComplete == 100.0) { - System.out.println("Image loading completed (" + percentageComplete + "%)."); - } else { - System.out.println(percentageComplete + "% complete ..."); - } - } - - public void imageLoadWarning(ImageLoader loader, String message) { - System.err.println("WARNING: " + loader + ": " + message); - } - - public void imageLoadMetaData(ImageLoader loader, ImageMetadata metadata) { - System.out.println("metadata ready = " + metadata); - } - }; - - ImageFrame[] prismImages = null; - try { - long startTime = System.nanoTime(); - prismImages = ImageStorage.loadAll(input, listener, width, height, preserveAspectRatio, smooth); - long finishTime = System.nanoTime(); - System.out.println("Execution time: " + ((finishTime - startTime) / 1000000.0F) + " ms"); - } catch (IOException e) { - System.err.print("ERROR!: "); - Throwable t = e.getCause(); - e.printStackTrace(); - if (t != null) { - t.printStackTrace(); - } - } - - if (prismImages != null) { - - for (int i = 0; i < prismImages.length; i++) { - ImageFrame im = prismImages[i]; - System.out.println(im.getImageType() + " " + im.getWidth() + "x" + im.getHeight()); - if (rawWidth < 0) { - rawWidth = im.getWidth(); - rawHeight = im.getHeight(); - } - ImageMetadata md = im.getMetadata(); - if (md != null) { - System.out.println(im.getMetadata()); - } - if (output != null) { - BufferedImage bi = getAsBufferedImage(im); - show(bi, input); - if (WRITE_OUTPUT) { - try { - Class.forName("javax.imageio.ImageIO"); - javax.imageio.ImageIO.write(bi, "PNG", - new java.io.File(output + "_" + i + ".png")); - } catch(Exception e) { - System.err.println("Cannot locate javax.imageio.ImageIO: output write skipped"); - } - } - } - } - } else { - System.out.println("No images loaded from " + input + "!"); - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/iio/ImageStorageTest.java.DISABLED 2015-09-11 21:24:00.381287260 -0400 @@ -0,0 +1,408 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.iio; + +import java.awt.Canvas; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferByte; +import java.io.IOException; +import java.nio.ByteBuffer; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * + * @author bpb + */ +public class ImageStorageTest { + + private static final boolean WRITE_OUTPUT = false; + + private static final float MINIFY_FRACTION = 0.57F; + private static final float MAGNIFY_FRACTION = 1.47F; + + private static int rawWidth = -1; + private static int rawHeight = -1; + + public static final void main(String[] args) throws Throwable { + String input = args[0]; + String output = null; + if (args.length > 1) { + output = args[1]; + } + ImageStorageTest test = new ImageStorageTest(); + int width = 111; + int height = 97; + boolean preserveAspectRatio = true; + boolean smooth = true; + test.loadAllTest(input, output, width, height, preserveAspectRatio, smooth); + Thread.sleep(3000); + System.exit(0); + } + + public static final BufferedImage getAsBufferedImage(ImageFrame frame) { + BufferedImage image = null; + int width = frame.getWidth(); + int height = frame.getHeight(); + int scanlineStride = frame.getStride(); + ByteBuffer bbuf = (ByteBuffer) frame.getImageData(); + byte[] pixels = null; + if (bbuf.hasArray()) { + pixels = bbuf.array(); + } else { + pixels = new byte[bbuf.capacity()]; + bbuf.get(pixels); + } + switch (frame.getImageType()) { + case GRAY: { + image = new BufferedImage(width, height, + BufferedImage.TYPE_BYTE_GRAY); + DataBufferByte db = + (DataBufferByte) image.getRaster().getDataBuffer(); + byte[] data = db.getData(); + int inLine = 0; + int outLine = 0; + for (int y = 0; y < height; y++) { + System.arraycopy(pixels, inLine, data, outLine, width); + inLine += scanlineStride; + outLine += width; + } + + } + break; +// case PALETTE: +// case PALETTE_ALPHA: { +// byte[][] p = frame.getPalette(); +// IndexColorModel icm = +// frame.getImageType() == ImageType.PALETTE ? new IndexColorModel(8, p[0].length, +// p[0], p[1], p[2]) : new IndexColorModel(8, p[0].length, +// p[0], p[1], p[2], p[3]); +// image = new BufferedImage(width, height, +// BufferedImage.TYPE_BYTE_INDEXED, icm); +// DataBufferByte db = +// (DataBufferByte) image.getRaster().getDataBuffer(); +// byte[] data = db.getData(); +// int inLine = 0; +// int outLine = 0; +// for (int y = 0; y < height; y++) { +// System.arraycopy(pixels, inLine, data, outLine, width); +// inLine += scanlineStride; +// outLine += width; +// } +// } +// break; + case RGB: { + image = new BufferedImage(width, height, + BufferedImage.TYPE_3BYTE_BGR); + for (int y = 0; y < height; y++) { + int off = y * scanlineStride; + for (int x = 0; x < width; x++) { + int rgb = ((pixels[off++] & 0xff) << 16) | + ((pixels[off++] & 0xff) << 8) | + (pixels[off++] & 0xff); + image.setRGB(x, y, rgb); + } + } + } + break; + case RGBA_PRE: { + image = new BufferedImage(width, height, + BufferedImage.TYPE_INT_ARGB_PRE); + for (int y = 0; y < height; y++) { + int off = y * scanlineStride; + for (int x = 0; x < width; x++) { + byte red = pixels[off++]; + byte green = pixels[off++]; + byte blue = pixels[off++]; + byte alpha = pixels[off++]; +// float f = alpha/255.0F; +// red = (byte)((red & 0xff)/f); +// green = (byte)((green & 0xff)/f); +// blue = (byte)((blue & 0xff)/f); + int rgb = ((alpha & 0xff) << 24) | + ((red & 0xff) << 16) | + ((green & 0xff) << 8) | + (blue & 0xff); + image.setRGB(x, y, rgb); + } + } +// DataBufferByte db = +// (DataBufferByte) image.getRaster().getDataBuffer(); +// byte[] data = db.getData(); +// for (int y = 0; y < height; y++) { +// int offPrism = y * scanlineStride; +// int offImage = y * width * 4; +// for (int x = 0; x < width; x++) { +// data[offImage++] = pixels[offPrism + 3]; // A +// data[offImage++] = pixels[offPrism + 2]; // B +// data[offImage++] = pixels[offPrism + 1]; // G +// data[offImage++] = pixels[offPrism]; // R +// offPrism += 4; +// } +// } + } + break; + default: + throw new UnsupportedOperationException("Unsupported test case " + + frame.getImageType()); + } + + return image; + } + + public static void show(Image img, String label) { + final Frame f = new Frame(); + f.addWindowListener(new WindowAdapter() { + + public void windowClosing(WindowEvent e) { + f.setVisible(false); + f.dispose(); + } + }); + f.setTitle(label); + f.add(new ImageCanvas(img)); + f.pack(); + f.setVisible(true); + } + + public static class ImageCanvas extends Canvas { + + private static final long serialVersionUID = 1L; + Image image; + + public ImageCanvas(Image img) { + this.image = img; + } + + public Dimension getPreferredSize() { + return new Dimension(image.getWidth(null), image.getHeight(null)); + } + + public void paint(Graphics g) { + g.drawImage(image, 0, 0, this); + } + } + + public ImageStorageTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + /** + * Test of loadAll method, of class ImageStorage. + */ + @Test + public void testLoadRaw() throws IOException, InterruptedException { + loadTest("testLoadRaw", "Output", 0, 0, false, false); + } + + /** + * Test of loadAll method, of class ImageStorage. + */ + @Test + public void testLoadMagnifyNoAspectRough() throws IOException, InterruptedException { + loadTest("testLoadMagnifyNoAspectRough", "Output_scaled", + (int)(MAGNIFY_FRACTION*rawHeight), (int)(MAGNIFY_FRACTION*rawWidth), + false, false); + } + + /** + * Test of loadAll method, of class ImageStorage. + */ + @Test + public void testLoadMagnifyAspectRough() throws IOException, InterruptedException { + loadTest("testLoadMagnifyAspectRough", "Output_scaled", + (int)(MAGNIFY_FRACTION*rawHeight), (int)(MAGNIFY_FRACTION*rawWidth), + true, false); + } + + /** + * Test of loadAll method, of class ImageStorage. + */ + @Test + public void testLoadMagnifyNoAspectSmooth() throws IOException, InterruptedException { + loadTest("testLoadMagnifyNoAspectSmooth", "Output_scaled", + (int)(MAGNIFY_FRACTION*rawHeight), (int)(MAGNIFY_FRACTION*rawWidth), + false, true); + } + + /** + * Test of loadAll method, of class ImageStorage. + */ + @Test + public void testLoadMagnifyAspectSmooth() throws IOException, InterruptedException { + loadTest("testLoadMagnifyAspectSmooth", "Output_scaled", + (int)(MAGNIFY_FRACTION*rawHeight), (int)(MAGNIFY_FRACTION*rawWidth), + true, true); + } + + /** + * Test of loadAll method, of class ImageStorage. + */ + @Test + public void testLoadMinifyNoAspectRough() throws IOException, InterruptedException { + loadTest("testLoadMinifyNoAspectRough", "Output_scaled", + (int)(MINIFY_FRACTION*rawHeight), (int)(MINIFY_FRACTION*rawWidth), + false, false); + } + + /** + * Test of loadAll method, of class ImageStorage. + */ + @Test + public void testLoadMinifyAspectRough() throws IOException, InterruptedException { + loadTest("testLoadMinifyAspectRough", "Output_scaled", + (int)(MINIFY_FRACTION*rawHeight), (int)(MINIFY_FRACTION*rawWidth), + true, false); + } + + /** + * Test of loadAll method, of class ImageStorage. + */ + @Test + public void testLoadMinifyNoAspectSmooth() throws IOException, InterruptedException { + loadTest("testLoadMinifyNoAspectSmooth", "Output_scaled", + (int)(MINIFY_FRACTION*rawHeight), (int)(MINIFY_FRACTION*rawWidth), + false, true); + } + + /** + * Test of loadAll method, of class ImageStorage. + */ + @Test + public void testLoadMinifyAspectSmooth() throws IOException, InterruptedException { + loadTest("testLoadMinifyAspectSmooth", "Output_scaled", + (int)(MINIFY_FRACTION*rawHeight), (int)(MINIFY_FRACTION*rawWidth), + true, true); + } + + private void loadTest(String testName, String outbasename, int width, int height, + boolean preserveAspectRatio, boolean smooth) + throws IOException, InterruptedException { + System.out.println(testName+", "+width+"x"+height+ + ", preserveAspectRatio: "+preserveAspectRatio+ + ", smooth: "+smooth); + String input = System.getProperty("image.input.url"); + String outBase = System.getProperty("user.home") + + System.getProperty("file.separator") + outbasename; + loadAllTest(input, outBase, width, height, preserveAspectRatio, smooth); + Thread.sleep(3000); + } + + private void loadAllTest(String input, String output, + int width, int height, boolean preserveAspectRatio, boolean smooth) + throws IOException { + ImageLoadListener listener = new ImageLoadListener() { + + public void imageLoadProgress(ImageLoader loader, float percentageComplete) { + if (percentageComplete == 0.0) { + System.out.println("Image loading started (" + percentageComplete + "%)."); + } else if (percentageComplete == 100.0) { + System.out.println("Image loading completed (" + percentageComplete + "%)."); + } else { + System.out.println(percentageComplete + "% complete ..."); + } + } + + public void imageLoadWarning(ImageLoader loader, String message) { + System.err.println("WARNING: " + loader + ": " + message); + } + + public void imageLoadMetaData(ImageLoader loader, ImageMetadata metadata) { + System.out.println("metadata ready = " + metadata); + } + }; + + ImageFrame[] prismImages = null; + try { + long startTime = System.nanoTime(); + prismImages = ImageStorage.loadAll(input, listener, width, height, preserveAspectRatio, smooth); + long finishTime = System.nanoTime(); + System.out.println("Execution time: " + ((finishTime - startTime) / 1000000.0F) + " ms"); + } catch (IOException e) { + System.err.print("ERROR!: "); + Throwable t = e.getCause(); + e.printStackTrace(); + if (t != null) { + t.printStackTrace(); + } + } + + if (prismImages != null) { + + for (int i = 0; i < prismImages.length; i++) { + ImageFrame im = prismImages[i]; + System.out.println(im.getImageType() + " " + im.getWidth() + "x" + im.getHeight()); + if (rawWidth < 0) { + rawWidth = im.getWidth(); + rawHeight = im.getHeight(); + } + ImageMetadata md = im.getMetadata(); + if (md != null) { + System.out.println(im.getMetadata()); + } + if (output != null) { + BufferedImage bi = getAsBufferedImage(im); + show(bi, input); + if (WRITE_OUTPUT) { + try { + Class.forName("javax.imageio.ImageIO"); + javax.imageio.ImageIO.write(bi, "PNG", + new java.io.File(output + "_" + i + ".png")); + } catch(Exception e) { + System.err.println("Cannot locate javax.imageio.ImageIO: output write skipped"); + } + } + } + } + } else { + System.out.println("No images loaded from " + input + "!"); + } + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/iio/ImageTestHelper.java 2015-09-11 21:24:01.273287250 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.iio; - -import java.awt.Color; -import java.awt.GradientPaint; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; -import java.util.Random; -import javax.imageio.IIOImage; -import javax.imageio.ImageIO; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.imageio.stream.ImageOutputStream; - -public class ImageTestHelper { - - public static void writeImage(BufferedImage bImg, String fileName, String format, String compression) - throws IOException - { - if (fileName != null) { - File file = new File(fileName); - file.delete(); - writeImage(bImg, file, format, compression); - } - } - - public static void writeImage(BufferedImage bImg, Object out, String format, String compression) - throws IOException - { - try (ImageOutputStream ios = ImageIO.createImageOutputStream(out)) { - Iterator iter = ImageIO.getImageWritersByFormatName(format); - ImageWriter writer = iter.next(); - ImageWriteParam iwp = writer.getDefaultWriteParam(); - if (compression != null) { - iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); - iwp.setCompressionType(compression); - } - writer.setOutput(ios); - try { - writer.write(null, new IIOImage(bImg, null, null), iwp); - } finally { - writer.dispose(); - ios.flush(); - } - } - } - - public static ByteArrayInputStream writeImageToStream(BufferedImage bImg, - String format, String compression) throws IOException - { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - writeImage(bImg, out, format, compression); - return new ByteArrayInputStream(out.toByteArray()); - } - - public static void drawImageGradient(BufferedImage bImg) { - int w = bImg.getWidth(); - int h = bImg.getHeight(); - Graphics2D graphics = bImg.createGraphics(); - GradientPaint g = new GradientPaint(0, 0, Color.RED, w, h, Color.GREEN); - graphics.setPaint(g); - graphics.fillRect(0, 0, w, h); - } - - public static void drawImageRandom(BufferedImage bImg) { - int w = bImg.getWidth(); - int h = bImg.getHeight(); - Random r = new Random(1); - for (int y = 0; y < h; y++) { - for (int x = 0; x < w; x++) { - bImg.setRGB(x, y, r.nextInt(1 << 24)); - } - } - } - - public static void drawImageHue(BufferedImage bImg) { - int w = bImg.getWidth(); - int h = bImg.getHeight(); - for (int y = 0; y < h; y++) { - float s = 2.0f * y / h; - if (s > 1) { - s = 1; - } - float b = 2.0f * (h - y) / h; - if (b > 1) { - b = 1; - } - for (int x = 0; x < w; x++) { - float hue = (float) x / w; - bImg.setRGB(x, y, Color.HSBtoRGB(hue, s, b)); - } - } - } - - public static void drawImageAll(BufferedImage bImg) { - int w = bImg.getWidth(); - int h = bImg.getHeight(); - //if (h*w < (1<<24)) return; - for (int y = 0; y < h; y++) { - for (int x = 0; x < w; x++) { - bImg.setRGB(x, y, y * h + x); - } - } - } - - public static InputStream createTestImageStream(String format) - throws IOException - { - BufferedImage bImg = new BufferedImage(509, 157, BufferedImage.TYPE_INT_RGB); - ImageTestHelper.drawImageRandom(bImg); - return ImageTestHelper.writeImageToStream(bImg, format, null); - } - - public static InputStream createStutteringInputStream(InputStream in) { - return new FilterInputStream(in) { - - private final Random rnd = new Random(0); - private int numReadStutters = 10; - private int numSkipStutters = 10; - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (numReadStutters > 0 && rnd.nextBoolean()) { - numReadStutters--; - return 0; - } - return in.read(b, off, 1); - } - - @Override - public long skip(long n) throws IOException { - if (numSkipStutters > 0 && rnd.nextBoolean()) { - numSkipStutters--; - return 0; - } - return in.skip(1); - } - }; - } - - public static ByteArrayInputStream constructStreamFromInts(int[] ints) { - byte[] bytes = new byte[ints.length]; - for (int i = 0; i < ints.length; i++) { - bytes[i] = (byte)ints[i]; - } - return new ByteArrayInputStream(bytes); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/iio/ImageTestHelper.java 2015-09-11 21:24:01.133287251 -0400 @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.iio; + +import java.awt.Color; +import java.awt.GradientPaint; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Iterator; +import java.util.Random; +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; + +public class ImageTestHelper { + + public static void writeImage(BufferedImage bImg, String fileName, String format, String compression) + throws IOException + { + if (fileName != null) { + File file = new File(fileName); + file.delete(); + writeImage(bImg, file, format, compression); + } + } + + public static void writeImage(BufferedImage bImg, Object out, String format, String compression) + throws IOException + { + try (ImageOutputStream ios = ImageIO.createImageOutputStream(out)) { + Iterator iter = ImageIO.getImageWritersByFormatName(format); + ImageWriter writer = iter.next(); + ImageWriteParam iwp = writer.getDefaultWriteParam(); + if (compression != null) { + iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + iwp.setCompressionType(compression); + } + writer.setOutput(ios); + try { + writer.write(null, new IIOImage(bImg, null, null), iwp); + } finally { + writer.dispose(); + ios.flush(); + } + } + } + + public static ByteArrayInputStream writeImageToStream(BufferedImage bImg, + String format, String compression) throws IOException + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + writeImage(bImg, out, format, compression); + return new ByteArrayInputStream(out.toByteArray()); + } + + public static void drawImageGradient(BufferedImage bImg) { + int w = bImg.getWidth(); + int h = bImg.getHeight(); + Graphics2D graphics = bImg.createGraphics(); + GradientPaint g = new GradientPaint(0, 0, Color.RED, w, h, Color.GREEN); + graphics.setPaint(g); + graphics.fillRect(0, 0, w, h); + } + + public static void drawImageRandom(BufferedImage bImg) { + int w = bImg.getWidth(); + int h = bImg.getHeight(); + Random r = new Random(1); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + bImg.setRGB(x, y, r.nextInt(1 << 24)); + } + } + } + + public static void drawImageHue(BufferedImage bImg) { + int w = bImg.getWidth(); + int h = bImg.getHeight(); + for (int y = 0; y < h; y++) { + float s = 2.0f * y / h; + if (s > 1) { + s = 1; + } + float b = 2.0f * (h - y) / h; + if (b > 1) { + b = 1; + } + for (int x = 0; x < w; x++) { + float hue = (float) x / w; + bImg.setRGB(x, y, Color.HSBtoRGB(hue, s, b)); + } + } + } + + public static void drawImageAll(BufferedImage bImg) { + int w = bImg.getWidth(); + int h = bImg.getHeight(); + //if (h*w < (1<<24)) return; + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + bImg.setRGB(x, y, y * h + x); + } + } + } + + public static InputStream createTestImageStream(String format) + throws IOException + { + BufferedImage bImg = new BufferedImage(509, 157, BufferedImage.TYPE_INT_RGB); + ImageTestHelper.drawImageRandom(bImg); + return ImageTestHelper.writeImageToStream(bImg, format, null); + } + + public static InputStream createStutteringInputStream(InputStream in) { + return new FilterInputStream(in) { + + private final Random rnd = new Random(0); + private int numReadStutters = 10; + private int numSkipStutters = 10; + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (numReadStutters > 0 && rnd.nextBoolean()) { + numReadStutters--; + return 0; + } + return in.read(b, off, 1); + } + + @Override + public long skip(long n) throws IOException { + if (numSkipStutters > 0 && rnd.nextBoolean()) { + numSkipStutters--; + return 0; + } + return in.skip(1); + } + }; + } + + public static ByteArrayInputStream constructStreamFromInts(int[] ints) { + byte[] bytes = new byte[ints.length]; + for (int i = 0; i < ints.length; i++) { + bytes[i] = (byte)ints[i]; + } + return new ByteArrayInputStream(bytes); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/iio/bmp/BMPImageLoaderTest.java 2015-09-11 21:24:01.953287242 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,235 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.iio.bmp; - -import com.sun.javafx.iio.ImageFrame; -import com.sun.javafx.iio.ImageLoader; -import com.sun.javafx.iio.ImageLoaderFactory; -import com.sun.javafx.iio.ImageTestHelper; -import static com.sun.javafx.iio.bmp.BMPImageLoader.checkDisjointMasks; -import static com.sun.javafx.iio.bmp.BMPImageLoader.isPow2Minus1; -import com.sun.prism.Image; -import java.awt.image.BufferedImage; -import java.awt.image.DataBuffer; -import java.awt.image.IndexColorModel; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import javax.imageio.ImageIO; -import javax.imageio.stream.MemoryCacheImageInputStream; -import static org.junit.Assert.*; -import org.junit.Test; - -public class BMPImageLoaderTest { - // if true, the test will write BMP files generated by JDK to the current directory - static final boolean writeFiles = false; - static final int testWidth = 509, testHeight = 157; - - int getByte(int dword, int shift) { - return (dword >> shift) & 0xff; - } - - boolean compareByte(int p1, int p2, int shift, int tolerance) { - return Math.abs(getByte(p1, shift) - getByte(p2, shift)) <= tolerance; - } - - boolean compareRGB(int p1, int p2, int tolerance) { - return compareByte(p1, p2, 24, tolerance) && - compareByte(p1, p2, 16, tolerance) && - compareByte(p1, p2, 8, tolerance); - } - - void compare(Image img, BufferedImage bImg) { - assertNotNull(img); - assertNotNull(bImg); - int w = bImg.getWidth(), h = bImg.getHeight(); - assertEquals("Unmatched width", w, img.getWidth()); - assertEquals("Unmatched height", h, img.getHeight()); - - for (int y = 0; y < h; y++) { - for (int x = 0; x < w; x++) { - int p1 = bImg.getRGB(x, y); - int p2 = img.getArgb(x, y); - if (!compareRGB(p1, p2, 1)) { - throw new org.junit.ComparisonFailure( - "pixel " + x + ", " + y + " does not match", - String.format("0x%08X", p1), String.format("0x%08X", p2) - ); - } - } - } - } - - Image loadImage(InputStream stream) throws IOException { - ImageLoaderFactory loaderFactory = BMPImageLoaderFactory.getInstance(); - ImageLoader loader = loaderFactory.createImageLoader(stream); - assertNotNull(loader); - - ImageFrame frame = loader.load(0, 0, 0, true, true); - return Image.convertImageFrame(frame); - } - - BufferedImage create4BitImage() { - int[] cmap = new int[16]; - int i = 0; - for (int r = 0; r < 2; r++) { - for (int g = 0; g < 2; g++) { - for (int b = 0; b < 2; b++) { - cmap[i++] = 0xff << 24 | r * 255 << 16 | g * 255 << 8 | b * 255; - if ((r | g | b) == 0) { - cmap[i++] = 0xffc0c0c0; - } else { - cmap[i++] = 0xff << 24 | r * 128 << 16 | g * 128 << 8 | b * 128; - } - } - } - } - IndexColorModel cm = new IndexColorModel(4, 16, cmap, 0, false, -1, DataBuffer.TYPE_BYTE); - return new BufferedImage(testWidth, testHeight, BufferedImage.TYPE_BYTE_BINARY, cm); - } - - BufferedImage createImage(int type) { - return new BufferedImage(testWidth, testHeight, type); - } - - void writeBMPFile(BufferedImage bImg, String fileName, String compression) { - try { - ImageTestHelper.writeImage(bImg, fileName, "bmp", compression); - } catch (IOException e) { - System.out.println("writeBMPFile " + fileName + " failed: " + e); - } - } - - Image getImage(BufferedImage bImg, String compression) throws IOException { - ByteArrayInputStream stream = - ImageTestHelper.writeImageToStream(bImg, "bmp", compression); - return loadImage(stream); - } - - void testImageType(int type, String fileName, String compression) throws IOException { - BufferedImage bImg = createImage(type); - testImage(bImg, fileName, compression); - } - - void testImageType(int type, String fileName) throws IOException { - BufferedImage bImg = createImage(type); - testImage(bImg, fileName, null); - } - - void testImage(BufferedImage bImg, String fileName, String compression) throws IOException { - //ImageTestHelper.drawImageHue(bImg); - //ImageTestHelper.drawImageAll(bImg); - ImageTestHelper.drawImageRandom(bImg); - if (writeFiles) { - writeBMPFile(bImg, fileName, compression); - } - Image image = getImage(bImg, compression); - compare(image, bImg); - } - - @Test - public void testRT32213() throws IOException { - final int[] bytes = { - 0x42, 0x4d, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x28, 0x00, - 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, - 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, - 0x00, 0x00 - }; - - ByteArrayInputStream stream = ImageTestHelper.constructStreamFromInts(bytes); - Image image = loadImage(stream); - stream.reset(); - BufferedImage bImg = ImageIO.read(new MemoryCacheImageInputStream(stream)); - compare(image, bImg); - } - - @Test - public void testRT15619() throws IOException { - InputStream stream = ImageTestHelper.createTestImageStream("bmp"); - InputStream testStream = ImageTestHelper.createStutteringInputStream(stream); - loadImage(testStream); - } - - @Test - public void test1Bit() throws IOException { - testImageType(BufferedImage.TYPE_BYTE_BINARY, "out1bit.bmp"); - } - - @Test - public void test4Bit() throws IOException { - testImage(create4BitImage(), "out4bit.bmp", null); - } - - //@Test - public void test4BitRLE() throws IOException { - testImage(create4BitImage(), "out4bitRLE.bmp", "BI_RLE4"); - } - - @Test - public void test8Bit() throws IOException { - testImageType(BufferedImage.TYPE_BYTE_INDEXED, "out8bit.bmp"); - } - - @Test - public void test8BitRLE() throws IOException { - testImageType(BufferedImage.TYPE_BYTE_INDEXED, "out8bitRLE.bmp", "BI_RLE8"); - } - - @Test - public void test16Bit() throws IOException { - testImageType(BufferedImage.TYPE_USHORT_555_RGB, "out16bit.bmp"); - } - - @Test - public void test24Bit() throws IOException { - testImageType(BufferedImage.TYPE_INT_RGB, "out24bit.bmp"); - } - - @Test - public void testBitfields() throws IOException { - testImageType(BufferedImage.TYPE_USHORT_555_RGB, "out16bit555.bmp", "BI_BITFIELDS"); - testImageType(BufferedImage.TYPE_USHORT_565_RGB, "out16bit565.bmp", "BI_BITFIELDS"); - } - - @Test - public void testMasks() { - assertTrue(checkDisjointMasks(1, 2, 4)); - assertTrue(checkDisjointMasks(0x00F, 0x0F0, 0xF00)); - assertFalse(checkDisjointMasks(1, 2, 5)); - assertFalse(checkDisjointMasks(2, 1, 6)); - - assertTrue(isPow2Minus1(1)); - assertTrue(isPow2Minus1(3)); - assertTrue(isPow2Minus1(7)); - assertFalse(isPow2Minus1(2)); - assertFalse(isPow2Minus1(11)); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/iio/bmp/BMPImageLoaderTest.java 2015-09-11 21:24:01.817287244 -0400 @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.iio.bmp; + +import com.sun.javafx.iio.ImageFrame; +import com.sun.javafx.iio.ImageLoader; +import com.sun.javafx.iio.ImageLoaderFactory; +import com.sun.javafx.iio.bmp.BMPImageLoaderFactory; +import com.sun.javafx.iio.bmp.BMPImageLoaderShim; +import test.com.sun.javafx.iio.ImageTestHelper; +import com.sun.prism.Image; +import java.awt.image.BufferedImage; +import java.awt.image.DataBuffer; +import java.awt.image.IndexColorModel; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import javax.imageio.ImageIO; +import javax.imageio.stream.MemoryCacheImageInputStream; +import static org.junit.Assert.*; +import org.junit.Test; + +public class BMPImageLoaderTest { + // if true, the test will write BMP files generated by JDK to the current directory + static final boolean writeFiles = false; + static final int testWidth = 509, testHeight = 157; + + int getByte(int dword, int shift) { + return (dword >> shift) & 0xff; + } + + boolean compareByte(int p1, int p2, int shift, int tolerance) { + return Math.abs(getByte(p1, shift) - getByte(p2, shift)) <= tolerance; + } + + boolean compareRGB(int p1, int p2, int tolerance) { + return compareByte(p1, p2, 24, tolerance) && + compareByte(p1, p2, 16, tolerance) && + compareByte(p1, p2, 8, tolerance); + } + + void compare(Image img, BufferedImage bImg) { + assertNotNull(img); + assertNotNull(bImg); + int w = bImg.getWidth(), h = bImg.getHeight(); + assertEquals("Unmatched width", w, img.getWidth()); + assertEquals("Unmatched height", h, img.getHeight()); + + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + int p1 = bImg.getRGB(x, y); + int p2 = img.getArgb(x, y); + if (!compareRGB(p1, p2, 1)) { + throw new org.junit.ComparisonFailure( + "pixel " + x + ", " + y + " does not match", + String.format("0x%08X", p1), String.format("0x%08X", p2) + ); + } + } + } + } + + Image loadImage(InputStream stream) throws IOException { + ImageLoaderFactory loaderFactory = BMPImageLoaderFactory.getInstance(); + ImageLoader loader = loaderFactory.createImageLoader(stream); + assertNotNull(loader); + + ImageFrame frame = loader.load(0, 0, 0, true, true); + return Image.convertImageFrame(frame); + } + + BufferedImage create4BitImage() { + int[] cmap = new int[16]; + int i = 0; + for (int r = 0; r < 2; r++) { + for (int g = 0; g < 2; g++) { + for (int b = 0; b < 2; b++) { + cmap[i++] = 0xff << 24 | r * 255 << 16 | g * 255 << 8 | b * 255; + if ((r | g | b) == 0) { + cmap[i++] = 0xffc0c0c0; + } else { + cmap[i++] = 0xff << 24 | r * 128 << 16 | g * 128 << 8 | b * 128; + } + } + } + } + IndexColorModel cm = new IndexColorModel(4, 16, cmap, 0, false, -1, DataBuffer.TYPE_BYTE); + return new BufferedImage(testWidth, testHeight, BufferedImage.TYPE_BYTE_BINARY, cm); + } + + BufferedImage createImage(int type) { + return new BufferedImage(testWidth, testHeight, type); + } + + void writeBMPFile(BufferedImage bImg, String fileName, String compression) { + try { + ImageTestHelper.writeImage(bImg, fileName, "bmp", compression); + } catch (IOException e) { + System.out.println("writeBMPFile " + fileName + " failed: " + e); + } + } + + Image getImage(BufferedImage bImg, String compression) throws IOException { + ByteArrayInputStream stream = + ImageTestHelper.writeImageToStream(bImg, "bmp", compression); + return loadImage(stream); + } + + void testImageType(int type, String fileName, String compression) throws IOException { + BufferedImage bImg = createImage(type); + testImage(bImg, fileName, compression); + } + + void testImageType(int type, String fileName) throws IOException { + BufferedImage bImg = createImage(type); + testImage(bImg, fileName, null); + } + + void testImage(BufferedImage bImg, String fileName, String compression) throws IOException { + //ImageTestHelper.drawImageHue(bImg); + //ImageTestHelper.drawImageAll(bImg); + ImageTestHelper.drawImageRandom(bImg); + if (writeFiles) { + writeBMPFile(bImg, fileName, compression); + } + Image image = getImage(bImg, compression); + compare(image, bImg); + } + + @Test + public void testRT32213() throws IOException { + final int[] bytes = { + 0x42, 0x4d, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x28, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, + 0x00, 0x00 + }; + + ByteArrayInputStream stream = ImageTestHelper.constructStreamFromInts(bytes); + Image image = loadImage(stream); + stream.reset(); + BufferedImage bImg = ImageIO.read(new MemoryCacheImageInputStream(stream)); + compare(image, bImg); + } + + @Test + public void testRT15619() throws IOException { + InputStream stream = ImageTestHelper.createTestImageStream("bmp"); + InputStream testStream = ImageTestHelper.createStutteringInputStream(stream); + loadImage(testStream); + } + + @Test + public void test1Bit() throws IOException { + testImageType(BufferedImage.TYPE_BYTE_BINARY, "out1bit.bmp"); + } + + @Test + public void test4Bit() throws IOException { + testImage(create4BitImage(), "out4bit.bmp", null); + } + + //@Test + public void test4BitRLE() throws IOException { + testImage(create4BitImage(), "out4bitRLE.bmp", "BI_RLE4"); + } + + @Test + public void test8Bit() throws IOException { + testImageType(BufferedImage.TYPE_BYTE_INDEXED, "out8bit.bmp"); + } + + @Test + public void test8BitRLE() throws IOException { + testImageType(BufferedImage.TYPE_BYTE_INDEXED, "out8bitRLE.bmp", "BI_RLE8"); + } + + @Test + public void test16Bit() throws IOException { + testImageType(BufferedImage.TYPE_USHORT_555_RGB, "out16bit.bmp"); + } + + @Test + public void test24Bit() throws IOException { + testImageType(BufferedImage.TYPE_INT_RGB, "out24bit.bmp"); + } + + @Test + public void testBitfields() throws IOException { + testImageType(BufferedImage.TYPE_USHORT_555_RGB, "out16bit555.bmp", "BI_BITFIELDS"); + testImageType(BufferedImage.TYPE_USHORT_565_RGB, "out16bit565.bmp", "BI_BITFIELDS"); + } + + @Test + public void testMasks() { + assertTrue(BMPImageLoaderShim.checkDisjointMasks(1, 2, 4)); + assertTrue(BMPImageLoaderShim.checkDisjointMasks(0x00F, 0x0F0, 0xF00)); + assertFalse(BMPImageLoaderShim.checkDisjointMasks(1, 2, 5)); + assertFalse(BMPImageLoaderShim.checkDisjointMasks(2, 1, 6)); + + assertTrue(BMPImageLoaderShim.isPow2Minus1(1)); + assertTrue(BMPImageLoaderShim.isPow2Minus1(3)); + assertTrue(BMPImageLoaderShim.isPow2Minus1(7)); + assertFalse(BMPImageLoaderShim.isPow2Minus1(2)); + assertFalse(BMPImageLoaderShim.isPow2Minus1(11)); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/iio/png/PNGImageLoaderTest.java 2015-09-11 21:24:02.425287237 -0400 @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.iio.png; + +import com.sun.javafx.iio.png.PNGImageLoader2; +import test.com.sun.javafx.iio.ImageTestHelper; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import org.junit.Test; + +public class PNGImageLoaderTest { + + private void testImage(InputStream stream) throws IOException { + PNGImageLoader2 loader = new PNGImageLoader2(stream); + loader.load(0, 0, 0, true, true); + } + + @Test + public void testRT35133() throws IOException { + InputStream stream = ImageTestHelper.createTestImageStream("png"); + InputStream testStream = ImageTestHelper.createStutteringInputStream(stream); + testImage(testStream); + } + + @Test(timeout = 1000, expected = IOException.class) + public void testRT27010() throws IOException { + int[] corruptedIDATLength = { + 137, 80, 78, 71, 13, 10, 26, 10, // signature + 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, // IHDR chunk + 0, 0, 4, 0, 0, 0, 4, 0, 8, 6, 0, 0, 0, // IHDR chunk data + 0x7f, 0x1d, 0x2b, 0x83, // IHDR chunk crc + 0x80, 0, 0x80, 0, 0x49, 0x44, 0x41, 0x54 // negative IDAT length + }; + + ByteArrayInputStream stream = ImageTestHelper.constructStreamFromInts(corruptedIDATLength); + testImage(stream); + } + + @Test(timeout = 1000, expected = IOException.class) + public void testRT27010MultipleIDAT() throws IOException { + int[] corruptedIDATLength = { + 137, 80, 78, 71, 13, 10, 26, 10, // signature + 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, // IHDR chunk + 0, 0, 4, 0, 0, 0, 4, 0, 8, 6, 0, 0, 0, // IHDR chunk data + 0x7f, 0x1d, 0x2b, 0x83, // IHDR chunk crc + 0, 0, 0, 1, 0x49, 0x44, 0x41, 0x54, // first IDAT + 0, // IDAT chunk data + 0, 0, 0, 0, // IDAT chunk crc + 0x80, 0, 0, 0, 0x49, 0x44, 0x41, 0x54, // second IDAT + }; + + ByteArrayInputStream stream = ImageTestHelper.constructStreamFromInts(corruptedIDATLength); + testImage(stream); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/image/ConverterTest.java 2015-09-11 21:24:03.101287229 -0400 @@ -0,0 +1,1022 @@ +/* + * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.image; + +import com.sun.javafx.image.AlphaType; +import com.sun.javafx.image.BytePixelGetter; +import com.sun.javafx.image.BytePixelSetter; +import com.sun.javafx.image.ByteToBytePixelConverter; +import com.sun.javafx.image.ByteToIntPixelConverter; +import com.sun.javafx.image.IntPixelGetter; +import com.sun.javafx.image.IntPixelSetter; +import com.sun.javafx.image.IntToBytePixelConverter; +import com.sun.javafx.image.IntToIntPixelConverter; +import com.sun.javafx.image.PixelConverter; +import com.sun.javafx.image.PixelGetter; +import com.sun.javafx.image.PixelSetter; +import com.sun.javafx.image.PixelUtils; +import com.sun.javafx.image.impl.ByteArgb; +import com.sun.javafx.image.impl.ByteBgr; +import com.sun.javafx.image.impl.ByteBgra; +import com.sun.javafx.image.impl.ByteBgraPre; +import com.sun.javafx.image.impl.ByteGray; +import com.sun.javafx.image.impl.ByteGrayAlpha; +import com.sun.javafx.image.impl.ByteGrayAlphaPre; +import com.sun.javafx.image.impl.ByteRgb; +import com.sun.javafx.image.impl.ByteRgba; +import com.sun.javafx.image.impl.IntArgb; +import com.sun.javafx.image.impl.IntArgbPre; +import static junit.framework.Assert.*; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import javafx.scene.image.PixelFormat; +import javafx.scene.image.WritablePixelFormat; +import javafx.scene.paint.Color; +import org.junit.Test; + +/** + */ +public class ConverterTest { + static ByteBuffer heapByteBuffer(int off, int len) { + ByteBuffer bbuf = ByteBuffer.allocate(off + len); + if (off > 0) { + bbuf.position(off); + bbuf = bbuf.slice(); + } + return bbuf; + } + + static ByteBuffer directByteBuffer(int off, int len) { + ByteBuffer bbuf = ByteBuffer.allocateDirect(off + len); + if (off > 0) { + bbuf.position(off); + bbuf = bbuf.slice(); + } + return bbuf; + } + + static IntBuffer heapIntBuffer(int off, int len) { + IntBuffer ibuf = IntBuffer.allocate(off + len); + if (off > 0) { + ibuf.position(off); + ibuf = ibuf.slice(); + } + return ibuf; + } + + static IntBuffer directIntBuffer(int off, int len) { + IntBuffer ibuf = ByteBuffer.allocateDirect((off + len) * 4).asIntBuffer(); + if (off > 0) { + ibuf.position(off); + ibuf = ibuf.slice(); + } + return ibuf; + } + + static Color derive(Color c, double opacity) { + return new Color(c.getRed(), c.getGreen(), c.getBlue(), c.getOpacity() * opacity); + } + + static int RgbToGray(int red, int green, int blue) { + return (int) (red * .3 + green * .59 + blue * .11); + } + + static int grayify(int argb) { + int alpha = (argb >> 24) & 0xff; + int red = (argb >> 16) & 0xff; + int green = (argb >> 8) & 0xff; + int blue = (argb ) & 0xff; + int gray = RgbToGray(red, green, blue); + return (alpha << 24) | (gray << 16) | (gray << 8) | gray; + } + + static int getArgb(Color c) { + int alpha = (int) (c.getOpacity() * 255f); + int red = (int) (c.getRed() * 255f); + int green = (int) (c.getGreen() * 255f); + int blue = (int) (c.getBlue() * 255f); + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + static int getArgbPre(Color c) { + double a = c.getOpacity(); + int alpha = (int) (a * 255f); + int red = (int) (a * c.getRed() * 255f); + int green = (int) (a * c.getGreen() * 255f); + int blue = (int) (a * c.getBlue() * 255f); + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + static class ByteFormat { + private final BytePixelGetter getter; + private final BytePixelSetter setter; + private final int aoff, roff, goff, boff, grayoff; + private final int ncomp; + + public ByteFormat(BytePixelGetter getter, + int aoff, int roff, int goff, int boff) + { + if (getter == null) throw new NullPointerException("getter must not be null"); + + this.getter = getter; + this.setter = null; + this.grayoff = -1; + this.aoff = aoff; + this.roff = roff; + this.goff = goff; + this.boff = boff; + this.ncomp = (aoff < 0) ? 3 : 4; + } + + public ByteFormat(BytePixelGetter getter, BytePixelSetter setter, + int aoff, int roff, int goff, int boff) + { + if (getter == null) throw new NullPointerException("getter must not be null"); + if (setter == null) throw new NullPointerException("setter must not be null"); + + this.getter = getter; + this.setter = setter; + this.grayoff = -1; + this.aoff = aoff; + this.roff = roff; + this.goff = goff; + this.boff = boff; + this.ncomp = (aoff < 0) ? 3 : 4; + } + + public ByteFormat(BytePixelGetter getter, + int aoff, int grayoff) + { + if (getter == null) throw new NullPointerException("getter must not be null"); + + this.getter = getter; + this.setter = null; + this.grayoff = grayoff; + this.aoff = aoff; + this.roff = -1; + this.goff = -1; + this.boff = -1; + this.ncomp = (aoff < 0) ? 1 : 2; + } + + public ByteFormat(BytePixelGetter getter, BytePixelSetter setter, + int aoff, int grayoff) + { + if (getter == null) throw new NullPointerException("getter must not be null"); + if (setter == null) throw new NullPointerException("setter must not be null"); + + this.getter = getter; + this.setter = setter; + this.grayoff = grayoff; + this.aoff = aoff; + this.roff = -1; + this.goff = -1; + this.boff = -1; + this.ncomp = (aoff < 0) ? 1 : 2; + } + + public int getNcomp() { + return ncomp; + } + + public int getArgb(byte barr[], int off) { + int alpha = (aoff < 0) ? 255 : (barr[off + aoff] & 0xff); + int red, green, blue; + if (isGray()) { + red = green = blue = barr[off + grayoff] & 0xff; + } else { + red = barr[off + roff] & 0xff; + green = barr[off + goff] & 0xff; + blue = barr[off + boff] & 0xff; + } + if (alpha < 255 && alpha > 0 && getter.getAlphaType() == AlphaType.PREMULTIPLIED) { + int halfa = alpha >> 1; + red = (red >= alpha) ? 255 : (red * 255 + halfa) / alpha; + green = (green >= alpha) ? 255 : (green * 255 + halfa) / alpha; + blue = (blue >= alpha) ? 255 : (blue * 255 + halfa) / alpha; + } + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + public int getArgb(ByteBuffer bbuf, int off) { + int alpha = (aoff < 0) ? 255 : (bbuf.get(off + aoff) & 0xff); + int red, green, blue; + if (isGray()) { + red = green = blue = bbuf.get(off + grayoff) & 0xff; + } else { + red = bbuf.get(off + roff) & 0xff; + green = bbuf.get(off + goff) & 0xff; + blue = bbuf.get(off + boff) & 0xff; + } + if (alpha < 255 && alpha > 0 && getter.getAlphaType() == AlphaType.PREMULTIPLIED) { + int halfa = alpha >> 1; + red = (red >= alpha) ? 255 : (red * 255 + halfa) / alpha; + green = (green >= alpha) ? 255 : (green * 255 + halfa) / alpha; + blue = (blue >= alpha) ? 255 : (blue * 255 + halfa) / alpha; + } + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + public void setArgb(byte barr[], int off, int argb) { + int alpha = (argb >> 24) & 0xff; + int red = (argb >> 16) & 0xff; + int green = (argb >> 8) & 0xff; + int blue = (argb ) & 0xff; + if (getter.getAlphaType() == AlphaType.PREMULTIPLIED) { + red = (red * alpha + 127) / 255; + green = (green * alpha + 127) / 255; + blue = (blue * alpha + 127) / 255; + } + if (aoff >= 0) { + barr[off + aoff] = (byte) alpha; + } + if (isGray()) { + int gray = RgbToGray(red, green, blue); + barr[off + grayoff] = (byte) gray; + } else { + barr[off + roff] = (byte) red; + barr[off + goff] = (byte) green; + barr[off + boff] = (byte) blue; + } + } + + public void setArgb(ByteBuffer bbuf, int off, int argb) { + int alpha = (argb >> 24) & 0xff; + int red = (argb >> 16) & 0xff; + int green = (argb >> 8) & 0xff; + int blue = (argb ) & 0xff; + if (getter.getAlphaType() == AlphaType.PREMULTIPLIED) { + red = (red * alpha + 127) / 255; + green = (green * alpha + 127) / 255; + blue = (blue * alpha + 127) / 255; + } + if (aoff >= 0) { + bbuf.put(off + aoff, (byte) alpha); + } + if (isGray()) { + int gray = RgbToGray(red, green, blue); + bbuf.put(off + grayoff, (byte) gray); + } else { + bbuf.put(off + roff, (byte) red); + bbuf.put(off + goff, (byte) green); + bbuf.put(off + boff, (byte) blue); + } + } + + public BytePixelGetter getGetter() { + return getter; + } + + public BytePixelSetter getSetter() { + return setter; + } + + public boolean isGray() { + return grayoff >= 0; + } + + public int getGrayOff() { + return grayoff; + } + + public int getAoff() { + return aoff; + } + + public int getRoff() { + return roff; + } + + public int getGoff() { + return goff; + } + + public int getBoff() { + return boff; + } + + @Override + public String toString() { + if (getter == null) { + return "ByteFormat{" + "setter=" + setter + '}'; + } else if (setter == null) { + return "ByteFormat{" + "getter=" + getter + '}'; + } else if (getter == setter) { + return "ByteFormat{" + "accessor=" + getter + '}'; + } else { + return "ByteFormat{" + "getter=" + getter + ", setter=" + setter + '}'; + } + } + } + + static class IntFormat { + private final IntPixelGetter getter; + private final IntPixelSetter setter; + private final int ashift, rshift, gshift, bshift; + + public IntFormat(IntPixelGetter getter, IntPixelSetter setter, + int ashift, int rshift, int gshift, int bshift) + { + if (getter == null) throw new NullPointerException("getter must not be null"); + if (setter == null) throw new NullPointerException("setter must not be null"); + + this.getter = getter; + this.setter = setter; + this.ashift = ashift; + this.rshift = rshift; + this.gshift = gshift; + this.bshift = bshift; + } + + private int convertPixel(int pixel) { + int alpha = (pixel >> ashift) & 0xff; + int red = (pixel >> rshift) & 0xff; + int green = (pixel >> gshift) & 0xff; + int blue = (pixel >> bshift) & 0xff; + if (alpha > 0 && alpha < 255 && getter.getAlphaType() == AlphaType.PREMULTIPLIED) { + int halfa = alpha >> 1; + red = (red >= alpha) ? 255 : (red * 255 + halfa) / alpha; + green = (green >= alpha) ? 255 : (green * 255 + halfa) / alpha; + blue = (blue >= alpha) ? 255 : (blue * 255 + halfa) / alpha; + } + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + private int convertArgb(int argb) { + int alpha = (argb >> 24) & 0xff; + int red = (argb >> 16) & 0xff; + int green = (argb >> 8) & 0xff; + int blue = (argb ) & 0xff; + if (alpha < 255 && getter.getAlphaType() == AlphaType.PREMULTIPLIED) { + red = (red * alpha + 127) / 255; + green = (green * alpha + 127) / 255; + blue = (blue * alpha + 127) / 255; + } + return (alpha << ashift) | (red << rshift) | (green << gshift) | (blue << bshift); + } + + public int getArgb(int iarr[], int off) { + return convertPixel(iarr[off]); + } + + public int getArgb(IntBuffer ibuf, int off) { + return convertPixel(ibuf.get(off)); + } + + public void setArgb(int iarr[], int off, int argb) { + iarr[off] = convertArgb(argb); + } + + public void setArgb(IntBuffer ibuf, int off, int argb) { + ibuf.put(off, convertArgb(argb)); + } + + public IntPixelGetter getGetter() { + return getter; + } + + public IntPixelSetter getSetter() { + return setter; + } + + public int getAshift() { + return ashift; + } + + public int getRshift() { + return rshift; + } + + public int getGshift() { + return gshift; + } + + public int getBshift() { + return bshift; + } + + @Override + public String toString() { + if (getter == null) { + return "IntFormat{" + "setter=" + setter + '}'; + } else if (setter == null) { + return "IntFormat{" + "getter=" + getter + '}'; + } else if (getter == setter) { + return "IntFormat{" + "accessor=" + getter + '}'; + } else { + return "IntFormat{" + "getter=" + getter + ", setter=" + setter + '}'; + } + } + } + + + static ByteFormat ByteFormats[] = { + new ByteFormat(ByteArgb.getter, ByteArgb.setter, 0, 1, 2, 3), + new ByteFormat(ByteBgra.getter, ByteBgra.setter, 3, 2, 1, 0), + new ByteFormat(ByteBgraPre.getter, ByteBgraPre.setter, 3, 2, 1, 0), + new ByteFormat(ByteRgba.getter, ByteRgba.setter, 3, 0, 1, 2), + new ByteFormat(ByteRgb.getter, -1, 0, 1, 2), + new ByteFormat(ByteBgr.getter, ByteBgr.setter, -1, 2, 1, 0), + + new ByteFormat(ByteGray.getter, ByteGray.setter, -1, 0), + new ByteFormat(ByteGrayAlpha.getter, ByteGrayAlpha.setter, 1, 0), + new ByteFormat(ByteGrayAlphaPre.getter, ByteGrayAlphaPre.setter, 1, 0), + }; + + static IntFormat IntFormats[] = { + new IntFormat(IntArgb.getter, IntArgb.setter, 24, 16, 8, 0), + new IntFormat(IntArgbPre.getter, IntArgbPre.setter, 24, 16, 8, 0), + }; + + static Color TestColors[] = { + Color.WHITE, + Color.BLACK, + Color.RED, + Color.GREEN, + Color.BLUE, + Color.TRANSPARENT, + derive(Color.WHITE, 0.5), + derive(Color.BLACK, 0.5), + derive(Color.RED, 0.5), + derive(Color.GREEN, 0.5), + derive(Color.BLUE, 0.5), + }; + + static Color OpaqueTestColors[] = { + Color.WHITE, + Color.BLACK, + Color.RED, + Color.GREEN, + Color.BLUE, + Color.CYAN, + Color.MAGENTA, + Color.YELLOW, + }; + + static void checkArgb(int argb1, int argb2, double delta) { + assertEquals("alpha", (argb1 >> 24) & 0xff, (argb2 >> 24) & 0xff); + assertEquals("red", (argb1 >> 16) & 0xff, (argb2 >> 16) & 0xff, delta); + assertEquals("green", (argb1 >> 8) & 0xff, (argb2 >> 8) & 0xff, delta); + assertEquals("blue", (argb1 ) & 0xff, (argb2 ) & 0xff, delta); + } + + void testget(ByteFormat bfmt, ByteBuffer bbuf, byte barr[], Color c) { + int refnon = getArgb(c); + int refpre = getArgbPre(c); + bfmt.setArgb(bbuf, 0, refnon); + bfmt.setArgb(barr, 0, refnon); + BytePixelGetter bpg = bfmt.getGetter(); + boolean premult = (bpg.getAlphaType() == AlphaType.PREMULTIPLIED); + double delta = 0.0; + if (bfmt.isGray()) { + refnon = grayify(refnon); + refpre = grayify(refpre); + delta += 1.0; + } + checkArgb(refnon, bpg.getArgb (bbuf, 0), delta + (premult ? 1.0 : 0.0)); + checkArgb(refpre, bpg.getArgbPre(bbuf, 0), delta + (premult ? 0.0 : 1.0)); + checkArgb(refnon, bpg.getArgb (barr, 0), delta + (premult ? 1.0 : 0.0)); + checkArgb(refpre, bpg.getArgbPre(barr, 0), delta + (premult ? 0.0 : 1.0)); + } + + void testget(IntFormat ifmt, IntBuffer ibuf, int iarr[], Color c) { + int refnon = getArgb(c); + int refpre = getArgbPre(c); + ifmt.setArgb(ibuf, 0, refnon); + ifmt.setArgb(iarr, 0, refnon); + IntPixelGetter bpg = ifmt.getGetter(); + boolean premult = (bpg.getAlphaType() == AlphaType.PREMULTIPLIED); + checkArgb(refnon, bpg.getArgb (ibuf, 0), premult ? 1.0 : 0.0); + checkArgb(refpre, bpg.getArgbPre(ibuf, 0), premult ? 0.0 : 1.0); + checkArgb(refnon, bpg.getArgb (iarr, 0), premult ? 1.0 : 0.0); + checkArgb(refpre, bpg.getArgbPre(iarr, 0), premult ? 0.0 : 1.0); + } + + void testset(ByteFormat bfmt, ByteBuffer bbuf, byte barr[], Color c) { + int refnon = getArgb(c); + int refpre = getArgbPre(c); + BytePixelSetter bps = bfmt.getSetter(); + bps.setArgb (bbuf, 0, refnon); + bps.setArgbPre(bbuf, 4, refpre); + bps.setArgb (barr, 0, refnon); + bps.setArgbPre(barr, 4, refpre); + boolean premult = (bps.getAlphaType() == AlphaType.PREMULTIPLIED); + double delta = 0.0; + if (bfmt.isGray()) { + refnon = grayify(refnon); + delta += 1.0; + } + checkArgb(refnon, bfmt.getArgb(bbuf, 0), delta + (premult ? 1.0 : 0.0)); + checkArgb(refnon, bfmt.getArgb(bbuf, 4), delta + (premult ? 1.0 : 1.0)); + checkArgb(refnon, bfmt.getArgb(barr, 0), delta + (premult ? 1.0 : 0.0)); + checkArgb(refnon, bfmt.getArgb(barr, 4), delta + (premult ? 1.0 : 1.0)); + } + + void testset(IntFormat ifmt, IntBuffer ibuf, int iarr[], Color c) { + int refnon = getArgb(c); + int refpre = getArgbPre(c); + IntPixelSetter ips = ifmt.getSetter(); + ips.setArgb (ibuf, 0, refnon); + ips.setArgbPre(ibuf, 1, refpre); + ips.setArgb (iarr, 0, refnon); + ips.setArgbPre(iarr, 1, refpre); + boolean premult = (ips.getAlphaType() == AlphaType.PREMULTIPLIED); + double delta = 0.0; + checkArgb(refnon, ifmt.getArgb(ibuf, 0), delta + (premult ? 1.0 : 0.0)); + checkArgb(refnon, ifmt.getArgb(ibuf, 1), delta + (premult ? 1.0 : 1.0)); + checkArgb(refnon, ifmt.getArgb(iarr, 0), delta + (premult ? 1.0 : 0.0)); + checkArgb(refnon, ifmt.getArgb(iarr, 1), delta + (premult ? 1.0 : 1.0)); + } + + @Test + public void testByteAccessors() { + testByteAccessors(heapByteBuffer(0, 8)); + testByteAccessors(heapByteBuffer(1, 8)); + testByteAccessors(directByteBuffer(0, 8)); + testByteAccessors(directByteBuffer(1, 8)); + } + + private void testByteAccessors(ByteBuffer bbuf) { + byte barr[] = new byte[8]; + for (ByteFormat bfmt : ByteFormats) { + BytePixelGetter getter = bfmt.getGetter(); + BytePixelSetter setter = bfmt.getSetter(); + if (getter != null && setter != null) { + assertEquals(getter.getAlphaType(), setter.getAlphaType()); + } + Color testColors[] = (getter.getAlphaType() == AlphaType.OPAQUE + ? OpaqueTestColors : TestColors); + for (Color c : testColors) { + if (getter != null) { + testget(bfmt, bbuf, barr, c); + } + if (setter != null) { + testset(bfmt, bbuf, barr, c); + } + } + } + } + + static final int FxColors[] = { + 0x00000000, + 0xffff0000, + 0xff00ff00, + 0xff0000ff, + 0xffffffff + }; + + static final PixelFormat FxFormats[] = { + PixelFormat.getByteBgraInstance(), + PixelFormat.getByteBgraPreInstance(), + PixelFormat.getByteRgbInstance(), + PixelFormat.getIntArgbInstance(), + PixelFormat.getIntArgbPreInstance(), + PixelFormat.createByteIndexedInstance(FxColors), + PixelFormat.createByteIndexedPremultipliedInstance(FxColors) + }; + + static final WritablePixelFormat FxWritableFormats[] = { + WritablePixelFormat.getByteBgraInstance(), + WritablePixelFormat.getByteBgraPreInstance(), + WritablePixelFormat.getIntArgbInstance(), + WritablePixelFormat.getIntArgbPreInstance() + }; + + static void checkAllTypesTested(PixelFormat formats[], boolean writable) { + if (writable) { + for (PixelFormat pf : formats) { + assertTrue(pf.isWritable()); + } + } + for (PixelFormat.Type type : PixelFormat.Type.values()) { + if (type == PixelFormat.Type.BYTE_INDEXED || + type == PixelFormat.Type.BYTE_RGB) + { + // Non-writable type + if (writable) continue; + } + boolean found = false; + for (PixelFormat pf : formats) { + if (pf.getType() == type) { + found = true; + break; + } + } + assertTrue(found); + } + } + + @Test + public void ensureFXConverters() { + checkAllTypesTested(FxFormats, false); + checkAllTypesTested(FxWritableFormats, true); + for (PixelFormat pf : FxFormats) { + PixelGetter getter = PixelUtils.getGetter(pf); + assertNotNull(getter); + for (WritablePixelFormat wpf : FxWritableFormats) { + PixelSetter setter = PixelUtils.getSetter(wpf); + assertNotNull(setter); + PixelConverter converter = PixelUtils.getConverter(getter, setter); + assertNotNull(converter); + } + } + } + + @Test + public void ensureJ2DConverters() { + assertNotNull(PixelUtils.getConverter(ByteGray.getter, ByteGray.setter)); + assertNotNull(PixelUtils.getConverter(ByteBgr.getter, ByteBgr.setter)); + assertNotNull(PixelUtils.getConverter(IntArgbPre.getter, IntArgbPre.setter)); + assertNotNull(PixelUtils.getConverter(ByteBgraPre.getter, IntArgbPre.setter)); + } + + @Test + public void testIntAccessors() { + testIntAccessors(heapIntBuffer(0, 2)); + testIntAccessors(heapIntBuffer(1, 2)); + testIntAccessors(directIntBuffer(0, 2)); + testIntAccessors(directIntBuffer(1, 2)); + } + + private void testIntAccessors(IntBuffer ibuf) { + int iarr[] = new int[2]; + for (IntFormat ifmt : IntFormats) { + IntPixelGetter getter = ifmt.getGetter(); + IntPixelSetter setter = ifmt.getSetter(); + if (getter != null && setter != null) { + assertEquals(getter.getAlphaType(), setter.getAlphaType()); + } + Color testColors[] = (getter.getAlphaType() == AlphaType.OPAQUE + ? OpaqueTestColors : TestColors); + for (Color c : testColors) { + if (getter != null) { + testget(ifmt, ibuf, iarr, c); + } + if (setter != null) { + testset(ifmt, ibuf, iarr, c); + } + } + } + } + + static boolean isGeneral(PixelConverter pc) { + Class enclosing = pc.getClass().getEnclosingClass(); + return (enclosing != null && + enclosing.getName().equals("com.sun.javafx.image.impl.General")); + } + + static void clear(ByteBuffer hbuf, ByteBuffer dbuf, byte arr[]) { + assertEquals(hbuf.capacity(), dbuf.capacity()); + assertEquals(hbuf.capacity(), arr.length); + byte bv = (byte) (Math.random() * 255); + for (int i = 0; i < arr.length; i++) { + hbuf.put(i, (byte) bv); + dbuf.put(i, (byte) bv); + arr[i] = bv; + } + } + + static void clear(IntBuffer hbuf, IntBuffer dbuf, int arr[]) { + assertEquals(hbuf.capacity(), dbuf.capacity()); + assertEquals(hbuf.capacity(), arr.length); + int iv = (int) (Math.random() * 0xffffffff); + for (int i = 0; i < arr.length; i++) { + hbuf.put(i, iv); + dbuf.put(i, iv); + arr[i] = iv; + } + } + + @Test + public void testB2BConverterTypes() { + testB2BConverterTypes(0); + testB2BConverterTypes(1); + } + + private void testB2BConverterTypes(int off) { + ByteBuffer srchbuf = heapByteBuffer(off, 4 * TestColors.length); + ByteBuffer srcdbuf = directByteBuffer(off, 4 * TestColors.length); + byte srcarr[] = new byte[4 * TestColors.length]; + ByteBuffer dsthbuf = heapByteBuffer(off, 4 * TestColors.length); + ByteBuffer dstdbuf = directByteBuffer(off, 4 * TestColors.length); + byte dstarr[] = new byte[4 * TestColors.length]; + for (ByteFormat bfmtgetter : ByteFormats) { + BytePixelGetter bpg = bfmtgetter.getGetter(); + for (ByteFormat bfmtsetter : ByteFormats) { + BytePixelSetter bps = bfmtsetter.getSetter(); + if (bps == null) continue; + ByteToBytePixelConverter b2bpc = + PixelUtils.getB2BConverter(bpg, bps); + if (bfmtsetter.getNcomp() < 4 && b2bpc == null) continue; + if (!isGeneral(b2bpc)) { + PixelConverter pc = PixelUtils.getConverter(bpg, bps); + assertEquals(b2bpc, pc); + } + assertEquals(b2bpc.getGetter(), bpg); + assertEquals(b2bpc.getSetter(), bps); + Color testColors[] = ((bpg.getAlphaType() == AlphaType.OPAQUE || + bps.getAlphaType() == AlphaType.OPAQUE) + ? OpaqueTestColors : TestColors); + int srcncomp = bfmtgetter.getNcomp(); + for (int i = 0; i < testColors.length; i++) { + bfmtgetter.setArgb(srchbuf, i * srcncomp, getArgb(testColors[i])); + bfmtgetter.setArgb(srcdbuf, i * srcncomp, getArgb(testColors[i])); + bfmtgetter.setArgb(srcarr, i * srcncomp, getArgb(testColors[i])); + } + int dstncomp = bfmtsetter.getNcomp(); + double delta = 0.0; + if (bpg.getAlphaType() == AlphaType.PREMULTIPLIED) delta += 1.0; + if (bps.getAlphaType() == AlphaType.PREMULTIPLIED) delta += 1.0; + boolean isgray = bfmtgetter.isGray() || bfmtsetter.isGray(); + if (isgray) { + delta += 1.0; + } + b2bpc.convert(srchbuf, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + b2bpc.convert(srchbuf, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + b2bpc.convert(srchbuf, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + if (isgray) refargb = grayify(refargb); + checkArgb(refargb, bfmtsetter.getArgb(dsthbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstdbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstarr, i * dstncomp), delta); + } + clear(dsthbuf, dstdbuf, dstarr); + b2bpc.convert(srcdbuf, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + b2bpc.convert(srcdbuf, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + b2bpc.convert(srcdbuf, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + if (isgray) refargb = grayify(refargb); + checkArgb(refargb, bfmtsetter.getArgb(dsthbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstdbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstarr, i * dstncomp), delta); + } + clear(dsthbuf, dstdbuf, dstarr); + b2bpc.convert(srcarr, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + b2bpc.convert(srcarr, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + b2bpc.convert(srcarr, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + if (isgray) refargb = grayify(refargb); + checkArgb(refargb, bfmtsetter.getArgb(dsthbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstdbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstarr, i * dstncomp), delta); + } + } + } + } + + @Test + public void testB2IConverterTypes() { + testB2IConverterTypes(0); + testB2IConverterTypes(1); + } + + private void testB2IConverterTypes(int off) { + ByteBuffer srchbuf = heapByteBuffer(off, 4 * TestColors.length); + ByteBuffer srcdbuf = directByteBuffer(off, 4 * TestColors.length); + byte srcarr[] = new byte[4 * TestColors.length]; + IntBuffer dsthbuf = heapIntBuffer(off, TestColors.length); + IntBuffer dstdbuf = directIntBuffer(off,TestColors.length); + int dstarr[] = new int[TestColors.length]; + for (ByteFormat bfmtgetter : ByteFormats) { + BytePixelGetter bpg = bfmtgetter.getGetter(); + for (IntFormat ifmtsetter : IntFormats) { + IntPixelSetter ips = ifmtsetter.getSetter(); + if (ips == null) continue; + ByteToIntPixelConverter b2ipc = + PixelUtils.getB2IConverter(bpg, ips); + // Should not be null - so far all int formats are full color+alpha + if (!isGeneral(b2ipc)) { + PixelConverter pc = PixelUtils.getConverter(bpg, ips); + assertEquals(b2ipc, pc); + } + assertEquals(b2ipc.getGetter(), bpg); + assertEquals(b2ipc.getSetter(), ips); + Color testColors[] = ((bpg.getAlphaType() == AlphaType.OPAQUE || + ips.getAlphaType() == AlphaType.OPAQUE) + ? OpaqueTestColors : TestColors); + int srcncomp = bfmtgetter.getNcomp(); + for (int i = 0; i < testColors.length; i++) { + bfmtgetter.setArgb(srchbuf, i * srcncomp, getArgb(testColors[i])); + bfmtgetter.setArgb(srcdbuf, i * srcncomp, getArgb(testColors[i])); + bfmtgetter.setArgb(srcarr, i * srcncomp, getArgb(testColors[i])); + } + double delta = 0.0; + if (bpg.getAlphaType() == AlphaType.PREMULTIPLIED) delta += 1.0; + if (ips.getAlphaType() == AlphaType.PREMULTIPLIED) delta += 1.0; + boolean isgray = bfmtgetter.isGray(); + if (isgray) { + delta += 1.0; + } + b2ipc.convert(srchbuf, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + b2ipc.convert(srchbuf, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + b2ipc.convert(srchbuf, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + if (isgray) refargb = grayify(refargb); + checkArgb(refargb, ifmtsetter.getArgb(dsthbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstdbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstarr, i), delta); + } + clear(dsthbuf, dstdbuf, dstarr); + b2ipc.convert(srcdbuf, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + b2ipc.convert(srcdbuf, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + b2ipc.convert(srcdbuf, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + if (isgray) refargb = grayify(refargb); + checkArgb(refargb, ifmtsetter.getArgb(dsthbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstdbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstarr, i), delta); + } + clear(dsthbuf, dstdbuf, dstarr); + b2ipc.convert(srcarr, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + b2ipc.convert(srcarr, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + b2ipc.convert(srcarr, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + if (isgray) refargb = grayify(refargb); + checkArgb(refargb, ifmtsetter.getArgb(dsthbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstdbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstarr, i), delta); + } + } + } + } + + @Test + public void testI2BConverterTypes() { + testI2BConverterTypes(0); + testI2BConverterTypes(1); + } + + private void testI2BConverterTypes(int off) { + IntBuffer srchbuf = heapIntBuffer(off, TestColors.length); + IntBuffer srcdbuf = directIntBuffer(off, TestColors.length); + int srcarr[] = new int[TestColors.length]; + ByteBuffer dsthbuf = heapByteBuffer(off, 4 * TestColors.length); + ByteBuffer dstdbuf = directByteBuffer(off, 4 * TestColors.length); + byte dstarr[] = new byte[4 * TestColors.length]; + for (IntFormat ifmtgetter : IntFormats) { + IntPixelGetter ipg = ifmtgetter.getGetter(); + for (ByteFormat bfmtsetter : ByteFormats) { + BytePixelSetter bps = bfmtsetter.getSetter(); + if (bps == null) continue; + IntToBytePixelConverter i2bpc = + PixelUtils.getI2BConverter(ipg, bps); + if (bfmtsetter.getNcomp() < 4 && i2bpc == null) continue; + if (!isGeneral(i2bpc)) { + PixelConverter pc = PixelUtils.getConverter(ipg, bps); + assertEquals(i2bpc, pc); + } + assertEquals(i2bpc.getGetter(), ipg); + assertEquals(i2bpc.getSetter(), bps); + Color testColors[] = ((ipg.getAlphaType() == AlphaType.OPAQUE || + bps.getAlphaType() == AlphaType.OPAQUE) + ? OpaqueTestColors : TestColors); + for (int i = 0; i < testColors.length; i++) { + ifmtgetter.setArgb(srchbuf, i, getArgb(testColors[i])); + ifmtgetter.setArgb(srcdbuf, i, getArgb(testColors[i])); + ifmtgetter.setArgb(srcarr, i, getArgb(testColors[i])); + } + int dstncomp = bfmtsetter.getNcomp(); + double delta = 0.0; + if (ipg.getAlphaType() == AlphaType.PREMULTIPLIED) delta += 1.0; + if (bps.getAlphaType() == AlphaType.PREMULTIPLIED) delta += 1.0; + boolean isgray = bfmtsetter.isGray(); + if (isgray) { + delta += 1.0; + } + i2bpc.convert(srchbuf, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + i2bpc.convert(srchbuf, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + i2bpc.convert(srchbuf, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + if (isgray) refargb = grayify(refargb); + checkArgb(refargb, bfmtsetter.getArgb(dsthbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstdbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstarr, i * dstncomp), delta); + } + clear(dsthbuf, dstdbuf, dstarr); + i2bpc.convert(srcdbuf, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + i2bpc.convert(srcdbuf, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + i2bpc.convert(srcdbuf, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + if (isgray) refargb = grayify(refargb); + checkArgb(refargb, bfmtsetter.getArgb(dsthbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstdbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstarr, i * dstncomp), delta); + } + clear(dsthbuf, dstdbuf, dstarr); + i2bpc.convert(srcarr, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + i2bpc.convert(srcarr, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + i2bpc.convert(srcarr, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + if (isgray) refargb = grayify(refargb); + checkArgb(refargb, bfmtsetter.getArgb(dsthbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstdbuf, i * dstncomp), delta); + checkArgb(refargb, bfmtsetter.getArgb(dstarr, i * dstncomp), delta); + } + } + } + } + + @Test + public void testI2IConverterTypes() { + testI2IConverterTypes(0); + testI2IConverterTypes(1); + } + + private void testI2IConverterTypes(int off) { + IntBuffer srchbuf = heapIntBuffer(off, TestColors.length); + IntBuffer srcdbuf = directIntBuffer(off, TestColors.length); + int srcarr[] = new int[TestColors.length]; + IntBuffer dsthbuf = heapIntBuffer(off, TestColors.length); + IntBuffer dstdbuf = directIntBuffer(off, TestColors.length); + int dstarr[] = new int[TestColors.length]; + for (IntFormat ifmtgetter : IntFormats) { + IntPixelGetter ipg = ifmtgetter.getGetter(); + for (IntFormat ifmtsetter : IntFormats) { + IntPixelSetter ips = ifmtsetter.getSetter(); + if (ips == null) continue; + IntToIntPixelConverter i2ipc = + PixelUtils.getI2IConverter(ipg, ips); + // Should not be null - so far all int formats are full color+alpha + if (!isGeneral(i2ipc)) { + PixelConverter pc = PixelUtils.getConverter(ipg, ips); + assertEquals(i2ipc, pc); + } + assertEquals(i2ipc.getGetter(), ipg); + assertEquals(i2ipc.getSetter(), ips); + Color testColors[] = ((ipg.getAlphaType() == AlphaType.OPAQUE || + ips.getAlphaType() == AlphaType.OPAQUE) + ? OpaqueTestColors : TestColors); + for (int i = 0; i < testColors.length; i++) { + ifmtgetter.setArgb(srchbuf, i, getArgb(testColors[i])); + ifmtgetter.setArgb(srcdbuf, i, getArgb(testColors[i])); + ifmtgetter.setArgb(srcarr, i, getArgb(testColors[i])); + } + double delta = 0.0; + if (ipg.getAlphaType() == AlphaType.PREMULTIPLIED) delta += 1.0; + if (ips.getAlphaType() == AlphaType.PREMULTIPLIED) delta += 1.0; + i2ipc.convert(srchbuf, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + i2ipc.convert(srchbuf, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + i2ipc.convert(srchbuf, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + checkArgb(refargb, ifmtsetter.getArgb(dsthbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstdbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstarr, i), delta); + } + clear(dsthbuf, dstdbuf, dstarr); + i2ipc.convert(srcdbuf, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + i2ipc.convert(srcdbuf, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + i2ipc.convert(srcdbuf, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + checkArgb(refargb, ifmtsetter.getArgb(dsthbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstdbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstarr, i), delta); + } + clear(dsthbuf, dstdbuf, dstarr); + i2ipc.convert(srcarr, 0, 0, dsthbuf, 0, 0, testColors.length, 1); + i2ipc.convert(srcarr, 0, 0, dstdbuf, 0, 0, testColors.length, 1); + i2ipc.convert(srcarr, 0, 0, dstarr, 0, 0, testColors.length, 1); + for (int i = 0; i < testColors.length; i++) { + int refargb = getArgb(testColors[i]); + checkArgb(refargb, ifmtsetter.getArgb(dsthbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstdbuf, i), delta); + checkArgb(refargb, ifmtsetter.getArgb(dstarr, i), delta); + } + } + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/CursorSizeConverter.java 2015-09-11 21:24:03.929287220 -0400 @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import javafx.geometry.Dimension2D; + +public abstract class CursorSizeConverter { + public static final CursorSizeConverter NO_CURSOR_SUPPORT = + createConstantConverter(0, 0); + + public static final CursorSizeConverter IDENTITY_CONVERTER = + new IdentityConverter(); + + protected CursorSizeConverter() { + } + + public abstract Dimension2D getBestCursorSize( + int preferredWidth, + int preferredHeight); + + public static CursorSizeConverter createConstantConverter( + final int width, final int height) { + return new ConstantConverter(width, height); + } + + private static final class ConstantConverter extends CursorSizeConverter { + final Dimension2D constantSize; + + public ConstantConverter(final int width, final int height) { + constantSize = new Dimension2D(width, height); + } + + @Override + public Dimension2D getBestCursorSize( + final int preferredWidth, + final int preferredHeight) { + return constantSize; + } + } + + private static final class IdentityConverter extends CursorSizeConverter { + @Override + public Dimension2D getBestCursorSize( + final int preferredWidth, + final int preferredHeight) { + return new Dimension2D(preferredWidth, preferredHeight); + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/SVGPathImpl.java 2015-09-11 21:24:04.753287211 -0400 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.javafx.geom.Path2D; +import com.sun.javafx.geom.PathConsumer2D; + +/** + */ +public class SVGPathImpl extends Path2D implements PathConsumer2D { + String content; + int windingRule; + + public SVGPathImpl(String content, int windingRule) { + this.content = content; + this.windingRule = windingRule; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + @Override + public String toString() { + return " content=" + content + ", windingRule=" + windingRule; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubAsyncImageLoader.java 2015-09-11 21:24:05.417287203 -0400 @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.javafx.runtime.async.AsyncOperation; +import com.sun.javafx.runtime.async.AsyncOperationListener; +import com.sun.javafx.tk.ImageLoader; + +public class StubAsyncImageLoader implements AsyncOperation { + private final ImageLoader imageLoader; + private final AsyncOperationListener listener; + + private boolean started; + private boolean cancelled; + private boolean finished; + + public StubAsyncImageLoader( + final ImageLoader imageLoader, + final AsyncOperationListener listener) { + this.imageLoader = imageLoader; + this.listener = listener; + } + + @Override + public void start() { + started = true; + } + + @Override + public void cancel() { + cancelled = true; + finished = true; + listener.onCancel(); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public boolean isDone() { + return finished; + } + + public boolean isStarted() { + return started; + } + + public void finish() { + finished = true; + listener.onProgress(100, 100); + listener.onCompletion(imageLoader); + } + + public void finish(final Exception e) { + finished = true; + listener.onException(e); + } + + public void setProgress(final int cur, final int max) { + listener.onProgress(cur, max); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubFilterable.java 2015-09-11 21:24:06.169287195 -0400 @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; +import com.sun.scenario.effect.Filterable; + +public class StubFilterable implements Filterable { + private final StubPlatformImage image; + + private StubFilterable(StubPlatformImage image) { + this.image = image; + } + + public static StubFilterable create(StubPlatformImage image) { + return new StubFilterable(image); + } + + @Override + public Object getData() { + throw new UnsupportedOperationException(); + } + + @Override + public int getContentWidth() { + return image.getImageInfo().getWidth(); + } + + @Override + public int getContentHeight() { + return image.getImageInfo().getHeight(); + } + + @Override + public int getPhysicalWidth() { + return image.getImageInfo().getWidth(); + } + + @Override + public int getPhysicalHeight() { + return image.getImageInfo().getHeight(); + } + + @Override + public float getPixelScale() { + return image.getPixelScale(); + } + + @Override + public void flush() { + } + + @Override + public void lock() { + } + + @Override + public void unlock() { + } + + @Override + public boolean isLost() { + return false; + } + + @Override + public int getMaxContentWidth() { + return image.getImageInfo().getWidth(); + } + + @Override + public int getMaxContentHeight() { + return image.getImageInfo().getHeight(); + } + + @Override + public void setContentWidth(int contentW) { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public void setContentHeight(int contentH) { + throw new UnsupportedOperationException("Not supported."); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubFontLoader.java 2015-09-11 21:24:06.981287186 -0400 @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.javafx.font.FontResource; +import com.sun.javafx.font.FontStrike; +import com.sun.javafx.font.PGFont; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.tk.FontLoader; +import com.sun.javafx.tk.FontMetrics; +import javafx.scene.text.Font; +import javafx.scene.text.FontPosture; +import javafx.scene.text.FontWeight; + +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +public class StubFontLoader extends FontLoader { + + @Override + public void loadFont(Font font) { + StubFont nativeFont = new StubFont(); + nativeFont.font = font; + String name = font.getName().trim().toLowerCase(Locale.ROOT); + if (name.equals("system") || name.equals("system regular")) { + font.impl_setNativeFont(nativeFont, font.getName(), "System", "Regular"); + } else if (name.equals("amble regular")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble", "Regular"); + } else if (name.equals("amble bold")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble", "Bold"); + } else if (name.equals("amble italic")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble", "Italic"); + } else if (name.equals("amble bold italic")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble", + "Bold Italic"); + } else if (name.equals("amble condensed")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble Cn", "Regular"); + } else if (name.equals("amble bold condensed")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble Cn", "Bold"); + } else if (name.equals("amble condensed italic")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble Cn", "Italic"); + } else if (name.equals("amble bold condensed italic")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble Cn", + "Bold Italic"); + } else if (name.equals("amble light")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble Lt", "Regular"); + } else if (name.equals("amble light italic")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble Lt", "Italic"); + } else if (name.equals("amble light condensed")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble LtCn", + "Regular"); + } else if (name.equals("amble light condensed italic")) { + font.impl_setNativeFont(nativeFont, font.getName(), "Amble LtCn", + "Italic"); + } + } + + @Override + public List getFamilies() { + return Arrays.asList("Amble", "Amble Cn", "Amble Lt", "Amble LtCn"); + } + + @Override + public List getFontNames() { + return Arrays.asList("Amble Regular", "Amble Bold", "Amble Italic", + "Amble Bold Italic", "Amble Condensed", "Amble Bold Condensed", + "Amble Condensed Italic", "Amble Bold Condensed Italic", + "Amble Light", "Amble Light Italic", "Amble Light Condensed", + "Amble Light Condensed Italic"); + } + + @Override + public List getFontNames(String family) { + String lower = family.trim().toLowerCase(Locale.ROOT); + if ("amble".equals(lower)) { + return Arrays.asList("Amble Regular", "Amble Bold", "Amble Italic", + "Amble Bold Italic"); + } else if ("amble cn".equals(lower)) { + return Arrays.asList("Amble Condensed", "Amble Bold Condensed", + "Amble Condensed Italic", "Amble Bold Condensed Italic"); + } else if ("amble lt".equals(lower)) { + return Arrays.asList("Amble Light", "Amble Light Italic"); + } else if ("amble ltcn".equals(lower)) { + return Arrays.asList("Amble Light Condensed", + "Amble Light Condensed Italic"); + } else { + return Arrays.asList(); + } + } + + @Override + public Font font(String family, FontWeight weight, FontPosture posture, + float size) { + family = family.trim(); + String fam = family.toLowerCase(Locale.ROOT); + String name = ""; + if ("amble".equals(fam)) { + if (weight != null + && weight.ordinal() < FontWeight.NORMAL.ordinal()) { + name = name + " Light"; + } else if (weight != null + && weight.ordinal() > FontWeight.NORMAL.ordinal()) { + name = name + " Bold"; + } else if (posture != FontPosture.ITALIC) { + name = name + " Regular"; + } + } else if ("amble cn".equals(fam) || "amble condensed".equals(fam)) { + if (weight != null + && weight.ordinal() < FontWeight.NORMAL.ordinal()) { + name = name + " Light"; + } else if (weight != null + && weight.ordinal() > FontWeight.NORMAL.ordinal()) { + name = name + " Bold"; + } + name = name + " Condensed"; + } else if ("amble lt".equals(fam)) { + if (weight.ordinal() <= FontWeight.NORMAL.ordinal()) { + name = name + " Light"; + } else if (weight != null + && weight.ordinal() < FontWeight.BOLD.ordinal() + && posture != FontPosture.ITALIC) { + name = name + " Regular"; + } else if (weight != null + && weight.ordinal() >= FontWeight.BOLD.ordinal()) { + name = name + " Bold"; + } + } else if ("amble ltcn".equals(fam)) { + if (weight.ordinal() <= FontWeight.NORMAL.ordinal()) { + name = name + " Light"; + } else if (weight != null + && weight.ordinal() >= FontWeight.BOLD.ordinal()) { + name = name + " Bold"; + } + name = name + " Condensed"; + } + if (posture == FontPosture.ITALIC) { + name = name + " Italic"; + } + String fn = "Amble" + name; + return new Font(fn, size); + } + + @Override + public Font loadFont(InputStream in, double size) { + return new Font("not implemented", size); + } + + @Override + public Font loadFont(String urlPath, double size) { + return new Font("not implemented", size); + } + + @Override + public FontMetrics getFontMetrics(Font font) { + float size = (float) font.getSize(); + return new FontMetrics(size, size, size, size/2, size/2, size/5, font); + } + + @Override + public float computeStringWidth(String s, Font f) { + // Assume that the font glyph size == font point size, mono-spaced + // TODO needs to make sense given getFontMetrics implementation + return (float) (f.getSize() * s.length()); + } + + @Override + public float getSystemFontSize() { + return 12; + } + + public static class StubFont implements PGFont { + public Font font; + + @Override public String getFullName() { + return font.getName(); + } + + @Override public String getFamilyName() { + return font.getFamily(); + } + + @Override public String getStyleName() { + return font.getStyle(); + } + + @Override public String getName() { + return font.getName(); + } + + @Override public float getSize() { + return (float) font.getSize(); + } + + @Override + public FontResource getFontResource() { + return null; + } + + @Override + public FontStrike getStrike(BaseTransform transform) { + return null; + } + + @Override + public FontStrike getStrike(BaseTransform transform, int smoothingType) { + return null; + } + + @Override + public int getFeatures() { + return 0; + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubImageLoader.java 2015-09-11 21:24:07.577287179 -0400 @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.javafx.tk.ImageLoader; +import com.sun.javafx.tk.PlatformImage; + +public final class StubImageLoader implements ImageLoader { + private final Object source; + + private final StubPlatformImageInfo imageInfo; + private final int loadWidth; + private final int loadHeight; + private final boolean preserveRatio; + private final boolean smooth; + + private final PlatformImage[] frames; + + public StubImageLoader(final Object source, + final StubPlatformImageInfo imageInfo, + final int loadWidth, + final int loadHeight, + final boolean preserveRatio, + final boolean smooth) { + this.source = source; + + this.imageInfo = imageInfo; + this.loadWidth = loadWidth; + this.loadHeight = loadHeight; + this.preserveRatio = preserveRatio; + this.smooth = smooth; + + frames = new PlatformImage[imageInfo.getFrameCount()]; + for (int i = 0; i < frames.length; ++i) { + frames[i] = source instanceof PlatformImage ? (PlatformImage) source : new StubPlatformImage(this, i); + } + } + + public Object getSource() { + return source; + } + + @Override + public Exception getException() { + return null; + } + + @Override + public int getFrameCount() { + return frames.length; + } + + @Override + public PlatformImage getFrame(final int i) { + return frames[i]; + } + + @Override + public int getFrameDelay(final int i) { + return imageInfo.getFrameDelay(i); + } + + @Override + public int getLoopCount() { + return imageInfo.getLoopCount(); + } + + @Override + public int getWidth() { + return imageInfo.getWidth(); + } + + @Override + public int getHeight() { + return imageInfo.getHeight(); + } + + public StubPlatformImageInfo getImageInfo() { + return imageInfo; + } + + public int getLoadHeight() { + return loadHeight; + } + + public int getLoadWidth() { + return loadWidth; + } + + public boolean getPreserveRatio() { + return preserveRatio; + } + + public boolean getSmooth() { + return smooth; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubImageLoaderFactory.java 2015-09-11 21:24:08.313287171 -0400 @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import java.util.HashMap; +import java.util.Map; + +import com.sun.javafx.runtime.async.AsyncOperation; +import com.sun.javafx.runtime.async.AsyncOperationListener; +import com.sun.javafx.tk.ImageLoader; +import com.sun.javafx.tk.PlatformImage; + +public final class StubImageLoaderFactory { + private final Map imageInfos; + + private StubAsyncImageLoader lastAsyncLoader; + + private final ImageLoader ERROR_IMAGE_LOADER = + new ImageLoader() { + private final Exception exception = + new Exception("Loading failed"); + + @Override + public Exception getException() { + return exception; + } + + @Override + public int getFrameCount() { + throw new IllegalStateException(); + } + + @Override + public PlatformImage getFrame(int i) { + throw new IllegalStateException(); + } + + @Override + public int getFrameDelay(int i) { + throw new IllegalStateException(); + } + + @Override + public int getLoopCount() { + throw new IllegalStateException(); + } + + @Override + public int getWidth() { + throw new IllegalStateException(); + } + + @Override + public int getHeight() { + throw new IllegalStateException(); + } + }; + + public StubImageLoaderFactory() { + imageInfos = new HashMap(); + } + + public void reset() { + imageInfos.clear(); + lastAsyncLoader = null; + } + + public void registerImage(final Object source, + final StubPlatformImageInfo imageInfo) { + imageInfos.put(source, imageInfo); + } + + public StubAsyncImageLoader getLastAsyncImageLoader() { + return lastAsyncLoader; + } + + public ImageLoader createImageLoader(final Object source, + final int loadWidth, + final int loadHeight, + final boolean preserveRatio, + final boolean smooth) { + final StubPlatformImageInfo imageInfo = imageInfos.get(source); + if (imageInfo == null) { + return ERROR_IMAGE_LOADER; + } + + return new StubImageLoader(source, imageInfo, loadWidth, loadHeight, + preserveRatio, smooth); + } + + public AsyncOperation createAsyncImageLoader( + final AsyncOperationListener listener, + final String url, final int loadWidth, final int loadHeight, + final boolean preserveRatio, final boolean smooth) { + final ImageLoader imageLoader = + createImageLoader(url, loadWidth, loadHeight, + preserveRatio, smooth); + final StubAsyncImageLoader asyncLoader = + new StubAsyncImageLoader(imageLoader, listener); + + lastAsyncLoader = asyncLoader; + return asyncLoader; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubMasterTimer.java 2015-09-11 21:24:09.049287162 -0400 @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.javafx.tk.Toolkit; +import com.sun.scenario.DelayedRunnable; +import com.sun.scenario.animation.AbstractMasterTimer; + +/** + * Stubbed implementation of AbstractMasterTimer. An instance + * of this is returned by Toolkit.getMasterTimer(). + */ +public class StubMasterTimer extends AbstractMasterTimer { + private long currentTimeMillis; + + protected StubMasterTimer() { + } + + protected int getPulseDuration(int precision) { + return precision / 60; + } + + protected void postUpdateAnimationRunnable(DelayedRunnable animationRunnable) { + Toolkit.getToolkit().setAnimationRunnable(animationRunnable); + } + + public void setCurrentTime(long millis) { + currentTimeMillis = millis; + } + + @Override + public long nanos() { + return currentTimeMillis * 1000000; + } + + @Override + public void pause() { } + + @Override + public void resume() { } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubPerformanceTracker.java 2015-09-11 21:24:09.877287153 -0400 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.javafx.perf.PerformanceTracker; + +public class StubPerformanceTracker extends PerformanceTracker { + public StubPerformanceTracker() { + } + + @Override public void doLogEvent(String s) { + } + + @Override public void doOutputLog() { + } + + @Override public long nanoTime() { + return 0; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubPlatformCursor.java 2015-09-11 21:24:10.617287145 -0400 @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import javafx.scene.Cursor; + +public class StubPlatformCursor { + public static final StubPlatformCursor DEFAULT = new StubPlatformCursor(); + + public static final StubPlatformCursor CROSSHAIR = new StubPlatformCursor(); + + public static final StubPlatformCursor TEXT = new StubPlatformCursor(); + + public static final StubPlatformCursor WAIT = new StubPlatformCursor(); + + public static final StubPlatformCursor SW_RESIZE = new StubPlatformCursor(); + + public static final StubPlatformCursor SE_RESIZE = new StubPlatformCursor(); + + public static final StubPlatformCursor NW_RESIZE = new StubPlatformCursor(); + + public static final StubPlatformCursor NE_RESIZE = new StubPlatformCursor(); + + public static final StubPlatformCursor N_RESIZE = new StubPlatformCursor(); + + public static final StubPlatformCursor S_RESIZE = new StubPlatformCursor(); + + public static final StubPlatformCursor W_RESIZE = new StubPlatformCursor(); + + public static final StubPlatformCursor E_RESIZE = new StubPlatformCursor(); + + public static final StubPlatformCursor HAND = new StubPlatformCursor(); + + public static final StubPlatformCursor MOVE = new StubPlatformCursor(); + + public static final StubPlatformCursor NONE = new StubPlatformCursor(); + + public static StubPlatformCursor getInstance(final Cursor cursor) { + StubPlatformCursor platformCursor; + + if (cursor == Cursor.CROSSHAIR) { + platformCursor = CROSSHAIR; + } else if (cursor == Cursor.TEXT) { + platformCursor = TEXT; + } else if (cursor == Cursor.WAIT) { + platformCursor = WAIT; + } else if (cursor == Cursor.SW_RESIZE) { + platformCursor = SW_RESIZE; + } else if (cursor == Cursor.SE_RESIZE) { + platformCursor = SE_RESIZE; + } else if (cursor == Cursor.NW_RESIZE) { + platformCursor = NW_RESIZE; + } else if (cursor == Cursor.NE_RESIZE) { + platformCursor = NE_RESIZE; + } else if ((cursor == Cursor.N_RESIZE) || (cursor == Cursor.V_RESIZE)) { + platformCursor = N_RESIZE; + } else if (cursor == Cursor.S_RESIZE) { + platformCursor = S_RESIZE; + } else if ((cursor == Cursor.W_RESIZE) || (cursor == Cursor.H_RESIZE)) { + platformCursor = W_RESIZE; + } else if (cursor == Cursor.E_RESIZE) { + platformCursor = E_RESIZE; + } else if (cursor == Cursor.HAND) { + platformCursor = HAND; + } else if (cursor == Cursor.MOVE) { + platformCursor = MOVE; + } else if (cursor == Cursor.NONE) { + platformCursor = NONE; + } else { + platformCursor = DEFAULT; + } + + return platformCursor; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubPlatformImage.java 2015-09-11 21:24:11.285287137 -0400 @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.javafx.tk.PlatformImage; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import javafx.scene.image.PixelFormat; +import javafx.scene.image.PixelReader; +import javafx.scene.image.WritablePixelFormat; + +public final class StubPlatformImage implements PlatformImage { + private final StubImageLoader imageLoader; + private final int frame; + + public StubPlatformImage(final StubImageLoader imageLoader, + final int frame) { + this.imageLoader = imageLoader; + this.frame = frame; + } + + public int getFrame() { + return frame; + } + + @Override + public float getPixelScale() { + return 1.0f; + } + + public StubImageLoader getImageLoader() { + return imageLoader; + } + + public StubPlatformImageInfo getImageInfo() { + return imageLoader.getImageInfo(); + } + + public Object getSource() { + return imageLoader.getSource(); + } + + @Override + public PixelFormat getPlatformPixelFormat() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isWritable() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public PlatformImage promoteToWritableImage() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getArgb(int x, int y) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setArgb(int x, int y, int argb) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void getPixels(int x, int y, int w, int h, + WritablePixelFormat pixelformat, + T pixels, int scanlineBytes) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void getPixels(int x, int y, int w, int h, + WritablePixelFormat pixelformat, + byte[] pixels, int offset, int scanlineBytes) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void getPixels(int x, int y, int w, int h, + WritablePixelFormat pixelformat, + int[] pixels, int offset, int scanlineInts) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setPixels(int x, int y, int w, int h, + PixelFormat pixelformat, + T pixels, int scanlineBytes) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setPixels(int x, int y, int w, int h, + PixelFormat pixelformat, + byte[] pixels, int offset, int scanlineBytes) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setPixels(int x, int y, int w, int h, + PixelFormat pixelformat, + int[] pixels, int offset, int scanlineInts) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setPixels(int dstx, int dsty, int w, int h, + PixelReader reader, int srcx, int srcy) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + + sb.append("StubPlatformImage[source = ") + .append(imageLoader.getSource()) + .append(", width = ").append(imageLoader.getWidth()) + .append(", height = ").append(imageLoader.getHeight()) + .append(", frame = ").append(frame) + .append("]"); + + return sb.toString(); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubPlatformImageCursor.java 2015-09-11 21:24:11.945287130 -0400 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +public class StubPlatformImageCursor extends StubPlatformCursor { + private final StubPlatformImage platformImage; + + private final float hotspotX; + + private final float hotspotY; + + public StubPlatformImageCursor(final StubPlatformImage platformImage, + final float hotspotX, + final float hotspotY) { + this.platformImage = platformImage; + this.hotspotX = hotspotX; + this.hotspotY = hotspotY; + } + + public StubPlatformImage getPlatformImage() { + return platformImage; + } + + public float getHotspotX() { + return hotspotX; + } + + public float getHotspotY() { + return hotspotY; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubPlatformImageInfo.java 2015-09-11 21:24:12.613287122 -0400 @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +public final class StubPlatformImageInfo { + private final int width; + private final int height; + private final int[] frameDelays; + private final int loopCount; + + public StubPlatformImageInfo(final int width, + final int height) { + this(width, height, null, 0); + } + + public StubPlatformImageInfo(final int width, + final int height, + final int[] frameDelays, final int loopCount) { + this.width = width; + this.height = height; + this.frameDelays = frameDelays; + this.loopCount = loopCount; + } + + public int getFrameCount() { + return (frameDelays != null) ? frameDelays.length : 1; + } + + public int getFrameDelay(final int index) { + return frameDelays[index]; + } + + int getLoopCount() { + return loopCount; + } + + public int getHeight() { + return height; + } + + public int getWidth() { + return width; + } + + public boolean contains(final int x, final int y) { + final int i = (2 * x / width) & 1; + final int j = (2 * y / height) & 1; + + return (i ^ j) == 0; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubPopupStage.java 2015-09-11 21:24:13.209287116 -0400 @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +public class StubPopupStage extends StubStage { + + @Override + public void close() { + getNotificationSender().closing(); + } + + @Override + public void setFullScreen(boolean fullScreen) { + getNotificationSender().changedFullscreen(fullScreen); + } + + @Override + public void setIconified(boolean iconified) { + getNotificationSender().changedIconified(iconified); + } + + @Override + public void setMaximized(boolean maximized) { + getNotificationSender().changedMaximized(maximized); + } + + @Override + public void setAlwaysOnTop(boolean alwaysOnTop) { + getNotificationSender().changedAlwaysOnTop(alwaysOnTop); + } + + @Override + public void setResizable(boolean resizable) { + getNotificationSender().changedResizable(resizable); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubScene.java 2015-09-11 21:24:13.889287108 -0400 @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import java.security.AccessControlContext; +import com.sun.javafx.sg.prism.NGCamera; +import com.sun.javafx.sg.prism.NGLightBase; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.javafx.tk.TKClipboard; +import com.sun.javafx.tk.TKScene; +import com.sun.javafx.tk.TKSceneListener; +import com.sun.javafx.tk.TKScenePaintListener; +import javafx.scene.Node; + +public class StubScene implements TKScene { + + StubStage stage; + private TKSceneListener listener; + private Object cursor; + private NGCamera camera; + Runnable inputMethodCompistionFinishedDelegate; + + @Override + public void dispose() { + // ignore + } + + public void waitForRenderingToComplete() { + // ignore + } + + public void waitForSynchronization() { + //ignore + } + + public void releaseSynchronization(boolean updateState) { + // ignore + } + + public void setTKSceneListener(TKSceneListener listener) { + this.listener = listener; + } + + public void setRoot(NGNode root) { + // ignore + } + + public void markDirty() { + // ignore + } + + public void setCamera(NGCamera ci) { + camera = ci; + } + + public void setFillPaint(Object fillPaint) { + // ignore + } + + public void setCursor(Object cursor) { + this.cursor = cursor; + } + + public Object getCursor() { + return cursor; + } + + public void enableInputMethodEvents(boolean enable) { + // ignore + } + + @Override + public void finishInputMethodComposition() { + if (inputMethodCompistionFinishedDelegate != null) { + inputMethodCompistionFinishedDelegate.run(); + } + } + + public void setInputMethodCompositionFinishDelegate(Runnable r) { + inputMethodCompistionFinishedDelegate = r; + } + + public void entireSceneNeedsRepaint() { + } + + @Override + public TKClipboard createDragboard(boolean isDragSource) { + return StubToolkit.createDragboard(); + } + + @Override + public void setTKScenePaintListener(TKScenePaintListener listener) { + // not implemented + } + + public TKSceneListener getListener() { + return listener; + } + + @Override + public NGLightBase[] getLights() { + // ignore + return null; + } + + @Override + public void setLights(NGLightBase[] lights) { + // ignore + } + + public NGCamera getCamera() { + return camera; + } + + @Override + public AccessControlContext getAccessControlContext() { + return null; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubStage.java 2015-09-11 21:24:14.721287099 -0400 @@ -0,0 +1,418 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import java.security.AccessControlContext; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +import com.sun.javafx.tk.FocusCause; +import com.sun.javafx.tk.TKScene; +import com.sun.javafx.tk.TKStage; +import com.sun.javafx.tk.TKStageListener; + +/** + * @author Richard Bair + */ +public class StubStage implements TKStage { + + private NotificationSender notificationSender = new NotificationSender(); + + @Override + public void setTKStageListener(TKStageListener listener) { + notificationSender.setListener(listener); + } + + @Override + public TKScene createTKScene(boolean depthBuffer, boolean msaa, AccessControlContext acc) { + return new StubScene(); + } + + @Override + public void setScene(TKScene scene) { + if (scene != null) { + StubScene s = (StubScene) scene; + s.stage = this; + notificationSender.setScene(s); + if (visible && width != -1 && height != -1) + s.getListener().changedSize(width, height); + } + } + + public int numTimesSetSizeAndLocation; + + // Platform place/resize the window with some + // "default" value. Pretending that the values + // below are those platform defaults. + public float x = 16; + public float y = 12; + public float width = 256; + public float height = 192; + + public boolean visible; + public float opacity; + + @Override + public void setBounds(float x, float y, boolean xSet, boolean ySet, + float width, float height, + float contentWidth, float contentHeight, + float xGravity, float yGravity) + { + numTimesSetSizeAndLocation++; + + boolean locationChanged = false; + + if (xSet && (this.x != x)) { + this.x = x; + locationChanged = true; + } + + if (ySet && (this.y != y)) { + this.y = y; + locationChanged = true; + } + + if (locationChanged) { + notificationSender.changedLocation(x, y); + } + + boolean sizeChanged = false; + + if (width > 0) { + if (this.width != width) { + this.width = width; + sizeChanged = true; + } + } else if (contentWidth > 0) { + if (this.width != contentWidth) { + this.width = contentWidth; + sizeChanged = true; + } + } + + if (height > 0) { + if (this.height != height) { + this.height = height; + sizeChanged = true; + } + } else if (contentHeight > 0) { + if (this.height != contentHeight) { + this.height = contentHeight; + sizeChanged = true; + } + } + + if (sizeChanged) { + notificationSender.changedSize(width, height); + } + } + + @Override + public float getUIScale() { + return 1.0f; + } + + @Override + public float getRenderScale() { + return 1.0f; + } + + // Just a helper method + public void setSize(float w, float h) { + setBounds(0, 0, false, false, w, h, 0, 0, 0, 0); + } + + // Just a helper method + public void setLocation(float x, float y) { + setBounds(x, y, true, true, 0, 0, 0, 0, 0, 0); + } + + @Override + public void setIcons(List icons) { + } + + @Override + public void setTitle(String title) { + } + + @Override + public void setVisible(boolean visible) { + this.visible = visible; + + if (!visible) { + notificationSender.changedFocused(false, FocusCause.DEACTIVATED); + } + + notificationSender.changedLocation(x, y); + notificationSender.changedSize(width, height); + } + + @Override + public void setOpacity(float opacity) { + this.opacity = opacity; + } + + @Override + public void setIconified(boolean iconified) { + notificationSender.changedIconified(iconified); + } + + @Override + public void setMaximized(boolean maximized) { + notificationSender.changedMaximized(maximized); + } + + @Override + public void setAlwaysOnTop(boolean alwaysOnTop) { + notificationSender.changedAlwaysOnTop(alwaysOnTop); + } + + @Override + public void setResizable(boolean resizable) { + notificationSender.changedResizable(resizable); + } + + @Override + public void setImportant(boolean important) { + } + + @Override + public void setFullScreen(boolean fullScreen) { + notificationSender.changedFullscreen(fullScreen); + } + + @Override + public void requestFocus() { + notificationSender.changedFocused(true, FocusCause.ACTIVATED); + } + + @Override + public void requestFocus(FocusCause cause) { + notificationSender.changedFocused(true, cause); + } + + @Override + public void toBack() { + } + + @Override + public void toFront() { + } + + @Override + public void close() { + } + + private boolean focusGrabbed; + + @Override + public boolean grabFocus() { + focusGrabbed = true; + return true; + } + + @Override + public void ungrabFocus() { + focusGrabbed = false; + } + + public boolean isFocusGrabbed() { + return focusGrabbed; + } + + @Override + public void setMinimumSize(int minWidth, int minHeight) { + } + + @Override + public void setMaximumSize(int maxWidth, int maxHeight) { + } + + public void holdNotifications() { + notificationSender.holdNotifications(); + } + + public void releaseNotifications() { + notificationSender.releaseNotifications(); + } + + public void releaseSingleNotification() { + notificationSender.releaseSingleNotification(); + } + + protected final TKStageListener getNotificationSender() { + return notificationSender; + } + + @Override + public void requestInput(String text, int type, double width, double height, + double Mxx, double Mxy, double Mxz, double Mxt, + double Myx, double Myy, double Myz, double Myt, + double Mzx, double Mzy, double Mzz, double Mzt) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void releaseInput() { + throw new UnsupportedOperationException("Not supported yet."); + } + + private interface Notification { + void execute(TKStageListener listener); + } + + private static final class NotificationSender implements TKStageListener { + private final Queue queue = + new LinkedList(); + + private boolean hold; + private TKStageListener listener; + private StubScene scene; + + public void setListener(final TKStageListener listener) { + this.listener = listener; + } + + public void setScene(final StubScene scene) { + this.scene = scene; + } + + public void holdNotifications() { + hold = true; + } + + public void releaseNotifications() { + hold = false; + flush(); + } + + private void releaseSingleNotification() { + queue.poll().execute(listener); + } + + @Override + public void changedLocation(final float x, final float y) { + process(listener1 -> listener1.changedLocation(x, y)); + } + + @Override + public void changedSize(final float width, final float height) { + process(listener1 -> { + listener1.changedSize(width, height); + if (scene != null && width != -1 && height != -1) { + scene.getListener().changedSize(width, height); + } + }); + } + + @Override + public void changedFocused(final boolean focused, + final FocusCause cause) { + process(listener1 -> listener1.changedFocused(focused, cause)); + } + + @Override + public void changedIconified(final boolean iconified) { + process(listener1 -> listener1.changedIconified(iconified)); + } + + @Override + public void changedMaximized(final boolean maximized) { + process(listener1 -> listener1.changedMaximized(maximized)); + } + + public void changedAlwaysOnTop(boolean alwaysOnTop) { + process(listener1 -> listener1.changedAlwaysOnTop(alwaysOnTop)); + } + + + @Override + public void changedResizable(final boolean resizable) { + process(listener1 -> listener1.changedResizable(resizable)); + } + + @Override + public void changedFullscreen(final boolean fs) { + process(listener1 -> listener1.changedFullscreen(fs)); + } + + @Override + public void closing() { + process(listener1 -> listener1.closing()); + } + + @Override + public void closed() { + process(listener1 -> listener1.closed()); + } + + @Override + public void focusUngrab() { + process(listener1 -> listener1.focusUngrab()); + } + + private void process(final Notification notification) { + if (hold) { + queue.offer(notification); + return; + } + + if (listener != null) { + notification.execute(listener); + } + } + + private void flush() { + if (listener == null) { + queue.clear(); + return; + } + + Notification nextNotification = queue.poll(); + while (nextNotification != null) { + nextNotification.execute(listener); + nextNotification = queue.poll(); + } + } + + /** + * Initialize accessibility + */ + public void initAccessibleTKStageListener() { + // TODO: Add code later + } + + @Override + public void changedScreen(Object from, Object to) { + // TODO: Add code later + } + + } + + public void setRTL(boolean b) { + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubTextLayout.java 2015-09-11 21:24:15.473287090 -0400 @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.Path2D; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.Shape; +import com.sun.javafx.scene.text.*; +import javafx.scene.shape.PathElement; +import javafx.scene.text.Font; + +public class StubTextLayout implements TextLayout { + + @Override + public boolean setContent(TextSpan[] spans) { + return true; + } + + private String text; + private Font font; + @Override + public boolean setContent(String text, Object font) { + this.text = text; + final StubFontLoader.StubFont stub = ((StubFontLoader.StubFont)font); + this.font = stub == null ? null : stub.font; + return true; + } + + @Override + public boolean setAlignment(int alignment) { + return true; + } + + @Override + public boolean setWrapWidth(float wrapWidth) { + return true; + } + + @Override + public boolean setLineSpacing(float spacing) { + return true; + } + + @Override + public boolean setDirection(int direction) { + return true; + } + + @Override + public boolean setBoundsType(int type) { + return true; + } + + @Override + public BaseBounds getBounds() { + return getBounds(null, new RectBounds()); + } + + @Override + public BaseBounds getBounds(TextSpan filter, BaseBounds bounds) { + final double fontSize = (font == null ? 0 : ((Font)font).getSize()); + final String[] lines = text.split("\n"); + double width = 0.0; + double height = fontSize * lines.length; + for (String line : lines) { + width = Math.max(width, fontSize * line.length()); + } + return bounds.deriveWithNewBounds(0, (float)-fontSize, 0, + (float)width, (float)(height-fontSize), 0); + } + + class StubTextLine implements TextLine { + @Override public GlyphList[] getRuns() { + return new GlyphList[0]; + } + @Override public RectBounds getBounds() { + return new RectBounds(); + } + @Override public float getLeftSideBearing() { + return 0; + } + @Override public float getRightSideBearing() { + return 0; + } + @Override public int getStart() { + return 0; + } + @Override public int getLength() { + return 0; + } + } + + @Override + public TextLine[] getLines() { + return new TextLine[] {new StubTextLine()}; + } + + @Override + public GlyphList[] getRuns() { + return new GlyphList[0]; + } + + @Override + public Shape getShape(int type, TextSpan filter) { + return new Path2D(); + } + + @Override + public HitInfo getHitInfo(float x, float y) { + // TODO this probably needs to be entirely rewritten... + if (text == null) { + final HitInfo hit = new HitInfo(); + hit.setCharIndex(0); + hit.setLeading(true); + return hit; + } + + final double fontSize = (font == null ? 0 : ((Font)font).getSize()); + final String[] lines = text.split("\n"); + int lineIndex = Math.min(lines.length - 1, (int) (y / fontSize)); + if (lineIndex >= lines.length) { + throw new IllegalStateException("Asked for hit info out of y range: x=" + x + "y=" + + + y + "text='" + text + "', lineIndex=" + lineIndex + ", numLines=" + lines.length + + ", fontSize=" + fontSize); + } + int offset = 0; + for (int i=0; i text.length()) { + throw new IllegalStateException("Asked for hit info out of x range"); + } + + final HitInfo hit = new HitInfo(); + hit.setCharIndex(offset + charPos); + return hit; + } + + @Override + public PathElement[] getCaretShape(int offset, boolean isLeading, float x, + float y) { + return new PathElement[0]; + } + + @Override + public PathElement[] getRange(int start, int end, int type, float x, float y) { + return new PathElement[0]; + } + + @Override + public BaseBounds getVisualBounds(int type) { + return new RectBounds(); + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubTextLayoutFactory.java 2015-09-11 21:24:16.065287084 -0400 @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.javafx.scene.text.TextLayout; +import com.sun.javafx.scene.text.TextLayoutFactory; + +public class StubTextLayoutFactory implements TextLayoutFactory { + + @Override + public TextLayout createLayout() { + return new StubTextLayout(); + } + + @Override + public TextLayout getLayout() { + return new StubTextLayout(); + } + + @Override + public void disposeLayout(TextLayout layout) { + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubToolkit.java 2015-09-11 21:24:16.741287076 -0400 @@ -0,0 +1,932 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * StubToolkit.java + */ + +package test.com.sun.javafx.pgstub; + +import com.sun.glass.ui.CommonDialogs.FileChooserResult; +import com.sun.javafx.application.PlatformImpl; +import com.sun.javafx.embed.HostInterface; +import com.sun.javafx.geom.Path2D; +import com.sun.javafx.geom.Shape; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.menu.MenuBase; +import com.sun.javafx.perf.PerformanceTracker; +import com.sun.javafx.runtime.async.AsyncOperation; +import com.sun.javafx.runtime.async.AsyncOperationListener; +import com.sun.javafx.scene.text.HitInfo; +import com.sun.javafx.scene.text.TextLayoutFactory; +import com.sun.javafx.tk.*; +import com.sun.prism.BasicStroke; +import com.sun.scenario.DelayedRunnable; +import com.sun.scenario.animation.AbstractMasterTimer; +import com.sun.scenario.effect.FilterContext; +import com.sun.scenario.effect.Filterable; +import javafx.application.ConditionalFeature; +import javafx.geometry.Dimension2D; +import javafx.scene.image.Image; +import javafx.scene.input.*; +import javafx.scene.paint.Color; +import javafx.scene.paint.ImagePattern; +import javafx.scene.paint.LinearGradient; +import javafx.scene.paint.RadialGradient; +import javafx.scene.shape.*; +import javafx.stage.FileChooser.ExtensionFilter; +import javafx.stage.Modality; +import javafx.stage.StageStyle; +import javafx.stage.Window; +import javafx.util.Pair; + +import java.io.File; +import java.io.InputStream; +import java.security.AccessControlContext; +import java.util.*; +import java.util.concurrent.Future; + +/** + * A Toolkit implementation for use with Testing. + * + * @author Richard + */ +public class StubToolkit extends Toolkit { + + private Map contextMap = new HashMap(); + + private StubMasterTimer masterTimer = new StubMasterTimer(); + + private PerformanceTracker performanceTracker = new StubPerformanceTracker(); + + private final StubImageLoaderFactory imageLoaderFactory = + new StubImageLoaderFactory(); + + private CursorSizeConverter cursorSizeConverter = + CursorSizeConverter.NO_CURSOR_SUPPORT; + + private int maximumCursorColors = 2; + + private TKScreenConfigurationListener screenConfigurationListener; + + private static final ScreenConfiguration[] DEFAULT_SCREEN_CONFIG = { + new ScreenConfiguration(0, 0, 1920, 1200, 0, 0, 1920, 1172, 96) + }; + + private ScreenConfiguration[] screenConfigurations = DEFAULT_SCREEN_CONFIG; + + static { + try { + // ugly hack to initialize "runLater" method in Platform.java + PlatformImpl.startup(() -> {}); + } catch (Exception ex) {} + + // allow tests to access PG scenegraph + // so that they can run with assertion enabled + javafx.scene.Scene.impl_setAllowPGAccess(true); + } + private boolean pulseRequested; + + /* + * overrides of Toolkit's abstract functions + */ + + @Override + public boolean init() { + return true; + } + + @Override + public TKStage createTKStage(Window peerWindow, boolean securityDialog, StageStyle stageStyle, boolean primary, Modality modality, TKStage owner, boolean rtl, AccessControlContext acc) { + + return new StubStage(); + } + + @Override + public TKStage createTKPopupStage(Window peerWindow, StageStyle popupStyle, TKStage owner, AccessControlContext acc) { + return new StubPopupStage(); + } + + @Override + public TKStage createTKEmbeddedStage(HostInterface host, AccessControlContext acc) { + return new StubStage(); + } + + @Override + public AppletWindow createAppletWindow(long parent, String serverName) { + // unsupported + return null; + } + + @Override + public void closeAppletWindow() { + // unsupported + } + + private final TKSystemMenu systemMenu = new StubSystemMenu(); + @Override + public TKSystemMenu getSystemMenu() { + return systemMenu; + } + + @Override + public void startup(Runnable runnable) { + runnable.run(); + } + + @Override + public void checkFxUserThread() { + // Do nothing + } + + @Override + public boolean isFxUserThread() { + // Always on the FX app thread + return true; + } + + @Override + public void defer(Runnable runnable) { + runnable.run(); + } + + @Override + public void exit() { + System.exit(0); + } + + @Override + public Future addRenderJob(RenderJob rj) { + return rj; + } + + @Override + public Map getContextMap() { + return contextMap; + } + + @Override public int getRefreshRate() { + return -1; + } + + private DelayedRunnable animationRunnable; + + @Override + public void setAnimationRunnable(DelayedRunnable animationRunnable) { + this.animationRunnable = animationRunnable; + } + + @Override + public PerformanceTracker getPerformanceTracker() { + return performanceTracker; + } + + @Override public PerformanceTracker createPerformanceTracker() { + return new StubPerformanceTracker(); + } + + @Override + protected Object createColorPaint(Color paint) { + return new com.sun.prism.paint.Color((float) paint.getRed(), + (float) paint.getGreen(), + (float) paint.getBlue(), + (float) paint.getOpacity()); + } + + @Override + protected Object createLinearGradientPaint(LinearGradient paint) { + // Non functioning but compiles + return new com.sun.prism.paint.Color(1, 1, 1, 1); + } + + @Override + protected Object createRadialGradientPaint(RadialGradient paint) { + // Non functioning but compiles + return new com.sun.prism.paint.Color(1, 1, 1, 1); + } + + @Override + protected Object createImagePatternPaint(ImagePattern paint) { + // Non functioning but compiles + return new com.sun.prism.paint.Color(1, 1, 1, 1); + } + + static BasicStroke tmpStroke = new BasicStroke(); + void initStroke(StrokeType pgtype, double strokewidth, + StrokeLineCap pgcap, + StrokeLineJoin pgjoin, float miterLimit) + { + int type; + if (pgtype == StrokeType.CENTERED) { + type = BasicStroke.TYPE_CENTERED; + } else if (pgtype == StrokeType.INSIDE) { + type = BasicStroke.TYPE_INNER; + } else { + type = BasicStroke.TYPE_OUTER; + } + + int cap; + if (pgcap == StrokeLineCap.BUTT) { + cap = BasicStroke.CAP_BUTT; + } else if (pgcap == StrokeLineCap.SQUARE) { + cap = BasicStroke.CAP_SQUARE; + } else { + cap = BasicStroke.CAP_ROUND; + } + + int join; + if (pgjoin == StrokeLineJoin.BEVEL) { + join = BasicStroke.JOIN_BEVEL; + } else if (pgjoin == StrokeLineJoin.MITER) { + join = BasicStroke.JOIN_MITER; + } else { + join = BasicStroke.JOIN_ROUND; + } + + tmpStroke.set(type, (float) strokewidth, cap, join, miterLimit); + } + + @Override + public void accumulateStrokeBounds(Shape shape, float bbox[], + StrokeType pgtype, + double strokewidth, + StrokeLineCap pgcap, + StrokeLineJoin pgjoin, + float miterLimit, + BaseTransform tx) + { + + initStroke(pgtype, strokewidth, pgcap, pgjoin, miterLimit); + // TODO: The accumulation could be done directly without creating a Shape + Shape.accumulate(bbox, tmpStroke.createStrokedShape(shape), tx); + } + + @Override + public boolean strokeContains(Shape shape, double x, double y, + StrokeType pgtype, + double strokewidth, + StrokeLineCap pgcap, + StrokeLineJoin pgjoin, + float miterLimit) + { + initStroke(pgtype, strokewidth, pgcap, pgjoin, miterLimit); + // TODO: The contains testing could be done directly without creating a Shape + return tmpStroke.createStrokedShape(shape).contains((float) x, (float) y); + } + + @Override + public Shape createStrokedShape(Shape shape, + StrokeType pgtype, + double strokewidth, + StrokeLineCap pgcap, + StrokeLineJoin pgjoin, + float miterLimit, + float[] dashArray, + float dashOffset) { + initStroke(pgtype, strokewidth, pgcap, pgjoin, miterLimit); + return tmpStroke.createStrokedShape(shape); + } + + public CursorSizeConverter getCursorSizeConverter() { + return cursorSizeConverter; + } + + public void setCursorSizeConverter( + CursorSizeConverter cursorSizeConverter) { + this.cursorSizeConverter = cursorSizeConverter; + } + + @Override + public Dimension2D getBestCursorSize(int preferredWidth, int preferredHeight) { + return cursorSizeConverter.getBestCursorSize(preferredWidth, + preferredHeight); + } + + @Override + public int getMaximumCursorColors() { + return maximumCursorColors; + } + + public void setMaximumCursorColors(int maximumCursorColors) { + this.maximumCursorColors = maximumCursorColors; + } + + @Override + public AbstractMasterTimer getMasterTimer() { + return masterTimer; + } + + @Override + public FontLoader getFontLoader() { + return new StubFontLoader(); + } + + @Override + public TextLayoutFactory getTextLayoutFactory() { + return new StubTextLayoutFactory(); + } + + @Override public boolean isSupported(ConditionalFeature feature) { + if (feature == ConditionalFeature.SCENE3D) { + return true; + } else if (feature == ConditionalFeature.TRANSPARENT_WINDOW) { + return true; + } + return false; + } + + /* + * additional testing functions + */ + public void fireTestPulse() { + firePulse(); + } + + public boolean isPulseRequested() { + return pulseRequested; + } + + public void clearPulseRequested() { + pulseRequested = false; + } + + // do nothing -- bringing in FrameJob and MasterTimer also bring in + // Settings and crap which isn't setup for the testing stuff because + // we don't run through a RuntimeProvider or do normal startup + // public @Override public void triggerNextPulse():Void { } + @Override public void requestNextPulse() { + pulseRequested = true; + } + + private TKClipboard clipboard = new TKClipboard() { + private Map map = new HashMap(); + private Image image; + private double offsetX; + private double offsetY; + + @Override + public void setSecurityContext(AccessControlContext ctx) { + } + + @Override public Set getContentTypes() { + return map.keySet(); + } + + @Override public boolean putContent(Pair... content) { + boolean good; + for (Pair pair : content) { + good = map.put(pair.getKey(), pair.getValue()) == pair.getValue(); + if (!good) return false; + } + return true; + } + + @Override public Object getContent(DataFormat dataFormat) { + return map.get(dataFormat); + } + + @Override public boolean hasContent(DataFormat dataFormat) { + return map.containsKey(dataFormat); + } + + @Override public Set getTransferModes() { + Set modes = new HashSet(); + modes.add(TransferMode.COPY); + return modes; + } + + @Override + public void setDragView(Image image) { + this.image = image; + } + + @Override + public void setDragViewOffsetX(double offsetX) { + this.offsetX = offsetX; + } + + @Override + public void setDragViewOffsetY(double offsetY) { + this.offsetY = offsetY; + } + + @Override + public Image getDragView() { + return image; + } + + @Override + public double getDragViewOffsetX() { + return offsetX; + } + + @Override + public double getDragViewOffsetY() { + return offsetY; + } + }; + + + @Override + public TKClipboard getSystemClipboard() { + return clipboard; + } + + @Override public TKClipboard getNamedClipboard(String name) { + return null; + } + + public static TKClipboard createDragboard() { + StubToolkit tk = (StubToolkit)Toolkit.getToolkit(); + if (tk.dndDelegate != null) { + return tk.dndDelegate.createDragboard(); + } + return null; + } + + @Override + public void enableDrop(TKScene s, TKDropTargetListener l) { + if (dndDelegate != null) { + dndDelegate.enableDrop(l); + } + } + + private ScreenConfigurationAccessor accessor = new ScreenConfigurationAccessor() { + @Override + public int getMinX(Object obj) { + return ((ScreenConfiguration) obj).getMinX(); + } + + @Override + public int getMinY(Object obj) { + return ((ScreenConfiguration) obj).getMinY(); + } + + @Override + public int getWidth(Object obj) { + return ((ScreenConfiguration) obj).getWidth(); + } + + @Override + public int getHeight(Object obj) { + return ((ScreenConfiguration) obj).getHeight(); + } + + @Override + public int getVisualMinX(Object obj) { + return ((ScreenConfiguration) obj).getVisualMinX(); + } + + @Override + public int getVisualMinY(Object obj) { + return ((ScreenConfiguration) obj).getVisualMinY(); + } + + @Override + public int getVisualWidth(Object obj) { + return ((ScreenConfiguration) obj).getVisualWidth(); + } + + @Override + public int getVisualHeight(Object obj) { + return ((ScreenConfiguration) obj).getVisualHeight(); + } + + @Override + public float getDPI(Object obj) { + return ((ScreenConfiguration) obj).getDPI(); + } + + @Override + public float getUIScale(Object obj) { + return ((ScreenConfiguration) obj).getScale(); + } + + @Override + public float getRenderScale(Object obj) { + return ((ScreenConfiguration) obj).getScale(); + } + }; + + @Override + public ScreenConfigurationAccessor setScreenConfigurationListener( + TKScreenConfigurationListener listener) { + screenConfigurationListener = listener; + return accessor; + } + + @Override + public ScreenConfiguration getPrimaryScreen() { + return screenConfigurations[0]; + } + + public void setScreens(ScreenConfiguration... screenConfigurations) { + this.screenConfigurations = screenConfigurations.clone(); + if (screenConfigurationListener != null) { + screenConfigurationListener.screenConfigurationChanged(); + } + } + + public void resetScreens() { + setScreens(DEFAULT_SCREEN_CONFIG); + } + + @Override + public List getScreens() { + return Arrays.asList(screenConfigurations); + } + + @Override + public ScreenConfigurationAccessor getScreenConfigurationAccessor() { + return accessor; + } + + @Override public void registerDragGestureListener(TKScene s, Set tm, TKDragGestureListener l) { + if (dndDelegate != null) { + dndDelegate.registerListener(l); + } + } + + @Override public void startDrag(TKScene scene, Set tm, TKDragSourceListener l, Dragboard dragboard) { + if (dndDelegate != null) { + dndDelegate.startDrag(scene, tm, l, dragboard); + } + } + + @Override + public ImageLoader loadImage(String url, int width, int height, + boolean preserveRatio, boolean smooth) { + return imageLoaderFactory.createImageLoader(url, width, height, + preserveRatio, smooth); + } + + @Override + public ImageLoader loadImage(InputStream stream, int width, int height, + boolean preserveRatio, boolean smooth) { + return imageLoaderFactory.createImageLoader(stream, width, height, + preserveRatio, smooth); + } + + @Override + public AsyncOperation loadImageAsync( + AsyncOperationListener listener, String url, int width, int height, + boolean preserveRatio, boolean smooth) { + return imageLoaderFactory.createAsyncImageLoader( + listener, url, width, height, preserveRatio, smooth); + } + + @Override + public ImageLoader loadPlatformImage(Object platformImage) { + return imageLoaderFactory.createImageLoader(platformImage, + 0, 0, false, false); + } + + @Override + public PlatformImage createPlatformImage(int w, int h) { + PlatformImage image = new StubWritablePlatformImage(w, h); + imageLoaderFactory.registerImage(image, new StubPlatformImageInfo(w, h)); + return image; + } + + @Override + public void waitFor(Task t) { + throw new UnsupportedOperationException(); + } + + @Override + public int getKeyCodeForChar(String character) { + if (charToKeyCodeMap != null) { + final KeyCode keyCode = charToKeyCodeMap.get(character); + if (keyCode != null) { + return keyCode.impl_getCode(); + } + } + + return 0; + } + + @Override + public PathElement[] convertShapeToFXPath(Object shape) { + // Had to be mocked up for TextField tests (for the caret!) + // Since the "shape" could be anything, I'm just returning + // something here, doesn't matter what. + return new PathElement[0]; + } + + @Override + public HitInfo convertHitInfoToFX(Object hit) { + return (HitInfo) hit; + } + + @Override + public Filterable toFilterable(Image img) { + return StubFilterable.create((StubPlatformImage)img.impl_getPlatformImage()); + } + + @Override + public FilterContext getFilterContext(Object config) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isForwardTraversalKey(KeyEvent e) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isBackwardTraversalKey(KeyEvent e) { + throw new UnsupportedOperationException(); + } + + @Override + public Object createSVGPathObject(SVGPath svgpath) { + int windingRule = (svgpath.getFillRule() == FillRule.NON_ZERO) ? + Path2D.WIND_NON_ZERO : Path2D.WIND_EVEN_ODD; + + return new SVGPathImpl(svgpath.getContent(), windingRule); + } + + @Override + public Path2D createSVGPath2D(SVGPath svgpath) { + int windingRule = (svgpath.getFillRule() == FillRule.NON_ZERO) ? + Path2D.WIND_NON_ZERO : Path2D.WIND_EVEN_ODD; + + return new SVGPathImpl(svgpath.getContent(), windingRule); + } + + @Override + public boolean imageContains(Object image, float x, float y) { + return ((StubPlatformImage) image).getImageInfo() + .contains((int) x, (int) y); + } + + public void setCurrentTime(long millis) { + masterTimer.setCurrentTime(millis); + } + + public void handleAnimation() { + if (animationRunnable != null) { + try { + animationRunnable.run(); + } catch (Throwable t) { + Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), t); + } + } + } + + public StubImageLoaderFactory getImageLoaderFactory() { + return imageLoaderFactory; + } + + public void setAnimationTime(final long millis) { + setCurrentTime(millis); + handleAnimation(); + fireTestPulse(); + } + + @Override + public void installInputMethodRequests(TKScene scene, InputMethodRequests requests) { + // just do nothing here. + } + + private Map charToKeyCodeMap; + + public void setCharToKeyCodeMap(Map charToKeyCodeMap) { + this.charToKeyCodeMap = charToKeyCodeMap; + } + + @Override + public Object renderToImage(ImageRenderingContext context) { + throw new UnsupportedOperationException(); + } + + @Override public boolean canStartNestedEventLoop() { + return false; + } + + @Override public Object enterNestedEventLoop(Object key) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override public void exitNestedEventLoop(Object key, Object rval) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isNestedLoopRunning() { + return false; + } + + private KeyCode platformShortcutKey = KeyCode.SHORTCUT; + + public void setPlatformShortcutKey(final KeyCode platformShortcutKey) { + this.platformShortcutKey = platformShortcutKey; + } + + public KeyCode getPlatformShortcutKey() { + return platformShortcutKey; + } + + private DndDelegate dndDelegate; + public void setDndDelegate(DndDelegate dndDelegate) { + this.dndDelegate = dndDelegate; + } + + + public interface DndDelegate { + void startDrag(TKScene scene, Set tm, + TKDragSourceListener l, Dragboard dragboard); + + TKClipboard createDragboard(); + + DragEvent convertDragEventToFx(Object event, Dragboard dragboard); + + void registerListener(TKDragGestureListener l); + + void enableDrop(TKDropTargetListener l); + } + + public interface CommonDialogsSupport { + FileChooserResult showFileChooser(TKStage ownerWindow, + String title, + File initialDirectory, + String initialFileName, + FileChooserType fileChooserType, + List extensionFilters, + ExtensionFilter selectedFilter); + + File showDirectoryChooser(TKStage ownerWindow, + String title, + File initialDirectory); + } + + private CommonDialogsSupport commonDialogsSupport; + public void setCommonDialogsSupport( + final CommonDialogsSupport commonDialogsSupport) { + this.commonDialogsSupport = commonDialogsSupport; + } + + @Override + public FileChooserResult showFileChooser(TKStage ownerWindow, + String title, + File initialDirectory, + String initialFileName, + FileChooserType fileChooserType, + List extensionFilters, + ExtensionFilter selectedFilter) { + return commonDialogsSupport.showFileChooser( + ownerWindow, + title, + initialDirectory, + initialFileName, + fileChooserType, + extensionFilters, + selectedFilter); + } + + + @Override + public File showDirectoryChooser(TKStage ownerWindow, + String title, + File initialDirectory) { + return commonDialogsSupport.showDirectoryChooser( + ownerWindow, + title, + initialDirectory); + } + + @Override + public long getMultiClickTime() { + return 500L; + } + + @Override + public int getMultiClickMaxX() { + return 5; + } + + @Override + public int getMultiClickMaxY() { + return 5; + } + + public static final class ScreenConfiguration { + private final int minX; + private final int minY; + private final int width; + private final int height; + private final int visualMinX; + private final int visualMinY; + private final int visualWidth; + private final int visualHeight; + private final float dpi; + private final float scale; + + public ScreenConfiguration(final int minX, final int minY, + final int width, final int height, + final int visualMinX, + final int visualMinY, + final int visualWidth, + final int visualHeight, + final float dpi) { + this.minX = minX; + this.minY = minY; + this.width = width; + this.height = height; + this.visualMinX = visualMinX; + this.visualMinY = visualMinY; + this.visualWidth = visualWidth; + this.visualHeight = visualHeight; + this.dpi = dpi; + this.scale = 1; // TODO: add a constructor that takes scale + } + + public int getMinX() { + return minX; + } + + public int getMinY() { + return minY; + } + + public int getWidth() { + return width; + } + + public int getHeight() { + return height; + } + + public int getVisualMinX() { + return visualMinX; + } + + public int getVisualMinY() { + return visualMinY; + } + + public int getVisualWidth() { + return visualWidth; + } + + public int getVisualHeight() { + return visualHeight; + } + + public float getDPI() { + return dpi; + } + + public float getScale() { + return scale; + } + } + + public static class StubSystemMenu implements TKSystemMenu { + + private List menus = null; + + @Override + public boolean isSupported() { + // Although not all platforms have a system menu, the only real + // interaction with the system menu is this TKSystemMenu instance + // so we'll return true on all platforms. + return true; +// final String os = System.getProperty("os.name"); +// return (os != null && os.startsWith("Mac")); + } + + @Override + public void setMenus(List menus) { + this.menus = menus; + } + + // make menus accessible to unit tests + public List getMenus() { + return menus; + } + + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/pgstub/StubWritablePlatformImage.java 2015-09-11 21:24:17.385287069 -0400 @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.pgstub; + +import javafx.scene.image.PixelFormat; +import javafx.scene.image.PixelReader; +import javafx.scene.image.WritablePixelFormat; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import com.sun.javafx.tk.PlatformImage; + +/** + */ +public class StubWritablePlatformImage implements PlatformImage { + private final int w, h; + private final int[] data; + + public StubWritablePlatformImage(int w, int h) { + this.w = w; + this.h = h; + this.data = new int[w * h]; + } + + @Override + public float getPixelScale() { + return 1; + } + + @Override + public int getArgb(int x, int y) { + return data[w * y + x]; + } + + @Override + public void setArgb(int x, int y, int argb) { + data[w * y + x] = argb; + } + + @Override + public PixelFormat getPlatformPixelFormat() { + return PixelFormat.getIntArgbInstance(); + } + + @Override + public boolean isWritable() { + return true; + } + + @Override + public PlatformImage promoteToWritableImage() { + return this; + } + + @Override + public void getPixels(int x, int y, int w, int h, WritablePixelFormat pixelformat, T pixels, int scanlineElems) { + } + + @Override + public void getPixels(int x, int y, int w, int h, WritablePixelFormat pixelformat, byte[] pixels, int offset, int scanlineBytes) { + } + + @Override + public void getPixels(int x, int y, int w, int h, WritablePixelFormat pixelformat, int[] pixels, int offset, int scanlineInts) { + } + + @Override + public void setPixels(int x, int y, int w, int h, PixelFormat pixelformat, T pixels, int scanlineBytes) { + } + + @Override + public void setPixels(int x, int y, int w, int h, PixelFormat pixelformat, byte[] pixels, int offset, int scanlineBytes) { + } + + @Override + public void setPixels(int x, int y, int w, int h, PixelFormat pixelformat, int[] pixels, int offset, int scanlineInts) { + } + + @Override + public void setPixels(int dstx, int dsty, int w, int h, PixelReader reader, int srcx, int srcy) { + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/scene/KeyboardShortcutsTest.java 2015-09-11 21:24:18.249287059 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.scene; - -import javafx.collections.ObservableList; -import javafx.scene.Group; -import javafx.scene.Parent; -import javafx.scene.Scene; -import javafx.scene.input.KeyCode; -import javafx.scene.input.KeyCodeCombination; -import javafx.scene.input.KeyCombination; -import javafx.scene.input.Mnemonic; -import javafx.scene.text.Text; -import javafx.stage.Stage; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - - -/* -** Test keyboard shortcuts. -*/ -public final class KeyboardShortcutsTest { - - private Stage stage; - private Scene scene; - - @Before - public void setUp() { - stage = new Stage(); - scene = new Scene(new Group(), 500, 500); - stage.setScene(scene); - - stage.show(); - } - - @After - public void tearDown() { - stage = null; - scene = null; - } - - - /* - ** Add a mnemonic - ** Make sure that it's there. - */ - @Test - public void addMnemonicTest() { - boolean nodeFound = false; - final Text node = new Text("text"); - - ((Group)scene.getRoot()).getChildren().add(node); - - KeyCodeCombination mnemonicKeyCombo = - new KeyCodeCombination(KeyCode.Q,KeyCombination.ALT_DOWN); - - Mnemonic myMnemonic = new Mnemonic(node, mnemonicKeyCombo); - scene.addMnemonic(myMnemonic); - - ObservableList mnemonicsList = scene.getMnemonics().get(mnemonicKeyCombo); - if (mnemonicsList != null) { - for (int i = 0 ; i < mnemonicsList.size() ; i++) { - if (mnemonicsList.get(i).getNode() == node) { - nodeFound = true; - } - } - } - assertTrue(nodeFound); - } - - - /* - ** Add a mnemonic, then remove it. - ** Make sure that it's gone. - */ - @Test - public void addAndRemoveMnemonicTest() { - boolean nodeFound = false; - final Text node = new Text("text"); - - ((Group)scene.getRoot()).getChildren().add(node); - - KeyCodeCombination mnemonicKeyCombo = - new KeyCodeCombination(KeyCode.Q,KeyCombination.ALT_DOWN); - - Mnemonic myMnemonic = new Mnemonic(node, mnemonicKeyCombo); - scene.addMnemonic(myMnemonic); - - /* - ** remove it..... - */ - scene.removeMnemonic(myMnemonic); - - ObservableList mnemonicsList = scene.getMnemonics().get(mnemonicKeyCombo); - if (mnemonicsList != null) { - for (int i = 0 ; i < mnemonicsList.size() ; i++) { - if (mnemonicsList.get(i).getNode() == node) { - nodeFound = true; - } - } - } - assertTrue(!nodeFound); - } - - @Test - public void mnemonicRemovedWithNodeTest() { - final Text node = new Text("text"); - ((Group)scene.getRoot()).getChildren().add(node); - - KeyCodeCombination mnemonicKeyCombo = - new KeyCodeCombination(KeyCode.Q,KeyCombination.ALT_DOWN); - - Mnemonic myMnemonic = new Mnemonic(node, mnemonicKeyCombo); - scene.addMnemonic(myMnemonic); - - ObservableList mnemonicsList = scene.getMnemonics().get(mnemonicKeyCombo); - - assertTrue(mnemonicsList.contains(myMnemonic)); - - scene.setRoot(new Group()); - - assertFalse(mnemonicsList.contains(myMnemonic)); - - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/scene/KeyboardShortcutsTest.java 2015-09-11 21:24:18.113287061 -0400 @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.scene; + +import javafx.collections.ObservableList; +import javafx.scene.Group; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyCodeCombination; +import javafx.scene.input.KeyCombination; +import javafx.scene.input.Mnemonic; +import javafx.scene.text.Text; +import javafx.stage.Stage; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + + +/* +** Test keyboard shortcuts. +*/ +public final class KeyboardShortcutsTest { + + private Stage stage; + private Scene scene; + + @Before + public void setUp() { + stage = new Stage(); + scene = new Scene(new Group(), 500, 500); + stage.setScene(scene); + + stage.show(); + } + + @After + public void tearDown() { + stage = null; + scene = null; + } + + + /* + ** Add a mnemonic + ** Make sure that it's there. + */ + @Test + public void addMnemonicTest() { + boolean nodeFound = false; + final Text node = new Text("text"); + + ((Group)scene.getRoot()).getChildren().add(node); + + KeyCodeCombination mnemonicKeyCombo = + new KeyCodeCombination(KeyCode.Q,KeyCombination.ALT_DOWN); + + Mnemonic myMnemonic = new Mnemonic(node, mnemonicKeyCombo); + scene.addMnemonic(myMnemonic); + + ObservableList mnemonicsList = scene.getMnemonics().get(mnemonicKeyCombo); + if (mnemonicsList != null) { + for (int i = 0 ; i < mnemonicsList.size() ; i++) { + if (mnemonicsList.get(i).getNode() == node) { + nodeFound = true; + } + } + } + assertTrue(nodeFound); + } + + + /* + ** Add a mnemonic, then remove it. + ** Make sure that it's gone. + */ + @Test + public void addAndRemoveMnemonicTest() { + boolean nodeFound = false; + final Text node = new Text("text"); + + ((Group)scene.getRoot()).getChildren().add(node); + + KeyCodeCombination mnemonicKeyCombo = + new KeyCodeCombination(KeyCode.Q,KeyCombination.ALT_DOWN); + + Mnemonic myMnemonic = new Mnemonic(node, mnemonicKeyCombo); + scene.addMnemonic(myMnemonic); + + /* + ** remove it..... + */ + scene.removeMnemonic(myMnemonic); + + ObservableList mnemonicsList = scene.getMnemonics().get(mnemonicKeyCombo); + if (mnemonicsList != null) { + for (int i = 0 ; i < mnemonicsList.size() ; i++) { + if (mnemonicsList.get(i).getNode() == node) { + nodeFound = true; + } + } + } + assertTrue(!nodeFound); + } + + @Test + public void mnemonicRemovedWithNodeTest() { + final Text node = new Text("text"); + ((Group)scene.getRoot()).getChildren().add(node); + + KeyCodeCombination mnemonicKeyCombo = + new KeyCodeCombination(KeyCode.Q,KeyCombination.ALT_DOWN); + + Mnemonic myMnemonic = new Mnemonic(node, mnemonicKeyCombo); + scene.addMnemonic(myMnemonic); + + ObservableList mnemonicsList = scene.getMnemonics().get(mnemonicKeyCombo); + + assertTrue(mnemonicsList.contains(myMnemonic)); + + scene.setRoot(new Group()); + + assertFalse(mnemonicsList.contains(myMnemonic)); + + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/scene/layout/RegionTest.java 2015-09-11 21:24:18.745287053 -0400 @@ -0,0 +1,474 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.scene.layout; + +import org.junit.Test; + +public class RegionTest { + + public RegionTest() { + } + + @Test public void dummy() { } +// CSSProperty getCssMetaDataByName(String name, List keys) { +// CSSProperty keyForName = null; +// for (CSSProperty k : keys) { +// if (k.getProperty().equals(name)) { +// keyForName = k; +// break; +// } +// } +// assertNotNull(keyForName); +// return keyForName; +// } +// +// ParsedValue getValueFor(Stylesheet stylesheet, String property ) { +// for (Rule rule : stylesheet.getRules()) { +// for (Declaration decl : rule.getDeclarations()) { +// if (property.equals(decl.getProperty())) { +// return decl.getParsedValue(); +// } +// } +// } +// fail("getValueFor " + property); +// return null; +// } +// +// @Test +// public void testConvertCSSPropertysToBackgroundFills() { +// +// Paint[] expectedColors = new Paint[] { +// Color.web("#ff0000"), +// Color.web("#00ff00"), +// Color.web("#0000ff") +// }; +// +// Insets[] expectedInsets = { +// new Insets(-1,-1,-1,-1), +// new Insets(0,0,0,0), +// new Insets(1,1,1,1), +// }; +// +// Insets[] expectedRadii = { +// new Insets(-1,-1,-1,-1), +// new Insets(0,0,0,0), +// new Insets(1,1,1,1), +// }; +// +// +// Stylesheet stylesheet = new CssParser().parse( +// "* { " + +// "-fx-background-color: #ff0000, #00ff00, #0000ff;" + +// "-fx-background-radius: -1, 0, 1; " + +// "-fx-background-insets: -1, 0, 1; " + +// "}"); +// +// Map keyValues = new HashMap(); +// +// ParsedValue cssColorValue = getValueFor(stylesheet, "-fx-background-color"); +// CSSProperty cssColorProperty = getCssMetaDataByName("-fx-background-color", BackgroundFill.getClassCssMetaData()); +// Object value = cssColorProperty.getConverter().convert(cssColorValue,Font.getDefault()); +// assertTrue(value instanceof Paint[]); +// Paint[] cssPaints = (Paint[])value; +// keyValues.put(cssColorProperty, cssPaints); +// +// ParsedValue cssRadiusValue = getValueFor(stylesheet, "-fx-background-radius"); +// CSSProperty cssRadiusProperty = getCssMetaDataByName("-fx-background-radius", BackgroundFill.getClassCssMetaData()); +// value = cssRadiusProperty.getConverter().convert(cssRadiusValue,Font.getDefault()); +// assertTrue(value instanceof Insets[]); +// keyValues.put(cssRadiusProperty, (Insets[])value); +// +// ParsedValue cssInsetsValue = getValueFor(stylesheet, "-fx-background-insets"); +// CSSProperty cssInsetsProperty = getCssMetaDataByName("-fx-background-insets", BackgroundFill.getClassCssMetaData()); +// value = cssInsetsProperty.getConverter().convert(cssInsetsValue,Font.getDefault()); +// assertTrue(value instanceof Insets[]); +// keyValues.put(cssInsetsProperty, (Insets[])value); +// +// +// List fills = BackgroundFillConverter.BACKGROUND_FILLS_CONVERTER.convert(keyValues); +// +// assertEquals(cssPaints.length, fills.size()); +// +// for (int f=0; f keyValues = new HashMap(); +// ParsedValue cssColorValue = getValueFor(stylesheet, "-fx-border-color"); +// CSSProperty cssColorProperty = getCssMetaDataByName("-fx-border-color", StrokeBorder.getClassCssMetaData()); +// Object value = cssColorProperty.getConverter().convert(cssColorValue,Font.getDefault()); +// assertTrue(value instanceof Paint[][]); +// Paint[][] cssPaints = (Paint[][])value; +// keyValues.put(cssColorProperty, cssPaints); +// +// ParsedValue cssInsetsValue = getValueFor(stylesheet, "-fx-border-insets"); +// CSSProperty cssInsetsProperty = getCssMetaDataByName("-fx-border-insets", StrokeBorder.getClassCssMetaData()); +// value = cssInsetsProperty.getConverter().convert(cssInsetsValue,Font.getDefault()); +// assertTrue(value instanceof Insets[]); +// Insets[] cssInsets = (Insets[])value; +// keyValues.put(cssInsetsProperty, cssInsets); +// +// ParsedValue cssRadiusValue = getValueFor(stylesheet, "-fx-border-radius"); +// CSSProperty cssRadiusProperty = getCssMetaDataByName("-fx-border-radius", StrokeBorder.getClassCssMetaData()); +// value = cssRadiusProperty.getConverter().convert(cssRadiusValue,Font.getDefault()); +// assertTrue(value instanceof Margins[]); +// Margins[] cssRadii = (Margins[])value; +// keyValues.put(cssRadiusProperty, cssRadii); +// +// ParsedValue cssWidthValue = getValueFor(stylesheet, "-fx-border-width"); +// CSSProperty cssWidthProperty = getCssMetaDataByName("-fx-border-width", StrokeBorder.getClassCssMetaData()); +// value = cssWidthProperty.getConverter().convert(cssWidthValue,Font.getDefault()); +// assertTrue(value instanceof Margins[]); +// Margins[] cssWidth = (Margins[])value; +// keyValues.put(cssWidthProperty, cssWidth); +// +// ParsedValue cssStyleValue = getValueFor(stylesheet, "-fx-border-style"); +// CSSProperty cssStyleProperty = getCssMetaDataByName("-fx-border-style", StrokeBorder.getClassCssMetaData()); +// value = cssStyleProperty.getConverter().convert(cssStyleValue,Font.getDefault()); +// assertTrue(value instanceof BorderStyle[][]); +// BorderStyle[][] cssStyle = (BorderStyle[][])value; +// keyValues.put(cssStyleProperty, cssStyle); +// +// +// List strokeBorders = StrokeBorderConverter.getInstance().convert(keyValues); +// +// assertEquals(cssPaints.length, strokeBorders.size()); +// +// for (int f=0; f keyValues = new HashMap(); +// +// ParsedValue cssBackgroundImageValue = getValueFor(stylesheet, "-fx-background-image"); +// CSSProperty cssBackgroundImageProperty = getCssMetaDataByName("-fx-background-image", BackgroundImage.getClassCssMetaData()); +// Object value = cssBackgroundImageProperty.getConverter().convert(cssBackgroundImageValue,Font.getDefault()); +// assertTrue(value instanceof String[]); +// String[] cssBackgroundImages = (String[])value; +// keyValues.put(cssBackgroundImageProperty, cssBackgroundImages); +// +// ParsedValue cssBackgroundRepeatValue = getValueFor(stylesheet, "-fx-background-repeat"); +// CSSProperty cssBackgroundRepeatProperty = getCssMetaDataByName("-fx-background-repeat", BackgroundImage.getClassCssMetaData()); +// value = cssBackgroundRepeatProperty.getConverter().convert(cssBackgroundRepeatValue,Font.getDefault()); +// assertTrue(value instanceof RepeatStruct[]); +// RepeatStruct[] cssBackgroundRepeats = (RepeatStruct[])value; +// keyValues.put(cssBackgroundRepeatProperty, cssBackgroundRepeats); +// +// ParsedValue cssBackgroundPositionValue = getValueFor(stylesheet, "-fx-background-position"); +// CSSProperty cssBackgroundPositionProperty = getCssMetaDataByName("-fx-background-position", BackgroundImage.getClassCssMetaData()); +// value = cssBackgroundPositionProperty.getConverter().convert(cssBackgroundPositionValue,Font.getDefault()); +// assertTrue(value instanceof BackgroundPosition[]); +// BackgroundPosition[] cssBackgroundPositions = (BackgroundPosition[])value; +// keyValues.put(cssBackgroundPositionProperty, cssBackgroundPositions); +// +// ParsedValue cssBackgroundSizeValue = getValueFor(stylesheet, "-fx-background-size"); +// CSSProperty cssBackgroundSizeProperty = getCssMetaDataByName("-fx-background-size", BackgroundImage.getClassCssMetaData()); +// value = cssBackgroundSizeProperty.getConverter().convert(cssBackgroundSizeValue,Font.getDefault()); +// assertTrue(value instanceof BackgroundSize[]); +// BackgroundSize[] cssBackgroundSizes = (BackgroundSize[])value; +// keyValues.put(cssBackgroundSizeProperty, cssBackgroundSizes); +// +// List images = BackgroundImageConverter.getInstance().convert(keyValues); +// +// assertEquals(cssBackgroundImages.length, images.size()); +// +// for (int i=0; i keyValues = new HashMap(); +// +// ParsedValue cssImageBorderValue = getValueFor(stylesheet, "-fx-border-image-source"); +// CSSProperty cssImageBorderProperty = getCssMetaDataByName("-fx-border-image-source", BorderImage.getClassCssMetaData()); +// Object value = cssImageBorderProperty.getConverter().convert(cssImageBorderValue,Font.getDefault()); +// assertTrue(value instanceof String[]); +// String[] cssImageBorders = (String[])value; +// keyValues.put(cssImageBorderProperty,cssImageBorders); +// +// ParsedValue cssImageRepeatValue = getValueFor(stylesheet, "-fx-border-image-repeat"); +// CSSProperty cssImageRepeatProperty = getCssMetaDataByName("-fx-border-image-repeat", BorderImage.getClassCssMetaData()); +// value = cssImageRepeatProperty.getConverter().convert(cssImageRepeatValue,Font.getDefault()); +// assertTrue(value instanceof BorderImageRepeat[]); +// BorderImageRepeat[] cssBorderImageRepeats = (BorderImageRepeat[])value; +// keyValues.put(cssImageRepeatProperty, cssBorderImageRepeats); +// +// ParsedValue cssSliceValue = getValueFor(stylesheet, "-fx-border-image-slice"); +// CSSProperty cssSliceProperty = getCssMetaDataByName("-fx-border-image-slice", BorderImage.getClassCssMetaData()); +// value = cssSliceProperty.getConverter().convert(cssSliceValue,Font.getDefault()); +// assertTrue(value instanceof BorderImageSlices[]); +// BorderImageSlices[] cssBorderImageSlices = (BorderImageSlices[])value; +// keyValues.put(cssSliceProperty, cssBorderImageSlices); +// +// ParsedValue cssWidthValue = getValueFor(stylesheet, "-fx-border-image-width"); +// CSSProperty cssWidthProperty = getCssMetaDataByName("-fx-border-image-width", BorderImage.getClassCssMetaData()); +// value = cssWidthProperty.getConverter().convert(cssWidthValue,Font.getDefault()); +// assertTrue(value instanceof Margins[]); +// Margins[] cssBorderImageWidths = (Margins[])value; +// keyValues.put(cssWidthProperty, cssBorderImageWidths); +// +// ParsedValue cssInsetsValue = getValueFor(stylesheet, "-fx-border-image-insets"); +// CSSProperty cssInsetsProperty = getCssMetaDataByName("-fx-border-image-insets", BorderImage.getClassCssMetaData()); +// value = cssInsetsProperty.getConverter().convert(cssInsetsValue,Font.getDefault()); +// assertTrue(value instanceof Insets[]); +// Insets[] cssBorderImageInsets = (Insets[])value; +// keyValues.put(cssInsetsProperty, cssBorderImageInsets); +// +// List images = BorderImageConverter.getInstance().convert(keyValues); +// +// assertEquals(cssImageBorders.length, images.size()); +// +// for (int i=0; i map = new HashMap(); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(0, fills.size()); +// } +// +// /* +// -fx-background-color: blue +// -fx-background-radius: +// -fx-background-insets: +// */ +// @Test public void scenario2() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Paint[] { Color.BLUE }); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(1, fills.size()); +// +// BackgroundFill fill = fills.get(0); +// BackgroundFill expected = new BackgroundFill(Color.BLUE, 0, 0, 0, 0, Insets.EMPTY); +// assertEquals(expected, fill); +// } +// +// /* +// -fx-background-color: blue +// -fx-background-radius: 10 +// -fx-background-insets: +// */ +// @Test public void scenario3() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Paint[] { Color.BLUE }); +// map.put(BackgroundFill.BACKGROUND_RADIUS, new Insets[] { new Insets(10) }); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(1, fills.size()); +// +// BackgroundFill fill = fills.get(0); +// BackgroundFill expected = new BackgroundFill(Color.BLUE, 10, 10, 10, 10, Insets.EMPTY); +// assertEquals(expected, fill); +// } +// +// /* +// -fx-background-color: blue +// -fx-background-radius: 1 2 3 4 +// -fx-background-insets: +// */ +// @Test public void scenario4() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Paint[] { Color.BLUE }); +// map.put(BackgroundFill.BACKGROUND_RADIUS, new Insets[] { new Insets(1.0, 2.0, 3.0, 4.0) }); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(1, fills.size()); +// +// BackgroundFill fill = fills.get(0); +// BackgroundFill expected = new BackgroundFill(Color.BLUE, 1, 2, 3, 4, Insets.EMPTY); +// assertEquals(expected, fill); +// } +// +// /* +// -fx-background-color: blue +// -fx-background-radius: 10 +// -fx-background-insets: 1 +// */ +// @Test public void scenario5() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Paint[] { Color.BLUE }); +// map.put(BackgroundFill.BACKGROUND_RADIUS, new Insets[] { new Insets(10) }); +// map.put(BackgroundFill.BACKGROUND_INSETS, new Insets[] { new Insets(1) }); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(1, fills.size()); +// +// BackgroundFill fill = fills.get(0); +// BackgroundFill expected = new BackgroundFill(Color.BLUE, 10, 10, 10, 10, new Insets(1)); +// assertEquals(expected, fill); +// } +// +// /* +// -fx-background-color: blue +// -fx-background-radius: 10, 20 +// -fx-background-insets: 1 +// */ +// @Test public void scenario6() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Paint[] { Color.BLUE }); +// map.put(BackgroundFill.BACKGROUND_RADIUS, new Insets[] { new Insets(10), new Insets(20) }); +// map.put(BackgroundFill.BACKGROUND_INSETS, new Insets[] { new Insets(1) }); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(1, fills.size()); +// +// BackgroundFill fill = fills.get(0); +// BackgroundFill expected = new BackgroundFill(Color.BLUE, 10, 10, 10, 10, new Insets(1)); +// assertEquals(expected, fill); +// } +// +// /* +// -fx-background-color: blue +// -fx-background-radius: 10 +// -fx-background-insets: 1, 2 +// */ +// @Test public void scenario7() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Paint[] { Color.BLUE }); +// map.put(BackgroundFill.BACKGROUND_RADIUS, new Insets[] { new Insets(10) }); +// map.put(BackgroundFill.BACKGROUND_INSETS, new Insets[] { new Insets(1), new Insets(2) }); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(1, fills.size()); +// +// BackgroundFill fill = fills.get(0); +// BackgroundFill expected = new BackgroundFill(Color.BLUE, 10, 10, 10, 10, new Insets(1)); +// assertEquals(expected, fill); +// } +// +// /* +// -fx-background-color: blue, green +// -fx-background-radius: 10 +// -fx-background-insets: 1 +// */ +// @Test public void scenario8() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Paint[] { Color.BLUE, Color.GREEN }); +// map.put(BackgroundFill.BACKGROUND_RADIUS, new Insets[] { new Insets(10) }); +// map.put(BackgroundFill.BACKGROUND_INSETS, new Insets[] { new Insets(1) }); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(2, fills.size()); +// +// BackgroundFill fill = fills.get(0); +// BackgroundFill expected = new BackgroundFill(Color.BLUE, 10, 10, 10, 10, new Insets(1)); +// assertEquals(expected, fill); +// +// fill = fills.get(1); +// expected = new BackgroundFill(Color.GREEN, 10, 10, 10, 10, new Insets(1)); +// assertEquals(expected, fill); +// } +// +// /* +// -fx-background-color: blue, green +// -fx-background-radius: 10, 20 +// -fx-background-insets: 1 +// */ +// @Test public void scenario9() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Paint[] { Color.BLUE, Color.GREEN }); +// map.put(BackgroundFill.BACKGROUND_RADIUS, new Insets[] { new Insets(10), new Insets(20) }); +// map.put(BackgroundFill.BACKGROUND_INSETS, new Insets[] { new Insets(1) }); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(2, fills.size()); +// +// BackgroundFill fill = fills.get(0); +// BackgroundFill expected = new BackgroundFill(Color.BLUE, 10, 10, 10, 10, new Insets(1)); +// assertEquals(expected, fill); +// +// fill = fills.get(1); +// expected = new BackgroundFill(Color.GREEN, 20, 20, 20, 20, new Insets(1)); +// assertEquals(expected, fill); +// } +// +// /* +// -fx-background-color: blue, green +// -fx-background-radius: 10 +// -fx-background-insets: 1, 2 +// */ +// @Test public void scenario10() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Paint[] { Color.BLUE, Color.GREEN }); +// map.put(BackgroundFill.BACKGROUND_RADIUS, new Insets[] { new Insets(10) }); +// map.put(BackgroundFill.BACKGROUND_INSETS, new Insets[] { new Insets(1), new Insets(2) }); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(2, fills.size()); +// +// BackgroundFill fill = fills.get(0); +// BackgroundFill expected = new BackgroundFill(Color.BLUE, 10, 10, 10, 10, new Insets(1)); +// assertEquals(expected, fill); +// +// fill = fills.get(1); +// expected = new BackgroundFill(Color.GREEN, 10, 10, 10, 10, new Insets(2)); +// assertEquals(expected, fill); +// } +// +// /* +// -fx-background-color: null +// -fx-background-radius: null +// -fx-background-insets: null +// */ +// @Test public void scenario11() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, null); +// map.put(BackgroundFill.BACKGROUND_RADIUS, null); +// map.put(BackgroundFill.BACKGROUND_INSETS, null); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(0, fills.size()); +// } +// +// /* +// -fx-background-color: [] +// -fx-background-radius: [] +// -fx-background-insets: [] +// */ +// @Test public void scenario12() { +// Map map = new HashMap(); +// map.put(BackgroundFill.BACKGROUND_COLOR, new Color[0]); +// map.put(BackgroundFill.BACKGROUND_RADIUS, new Insets[0]); +// map.put(BackgroundFill.BACKGROUND_INSETS, new Insets[0]); +// List fills = BackgroundFillConverter.getInstance().convert(map); +// assertEquals(0, fills.size()); +// } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/scene/layout/region/BackgroundFillTest.java 2015-09-11 21:24:20.101287038 -0400 @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.scene.layout.region; + +import javafx.geometry.Insets; +import javafx.scene.layout.BackgroundFill; +import javafx.scene.paint.Color; +import org.junit.Test; + +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Tests for the BackgroundFill class + */ +public class BackgroundFillTest { + + @Test public void valuesAreSetCorrectly() { +// BackgroundFill obj = new BackgroundFill(Color.ORANGE, 1, 2, 3, 4, new Insets(20)); +// assertEquals(Color.ORANGE, obj.getFill()); +// assertEquals(1, obj.getTopLeftCornerRadius(), 0); +// assertEquals(2, obj.getTopRightCornerRadius(), 0); +// assertEquals(3, obj.getBottomRightCornerRadius(), 0); +// assertEquals(4, obj.getBottomLeftCornerRadius(), 0); +// assertEquals(new Insets(20), obj.getOffsets()); + } + + @Test public void hashingReturnsSameObject() { +// HashMap map = new HashMap(); +// BackgroundFill obj = new BackgroundFill(Color.ORANGE, 1, 2, 3, 4, new Insets(20)); +// map.put(obj, "YES"); +// assertEquals("YES", map.get(obj)); +// +// BackgroundFill equivalent = new BackgroundFill(Color.ORANGE, 1, 2, 3, 4, new Insets(20)); +// assertEquals("YES", map.get(equivalent)); +// +// BackgroundFill different = new BackgroundFill(Color.ORANGE, 1, /*different!*/3, 3, 4, new Insets(20)); +// assertFalse(map.containsKey(different)); + } + + @Test public void equality() { +// BackgroundFill obj = new BackgroundFill(Color.ORANGE, 1, 2, 3, 4, new Insets(20)); +// BackgroundFill equivalent = new BackgroundFill(Color.ORANGE, 1, 2, 3, 4, new Insets(20)); +// assertTrue(obj.equals(equivalent)); +// +// BackgroundFill different = new BackgroundFill(Color.ORANGE, 1, /*different!*/3, 3, 4, new Insets(20)); +// assertFalse(obj.equals(different)); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/scene/layout/region/BackgroundImageTest.java 2015-09-11 21:24:20.925287029 -0400 @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.scene.layout.region; + +import org.junit.Test; + +/** + * Tests for the BackgroundImage class + */ +public class BackgroundImageTest { + + @Test public void dummy() { } + +// @Test public void valuesAreSetCorrectly() { +// Image image = new Image("http://dummyUrl", true); +// BackgroundImage obj = new BackgroundImage(image, Repeat.SPACE, Repeat.ROUND, +// 1, 2, 3, 4, 5, 6, true, false, true, false, true, false); +// +// assertEquals(image, obj.getImage()); +// assertEquals(Repeat.SPACE, obj.getRepeatX()); +// assertEquals(Repeat.ROUND, obj.getRepeatY()); +// assertEquals(1, obj.getTop(), 0); +// assertEquals(2, obj.getRight(), 0); +// assertEquals(3, obj.getBottom(), 0); +// assertEquals(4, obj.getLeft(), 0); +// assertEquals(5, obj.getWidth(), 0); +// assertEquals(6, obj.getHeight(), 0); +// assertTrue(obj.isProportionalHPos()); +// assertFalse(obj.isProportionalVPos()); +// assertTrue(obj.isProportionalWidth()); +// assertFalse(obj.isProportionalHeight()); +// assertTrue(obj.isContain()); +// assertFalse(obj.isCover()); +// } +// +// @Test public void valuesAreSetCorrectly2() { +// Image image = new Image("http://dummyUrl", true); +// BackgroundImage obj = new BackgroundImage(image, Repeat.SPACE, Repeat.ROUND, +// 1, 2, 3, 4, 5, 6, false, true, false, true, false, true); +// +// assertEquals(image, obj.getImage()); +// assertEquals(Repeat.SPACE, obj.getRepeatX()); +// assertEquals(Repeat.ROUND, obj.getRepeatY()); +// assertEquals(1, obj.getTop(), 0); +// assertEquals(2, obj.getRight(), 0); +// assertEquals(3, obj.getBottom(), 0); +// assertEquals(4, obj.getLeft(), 0); +// assertEquals(5, obj.getWidth(), 0); +// assertEquals(6, obj.getHeight(), 0); +// assertFalse(obj.isProportionalHPos()); +// assertTrue(obj.isProportionalVPos()); +// assertFalse(obj.isProportionalWidth()); +// assertTrue(obj.isProportionalHeight()); +// assertFalse(obj.isContain()); +// assertTrue(obj.isCover()); +// } +// +// @Test public void hashingReturnsSameObject() { +// Map map = new HashMap(); +// Image image = new Image("http://dummyUrl", true); +// BackgroundImage obj = new BackgroundImage(image, Repeat.SPACE, Repeat.ROUND, +// 1, 2, 3, 4, 5, 6, true, false, true, false, true, false); +// map.put(obj, "YES"); +// assertEquals("YES", map.get(obj)); +// +// BackgroundImage equivalent = new BackgroundImage(image, Repeat.SPACE, Repeat.ROUND, +// 1, 2, 3, 4, 5, 6, true, false, true, false, true, false); +// assertEquals("YES", map.get(equivalent)); +// +// BackgroundImage different = new BackgroundImage(image, Repeat.SPACE, Repeat.ROUND, +// 1, 2, 3, 4, 5, 6, false, true, false, true, false, true); +// assertFalse(map.containsKey(different)); +// } +// +// @Test public void equality() { +// Image image = new Image("http://dummyUrl", true); +// BackgroundImage obj = new BackgroundImage(image, Repeat.SPACE, Repeat.ROUND, +// 1, 2, 3, 4, 5, 6, true, false, true, false, true, false); +// +// BackgroundImage equivalent = new BackgroundImage(image, Repeat.SPACE, Repeat.ROUND, +// 1, 2, 3, 4, 5, 6, true, false, true, false, true, false); +// +// assertEquals(obj, equivalent); +// +// BackgroundImage different = new BackgroundImage(image, Repeat.SPACE, Repeat.ROUND, +// 1, 2, 3, 4, 5, 6, false, true, false, true, false, true); +// assertFalse(obj.equals(different)); +// } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/scene/layout/region/BackgroundRepeatConverterTest.java 2015-09-11 21:24:21.597287021 -0400 @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.scene.layout.region; + +import javafx.scene.layout.BackgroundRepeat; +import org.junit.Ignore; +import org.junit.Test; +import javafx.css.ParsedValue; +import com.sun.javafx.css.ParsedValueImpl; +import com.sun.javafx.scene.layout.region.RepeatStruct; + +import static org.junit.Assert.assertEquals; +import com.sun.javafx.scene.layout.region.RepeatStructConverter; +import com.sun.javafx.scene.layout.region.RepeatStructConverter; + +/** + */ +public class BackgroundRepeatConverterTest { + /* + -fx-background-repeat: + */ + @Test public void scenario1() { + ParsedValueImpl[][], RepeatStruct[]> value = + new ParsedValueImpl[][], RepeatStruct[]>( + new ParsedValueImpl[0][0], null + ); + RepeatStruct[] results = RepeatStructConverter.getInstance().convert(value, null); + assertEquals(0, results.length, 0); + } + + /* + -fx-background-repeat: null + */ + @Ignore ("this doesn't work, but I'm not sure what would happen with a null background-repeat in reality") + @Test public void scenario2() { + ParsedValue[][] values = new ParsedValueImpl[][] { + {null} + }; + + ParsedValueImpl[][], RepeatStruct[]> value = + new ParsedValueImpl[][], RepeatStruct[]>( + values, null + ); + RepeatStruct[] results = RepeatStructConverter.getInstance().convert(value, null); + assertEquals(0, results.length, 0); + } + + /* + -fx-background-repeat: repeat round + */ + @Test public void scenario3() { + ParsedValue[][] values = new ParsedValueImpl[][] { + { new ParsedValueImpl("repeat", null), new ParsedValueImpl("round", null) } + }; + + ParsedValue[][], RepeatStruct[]> value = + new ParsedValueImpl[][], RepeatStruct[]>( + values, null + ); + RepeatStruct[] results = RepeatStructConverter.getInstance().convert(value, null); + assertEquals(1, results.length, 0); + assertEquals(BackgroundRepeat.REPEAT, results[0].repeatX); + assertEquals(BackgroundRepeat.ROUND, results[0].repeatY); + } + + /* + -fx-background-repeat: space no-repeat + */ + @Test public void scenario4() { + ParsedValue[][] values = new ParsedValueImpl[][] { + { new ParsedValueImpl("space", null), new ParsedValueImpl("no-repeat", null) } + }; + + ParsedValue[][], RepeatStruct[]> value = + new ParsedValueImpl[][], RepeatStruct[]>( + values, null + ); + RepeatStruct[] results = RepeatStructConverter.getInstance().convert(value, null); + assertEquals(1, results.length, 0); + assertEquals(BackgroundRepeat.SPACE, results[0].repeatX); + assertEquals(BackgroundRepeat.NO_REPEAT, results[0].repeatY); + } + + /* + -fx-background-repeat: no-repeat repeat, space round + */ + @Test public void scenario5() { + ParsedValue[][] values = new ParsedValueImpl[][] { + { new ParsedValueImpl("no-repeat", null), new ParsedValueImpl("repeat", null) }, + { new ParsedValueImpl("space", null), new ParsedValueImpl("round", null) } + }; + + ParsedValue[][], RepeatStruct[]> value = + new ParsedValueImpl[][], RepeatStruct[]>( + values, null + ); + RepeatStruct[] results = RepeatStructConverter.getInstance().convert(value, null); + assertEquals(2, results.length, 0); + assertEquals(BackgroundRepeat.NO_REPEAT, results[0].repeatX); + assertEquals(BackgroundRepeat.REPEAT, results[0].repeatY); + assertEquals(BackgroundRepeat.SPACE, results[1].repeatX); + assertEquals(BackgroundRepeat.ROUND, results[1].repeatY); + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/scene/transform/TransformUtilsTest.java 2015-09-11 21:24:22.317287013 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,233 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.scene.transform; - -import com.sun.javafx.test.TransformHelper; -import javafx.scene.transform.Transform; -import com.sun.javafx.geom.transform.Affine3D; -import java.util.LinkedList; -import java.util.List; -import javafx.scene.transform.TransformOperationsTest; -import javafx.scene.transform.Translate; -import static org.junit.Assert.*; - -import org.junit.Test; - -public class TransformUtilsTest { - @Test - public void shouldCreateCorrectImmutableTransform() { - Transform t = TransformUtils.immutableTransform( - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12); - - TransformHelper.assertMatrix(t, - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12); - } - - @Test - public void immutableTransformShouldApplyCorrectly() { - Affine3D a = new Affine3D(); - a.translate(10, 20); - - Transform t = TransformUtils.immutableTransform( - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12); - - t.impl_apply(a); - - TransformHelper.assertMatrix(a, - 1, 2, 3, 14, - 5, 6, 7, 28, - 9, 10, 11, 12); - } - - @Test - public void immutableTransformShouldCopyCorrectly() { - Transform src = TransformUtils.immutableTransform( - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12); - - Transform t = src.clone(); - - TransformHelper.assertMatrix(t, - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12); - } - - @Test public void testImmutableTransformToString() { - final Transform trans = TransformUtils.immutableTransform( - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12); - - String s = trans.toString(); - - assertNotNull(s); - assertFalse(s.isEmpty()); - } - - @Test public void testImmutableTransformState() { - int counter = 0; - for (Object o : TransformOperationsTest.getParams()) { - Object[] arr = (Object[]) o; - if (arr[0] instanceof TransformUtils.ImmutableTransform) { - TransformUtils.ImmutableTransform t = - (TransformUtils.ImmutableTransform) arr[0]; - - TransformHelper.assertStateOk("Checking state of transform #" + - (counter++) + " of TransformOperationsTest", t, - t.getState3d(), t.getState2d()); - } - } - } - - @Test public void testReusedImmutableTransform() { - int counter = 0; - for (Object o : TransformOperationsTest.getParams()) { - Object[] arr = (Object[]) o; - if (arr[0] instanceof TransformUtils.ImmutableTransform) { - - Transform t = (Transform) arr[0]; - - - // reusing - Transform reuse = TransformUtils.immutableTransform( - new Translate(10, 20)); - - Transform returned = TransformUtils.immutableTransform(reuse, t); - - assertSame("Checking reusing immutable transform to values of #" - + counter + " of TransformOperationsTest", reuse, returned); - - TransformHelper.assertStateOk( - "Checking reusing immutable transform to values of #" - + counter + " of TransformOperationsTest", - (TransformUtils.ImmutableTransform) returned, - ((TransformUtils.ImmutableTransform) returned).getState3d(), - ((TransformUtils.ImmutableTransform) returned).getState2d()); - - TransformHelper.assertMatrix("Checking reusing immutable " - + "transform to values of #" + counter - + " of TransformOperationsTest", returned, t); - - // creating new - Transform returned2 = TransformUtils.immutableTransform(null, t); - - assertNotSame("Checking reusing immutable transform to values of #" - + counter + " of TransformOperationsTest", returned2, t); - - TransformHelper.assertStateOk( - "Checking reusing immutable transform to values of #" - + counter + " of TransformOperationsTest", - (TransformUtils.ImmutableTransform) returned2, - ((TransformUtils.ImmutableTransform) returned2).getState3d(), - ((TransformUtils.ImmutableTransform) returned2).getState2d()); - - TransformHelper.assertMatrix("Checking reusing immutable " - + "transform to values of #" + counter - + " of TransformOperationsTest", returned2, t); - - counter++; - } - } - } - - @Test public void testConcatenatedImmutableTransform() { - - List ts = new LinkedList<>(); - for (Object o : TransformOperationsTest.getParams()) { - Object[] arr = (Object[]) o; - if (arr[0] instanceof TransformUtils.ImmutableTransform) { - ts.add((TransformUtils.ImmutableTransform) arr[0]); - } - } - - int outer = 0; - for (TransformUtils.ImmutableTransform t1 : ts) { - int inner = 0; - for (TransformUtils.ImmutableTransform t2 : ts) { - int orig = 0; - // reusing - for (TransformUtils.ImmutableTransform t3 : ts) { - Transform clone = t3.clone(); - Transform conc = TransformUtils.immutableTransform( - clone, t1, t2); - - assertSame("Checking state of concatenation of " - + "transform #" + outer + " and #" + inner + - " reusing #" + orig + - " of TransformOperationsTest", clone, conc); - TransformHelper.assertStateOk( - "Checking state of concatenation of " - + "transform #" + outer + " and #" + inner + - " reusing #" + orig + - " of TransformOperationsTest", - (TransformUtils.ImmutableTransform) conc, - ((TransformUtils.ImmutableTransform) conc).getState3d(), - ((TransformUtils.ImmutableTransform) conc).getState2d()); - TransformHelper.assertMatrix( - "Checking state of concatenation of " - + "transform #" + outer + " and #" + inner + - " reusing #" + orig + - " of TransformOperationsTest", conc, - TransformHelper.concatenate(t1, t2)); - orig++; - } - - // creating new - Transform conc2 = TransformUtils.immutableTransform( - null, t1, t2); - - assertNotSame("Checking state of concatenation of " - + "transform #" + outer + " and #" + inner + - " of TransformOperationsTest", conc2, t1); - assertNotSame("Checking state of concatenation of " - + "transform #" + outer + " and #" + inner + - " of TransformOperationsTest", conc2, t2); - TransformHelper.assertStateOk( - "Checking state of concatenation of " - + "transform #" + outer + " and #" + inner + - " of TransformOperationsTest", - (TransformUtils.ImmutableTransform) conc2, - ((TransformUtils.ImmutableTransform) conc2).getState3d(), - ((TransformUtils.ImmutableTransform) conc2).getState2d()); - TransformHelper.assertMatrix( - "Checking state of concatenation of " - + "transform #" + outer + " and #" + inner + - " of TransformOperationsTest", conc2, - TransformHelper.concatenate(t1, t2)); - inner++; - } - outer++; - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/scene/transform/TransformUtilsTest.java 2015-09-11 21:24:22.181287015 -0400 @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.scene.transform; + +import test.com.sun.javafx.test.TransformHelper; +import javafx.scene.transform.Transform; +import com.sun.javafx.geom.transform.Affine3D; +import com.sun.javafx.scene.transform.TransformUtils; +import com.sun.javafx.scene.transform.TransformUtilsShim; +import java.util.LinkedList; +import java.util.List; +import test.javafx.scene.transform.TransformOperationsTest; +import javafx.scene.transform.Translate; +import static org.junit.Assert.*; + +import org.junit.Test; + +public class TransformUtilsTest { + @Test + public void shouldCreateCorrectImmutableTransform() { + Transform t = TransformUtilsShim.getImmutableTransform( + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12); + + TransformHelper.assertMatrix(t, + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12); + } + + @Test + public void immutableTransformShouldApplyCorrectly() { + Affine3D a = new Affine3D(); + a.translate(10, 20); + + Transform t = TransformUtilsShim.getImmutableTransform( + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12); + + t.impl_apply(a); + + TransformHelper.assertMatrix(a, + 1, 2, 3, 14, + 5, 6, 7, 28, + 9, 10, 11, 12); + } + + @Test + public void immutableTransformShouldCopyCorrectly() { + Transform src = TransformUtilsShim.getImmutableTransform( + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12); + + Transform t = src.clone(); + + TransformHelper.assertMatrix(t, + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12); + } + + @Test public void testImmutableTransformToString() { + Transform trans = TransformUtilsShim.getImmutableTransform( + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12); + + String s = trans.toString(); + + assertNotNull(s); + assertFalse(s.isEmpty()); + } + + @Test public void testImmutableTransformState() { + int counter = 0; + for (Object o : TransformOperationsTest.getParams()) { + Object[] arr = (Object[]) o; + if (arr[0] instanceof TransformUtilsShim.ImmutableTransformShim) { + TransformUtilsShim.ImmutableTransformShim t = + (TransformUtilsShim.ImmutableTransformShim) arr[0]; + + TransformHelper.assertStateOk("Checking state of transform #" + + (counter++) + " of TransformOperationsTest", t, + TransformUtilsShim.getImmutableState3d(t), + TransformUtilsShim.getImmutableState2d(t)); + } + } + } + + @Test public void testReusedImmutableTransform() { + int counter = 0; + for (Object o : TransformOperationsTest.getParams()) { + Object[] arr = (Object[]) o; + if (arr[0] instanceof TransformUtilsShim.ImmutableTransformShim) { + + Transform t = (Transform) arr[0]; + + + // reusing + Transform reuse = TransformUtils.immutableTransform( + new Translate(10, 20)); + + Transform returned = TransformUtils.immutableTransform(reuse, t); + + assertSame("Checking reusing immutable transform to values of #" + + counter + " of TransformOperationsTest", reuse, returned); + + TransformHelper.assertStateOk( + "Checking reusing immutable transform to values of #" + + counter + " of TransformOperationsTest", + returned, + (TransformUtilsShim.getImmutableState3d(returned)), + (TransformUtilsShim.getImmutableState2d(returned))); + + TransformHelper.assertMatrix("Checking reusing immutable " + + "transform to values of #" + counter + + " of TransformOperationsTest", returned, t); + + // creating new + Transform returned2 = TransformUtils.immutableTransform(null, t); + + assertNotSame("Checking reusing immutable transform to values of #" + + counter + " of TransformOperationsTest", returned2, t); + + TransformHelper.assertStateOk( + "Checking reusing immutable transform to values of #" + + counter + " of TransformOperationsTest", + returned2, + TransformUtilsShim.getImmutableState3d(returned), + TransformUtilsShim.getImmutableState2d(returned)); + + TransformHelper.assertMatrix("Checking reusing immutable " + + "transform to values of #" + counter + + " of TransformOperationsTest", returned2, t); + + counter++; + } + } + } + + @Test public void testConcatenatedImmutableTransform() { + + List ts = new LinkedList<>(); + for (Object o : TransformOperationsTest.getParams()) { + Object[] arr = (Object[]) o; + if (arr[0] instanceof TransformUtilsShim.ImmutableTransformShim) { + ts.add((TransformUtilsShim.ImmutableTransformShim) arr[0]); + } + } + + int outer = 0; + for (TransformUtilsShim.ImmutableTransformShim t1 : ts) { + int inner = 0; + for (TransformUtilsShim.ImmutableTransformShim t2 : ts) { + int orig = 0; + // reusing + for (TransformUtilsShim.ImmutableTransformShim t3 : ts) { + Transform clone = t3.clone(); + Transform conc = TransformUtils.immutableTransform( + clone, t1, t2); + + assertSame("Checking state of concatenation of " + + "transform #" + outer + " and #" + inner + + " reusing #" + orig + + " of TransformOperationsTest", clone, conc); + TransformHelper.assertStateOk( + "Checking state of concatenation of " + + "transform #" + outer + " and #" + inner + + " reusing #" + orig + + " of TransformOperationsTest", + (TransformUtilsShim.ImmutableTransformShim) conc, + TransformUtilsShim.getImmutableState3d(conc), + TransformUtilsShim.getImmutableState2d(conc)); + TransformHelper.assertMatrix( + "Checking state of concatenation of " + + "transform #" + outer + " and #" + inner + + " reusing #" + orig + + " of TransformOperationsTest", conc, + TransformHelper.concatenate(t1, t2)); + orig++; + } + + // creating new + Transform conc2 = TransformUtils.immutableTransform( + null, t1, t2); + + assertNotSame("Checking state of concatenation of " + + "transform #" + outer + " and #" + inner + + " of TransformOperationsTest", conc2, t1); + assertNotSame("Checking state of concatenation of " + + "transform #" + outer + " and #" + inner + + " of TransformOperationsTest", conc2, t2); + TransformHelper.assertStateOk( + "Checking state of concatenation of " + + "transform #" + outer + " and #" + inner + + " of TransformOperationsTest", + (TransformUtilsShim.ImmutableTransformShim) conc2, + TransformUtilsShim.getImmutableState3d(conc2), + TransformUtilsShim.getImmutableState2d(conc2)); + TransformHelper.assertMatrix( + "Checking state of concatenation of " + + "transform #" + outer + " and #" + inner + + " of TransformOperationsTest", conc2, + TransformHelper.concatenate(t1, t2)); + inner++; + } + outer++; + } + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/scene/traversal/TopMostTraversalEngineTest.java 2015-09-11 21:24:22.961287006 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,509 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.scene.traversal; - -import javafx.scene.Group; -import javafx.scene.Node; -import javafx.scene.Parent; -import javafx.scene.shape.Rectangle; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -public class TopMostTraversalEngineTest { - private TopMostTraversalEngine engine; - private Group root; - - @Before - public void setUp() { - root = new Group(); - engine = new TopMostTraversalEngine(new ContainerTabOrder()) { - @Override - protected Parent getRoot() { - return root; - } - }; - } - - @Test - public void selectFirst() { - final Node focusableNode = createFocusableNode(); - Group g = new Group(focusableNode, createFocusableNode()); - root.getChildren().add(g); - - assertEquals(focusableNode, engine.selectFirst()); - } - - @Test - public void selectFirstSkipInvisible() { - final Node n1 = createFocusableDisabledNode(); - final Node n2 = createFocusableNode(); - root.getChildren().addAll(n1, n2); - - assertEquals(n2, engine.selectFirst()); - } - - @Test - public void selectFirstUseParentEngine() { - Group g = new Group(createFocusableNode()); - g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { - @Override - public Node select(Node owner, Direction dir, TraversalContext context) { - return null; - } - - @Override - public Node selectFirst(TraversalContext context) { - return null; - } - - @Override - public Node selectLast(TraversalContext context) { - return null; - } - })); - g.setDisable(true); - root.getChildren().add(g); - - final Node focusableNode = createFocusableNode(); - g = new Group(createFocusableNode(), focusableNode, createFocusableNode()); - g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { - @Override - public Node select(Node owner, Direction dir, TraversalContext context) { - fail(); - return null; - } - - @Override - public Node selectFirst(TraversalContext context) { - return focusableNode; - } - - @Override - public Node selectLast(TraversalContext context) { - fail(); - return null; - } - })); - - root.getChildren().add(g); - - assertEquals(focusableNode, engine.selectFirst()); - } - - @Test - public void selectFirstFocusableParent() { - Group g = new Group(createFocusableNode(), createFocusableNode()); - g.setFocusTraversable(true); - root.getChildren().add(g); - - assertEquals(g, engine.selectFirst()); - } - - @Test - public void selectFirstTraverseOverride() { - Group g = new Group(createFocusableNode(), createFocusableNode()); - g.setFocusTraversable(true); - final ParentTraversalEngine pEngine = new ParentTraversalEngine(g); - pEngine.setOverriddenFocusTraversability(false); - g.setImpl_traversalEngine(pEngine); - - root.getChildren().add(g); - - assertEquals(g.getChildren().get(0), engine.selectFirst()); - } - - - @Test - public void selectLast() { - final Node focusableNode = createFocusableNode(); - Group g = new Group(createFocusableNode(), focusableNode); - root.getChildren().add(g); - - assertEquals(focusableNode, engine.selectLast()); - } - - @Test - public void selectLastSkipInvisible() { - final Node n1 = createFocusableNode(); - final Node n2 = createFocusableDisabledNode(); - root.getChildren().addAll(n1, n2); - - assertEquals(n1, engine.selectFirst()); - } - - @Test - public void selectLastUseParentEngine() { - final Node focusableNode = createFocusableNode(); - Group g = new Group(createFocusableNode(), focusableNode, createFocusableNode()); - g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { - @Override - public Node select(Node owner, Direction dir, TraversalContext context) { - fail(); - return null; - } - - @Override - public Node selectFirst(TraversalContext context) { - fail(); - return null; - } - - @Override - public Node selectLast(TraversalContext context) { - return focusableNode; - } - })); - - root.getChildren().add(g); - - - g = new Group(createFocusableNode()); - g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { - @Override - public Node select(Node owner, Direction dir, TraversalContext context) { - return null; - } - - @Override - public Node selectFirst(TraversalContext context) { - return null; - } - - @Override - public Node selectLast(TraversalContext context) { - return null; - } - })); - g.setDisable(true); - root.getChildren().add(g); - - - assertEquals(focusableNode, engine.selectLast()); - } - - @Test - public void selectLastFocusableParent() { - final Node focusableNode = createFocusableNode(); - Group g = new Group(createFocusableNode(), focusableNode); - g.setFocusTraversable(true); - root.getChildren().add(g); - - assertEquals(focusableNode, engine.selectLast()); - } - - @Test - public void selectLastFocusableParent_2() { - Group g = new Group(new Rectangle()); - g.setFocusTraversable(true); - root.getChildren().add(g); - - assertEquals(g, engine.selectLast()); - } - - @Test - public void selectLastTraverseOverride() { - Group g = new Group(); - g.setFocusTraversable(true); - final ParentTraversalEngine pEngine = new ParentTraversalEngine(g); - pEngine.setOverriddenFocusTraversability(false); - g.setImpl_traversalEngine(pEngine); - - Node focusableNode = createFocusableNode(); - - root.getChildren().addAll(focusableNode, g); - - assertEquals(focusableNode, engine.selectLast()); - } - - @Test - public void selectNext() { - Node n1 = createFocusableNode(); - Node n2 = createFocusableNode(); - Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); - - root.getChildren().addAll(g); - - assertEquals(n2, engine.trav(n1, Direction.NEXT)); - } - - @Test - public void selectNextFromParent() { - Node ng1 = createFocusableNode(); - Node n1 = new Group(new Rectangle(), createFocusableDisabledNode(), ng1, createFocusableNode()); - Node n2 = createFocusableNode(); - Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); - - root.getChildren().addAll(g); - - assertEquals(ng1, engine.trav(n1, Direction.NEXT)); - } - - @Test - public void selectNextFromParent_2() { - Node n1 = new Group(createFocusableDisabledNode(), createFocusableDisabledNode()); - Node n2 = createFocusableNode(); - Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); - - root.getChildren().addAll(g); - - assertEquals(n2, engine.trav(n1, Direction.NEXT)); - } - - @Test - public void selectNextInParentSibling() { - Node n1 = createFocusableNode(); - final Node n2 = createFocusableNode(); - - root.getChildren().addAll(createFocusableNode(), new Group(new Group(n1, createFocusableDisabledNode(), createFocusableDisabledNode()), - new Group(createFocusableDisabledNode())), new Group(n2)); - - assertEquals(n2, engine.trav(n1, Direction.NEXT)); - } - - @Test - public void selectNextFocusableParent() { - Node n1 = createFocusableNode(); - Group g = new Group(createFocusableNode()); - g.setFocusTraversable(true); - - root.getChildren().addAll(new Group(createFocusableNode(), n1, createFocusableDisabledNode(), g)); - - assertEquals(g, engine.trav(n1, Direction.NEXT)); - } - - @Test - public void selectNextInOverridenAlgorithm() { - Node n1 = createFocusableNode(); - Node n2 = createFocusableNode(); - Group g = new Group(n1, createFocusableNode(), n2); - g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { - @Override - public Node select(Node owner, Direction dir, TraversalContext context) { - assertEquals(Direction.NEXT, dir); - return n2; - } - - @Override - public Node selectFirst(TraversalContext context) { - fail(); - return null; - } - - @Override - public Node selectLast(TraversalContext context) { - fail(); - return null; - } - })); - - root.getChildren().add(g); - - assertEquals(n2, engine.trav(n1, Direction.NEXT)); - } - - - @Test - public void selectNextInOverridenAlgorithm_NothingSelected() { - Node n1 = createFocusableNode(); - Node n2 = createFocusableNode(); - Group g = new Group(n1, createFocusableNode(), n2); - g.setFocusTraversable(true); - g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { - @Override - public Node select(Node owner, Direction dir, TraversalContext context) { - assertEquals(Direction.NEXT, dir); - return null; - } - - @Override - public Node selectFirst(TraversalContext context) { - fail(); - return null; - } - - @Override - public Node selectLast(TraversalContext context) { - fail(); - return null; - } - })); - - final Node n3 = createFocusableNode(); - root.getChildren().addAll(g, n3); - - assertEquals(n3, engine.trav(n1, Direction.NEXT)); - } - - @Test - public void selectNextInLine() { - Node n1 = new Group(createFocusableNode(), createFocusableNode()); - n1.setFocusTraversable(true); - Node n2 = createFocusableNode(); - Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); - - root.getChildren().addAll(g); - - assertEquals(n2, engine.trav(n1, Direction.NEXT_IN_LINE)); - } - - - @Test - public void selectPrevious() { - Node n1 = createFocusableNode(); - Node n2 = createFocusableNode(); - Group g = new Group(createFocusableNode(), n2, new Rectangle(), n1, createFocusableNode()); - - root.getChildren().addAll(g); - - assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); - } - - @Test - public void selectPreviousFromParent() { - Node ng1 = createFocusableNode(); - Node n1 = new Group(new Rectangle(), createFocusableDisabledNode(), ng1, createFocusableNode()); - Node n2 = createFocusableNode(); - Group g = new Group(createFocusableNode(), n2, new Rectangle(), n1, createFocusableNode()); - - root.getChildren().addAll(g); - - assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); - } - - @Test - public void selectPreviousFromParent_2() { - Node n1 = new Group(createFocusableDisabledNode(), createFocusableDisabledNode()); - Node n2 = createFocusableNode(); - Group g = new Group(createFocusableNode(), n2, new Rectangle(), n1, createFocusableNode()); - - root.getChildren().addAll(g); - - assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); - } - - @Test - public void selectPreviousInParentSibling() { - Node n1 = createFocusableNode(); - final Node n2 = createFocusableNode(); - - root.getChildren().addAll(new Group(n2), new Group(createFocusableDisabledNode()), - new Group(new Group(createFocusableDisabledNode(), n1, createFocusableDisabledNode())), - createFocusableNode()); - - assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); - } - - @Test - public void selectPreviousFocusableParentsNode() { - Node n1 = createFocusableNode(); - final Node n2 = createFocusableNode(); - Group g = new Group(n2); - g.setFocusTraversable(true); - - root.getChildren().addAll(new Group(createFocusableNode(), g, n1, createFocusableDisabledNode())); - - assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); - } - - @Test - public void selectPreviousFocusableParent() { - Node n1 = createFocusableNode(); - final Node n2 = createFocusableNode(); - Group g = new Group(createFocusableDisabledNode(), n2); - g.setFocusTraversable(true); - - root.getChildren().addAll(new Group(createFocusableNode(), n1, g, createFocusableDisabledNode())); - - assertEquals(g, engine.trav(n2, Direction.PREVIOUS)); - } - - @Test - public void selectNextToLast() { - Node n1 = createFocusableNode(); - Node n2 = createFocusableNode(); - - root.getChildren().addAll(new Group(n2), new Group(createFocusableNode(), n1)); - - assertEquals(n2, engine.trav(n1, Direction.NEXT)); - } - - - @Test - public void selectPreviousToFirst() { - Node n1 = createFocusableNode(); - Node n2 = createFocusableNode(); - - root.getChildren().addAll(new Group(n1, createFocusableNode()), new Group(n2)); - - assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); - } - - - @Test - public void selectPreviousInOverridenAlgorithm() { - Node n1 = createFocusableNode(); - Node n2 = createFocusableNode(); - Group g = new Group(n2, createFocusableNode(), n1); - g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { - @Override - public Node select(Node owner, Direction dir, TraversalContext context) { - assertEquals(Direction.PREVIOUS, dir); - return n2; - } - - @Override - public Node selectFirst(TraversalContext context) { - fail(); - return null; - } - - @Override - public Node selectLast(TraversalContext context) { - fail(); - return null; - } - })); - - root.getChildren().add(g); - - assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); - } - - private Node createFocusableNode() { - Node n = new Rectangle(); - n.setFocusTraversable(true); - return n; - } - - private Node createFocusableDisabledNode() { - Node n = createFocusableNode(); - n.setDisable(true); - return n; - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/scene/traversal/TopMostTraversalEngineTest.java 2015-09-11 21:24:22.825287008 -0400 @@ -0,0 +1,518 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.scene.traversal; + +import com.sun.javafx.scene.traversal.Algorithm; +import com.sun.javafx.scene.traversal.ContainerTabOrder; +import com.sun.javafx.scene.traversal.ContainerTabOrderShim; +import com.sun.javafx.scene.traversal.Direction; +import com.sun.javafx.scene.traversal.ParentTraversalEngine; +import com.sun.javafx.scene.traversal.TopMostTraversalEngine; +import com.sun.javafx.scene.traversal.TopMostTraversalEngineShim; +import com.sun.javafx.scene.traversal.TraversalContext; +import javafx.scene.Group; +import javafx.scene.Node; +import javafx.scene.Parent; +import javafx.scene.ParentShim; +import javafx.scene.shape.Rectangle; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class TopMostTraversalEngineTest { + private TopMostTraversalEngineShim engine; + private Group root; + + @Before + public void setUp() { + root = new Group(); + engine = new TopMostTraversalEngineShim(new ContainerTabOrderShim()) { + @Override + protected Parent getRoot() { + return root; + } + }; + } + + @Test + public void selectFirst() { + final Node focusableNode = createFocusableNode(); + Group g = new Group(focusableNode, createFocusableNode()); + ParentShim.getChildren(root).add(g); + + assertEquals(focusableNode, engine.selectFirst()); + } + + @Test + public void selectFirstSkipInvisible() { + final Node n1 = createFocusableDisabledNode(); + final Node n2 = createFocusableNode(); + ParentShim.getChildren(root).addAll(n1, n2); + + assertEquals(n2, engine.selectFirst()); + } + + @Test + public void selectFirstUseParentEngine() { + Group g = new Group(createFocusableNode()); + g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { + @Override + public Node select(Node owner, Direction dir, TraversalContext context) { + return null; + } + + @Override + public Node selectFirst(TraversalContext context) { + return null; + } + + @Override + public Node selectLast(TraversalContext context) { + return null; + } + })); + g.setDisable(true); + ParentShim.getChildren(root).add(g); + + final Node focusableNode = createFocusableNode(); + g = new Group(createFocusableNode(), focusableNode, createFocusableNode()); + g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { + @Override + public Node select(Node owner, Direction dir, TraversalContext context) { + fail(); + return null; + } + + @Override + public Node selectFirst(TraversalContext context) { + return focusableNode; + } + + @Override + public Node selectLast(TraversalContext context) { + fail(); + return null; + } + })); + + ParentShim.getChildren(root).add(g); + + assertEquals(focusableNode, engine.selectFirst()); + } + + @Test + public void selectFirstFocusableParent() { + Group g = new Group(createFocusableNode(), createFocusableNode()); + g.setFocusTraversable(true); + ParentShim.getChildren(root).add(g); + + assertEquals(g, engine.selectFirst()); + } + + @Test + public void selectFirstTraverseOverride() { + Group g = new Group(createFocusableNode(), createFocusableNode()); + g.setFocusTraversable(true); + final ParentTraversalEngine pEngine = new ParentTraversalEngine(g); + pEngine.setOverriddenFocusTraversability(false); + g.setImpl_traversalEngine(pEngine); + + ParentShim.getChildren(root).add(g); + + assertEquals(ParentShim.getChildren(g).get(0), engine.selectFirst()); + } + + + @Test + public void selectLast() { + final Node focusableNode = createFocusableNode(); + Group g = new Group(createFocusableNode(), focusableNode); + ParentShim.getChildren(root).add(g); + + assertEquals(focusableNode, engine.selectLast()); + } + + @Test + public void selectLastSkipInvisible() { + final Node n1 = createFocusableNode(); + final Node n2 = createFocusableDisabledNode(); + ParentShim.getChildren(root).addAll(n1, n2); + + assertEquals(n1, engine.selectFirst()); + } + + @Test + public void selectLastUseParentEngine() { + final Node focusableNode = createFocusableNode(); + Group g = new Group(createFocusableNode(), focusableNode, createFocusableNode()); + g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { + @Override + public Node select(Node owner, Direction dir, TraversalContext context) { + fail(); + return null; + } + + @Override + public Node selectFirst(TraversalContext context) { + fail(); + return null; + } + + @Override + public Node selectLast(TraversalContext context) { + return focusableNode; + } + })); + + ParentShim.getChildren(root).add(g); + + + g = new Group(createFocusableNode()); + g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { + @Override + public Node select(Node owner, Direction dir, TraversalContext context) { + return null; + } + + @Override + public Node selectFirst(TraversalContext context) { + return null; + } + + @Override + public Node selectLast(TraversalContext context) { + return null; + } + })); + g.setDisable(true); + ParentShim.getChildren(root).add(g); + + + assertEquals(focusableNode, engine.selectLast()); + } + + @Test + public void selectLastFocusableParent() { + final Node focusableNode = createFocusableNode(); + Group g = new Group(createFocusableNode(), focusableNode); + g.setFocusTraversable(true); + ParentShim.getChildren(root).add(g); + + assertEquals(focusableNode, engine.selectLast()); + } + + @Test + public void selectLastFocusableParent_2() { + Group g = new Group(new Rectangle()); + g.setFocusTraversable(true); + ParentShim.getChildren(root).add(g); + + assertEquals(g, engine.selectLast()); + } + + @Test + public void selectLastTraverseOverride() { + Group g = new Group(); + g.setFocusTraversable(true); + final ParentTraversalEngine pEngine = new ParentTraversalEngine(g); + pEngine.setOverriddenFocusTraversability(false); + g.setImpl_traversalEngine(pEngine); + + Node focusableNode = createFocusableNode(); + + ParentShim.getChildren(root).addAll(focusableNode, g); + + assertEquals(focusableNode, engine.selectLast()); + } + + @Test + public void selectNext() { + Node n1 = createFocusableNode(); + Node n2 = createFocusableNode(); + Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); + + ParentShim.getChildren(root).addAll(g); + + assertEquals(n2, engine.trav(n1, Direction.NEXT)); + } + + @Test + public void selectNextFromParent() { + Node ng1 = createFocusableNode(); + Node n1 = new Group(new Rectangle(), createFocusableDisabledNode(), ng1, createFocusableNode()); + Node n2 = createFocusableNode(); + Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); + + ParentShim.getChildren(root).addAll(g); + + assertEquals(ng1, engine.trav(n1, Direction.NEXT)); + } + + @Test + public void selectNextFromParent_2() { + Node n1 = new Group(createFocusableDisabledNode(), createFocusableDisabledNode()); + Node n2 = createFocusableNode(); + Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); + + ParentShim.getChildren(root).addAll(g); + + assertEquals(n2, engine.trav(n1, Direction.NEXT)); + } + + @Test + public void selectNextInParentSibling() { + Node n1 = createFocusableNode(); + final Node n2 = createFocusableNode(); + + ParentShim.getChildren(root).addAll(createFocusableNode(), new Group(new Group(n1, createFocusableDisabledNode(), createFocusableDisabledNode()), + new Group(createFocusableDisabledNode())), new Group(n2)); + + assertEquals(n2, engine.trav(n1, Direction.NEXT)); + } + + @Test + public void selectNextFocusableParent() { + Node n1 = createFocusableNode(); + Group g = new Group(createFocusableNode()); + g.setFocusTraversable(true); + + ParentShim.getChildren(root).addAll(new Group(createFocusableNode(), n1, createFocusableDisabledNode(), g)); + + assertEquals(g, engine.trav(n1, Direction.NEXT)); + } + + @Test + public void selectNextInOverridenAlgorithm() { + Node n1 = createFocusableNode(); + Node n2 = createFocusableNode(); + Group g = new Group(n1, createFocusableNode(), n2); + g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { + @Override + public Node select(Node owner, Direction dir, TraversalContext context) { + assertEquals(Direction.NEXT, dir); + return n2; + } + + @Override + public Node selectFirst(TraversalContext context) { + fail(); + return null; + } + + @Override + public Node selectLast(TraversalContext context) { + fail(); + return null; + } + })); + + ParentShim.getChildren(root).add(g); + + assertEquals(n2, engine.trav(n1, Direction.NEXT)); + } + + + @Test + public void selectNextInOverridenAlgorithm_NothingSelected() { + Node n1 = createFocusableNode(); + Node n2 = createFocusableNode(); + Group g = new Group(n1, createFocusableNode(), n2); + g.setFocusTraversable(true); + g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { + @Override + public Node select(Node owner, Direction dir, TraversalContext context) { + assertEquals(Direction.NEXT, dir); + return null; + } + + @Override + public Node selectFirst(TraversalContext context) { + fail(); + return null; + } + + @Override + public Node selectLast(TraversalContext context) { + fail(); + return null; + } + })); + + final Node n3 = createFocusableNode(); + ParentShim.getChildren(root).addAll(g, n3); + + assertEquals(n3, engine.trav(n1, Direction.NEXT)); + } + + @Test + public void selectNextInLine() { + Node n1 = new Group(createFocusableNode(), createFocusableNode()); + n1.setFocusTraversable(true); + Node n2 = createFocusableNode(); + Group g = new Group(createFocusableNode(), n1, new Rectangle(), n2, createFocusableNode()); + + ParentShim.getChildren(root).addAll(g); + + assertEquals(n2, engine.trav(n1, Direction.NEXT_IN_LINE)); + } + + + @Test + public void selectPrevious() { + Node n1 = createFocusableNode(); + Node n2 = createFocusableNode(); + Group g = new Group(createFocusableNode(), n2, new Rectangle(), n1, createFocusableNode()); + + ParentShim.getChildren(root).addAll(g); + + assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); + } + + @Test + public void selectPreviousFromParent() { + Node ng1 = createFocusableNode(); + Node n1 = new Group(new Rectangle(), createFocusableDisabledNode(), ng1, createFocusableNode()); + Node n2 = createFocusableNode(); + Group g = new Group(createFocusableNode(), n2, new Rectangle(), n1, createFocusableNode()); + + ParentShim.getChildren(root).addAll(g); + + assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); + } + + @Test + public void selectPreviousFromParent_2() { + Node n1 = new Group(createFocusableDisabledNode(), createFocusableDisabledNode()); + Node n2 = createFocusableNode(); + Group g = new Group(createFocusableNode(), n2, new Rectangle(), n1, createFocusableNode()); + + ParentShim.getChildren(root).addAll(g); + + assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); + } + + @Test + public void selectPreviousInParentSibling() { + Node n1 = createFocusableNode(); + final Node n2 = createFocusableNode(); + + ParentShim.getChildren(root).addAll(new Group(n2), new Group(createFocusableDisabledNode()), + new Group(new Group(createFocusableDisabledNode(), n1, createFocusableDisabledNode())), + createFocusableNode()); + + assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); + } + + @Test + public void selectPreviousFocusableParentsNode() { + Node n1 = createFocusableNode(); + final Node n2 = createFocusableNode(); + Group g = new Group(n2); + g.setFocusTraversable(true); + + ParentShim.getChildren(root).addAll(new Group(createFocusableNode(), g, n1, createFocusableDisabledNode())); + + assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); + } + + @Test + public void selectPreviousFocusableParent() { + Node n1 = createFocusableNode(); + final Node n2 = createFocusableNode(); + Group g = new Group(createFocusableDisabledNode(), n2); + g.setFocusTraversable(true); + + ParentShim.getChildren(root).addAll(new Group(createFocusableNode(), n1, g, createFocusableDisabledNode())); + + assertEquals(g, engine.trav(n2, Direction.PREVIOUS)); + } + + @Test + public void selectNextToLast() { + Node n1 = createFocusableNode(); + Node n2 = createFocusableNode(); + + ParentShim.getChildren(root).addAll(new Group(n2), new Group(createFocusableNode(), n1)); + + assertEquals(n2, engine.trav(n1, Direction.NEXT)); + } + + + @Test + public void selectPreviousToFirst() { + Node n1 = createFocusableNode(); + Node n2 = createFocusableNode(); + + ParentShim.getChildren(root).addAll(new Group(n1, createFocusableNode()), new Group(n2)); + + assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); + } + + + @Test + public void selectPreviousInOverridenAlgorithm() { + Node n1 = createFocusableNode(); + Node n2 = createFocusableNode(); + Group g = new Group(n2, createFocusableNode(), n1); + g.setImpl_traversalEngine(new ParentTraversalEngine(g, new Algorithm() { + @Override + public Node select(Node owner, Direction dir, TraversalContext context) { + assertEquals(Direction.PREVIOUS, dir); + return n2; + } + + @Override + public Node selectFirst(TraversalContext context) { + fail(); + return null; + } + + @Override + public Node selectLast(TraversalContext context) { + fail(); + return null; + } + })); + + ParentShim.getChildren(root).add(g); + + assertEquals(n2, engine.trav(n1, Direction.PREVIOUS)); + } + + private Node createFocusableNode() { + Node n = new Rectangle(); + n.setFocusTraversable(true); + return n; + } + + private Node createFocusableDisabledNode() { + Node n = createFocusableNode(); + n.setDisable(true); + return n; + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/scene/traversal/TraversalTest.java 2015-09-11 21:24:23.661286998 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.scene.traversal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; - -import javafx.geometry.Bounds; -import javafx.scene.Group; -import javafx.scene.Node; -import javafx.scene.Scene; -import javafx.scene.shape.Rectangle; -import javafx.stage.Stage; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests for TraversalEngine with the default ContainerTabOrder algorithm, - * tests if using the WeightedClosestCorner algorithm have been - * left in comments. - */ -@RunWith(Parameterized.class) -public final class TraversalTest { - private final int fromNumber; - private final Direction direction; - private final int toNumber; - private final int toNumberTransformed; - - private Stage stage; - private Scene scene; - /** - * 3x3 keypad. - *

- * Untransformed keypad: - *

    - *
  • 1 2 3
  • - *
  • 4 5 6
  • - *
  • 7 8 9
  • - *
- *

- * Transformed keypad: - *

    - *
  • 7 4 1
  • - *
  • 8 5 2
  • - *
  • 9 6 3
  • - *
- */ - private Node[] keypadNodes; - private SceneTraversalEngine traversalEngine; - - /* - * Parameters: [fromNumber], [direction], [toNumber], [toNumberTransformed] - */ - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { - /* traversal from center */ - { 5, Direction.LEFT, 4, 8 }, - { 5, Direction.RIGHT, 6, 2 }, - { 5, Direction.UP, 2, 4 }, - { 5, Direction.DOWN, 8, 6 }, - - // using WeightedClosestCorner, target varies according to transform - //{ 5, Direction.PREVIOUS, 4, 8 }, - //{ 5, Direction.NEXT, 6, 2 }, - - // using ContainerTabOrder, target is always the same - { 5, Direction.PREVIOUS, 4, 4 }, - { 5, Direction.NEXT, 6, 6 }, - - /* traversal from borders (untransformed) */ - { 4, Direction.LEFT, 4, 7 }, - { 6, Direction.RIGHT, 6, 3 }, - { 2, Direction.UP, 2, 1 }, - { 8, Direction.DOWN, 8, 9 }, - - // using WeightedClosestCorner, target varies according to transform - //{ 4, Direction.PREVIOUS, 3, 7 }, - //{ 1, Direction.PREVIOUS, 9, 4 }, - //{ 6, Direction.NEXT, 7, 3 }, - //{ 9, Direction.NEXT, 1, 6 }, - - // using ContainerTabOrder, target always the same - { 4, Direction.PREVIOUS, 3, 3 }, - { 1, Direction.PREVIOUS, 9, 9 }, - { 6, Direction.NEXT, 7, 7 }, - { 9, Direction.NEXT, 1, 1 }, - - /* traversal from borders (transformed) */ - { 2, Direction.RIGHT, 3, 2 }, - { 8, Direction.LEFT, 7, 8 }, - { 4, Direction.UP, 1, 4 }, - { 6, Direction.DOWN, 9, 6 }, - - // using WeightedClosestCorner, target varies according to transform - //{ 8, Direction.PREVIOUS, 7, 1 }, - //{ 7, Direction.PREVIOUS, 6, 3 }, - //{ 2, Direction.NEXT, 3, 9 }, - //{ 3, Direction.NEXT, 4, 7 } - - // using ContainerTabOrder, target always the same - { 8, Direction.PREVIOUS, 7, 7 }, - { 7, Direction.PREVIOUS, 6, 6 }, - { 2, Direction.NEXT, 3, 3 }, - { 3, Direction.NEXT, 4, 4 } - }); - } - - public TraversalTest(final int fromNumber, - final Direction direction, - final int toNumber, - final int toNumberTransformed) { - this.fromNumber = fromNumber; - this.direction = direction; - this.toNumber = toNumber; - this.toNumberTransformed = toNumberTransformed; - } - - @Before - public void setUp() { - stage = new Stage(); - scene = new Scene(new Group(), 500, 500); - stage.setScene(scene); - - traversalEngine = new SceneTraversalEngine(scene); - - keypadNodes = createKeypadNodesInScene(scene, traversalEngine); - - stage.show(); - stage.requestFocus(); - } - - @After - public void tearDown() { - stage = null; - scene = null; - keypadNodes = null; - traversalEngine = null; - } - - @Test - public void untransformedTraversalTest() { - keypadNodes[fromNumber - 1].requestFocus(); - traversalEngine.trav(keypadNodes[fromNumber - 1], direction); - assertTrue(keypadNodes[toNumber - 1].isFocused()); - } - - @Test - public void transformedTraversalTest() { - scene.getRoot().setRotate(90); - keypadNodes[fromNumber - 1].requestFocus(); - traversalEngine.trav(keypadNodes[fromNumber - 1], direction); - assertTrue(keypadNodes[toNumberTransformed - 1].isFocused()); - } - - @Test - public void traverseListenerTest() { - final TraverseListenerImpl traverseListener = - new TraverseListenerImpl(); - traversalEngine.addTraverseListener(traverseListener); - keypadNodes[fromNumber - 1].requestFocus(); - traversalEngine.trav(keypadNodes[fromNumber - 1], direction); - if (fromNumber != toNumber) { - assertEquals(1, traverseListener.getCallCounter()); - assertSame(keypadNodes[toNumber - 1], - traverseListener.getLastNode()); - } else { - assertEquals(0, traverseListener.getCallCounter()); - } - } - - private static Node[] createKeypadNodesInScene( - final Scene scene, - final TraversalEngine traversalEngine) { - final Node[] keypad = new Node[9]; - - int index = 0; - for (int row = 0; row < 3; ++row) { - for (int column = 0; column < 3; ++column) { - final Node keyNode = new Rectangle(10 + column * 50, - 10 + row * 50, - 40, 40); - keyNode.setFocusTraversable(true); - - keypad[index++] = keyNode; - ((Group)scene.getRoot()).getChildren().add(keyNode); - } - } - - return keypad; - } - - private static final class TraverseListenerImpl - implements TraverseListener { - private int callCounter; - private Node lastNode; - - public int getCallCounter() { - return callCounter; - } - - public Node getLastNode() { - return lastNode; - } - - @Override - public void onTraverse(final Node node, final Bounds bounds) { - ++callCounter; - lastNode = node; - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/scene/traversal/TraversalTest.java 2015-09-11 21:24:23.525287000 -0400 @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.scene.traversal; + +import com.sun.javafx.scene.traversal.Direction; +import com.sun.javafx.scene.traversal.Direction; +import com.sun.javafx.scene.traversal.SceneTraversalEngine; +import com.sun.javafx.scene.traversal.SceneTraversalEngine; +import com.sun.javafx.scene.traversal.TraversalEngine; +import com.sun.javafx.scene.traversal.TraversalEngine; +import com.sun.javafx.scene.traversal.TraverseListener; +import com.sun.javafx.scene.traversal.TraverseListener; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collection; + +import javafx.geometry.Bounds; +import javafx.scene.Group; +import javafx.scene.Node; +import javafx.scene.Scene; +import javafx.scene.shape.Rectangle; +import javafx.stage.Stage; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +/** + * Tests for TraversalEngine with the default ContainerTabOrder algorithm, + * tests if using the WeightedClosestCorner algorithm have been + * left in comments. + */ +@RunWith(Parameterized.class) +public final class TraversalTest { + private final int fromNumber; + private final Direction direction; + private final int toNumber; + private final int toNumberTransformed; + + private Stage stage; + private Scene scene; + /** + * 3x3 keypad. + *

+ * Untransformed keypad: + *

    + *
  • 1 2 3
  • + *
  • 4 5 6
  • + *
  • 7 8 9
  • + *
+ *

+ * Transformed keypad: + *

    + *
  • 7 4 1
  • + *
  • 8 5 2
  • + *
  • 9 6 3
  • + *
+ */ + private Node[] keypadNodes; + private SceneTraversalEngine traversalEngine; + + /* + * Parameters: [fromNumber], [direction], [toNumber], [toNumberTransformed] + */ + @Parameters + public static Collection data() { + return Arrays.asList(new Object[][] { + /* traversal from center */ + { 5, Direction.LEFT, 4, 8 }, + { 5, Direction.RIGHT, 6, 2 }, + { 5, Direction.UP, 2, 4 }, + { 5, Direction.DOWN, 8, 6 }, + + // using WeightedClosestCorner, target varies according to transform + //{ 5, Direction.PREVIOUS, 4, 8 }, + //{ 5, Direction.NEXT, 6, 2 }, + + // using ContainerTabOrder, target is always the same + { 5, Direction.PREVIOUS, 4, 4 }, + { 5, Direction.NEXT, 6, 6 }, + + /* traversal from borders (untransformed) */ + { 4, Direction.LEFT, 4, 7 }, + { 6, Direction.RIGHT, 6, 3 }, + { 2, Direction.UP, 2, 1 }, + { 8, Direction.DOWN, 8, 9 }, + + // using WeightedClosestCorner, target varies according to transform + //{ 4, Direction.PREVIOUS, 3, 7 }, + //{ 1, Direction.PREVIOUS, 9, 4 }, + //{ 6, Direction.NEXT, 7, 3 }, + //{ 9, Direction.NEXT, 1, 6 }, + + // using ContainerTabOrder, target always the same + { 4, Direction.PREVIOUS, 3, 3 }, + { 1, Direction.PREVIOUS, 9, 9 }, + { 6, Direction.NEXT, 7, 7 }, + { 9, Direction.NEXT, 1, 1 }, + + /* traversal from borders (transformed) */ + { 2, Direction.RIGHT, 3, 2 }, + { 8, Direction.LEFT, 7, 8 }, + { 4, Direction.UP, 1, 4 }, + { 6, Direction.DOWN, 9, 6 }, + + // using WeightedClosestCorner, target varies according to transform + //{ 8, Direction.PREVIOUS, 7, 1 }, + //{ 7, Direction.PREVIOUS, 6, 3 }, + //{ 2, Direction.NEXT, 3, 9 }, + //{ 3, Direction.NEXT, 4, 7 } + + // using ContainerTabOrder, target always the same + { 8, Direction.PREVIOUS, 7, 7 }, + { 7, Direction.PREVIOUS, 6, 6 }, + { 2, Direction.NEXT, 3, 3 }, + { 3, Direction.NEXT, 4, 4 } + }); + } + + public TraversalTest(final int fromNumber, + final Direction direction, + final int toNumber, + final int toNumberTransformed) { + this.fromNumber = fromNumber; + this.direction = direction; + this.toNumber = toNumber; + this.toNumberTransformed = toNumberTransformed; + } + + @Before + public void setUp() { + stage = new Stage(); + scene = new Scene(new Group(), 500, 500); + stage.setScene(scene); + + traversalEngine = new SceneTraversalEngine(scene); + + keypadNodes = createKeypadNodesInScene(scene, traversalEngine); + + stage.show(); + stage.requestFocus(); + } + + @After + public void tearDown() { + stage = null; + scene = null; + keypadNodes = null; + traversalEngine = null; + } + + @Test + public void untransformedTraversalTest() { + keypadNodes[fromNumber - 1].requestFocus(); + traversalEngine.trav(keypadNodes[fromNumber - 1], direction); + assertTrue(keypadNodes[toNumber - 1].isFocused()); + } + + @Test + public void transformedTraversalTest() { + scene.getRoot().setRotate(90); + keypadNodes[fromNumber - 1].requestFocus(); + traversalEngine.trav(keypadNodes[fromNumber - 1], direction); + assertTrue(keypadNodes[toNumberTransformed - 1].isFocused()); + } + + @Test + public void traverseListenerTest() { + final TraverseListenerImpl traverseListener = + new TraverseListenerImpl(); + traversalEngine.addTraverseListener(traverseListener); + keypadNodes[fromNumber - 1].requestFocus(); + traversalEngine.trav(keypadNodes[fromNumber - 1], direction); + if (fromNumber != toNumber) { + assertEquals(1, traverseListener.getCallCounter()); + assertSame(keypadNodes[toNumber - 1], + traverseListener.getLastNode()); + } else { + assertEquals(0, traverseListener.getCallCounter()); + } + } + + private static Node[] createKeypadNodesInScene( + final Scene scene, + final TraversalEngine traversalEngine) { + final Node[] keypad = new Node[9]; + + int index = 0; + for (int row = 0; row < 3; ++row) { + for (int column = 0; column < 3; ++column) { + final Node keyNode = new Rectangle(10 + column * 50, + 10 + row * 50, + 40, 40); + keyNode.setFocusTraversable(true); + + keypad[index++] = keyNode; + ((Group)scene.getRoot()).getChildren().add(keyNode); + } + } + + return keypad; + } + + private static final class TraverseListenerImpl + implements TraverseListener { + private int callCounter; + private Node lastNode; + + public int getCallCounter() { + return callCounter; + } + + public Node getLastNode() { + return lastNode; + } + + @Override + public void onTraverse(final Node node, final Bounds bounds) { + ++callCounter; + lastNode = node; + } + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/scene/traversal/TraverseInvisibleTest.java 2015-09-11 21:24:24.273286991 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,168 +0,0 @@ -/* - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.scene.traversal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; - -import javafx.geometry.Bounds; -import javafx.scene.Group; -import javafx.scene.Node; -import javafx.scene.Scene; -import javafx.scene.shape.Rectangle; -import javafx.stage.Stage; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests TraversalEngine with invisible nodes, using the default ContainerTabOrder algorithm, - */ -@RunWith(Parameterized.class) -public final class TraverseInvisibleTest { - private final int fromNumber; - private final Direction direction; - private final int invisibleNumber; - private final int toNumber; - - private Stage stage; - private Scene scene; - private Node[] keypadNodes; - private SceneTraversalEngine traversalEngine; - - /* - ** - ** Parameters: [fromNumber], [direction], [invisibleNumber], [toNumber] - ** The Grid looks like : - ** 0 1 2 - ** 3 4 5 - ** 6 7 8 - */ - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { - { 3, Direction.RIGHT, 4, 5}, - { 5, Direction.LEFT, 4, 3}, - { 4, Direction.NEXT, 5, 6}, - { 6, Direction.PREVIOUS, 5, 4}, - { 8, Direction.UP, 5, 2 }, - { 2, Direction.DOWN, 5, 8 } - }); - } - - public TraverseInvisibleTest(final int fromNumber, - final Direction direction, - final int invisibleNumber, - final int toNumber) { - this.fromNumber = fromNumber; - this.direction = direction; - this.invisibleNumber = invisibleNumber; - this.toNumber = toNumber; - } - - @Before - public void setUp() { - stage = new Stage(); - scene = new Scene(new Group(), 500, 500); - stage.setScene(scene); - - traversalEngine = new SceneTraversalEngine(scene); - - keypadNodes = createKeypadNodesInScene(scene, traversalEngine); - stage.show(); - stage.requestFocus(); - } - - @After - public void tearDown() { - stage = null; - scene = null; - keypadNodes = null; - traversalEngine = null; - } - - @Test - public void traverseOverInvisible() { - keypadNodes[fromNumber].requestFocus(); - keypadNodes[invisibleNumber].setVisible(false); - traversalEngine.trav(keypadNodes[fromNumber], direction); - - assertTrue(keypadNodes[toNumber].isFocused()); - - keypadNodes[invisibleNumber - 1].setVisible(true); - } - - - - private static Node[] createKeypadNodesInScene( - final Scene scene, - final TraversalEngine traversalEngine) { - final Node[] keypad = new Node[9]; - - int index = 0; - for (int row = 0; row < 3; ++row) { - for (int column = 0; column < 3; ++column) { - final Node keyNode = new Rectangle(10 + column * 50, - 10 + row * 50, - 40, 40); - keyNode.setFocusTraversable(true); - - keypad[index++] = keyNode; - ((Group)scene.getRoot()).getChildren().add(keyNode); - } - } - - return keypad; - } - - private static final class TraverseListenerImpl - implements TraverseListener { - private int callCounter; - private Node lastNode; - - public int getCallCounter() { - return callCounter; - } - - public Node getLastNode() { - return lastNode; - } - - @Override - public void onTraverse(final Node node, final Bounds bounds) { - ++callCounter; - lastNode = node; - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/scene/traversal/TraverseInvisibleTest.java 2015-09-11 21:24:24.133286993 -0400 @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.scene.traversal; + +import com.sun.javafx.scene.traversal.Direction; +import com.sun.javafx.scene.traversal.Direction; +import com.sun.javafx.scene.traversal.SceneTraversalEngine; +import com.sun.javafx.scene.traversal.SceneTraversalEngine; +import com.sun.javafx.scene.traversal.TraversalEngine; +import com.sun.javafx.scene.traversal.TraversalEngine; +import com.sun.javafx.scene.traversal.TraverseListener; +import com.sun.javafx.scene.traversal.TraverseListener; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collection; + +import javafx.geometry.Bounds; +import javafx.scene.Group; +import javafx.scene.Node; +import javafx.scene.Scene; +import javafx.scene.shape.Rectangle; +import javafx.stage.Stage; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +/** + * Tests TraversalEngine with invisible nodes, using the default ContainerTabOrder algorithm, + */ +@RunWith(Parameterized.class) +public final class TraverseInvisibleTest { + private final int fromNumber; + private final Direction direction; + private final int invisibleNumber; + private final int toNumber; + + private Stage stage; + private Scene scene; + private Node[] keypadNodes; + private SceneTraversalEngine traversalEngine; + + /* + ** + ** Parameters: [fromNumber], [direction], [invisibleNumber], [toNumber] + ** The Grid looks like : + ** 0 1 2 + ** 3 4 5 + ** 6 7 8 + */ + @Parameters + public static Collection data() { + return Arrays.asList(new Object[][] { + { 3, Direction.RIGHT, 4, 5}, + { 5, Direction.LEFT, 4, 3}, + { 4, Direction.NEXT, 5, 6}, + { 6, Direction.PREVIOUS, 5, 4}, + { 8, Direction.UP, 5, 2 }, + { 2, Direction.DOWN, 5, 8 } + }); + } + + public TraverseInvisibleTest(final int fromNumber, + final Direction direction, + final int invisibleNumber, + final int toNumber) { + this.fromNumber = fromNumber; + this.direction = direction; + this.invisibleNumber = invisibleNumber; + this.toNumber = toNumber; + } + + @Before + public void setUp() { + stage = new Stage(); + scene = new Scene(new Group(), 500, 500); + stage.setScene(scene); + + traversalEngine = new SceneTraversalEngine(scene); + + keypadNodes = createKeypadNodesInScene(scene, traversalEngine); + stage.show(); + stage.requestFocus(); + } + + @After + public void tearDown() { + stage = null; + scene = null; + keypadNodes = null; + traversalEngine = null; + } + + @Test + public void traverseOverInvisible() { + keypadNodes[fromNumber].requestFocus(); + keypadNodes[invisibleNumber].setVisible(false); + traversalEngine.trav(keypadNodes[fromNumber], direction); + + assertTrue(keypadNodes[toNumber].isFocused()); + + keypadNodes[invisibleNumber - 1].setVisible(true); + } + + + + private static Node[] createKeypadNodesInScene( + final Scene scene, + final TraversalEngine traversalEngine) { + final Node[] keypad = new Node[9]; + + int index = 0; + for (int row = 0; row < 3; ++row) { + for (int column = 0; column < 3; ++column) { + final Node keyNode = new Rectangle(10 + column * 50, + 10 + row * 50, + 40, 40); + keyNode.setFocusTraversable(true); + + keypad[index++] = keyNode; + ((Group)scene.getRoot()).getChildren().add(keyNode); + } + } + + return keypad; + } + + private static final class TraverseListenerImpl + implements TraverseListener { + private int callCounter; + private Node lastNode; + + public int getCallCounter() { + return callCounter; + } + + public Node getLastNode() { + return lastNode; + } + + @Override + public void onTraverse(final Node node, final Bounds bounds) { + ++callCounter; + lastNode = node; + } + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/CacheFilterTest.java 2015-09-11 21:24:25.045286983 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.javafx.geom.transform.GeneralTransform3D; -import com.sun.javafx.geom.transform.Translate2D; -import javafx.scene.CacheHint; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - */ -public class CacheFilterTest { - - /****************************************************************** - * * - * Tests to make sure that the different cache hints get * - * turned into the right values for rotateHint and scaleHint. * - * * - *****************************************************************/ - - @Test public void settingCacheHintToDefaultInConstructor() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.DEFAULT); - assertFalse(cf.isRotateHint()); - assertFalse(cf.isScaleHint()); - } - - @Test public void settingCacheHintToDefault() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.SPEED); - cf.setHint(CacheHint.DEFAULT); - assertFalse(cf.isRotateHint()); - assertFalse(cf.isScaleHint()); - } - - @Test public void settingCacheHintToSpeedInConstructor() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.SPEED); - assertTrue(cf.isRotateHint()); - assertTrue(cf.isScaleHint()); - } - - @Test public void settingCacheHintToSpeed() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.DEFAULT); - cf.setHint(CacheHint.SPEED); - assertTrue(cf.isRotateHint()); - assertTrue(cf.isScaleHint()); - } - - @Test public void settingCacheHintToQualityInConstructor() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.QUALITY); - assertFalse(cf.isRotateHint()); - assertFalse(cf.isScaleHint()); - } - - @Test public void settingCacheHintToQuality() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.SPEED); - cf.setHint(CacheHint.QUALITY); - assertFalse(cf.isRotateHint()); - assertFalse(cf.isScaleHint()); - } - - @Test public void settingCacheHintToRotateInConstructor() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.ROTATE); - assertTrue(cf.isRotateHint()); - assertFalse(cf.isScaleHint()); - } - - @Test public void settingCacheHintToRotate() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.DEFAULT); - cf.setHint(CacheHint.ROTATE); - assertTrue(cf.isRotateHint()); - assertFalse(cf.isScaleHint()); - } - - @Test public void settingCacheHintToScaleInConstructor() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.SCALE); - assertFalse(cf.isRotateHint()); - assertTrue(cf.isScaleHint()); - } - - @Test public void settingCacheHintToScale() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.DEFAULT); - cf.setHint(CacheHint.SCALE); - assertFalse(cf.isRotateHint()); - assertTrue(cf.isScaleHint()); - } - - @Test public void settingCacheHintToScaleAndRotateInConstructor() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.SCALE_AND_ROTATE); - assertTrue(cf.isRotateHint()); - assertTrue(cf.isScaleHint()); - } - - @Test public void settingCacheHintToScaleAndRotate() { - NGRectangle r = new NGRectangle(); - CacheFilter cf = new CacheFilter(r, CacheHint.DEFAULT); - cf.setHint(CacheHint.SCALE_AND_ROTATE); - assertTrue(cf.isRotateHint()); - assertTrue(cf.isScaleHint()); - } - - @Test public void cacheFilterReturnsCorrectDirtyBounds() { - - NGRectangle r = new NGRectangle(); - r.updateRectangle(0.3f, 0.9f, 100.3f, 119.9f, 0, 0); - r.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); - r.setTransformedBounds(new RectBounds(0.3f, 0.9f, 100.6f, 120.8f), false); - CacheFilter cf = new CacheFilter(r, CacheHint.DEFAULT); - RectBounds result = new RectBounds(); - cf.computeDirtyBounds(result, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - assertEquals(new RectBounds(0, 0, 101, 121), result); - - r.clearDirty(); - - final Translate2D translation = new Translate2D(10, 10); - r.setTransformMatrix(translation); - r.setTransformedBounds(new RectBounds(10.3f, 10, 110.6f, 130.8f), false); - cf.computeDirtyBounds(result, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - assertEquals(new RectBounds(0, 0, 111, 131), result); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/CacheFilterTest.java 2015-09-11 21:24:24.833286985 -0400 @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; +import com.sun.javafx.geom.transform.Translate2D; +import com.sun.javafx.sg.prism.CacheFilter; +import com.sun.javafx.sg.prism.CacheFilterShim; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.javafx.sg.prism.NGRectangle; +import javafx.scene.CacheHint; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + */ +public class CacheFilterTest { + + /****************************************************************** + * * + * Tests to make sure that the different cache hints get * + * turned into the right values for rotateHint and scaleHint. * + * * + *****************************************************************/ + + @Test public void settingCacheHintToDefaultInConstructor() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.DEFAULT); + assertFalse(CacheFilterShim.isRotateHint(cf)); + assertFalse(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToDefault() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.SPEED); + cf.setHint(CacheHint.DEFAULT); + assertFalse(CacheFilterShim.isRotateHint(cf)); + assertFalse(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToSpeedInConstructor() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.SPEED); + assertTrue(CacheFilterShim.isRotateHint(cf)); + assertTrue(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToSpeed() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.DEFAULT); + cf.setHint(CacheHint.SPEED); + assertTrue(CacheFilterShim.isRotateHint(cf)); + assertTrue(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToQualityInConstructor() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.QUALITY); + assertFalse(CacheFilterShim.isRotateHint(cf)); + assertFalse(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToQuality() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.SPEED); + cf.setHint(CacheHint.QUALITY); + assertFalse(CacheFilterShim.isRotateHint(cf)); + assertFalse(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToRotateInConstructor() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.ROTATE); + assertTrue(CacheFilterShim.isRotateHint(cf)); + assertFalse(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToRotate() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.DEFAULT); + cf.setHint(CacheHint.ROTATE); + assertTrue(CacheFilterShim.isRotateHint(cf)); + assertFalse(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToScaleInConstructor() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.SCALE); + assertFalse(CacheFilterShim.isRotateHint(cf)); + assertTrue(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToScale() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.DEFAULT); + cf.setHint(CacheHint.SCALE); + assertFalse(CacheFilterShim.isRotateHint(cf)); + assertTrue(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToScaleAndRotateInConstructor() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.SCALE_AND_ROTATE); + assertTrue(CacheFilterShim.isRotateHint(cf)); + assertTrue(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void settingCacheHintToScaleAndRotate() { + NGRectangle r = new NGRectangle(); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.DEFAULT); + cf.setHint(CacheHint.SCALE_AND_ROTATE); + assertTrue(CacheFilterShim.isRotateHint(cf)); + assertTrue(CacheFilterShim.isScaleHint(cf)); + } + + @Test public void cacheFilterReturnsCorrectDirtyBounds() { + + NGRectangle r = new NGRectangle(); + r.updateRectangle(0.3f, 0.9f, 100.3f, 119.9f, 0, 0); + r.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); + r.setTransformedBounds(new RectBounds(0.3f, 0.9f, 100.6f, 120.8f), false); + CacheFilter cf = CacheFilterShim.getCacheFilter(r, CacheHint.DEFAULT); + RectBounds result = new RectBounds(); + CacheFilterShim.computeDirtyBounds(cf, result, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + assertEquals(new RectBounds(0, 0, 101, 121), result); + + NGNodeShim.clearDirty(r); + + final Translate2D translation = new Translate2D(10, 10); + r.setTransformMatrix(translation); + r.setTransformedBounds(new RectBounds(10.3f, 10, 110.6f, 130.8f), false); + CacheFilterShim.computeDirtyBounds(cf, result, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + assertEquals(new RectBounds(0, 0, 111, 131), result); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/ContentBoundsTest.java 2015-09-11 21:24:25.653286976 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import javafx.scene.Group; -import javafx.scene.Node; -import javafx.scene.Parent; -import javafx.scene.Scene; -import javafx.scene.shape.Rectangle; -import com.sun.javafx.geom.BaseBounds; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.Affine2D; -import com.sun.javafx.geom.transform.BaseTransform; -import org.junit.Test; -import static org.junit.Assert.assertEquals; - -/** - */ -public class ContentBoundsTest { - public static final BaseTransform IDENTITY; - public static final BaseTransform TRANSLATE; - public static final BaseTransform SCALE; - public static final BaseTransform ROTATE; - public static final BaseTransform SCALE_TRANSLATE; - public static final BaseTransform TRANSLATE_SCALE; - - public static BaseTransform translate(BaseTransform transform, - double tx, double ty) - { - transform = BaseTransform.getInstance(transform); - return transform.deriveWithConcatenation(1, 0, 0, 1, tx, ty); - } - - public static BaseTransform scale(BaseTransform transform, - double sx, double sy) - { - transform = BaseTransform.getInstance(transform); - return transform.deriveWithConcatenation(sx, 0, 0, sy, 0, 0); - } - - public static BaseTransform rotate(BaseTransform transform, - double degrees) - { - Affine2D t2d = new Affine2D(transform); - t2d.rotate(Math.toRadians(degrees)); - return t2d; - } - - static { - IDENTITY = BaseTransform.IDENTITY_TRANSFORM; - TRANSLATE = translate(IDENTITY, 42.3, 16.5); - SCALE = scale(IDENTITY, 0.7, 0.6); - ROTATE = rotate(IDENTITY, 135); - TRANSLATE_SCALE = scale(TRANSLATE, 0.8, 0.9); - SCALE_TRANSLATE = translate(SCALE, 23.7, 83.5); - } - - public static Node translate(double tx, double ty, Node n) { - n.setTranslateX(tx); - n.setTranslateY(ty); - return n; - } - - public static Node scale(double sx, double sy, Node n) { - n.setScaleX(sx); - n.setScaleY(sy); - return n; - } - - public static Node rotate(double rot, Node n) { - n.setRotate(rot); - return n; - } - - public static Node group(Node... n) { - Group g = new Group(n); - return g; - } - - public static Node makeRectangle(double x, double y, double w, double h) { - return new Rectangle(x, y, w, h); - } - - public static NGNode getValidatedPGNode(Node n) { - if (n instanceof Parent) { - for (Node child : ((Parent) n).getChildrenUnmodifiable()) { - getValidatedPGNode(child); - } - } - NGNode pgn = n.impl_getPeer(); - // Eeek, this is gross! I have to use reflection to invoke this - // method so that bounds are updated... - try { - java.lang.reflect.Method method = Node.class.getDeclaredMethod("updateBounds"); - method.setAccessible(true); - method.invoke(n); - } catch (Exception e) { - throw new RuntimeException("Failed to update bounds", e); - } - n.impl_updatePeer(); - return pgn; - } - - public static BaseBounds getBounds(Node n, BaseTransform tx) { - Scene.impl_setAllowPGAccess(true); - NGNode pgn = getValidatedPGNode(n); - Scene.impl_setAllowPGAccess(false); - return pgn.getContentBounds(new RectBounds(), tx); - } - - public static class TestPoint { - private float x; - private float y; - private boolean contains; - - public TestPoint(float x, float y, boolean contains) { - this.x = x; - this.y = y; - this.contains = contains; - } - - public boolean isContains() { - return contains; - } - - public float getX() { - return x; - } - - public float getY() { - return y; - } - } - - public static void checkContentPoint(Node n, TestPoint tp, - BaseTransform transform) - { - BaseBounds bounds = getBounds(n, transform); - float c[] = new float[] {tp.getX(), tp.getY()}; - transform.transform(c, 0, c, 0, 1); - boolean success = false; - try { - assertEquals(bounds.contains(c[0], c[1]), tp.isContains()); - success = true; - } finally { - if (!success) { - System.err.println("Failed on bounds = "+bounds); - System.err.println("with transform = "+transform); - System.err.println("with x, y = "+tp.getX()+", "+tp.getY()); - System.err.println("and tx, ty = "+c[0]+", "+c[1]); - } - } - } - - // When a chain of transforms is involved, it can help to back off - // slightly from the edges of a shape using this tiny constant - // to avoid failing a test due to floating point rounding error. - static final float EPSILON = 1e-6f; - - public TestPoint[] rectPoints(float x, float y, float w, float h) { - return new TestPoint[] { - new TestPoint(x +EPSILON, y +EPSILON, true), - new TestPoint(x+w-EPSILON, y +EPSILON, true), - new TestPoint(x +EPSILON, y+h-EPSILON, true), - new TestPoint(x+w-EPSILON, y+h-EPSILON, true), - new TestPoint(x+w, y+h+h, false) - }; - } - - public BaseBounds getBounds(TestPoint... testpts) { - RectBounds rb = new RectBounds(); - for (TestPoint tp : testpts) { - if (tp.isContains()) { - rb.add(tp.getX(), tp.getY()); - } - } - return rb; - } - - public TestPoint[] translate(float tx, float ty, TestPoint... testpts) { - TestPoint ret[] = new TestPoint[testpts.length]; - for (int i = 0; i < testpts.length; i++) { - TestPoint tp = testpts[i]; - ret[i] = new TestPoint(tp.getX() + tx, tp.getY() + ty, - tp.isContains()); - } - return ret; - } - - public TestPoint[] scale(float sx, float sy, TestPoint... testpts) { - BaseBounds bounds = getBounds(testpts); - float cx = (bounds.getMinX() + bounds.getMaxX()) / 2.0f; - float cy = (bounds.getMinY() + bounds.getMaxY()) / 2.0f; - TestPoint ret[] = new TestPoint[testpts.length]; - for (int i = 0; i < testpts.length; i++) { - TestPoint tp = testpts[i]; - ret[i] = new TestPoint((tp.getX() - cx) * sx + cx, - (tp.getY() - cy) * sy + cy, - tp.isContains()); - } - return ret; - } - - public TestPoint[] rotate(double degrees, TestPoint... testpts) { - BaseBounds bounds = getBounds(testpts); - float cx = (bounds.getMinX() + bounds.getMaxX()) / 2.0f; - float cy = (bounds.getMinY() + bounds.getMaxY()) / 2.0f; - TestPoint ret[] = new TestPoint[testpts.length]; - double radians = Math.toRadians(degrees); - float cos = (float) Math.cos(radians); - float sin = (float) Math.sin(radians); - for (int i = 0; i < testpts.length; i++) { - TestPoint tp = testpts[i]; - float relx = tp.getX() - cx; - float rely = tp.getY() - cy; - ret[i] = new TestPoint(relx * cos - rely * sin + cx, - relx * sin + rely * cos + cy, - tp.isContains()); - } - return ret; - } - - public void checkPoints(Node n, TestPoint... testpts) { - for (TestPoint tp : testpts) { - checkContentPoint(n, tp, IDENTITY); - checkContentPoint(n, tp, TRANSLATE); - checkContentPoint(n, tp, SCALE); - checkContentPoint(n, tp, ROTATE); - checkContentPoint(n, tp, TRANSLATE_SCALE); - checkContentPoint(n, tp, SCALE_TRANSLATE); - } - } - - @Test public void testRectangle() { - Node r = makeRectangle(10, 10, 20, 20); - checkPoints(r, rectPoints(10, 10, 20, 20)); - } - - @Test public void testTranslatedRectangle() { - Node r = translate(234.7f, 176.3f, makeRectangle(10, 10, 20, 20)); - // Content bounds is local to the node, so we ignore the tx, ty - checkPoints(r, rectPoints(10, 10, 20, 20)); - } - - @Test public void testScaledRectangle() { - Node r = scale(1.3, 1.1, makeRectangle(10, 10, 20, 20)); - // Content bounds is local to the node, so we ignore the sx, sy - checkPoints(r, rectPoints(10, 10, 20, 20)); - } - - @Test public void testRotatedRectangle() { - Node r = rotate(15, makeRectangle(10, 10, 20, 20)); - // Content bounds is local to the node, so we ignore the rot - checkPoints(r, rectPoints(10, 10, 20, 20)); - } - - @Test public void testGroupedRectangle() { - Node r = group(makeRectangle(10, 10, 20, 20)); - checkPoints(r, rectPoints(10, 10, 20, 20)); - } - - @Test public void testGroupedTranslatedRectangle() { - float tx = 234.7f; - float ty = 165.3f; - Node r = group(translate(tx, ty, makeRectangle(10, 10, 20, 20))); - checkPoints(r, translate(tx, ty, rectPoints(10, 10, 20, 20))); - } - - @Test public void testGroupedScaledRectangle() { - float sx = 1.3f; - float sy = 1.1f; - Node n = group(scale(sx, sy, makeRectangle(10, 10, 20, 20))); - checkPoints(n, scale(sx, sy, rectPoints(10, 10, 20, 20))); - } - - @Test public void testGroupedScaledGroupedTranslatedGroupedRotatedRectangle() { - float sx = 1.3f; - float sy = 1.1f; - float tx = 35.7f; - float ty = 93.1f; - float rot = 25; - Node n = group(scale(sx, sy, - group(translate(tx, ty, - group(rotate(rot, - makeRectangle(10, 10, 20, 20))))))); - checkPoints(n, scale(sx, sy, - translate(tx, ty, - rotate(rot, - rectPoints(10, 10, 20, 20))))); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/ContentBoundsTest.java 2015-09-11 21:24:25.517286977 -0400 @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import javafx.scene.Group; +import javafx.scene.Node; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.shape.Rectangle; +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.Affine2D; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.sg.prism.NGNode; +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +/** + */ +public class ContentBoundsTest { + public static final BaseTransform IDENTITY; + public static final BaseTransform TRANSLATE; + public static final BaseTransform SCALE; + public static final BaseTransform ROTATE; + public static final BaseTransform SCALE_TRANSLATE; + public static final BaseTransform TRANSLATE_SCALE; + + public static BaseTransform translate(BaseTransform transform, + double tx, double ty) + { + transform = BaseTransform.getInstance(transform); + return transform.deriveWithConcatenation(1, 0, 0, 1, tx, ty); + } + + public static BaseTransform scale(BaseTransform transform, + double sx, double sy) + { + transform = BaseTransform.getInstance(transform); + return transform.deriveWithConcatenation(sx, 0, 0, sy, 0, 0); + } + + public static BaseTransform rotate(BaseTransform transform, + double degrees) + { + Affine2D t2d = new Affine2D(transform); + t2d.rotate(Math.toRadians(degrees)); + return t2d; + } + + static { + IDENTITY = BaseTransform.IDENTITY_TRANSFORM; + TRANSLATE = translate(IDENTITY, 42.3, 16.5); + SCALE = scale(IDENTITY, 0.7, 0.6); + ROTATE = rotate(IDENTITY, 135); + TRANSLATE_SCALE = scale(TRANSLATE, 0.8, 0.9); + SCALE_TRANSLATE = translate(SCALE, 23.7, 83.5); + } + + public static Node translate(double tx, double ty, Node n) { + n.setTranslateX(tx); + n.setTranslateY(ty); + return n; + } + + public static Node scale(double sx, double sy, Node n) { + n.setScaleX(sx); + n.setScaleY(sy); + return n; + } + + public static Node rotate(double rot, Node n) { + n.setRotate(rot); + return n; + } + + public static Node group(Node... n) { + Group g = new Group(n); + return g; + } + + public static Node makeRectangle(double x, double y, double w, double h) { + return new Rectangle(x, y, w, h); + } + + public static NGNode getValidatedPGNode(Node n) { + if (n instanceof Parent) { + for (Node child : ((Parent) n).getChildrenUnmodifiable()) { + getValidatedPGNode(child); + } + } + NGNode pgn = n.impl_getPeer(); + // Eeek, this is gross! I have to use reflection to invoke this + // method so that bounds are updated... + try { + java.lang.reflect.Method method = Node.class.getDeclaredMethod("updateBounds"); + method.setAccessible(true); + method.invoke(n); + } catch (Exception e) { + throw new RuntimeException("Failed to update bounds", e); + } + n.impl_updatePeer(); + return pgn; + } + + public static BaseBounds getBounds(Node n, BaseTransform tx) { + Scene.impl_setAllowPGAccess(true); + NGNode pgn = getValidatedPGNode(n); + Scene.impl_setAllowPGAccess(false); + return pgn.getContentBounds(new RectBounds(), tx); + } + + public static class TestPoint { + private float x; + private float y; + private boolean contains; + + public TestPoint(float x, float y, boolean contains) { + this.x = x; + this.y = y; + this.contains = contains; + } + + public boolean isContains() { + return contains; + } + + public float getX() { + return x; + } + + public float getY() { + return y; + } + } + + public static void checkContentPoint(Node n, TestPoint tp, + BaseTransform transform) + { + BaseBounds bounds = getBounds(n, transform); + float c[] = new float[] {tp.getX(), tp.getY()}; + transform.transform(c, 0, c, 0, 1); + boolean success = false; + try { + assertEquals(bounds.contains(c[0], c[1]), tp.isContains()); + success = true; + } finally { + if (!success) { + System.err.println("Failed on bounds = "+bounds); + System.err.println("with transform = "+transform); + System.err.println("with x, y = "+tp.getX()+", "+tp.getY()); + System.err.println("and tx, ty = "+c[0]+", "+c[1]); + } + } + } + + // When a chain of transforms is involved, it can help to back off + // slightly from the edges of a shape using this tiny constant + // to avoid failing a test due to floating point rounding error. + static final float EPSILON = 1e-6f; + + public TestPoint[] rectPoints(float x, float y, float w, float h) { + return new TestPoint[] { + new TestPoint(x +EPSILON, y +EPSILON, true), + new TestPoint(x+w-EPSILON, y +EPSILON, true), + new TestPoint(x +EPSILON, y+h-EPSILON, true), + new TestPoint(x+w-EPSILON, y+h-EPSILON, true), + new TestPoint(x+w, y+h+h, false) + }; + } + + public BaseBounds getBounds(TestPoint... testpts) { + RectBounds rb = new RectBounds(); + for (TestPoint tp : testpts) { + if (tp.isContains()) { + rb.add(tp.getX(), tp.getY()); + } + } + return rb; + } + + public TestPoint[] translate(float tx, float ty, TestPoint... testpts) { + TestPoint ret[] = new TestPoint[testpts.length]; + for (int i = 0; i < testpts.length; i++) { + TestPoint tp = testpts[i]; + ret[i] = new TestPoint(tp.getX() + tx, tp.getY() + ty, + tp.isContains()); + } + return ret; + } + + public TestPoint[] scale(float sx, float sy, TestPoint... testpts) { + BaseBounds bounds = getBounds(testpts); + float cx = (bounds.getMinX() + bounds.getMaxX()) / 2.0f; + float cy = (bounds.getMinY() + bounds.getMaxY()) / 2.0f; + TestPoint ret[] = new TestPoint[testpts.length]; + for (int i = 0; i < testpts.length; i++) { + TestPoint tp = testpts[i]; + ret[i] = new TestPoint((tp.getX() - cx) * sx + cx, + (tp.getY() - cy) * sy + cy, + tp.isContains()); + } + return ret; + } + + public TestPoint[] rotate(double degrees, TestPoint... testpts) { + BaseBounds bounds = getBounds(testpts); + float cx = (bounds.getMinX() + bounds.getMaxX()) / 2.0f; + float cy = (bounds.getMinY() + bounds.getMaxY()) / 2.0f; + TestPoint ret[] = new TestPoint[testpts.length]; + double radians = Math.toRadians(degrees); + float cos = (float) Math.cos(radians); + float sin = (float) Math.sin(radians); + for (int i = 0; i < testpts.length; i++) { + TestPoint tp = testpts[i]; + float relx = tp.getX() - cx; + float rely = tp.getY() - cy; + ret[i] = new TestPoint(relx * cos - rely * sin + cx, + relx * sin + rely * cos + cy, + tp.isContains()); + } + return ret; + } + + public void checkPoints(Node n, TestPoint... testpts) { + for (TestPoint tp : testpts) { + checkContentPoint(n, tp, IDENTITY); + checkContentPoint(n, tp, TRANSLATE); + checkContentPoint(n, tp, SCALE); + checkContentPoint(n, tp, ROTATE); + checkContentPoint(n, tp, TRANSLATE_SCALE); + checkContentPoint(n, tp, SCALE_TRANSLATE); + } + } + + @Test public void testRectangle() { + Node r = makeRectangle(10, 10, 20, 20); + checkPoints(r, rectPoints(10, 10, 20, 20)); + } + + @Test public void testTranslatedRectangle() { + Node r = translate(234.7f, 176.3f, makeRectangle(10, 10, 20, 20)); + // Content bounds is local to the node, so we ignore the tx, ty + checkPoints(r, rectPoints(10, 10, 20, 20)); + } + + @Test public void testScaledRectangle() { + Node r = scale(1.3, 1.1, makeRectangle(10, 10, 20, 20)); + // Content bounds is local to the node, so we ignore the sx, sy + checkPoints(r, rectPoints(10, 10, 20, 20)); + } + + @Test public void testRotatedRectangle() { + Node r = rotate(15, makeRectangle(10, 10, 20, 20)); + // Content bounds is local to the node, so we ignore the rot + checkPoints(r, rectPoints(10, 10, 20, 20)); + } + + @Test public void testGroupedRectangle() { + Node r = group(makeRectangle(10, 10, 20, 20)); + checkPoints(r, rectPoints(10, 10, 20, 20)); + } + + @Test public void testGroupedTranslatedRectangle() { + float tx = 234.7f; + float ty = 165.3f; + Node r = group(translate(tx, ty, makeRectangle(10, 10, 20, 20))); + checkPoints(r, translate(tx, ty, rectPoints(10, 10, 20, 20))); + } + + @Test public void testGroupedScaledRectangle() { + float sx = 1.3f; + float sy = 1.1f; + Node n = group(scale(sx, sy, makeRectangle(10, 10, 20, 20))); + checkPoints(n, scale(sx, sy, rectPoints(10, 10, 20, 20))); + } + + @Test public void testGroupedScaledGroupedTranslatedGroupedRotatedRectangle() { + float sx = 1.3f; + float sy = 1.1f; + float tx = 35.7f; + float ty = 93.1f; + float rot = 25; + Node n = group(scale(sx, sy, + group(translate(tx, ty, + group(rotate(rot, + makeRectangle(10, 10, 20, 20))))))); + checkPoints(n, scale(sx, sy, + translate(tx, ty, + rotate(rot, + rectPoints(10, 10, 20, 20))))); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/CullingTest.java 2015-09-11 21:24:26.289286969 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,232 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import com.sun.javafx.geom.DirtyRegionContainer; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.javafx.geom.transform.GeneralTransform3D; -import org.junit.Assert; -import org.junit.Test; - -public class CullingTest extends NGTestBase { - - @Test - public void test_setCullBits_intersect() { - NGNode bn = createRectangle(0, 0, 100, 100); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 150, 150), - new RectBounds(70, 70, 170, 170) - }); - bn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - Assert.assertEquals(1 |(1 << 2), bn.cullingBits); - } - - @Test - public void test_setCullBits_disjoint() { - NGNode bn = createRectangle(0, 0, 100, 100); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(110, 110, 150, 150), - new RectBounds(0, 101, 170, 170) - }); - bn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - Assert.assertEquals(0, bn.cullingBits); - } - - @Test - public void test_setCullBits_within() { - NGNode bn = createRectangle(50, 50, 100, 100); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(40, 40, 170, 170), - new RectBounds(0, 0, 200, 200) - }); - bn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - Assert.assertEquals(2 | (2 << 2), bn.cullingBits); - } - - @Test - public void test_setCullBits_region_within() { - NGNode bn = createRectangle(0, 0, 100, 100); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(40, 40, 70, 70), - new RectBounds(10, 10, 20, 20) - }); - bn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - Assert.assertEquals(1 | (1 << 2), bn.cullingBits); - } - - @Test - public void test_setCullBits_empty() { - NGNode bn = createRectangle(50, 50, 100, 100); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(40, 40, 170, 170), - new RectBounds().makeEmpty() - }); - bn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - Assert.assertEquals(2, bn.cullingBits); - } - - @Test - public void test_setCullBits_null() { - NGNode bn = createRectangle(50, 50, 100, 100); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(40, 40, 170, 170), - null - }); - bn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - Assert.assertEquals(2, bn.cullingBits); - } - - @Test - public void test_setCullBits_empty_regions() { - NGNode bn = createRectangle(50, 50, 100, 100); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[]{}); - bn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - Assert.assertEquals(0, bn.cullingBits); - } - - @Test - public void test_group_disjoint() { - NGNode bn1 = createRectangle(150, 0, 50, 50); - NGNode bn2 = createRectangle(150, 60, 50, 50); - NGGroup gbn = createGroup(bn1, bn2); - translate(gbn, 10, 10); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(0, 0, 100, 100), new RectBounds(0, 110, 100, 210)}); - gbn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - Assert.assertEquals(0, gbn.cullingBits); - for(NGNode n : gbn.getChildren()) { - Assert.assertEquals(0, n.cullingBits); - } - } - - @Test - public void test_group_intersect() { - NGNode bn1 = createRectangle(50, 50, 30, 30); - NGNode bn2 = createRectangle(50, 120, 30, 30); - NGGroup gbn = createGroup(bn1, bn2); - translate(gbn, 10, 10); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(0, 0, 100, 100), new RectBounds(0, 110, 100, 210)}); - gbn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - - //check group - Assert.assertEquals(1 | (1 << 2), gbn.cullingBits); - - //check children - Assert.assertEquals(2, bn1.cullingBits); - Assert.assertEquals(2 << 2, bn2.cullingBits); - } - - @Test - public void test_group_within() { - NGNode bn1 = createRectangle(50, 50, 30, 30); - NGNode bn2 = createRectangle(50, 10, 30, 30); - NGGroup gbn = createGroup(bn1, bn2); - translate(gbn, 10, 10); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(0, 0, 100, 100), new RectBounds(0, 110, 100, 210)}); - gbn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - - //check group - Assert.assertEquals(2, gbn.cullingBits); - - //check children (as the group is "completely covered", the children should not have been processed) - Assert.assertEquals(0, bn1.cullingBits); - Assert.assertEquals(0, bn2.cullingBits); - } - - @Test - public void test_region_within_group() { - NGNode bn1 = createRectangle(50, 10, 100, 100); - NGNode bn2 = createRectangle(50, 120, 100, 100); - NGGroup gbn = createGroup(bn1, bn2); - translate(gbn, 5, 5); - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(70, 20, 100, 105), new RectBounds(70, 130, 100, 200)}); - gbn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - - //check group - Assert.assertEquals(1 | (1 << 2), gbn.cullingBits); - - //check children - Assert.assertEquals(1, bn1.cullingBits); - Assert.assertEquals(1 << 2, bn2.cullingBits); - } - - @Test - public void test_region_within_group_group() { - NGNode bn1 = createRectangle(50, 10, 100, 100); - NGNode bn2 = createRectangle(50, 120, 100, 100); - NGNode g1bn = createGroup(bn1, bn2); - translate(g1bn, 5, 5); - - NGNode bn3 = createRectangle(200, 200, 100, 100); - NGNode gbn = createGroup(g1bn, bn3); - translate(gbn, 5, 5); - - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(70, 25, 100, 105), new RectBounds(70, 130, 100, 200)}); - gbn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - - //check group - Assert.assertEquals(1 | (1 << 2), gbn.cullingBits); - - //check group1 - Assert.assertEquals(1 | (1 << 2), g1bn.cullingBits); - - //check children - Assert.assertEquals(1, bn1.cullingBits); - Assert.assertEquals(1 << 2, bn2.cullingBits); - Assert.assertEquals(0, bn3.cullingBits); - } - - @Test - public void test_rectangle_group_full_within_then_partial() { - NGNode bn1 = createRectangle(50, 50, 100, 100); - NGNode gbn = createGroup(bn1); - - DirtyRegionContainer drc = new DirtyRegionContainer(2); - drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(0, 0, 160, 160), new RectBounds(80, 80, 100, 100)}); - gbn.markCullRegions(drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - - Assert.assertEquals(2 | (1 << 2), gbn.cullingBits); - Assert.assertEquals(1 << 2, bn1.cullingBits); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/CullingTest.java 2015-09-11 21:24:26.153286970 -0400 @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; +import com.sun.javafx.sg.prism.NGGroup; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.javafx.sg.prism.NGNodeShim; +import org.junit.Assert; +import org.junit.Test; + +public class CullingTest extends NGTestBase { + + @Test + public void test_setCullBits_intersect() { + NGNode bn = createRectangle(0, 0, 100, 100); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 150, 150), + new RectBounds(70, 70, 170, 170) + }); + NGNodeShim.markCullRegions(bn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + Assert.assertEquals(1 |(1 << 2), NGNodeShim.cullingBits(bn)); + } + + @Test + public void test_setCullBits_disjoint() { + NGNode bn = createRectangle(0, 0, 100, 100); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(110, 110, 150, 150), + new RectBounds(0, 101, 170, 170) + }); + NGNodeShim.markCullRegions(bn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + Assert.assertEquals(0, NGNodeShim.cullingBits(bn)); + } + + @Test + public void test_setCullBits_within() { + NGNode bn = createRectangle(50, 50, 100, 100); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(40, 40, 170, 170), + new RectBounds(0, 0, 200, 200) + }); + NGNodeShim.markCullRegions(bn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + Assert.assertEquals(2 | (2 << 2), NGNodeShim.cullingBits(bn)); + } + + @Test + public void test_setCullBits_region_within() { + NGNode bn = createRectangle(0, 0, 100, 100); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(40, 40, 70, 70), + new RectBounds(10, 10, 20, 20) + }); + NGNodeShim.markCullRegions(bn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + Assert.assertEquals(1 | (1 << 2), NGNodeShim.cullingBits(bn)); + } + + @Test + public void test_setCullBits_empty() { + NGNode bn = createRectangle(50, 50, 100, 100); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(40, 40, 170, 170), + new RectBounds().makeEmpty() + }); + NGNodeShim.markCullRegions(bn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + Assert.assertEquals(2, NGNodeShim.cullingBits(bn)); + } + + @Test + public void test_setCullBits_null() { + NGNode bn = createRectangle(50, 50, 100, 100); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(40, 40, 170, 170), + null + }); + NGNodeShim.markCullRegions(bn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + Assert.assertEquals(2, NGNodeShim.cullingBits(bn)); + } + + @Test + public void test_setCullBits_empty_regions() { + NGNode bn = createRectangle(50, 50, 100, 100); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[]{}); + NGNodeShim.markCullRegions(bn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + Assert.assertEquals(0, NGNodeShim.cullingBits(bn)); + } + + @Test + public void test_group_disjoint() { + NGNode bn1 = createRectangle(150, 0, 50, 50); + NGNode bn2 = createRectangle(150, 60, 50, 50); + NGGroup gbn = createGroup(bn1, bn2); + translate(gbn, 10, 10); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(0, 0, 100, 100), new RectBounds(0, 110, 100, 210)}); + NGNodeShim.markCullRegions(gbn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + Assert.assertEquals(0, NGNodeShim.cullingBits(gbn)); + for(NGNode n : gbn.getChildren()) { + Assert.assertEquals(0, NGNodeShim.cullingBits(n)); + } + } + + @Test + public void test_group_intersect() { + NGNode bn1 = createRectangle(50, 50, 30, 30); + NGNode bn2 = createRectangle(50, 120, 30, 30); + NGGroup gbn = createGroup(bn1, bn2); + translate(gbn, 10, 10); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(0, 0, 100, 100), new RectBounds(0, 110, 100, 210)}); + NGNodeShim.markCullRegions(gbn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + + //check group + Assert.assertEquals(1 | (1 << 2), NGNodeShim.cullingBits(gbn)); + + //check children + Assert.assertEquals(2, NGNodeShim.cullingBits(bn1)); + Assert.assertEquals(2 << 2, NGNodeShim.cullingBits(bn2)); + } + + @Test + public void test_group_within() { + NGNode bn1 = createRectangle(50, 50, 30, 30); + NGNode bn2 = createRectangle(50, 10, 30, 30); + NGGroup gbn = createGroup(bn1, bn2); + translate(gbn, 10, 10); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(0, 0, 100, 100), new RectBounds(0, 110, 100, 210)}); + NGNodeShim.markCullRegions(gbn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + + //check group + Assert.assertEquals(2, NGNodeShim.cullingBits(gbn)); + + //check children (as the group is "completely covered", the children should not have been processed) + Assert.assertEquals(0, NGNodeShim.cullingBits(bn1)); + Assert.assertEquals(0, NGNodeShim.cullingBits(bn2)); + } + + @Test + public void test_region_within_group() { + NGNode bn1 = createRectangle(50, 10, 100, 100); + NGNode bn2 = createRectangle(50, 120, 100, 100); + NGGroup gbn = createGroup(bn1, bn2); + translate(gbn, 5, 5); + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(70, 20, 100, 105), new RectBounds(70, 130, 100, 200)}); + NGNodeShim.markCullRegions(gbn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + + //check group + Assert.assertEquals(1 | (1 << 2), NGNodeShim.cullingBits(gbn)); + + //check children + Assert.assertEquals(1, NGNodeShim.cullingBits(bn1)); + Assert.assertEquals(1 << 2, NGNodeShim.cullingBits(bn2)); + } + + @Test + public void test_region_within_group_group() { + NGNode bn1 = createRectangle(50, 10, 100, 100); + NGNode bn2 = createRectangle(50, 120, 100, 100); + NGNode g1bn = createGroup(bn1, bn2); + translate(g1bn, 5, 5); + + NGNode bn3 = createRectangle(200, 200, 100, 100); + NGNode gbn = createGroup(g1bn, bn3); + translate(gbn, 5, 5); + + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(70, 25, 100, 105), new RectBounds(70, 130, 100, 200)}); + NGNodeShim.markCullRegions(gbn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + + //check group + Assert.assertEquals(1 | (1 << 2), NGNodeShim.cullingBits(gbn)); + + //check group1 + Assert.assertEquals(1 | (1 << 2), NGNodeShim.cullingBits(g1bn)); + + //check children + Assert.assertEquals(1, NGNodeShim.cullingBits(bn1)); + Assert.assertEquals(1 << 2, NGNodeShim.cullingBits(bn2)); + Assert.assertEquals(0, NGNodeShim.cullingBits(bn3)); + } + + @Test + public void test_rectangle_group_full_within_then_partial() { + NGNode bn1 = createRectangle(50, 50, 100, 100); + NGNode gbn = createGroup(bn1); + + DirtyRegionContainer drc = new DirtyRegionContainer(2); + drc.deriveWithNewRegions(new RectBounds[]{new RectBounds(0, 0, 160, 160), new RectBounds(80, 80, 100, 100)}); + NGNodeShim.markCullRegions(gbn,drc, -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + + Assert.assertEquals(2 | (1 << 2), NGNodeShim.cullingBits(gbn)); + Assert.assertEquals(1 << 2, NGNodeShim.cullingBits(bn1)); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/DirtyRegionClipTest.java 2015-09-11 21:24:27.057286960 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,175 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.sun.javafx.sg.prism; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import com.sun.javafx.geom.BaseBounds; -import com.sun.javafx.geom.DirtyRegionContainer; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.BaseTransform; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import static org.junit.Assert.assertEquals; - -@RunWith(Parameterized.class) -public class DirtyRegionClipTest extends DirtyRegionTestBase { - - /** - * Gets the test parameters to use when running these tests. The parameters - * are a combination of a Polluter and a Creator. The Creator is used to - * create the node to be tested (might be a rectangle, or Group, or something - * more complex), while the Polluter is responsible for making the test node - * dirty by some means. Since the Polluter knows what it did to make the node - * dirty, it is also responsible for computing and returning what the expected - * change to the node's geometry is, such that the test code can create the - * union and test for the appropriate dirty region for this specific node. - */ - @Parameterized.Parameters - public static Collection createParameters() { - // This polluter will translate the test node in a positive direction - final Polluter pollutePositiveTranslation = new Polluter() { - { tx = BaseTransform.getTranslateInstance(50, 50); } - @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } - @Override public String toString() { return "Pollute Positive Translation"; } - }; - - // We will populate this list with the parameters with which we will test. - // Each Object[] within the params is composed of a Creator and a Polluter. - List params = new ArrayList(); - // A standard list of polluters which applies to all tests - List polluters = Arrays.asList(new Polluter[]{ - pollutePositiveTranslation - }); - - // Construct the Creator / Polluter pair for Groups - for (final Polluter polluter : polluters) { - params.add(new Object[] {new Creator() { - @Override public NGNode create() { return createGroup(createRectangle(0, 0, 100, 100)); } - @Override public String toString() { return "Group with one Rectangle"; } - }, polluter}); - } - - // Construct the Creator / Polluter pair for Rectangles - List rectanglePolluters = new ArrayList(polluters); - rectanglePolluters.add(new Polluter() { - @Override public void pollute(NGNode node) { - NGRectangle rect = (NGRectangle)node; - BaseBounds bounds = rect.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); - rect.updateRectangle(bounds.getMinX(), bounds.getMinY(), 25, 25, 0, 0); - } - @Override public String toString() { return "Pollute Rectangle Geometry"; } - }); - for (final Polluter polluter : rectanglePolluters) { - params.add(new Object[] {new Creator() { - @Override public NGNode create() { return createRectangle(0, 0, 100, 100); } - @Override public String toString() { return "Rectangle"; } - }, polluter}); - } - // Return the populated params collection - return params; - } - - public DirtyRegionClipTest(Creator creator, Polluter polluter) { - super(creator, polluter); - } - - /** - * Constructs a non-overlapping grid of nodes. Each node is a direct child - * of the root node. They may end up overlapping when they become dirty, - * but they don't start out that way! Each node is placed where it belongs - * in the grid by translating them into place. - */ - @Before public void setUp() { - // create the grid - NGNode[] content = new NGNode[9]; - for (int row=0; row<3; row++) { - for (int col=0; col<3; col++) { - NGNode node = creator.create(); - BaseTransform tx = BaseTransform.IDENTITY_TRANSFORM; - tx = tx.deriveWithTranslation((col * 110), (row * 110)); - transform(node, tx); - content[(row * 3) + col] = node; - } - } - root = createGroup(content); - - // The grid is created & populated. We'll now go through and manually - // clean them all up so that when we perform the test, it is from the - // starting point of a completely cleaned tree - root.render(TestGraphics.TEST_GRAPHICS); - } - - @Test public void sanityCheck() { - NGNode node = root.getChildren().get(0); - assertEquals(new RectBounds(0, 0, 100, 100), node.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - assertEquals(new RectBounds(0, 0, 100, 100), node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - - node = root.getChildren().get(1); - assertEquals(new RectBounds(0, 0, 100, 100), node.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - assertEquals(new RectBounds(110, 0, 210, 100), node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - - node = root.getChildren().get(root.getChildren().size()/2); //middle child (index 4) - assertEquals(new RectBounds(0, 0, 100, 100), node.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - assertEquals(new RectBounds(110, 110, 210, 210), node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - } - - /** - * Dirty region bounds are bigger than clip bounds and whole clip lies - * inside the dirty region. - */ - @Test public void dirtyRegionContainsClip() { - windowClip = new RectBounds(115, 115, 120, 120); - - NGNode middleChild = root.getChildren().get(root.getChildren().size()/2); - assertContainsClip(root, polluter.polluteAndGetExpectedBounds(middleChild), DirtyRegionContainer.DTR_CONTAINS_CLIP); - } - - /** - * Dirty region bounds partially overlap with clip bounds. - */ - @Test public void dirtyRegionPartiallyOverlapsClip() { - windowClip = new RectBounds(90, 90, 120, 120); - - NGNode middleChild = root.getChildren().get(root.getChildren().size()/2); - assertContainsClip(root, polluter.polluteAndGetExpectedBounds(middleChild), DirtyRegionContainer.DTR_OK); - } - - /** - * Dirty region bounds are smaller than clip bounds and the dirty region - * lies inside the clip. - */ - @Test public void dirtyRegionDoesNotContainClip() { - NGNode middleChild = root.getChildren().get(root.getChildren().size()/2); - assertContainsClip(root, polluter.polluteAndGetExpectedBounds(middleChild), DirtyRegionContainer.DTR_OK); - } - -} \ No newline at end of file --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/DirtyRegionClipTest.java 2015-09-11 21:24:26.849286962 -0400 @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package test.com.sun.javafx.sg.prism; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.javafx.sg.prism.NGRectangle; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import static org.junit.Assert.assertEquals; + +@RunWith(Parameterized.class) +public class DirtyRegionClipTest extends DirtyRegionTestBase { + + /** + * Gets the test parameters to use when running these tests. The parameters + * are a combination of a Polluter and a Creator. The Creator is used to + * create the node to be tested (might be a rectangle, or Group, or something + * more complex), while the Polluter is responsible for making the test node + * dirty by some means. Since the Polluter knows what it did to make the node + * dirty, it is also responsible for computing and returning what the expected + * change to the node's geometry is, such that the test code can create the + * union and test for the appropriate dirty region for this specific node. + */ + @Parameterized.Parameters + public static Collection createParameters() { + // This polluter will translate the test node in a positive direction + final Polluter pollutePositiveTranslation = new Polluter() { + { tx = BaseTransform.getTranslateInstance(50, 50); } + @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } + @Override public String toString() { return "Pollute Positive Translation"; } + }; + + // We will populate this list with the parameters with which we will test. + // Each Object[] within the params is composed of a Creator and a Polluter. + List params = new ArrayList(); + // A standard list of polluters which applies to all tests + List polluters = Arrays.asList(new Polluter[]{ + pollutePositiveTranslation + }); + + // Construct the Creator / Polluter pair for Groups + for (final Polluter polluter : polluters) { + params.add(new Object[] {new Creator() { + @Override public NGNode create() { return createGroup(createRectangle(0, 0, 100, 100)); } + @Override public String toString() { return "Group with one Rectangle"; } + }, polluter}); + } + + // Construct the Creator / Polluter pair for Rectangles + List rectanglePolluters = new ArrayList(polluters); + rectanglePolluters.add(new Polluter() { + @Override public void pollute(NGNode node) { + NGRectangle rect = (NGRectangle)node; + BaseBounds bounds = rect.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); + rect.updateRectangle(bounds.getMinX(), bounds.getMinY(), 25, 25, 0, 0); + } + @Override public String toString() { return "Pollute Rectangle Geometry"; } + }); + for (final Polluter polluter : rectanglePolluters) { + params.add(new Object[] {new Creator() { + @Override public NGNode create() { return createRectangle(0, 0, 100, 100); } + @Override public String toString() { return "Rectangle"; } + }, polluter}); + } + // Return the populated params collection + return params; + } + + public DirtyRegionClipTest(Creator creator, Polluter polluter) { + super(creator, polluter); + } + + /** + * Constructs a non-overlapping grid of nodes. Each node is a direct child + * of the root node. They may end up overlapping when they become dirty, + * but they don't start out that way! Each node is placed where it belongs + * in the grid by translating them into place. + */ + @Before public void setUp() { + // create the grid + NGNode[] content = new NGNode[9]; + for (int row=0; row<3; row++) { + for (int col=0; col<3; col++) { + NGNode node = creator.create(); + BaseTransform tx = BaseTransform.IDENTITY_TRANSFORM; + tx = tx.deriveWithTranslation((col * 110), (row * 110)); + transform(node, tx); + content[(row * 3) + col] = node; + } + } + root = createGroup(content); + + // The grid is created & populated. We'll now go through and manually + // clean them all up so that when we perform the test, it is from the + // starting point of a completely cleaned tree + root.render(TestGraphics.TEST_GRAPHICS); + } + + @Test public void sanityCheck() { + NGNode node = root.getChildren().get(0); + assertEquals(new RectBounds(0, 0, 100, 100), node.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); + assertEquals(new RectBounds(0, 0, 100, 100), node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); + + node = root.getChildren().get(1); + assertEquals(new RectBounds(0, 0, 100, 100), node.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); + assertEquals(new RectBounds(110, 0, 210, 100), node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); + + node = root.getChildren().get(root.getChildren().size()/2); //middle child (index 4) + assertEquals(new RectBounds(0, 0, 100, 100), node.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); + assertEquals(new RectBounds(110, 110, 210, 210), node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); + } + + /** + * Dirty region bounds are bigger than clip bounds and whole clip lies + * inside the dirty region. + */ + @Test public void dirtyRegionContainsClip() { + windowClip = new RectBounds(115, 115, 120, 120); + + NGNode middleChild = root.getChildren().get(root.getChildren().size()/2); + assertContainsClip(root, polluter.polluteAndGetExpectedBounds(middleChild), DirtyRegionContainer.DTR_CONTAINS_CLIP); + } + + /** + * Dirty region bounds partially overlap with clip bounds. + */ + @Test public void dirtyRegionPartiallyOverlapsClip() { + windowClip = new RectBounds(90, 90, 120, 120); + + NGNode middleChild = root.getChildren().get(root.getChildren().size()/2); + assertContainsClip(root, polluter.polluteAndGetExpectedBounds(middleChild), DirtyRegionContainer.DTR_OK); + } + + /** + * Dirty region bounds are smaller than clip bounds and the dirty region + * lies inside the clip. + */ + @Test public void dirtyRegionDoesNotContainClip() { + NGNode middleChild = root.getChildren().get(root.getChildren().size()/2); + assertContainsClip(root, polluter.polluteAndGetExpectedBounds(middleChild), DirtyRegionContainer.DTR_OK); + } + +} \ No newline at end of file --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/DirtyRegionTestBase.java 2015-09-11 21:24:27.701286953 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,474 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import javafx.geometry.Insets; -import javafx.scene.layout.Background; -import javafx.scene.layout.BackgroundFill; -import javafx.scene.layout.CornerRadii; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import com.sun.javafx.geom.BaseBounds; -import com.sun.javafx.geom.DirtyRegionContainer; -import com.sun.javafx.geom.DirtyRegionPool; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.javafx.geom.transform.GeneralTransform3D; -import com.sun.prism.paint.Color; -import org.junit.runners.Parameterized; -import static org.junit.Assert.assertEquals; - -/** - * A base class for all testing of the dirty regions. This class contains - * some useful infrastructure for testing dirty regions, such as the ability - * to assert that a dirty region matches the expected region; the ability to - * manage the state on an NG node appropriately (ensuring that the transform, - * transformed bounds, effect, etc are all managed correctly); and ensuring - * that all test are run over a set of common parameters, such as when a - * Node becomes dirty due to opacity changing, visibility changing, geometry - * changing, and so forth. - *

- * The DirtyRegionTestBase is parametrized, using different node types - * (rectangle, ellipse, group) and different methods for becoming dirty - * (visibility change, geometry change, etc). The cross product of these - * forms the parameters for the test. Each test method is called using the - * combination of a node type & dirty method. - */ -public class DirtyRegionTestBase extends NGTestBase { - /** - * Gets the test parameters to use when running these tests. The parameters - * are a combination of a Polluter and a Creator. The Creator is used to - * create the node to be tested (might be a rectangle, or Group, or something - * more complex), while the Polluter is responsible for making the test node - * dirty by some means. Since the Polluter knows what it did to make the node - * dirty, it is also responsible for computing and returning what the expected - * change to the node's geometry is, such that the test code can create the - * union and test for the appropriate dirty region for this specific node. - */ - @Parameterized.Parameters - public static Collection createParameters() { - // This polluter will change the opacity of the test node - final Polluter polluteOpacity = new Polluter() { - @Override public void pollute(NGNode node) { node.setOpacity(.5f); } - @Override public String toString() { return "Pollute Opacity"; } - }; - // This polluter will restore the opacity of the test node. That is, - // the test node did have 0 opacity and now it is going to be changed - // to an opacity of 1. - final Polluter restoreOpacity = new Polluter() { - @Override public void pollute(NGNode node) { - // I need to hide the node, and then clean up all the dirty - // state associated with it, and then make it visible again. - // This simulates making it invisible, painting, and then - // making it visible again. - node.setOpacity(0f); - NGNode parent = node; - while(parent.getParent() != null) parent = parent.getParent(); - parent.render(TestGraphics.TEST_GRAPHICS); - // Now we can go ahead and set the opacity - node.setOpacity(1f); - } - @Override public String toString() { return "Restore Opacity"; } - }; - // This polluter will change the fill of the node. This only works if - // the test node is of a shape type (the code which creates the test - // parameters will make sure to only use polluteFill with creators - // which are create Shapes) - final Polluter polluteFill = new Polluter() { - @Override public void pollute(NGNode node) { - if (node instanceof NGShape) { - com.sun.javafx.sg.prism.NGShape shape = (NGShape)node; - shape.setFillPaint(new Color(.43f, .23f, .66f, 1f)); - } else if (node instanceof NGRegion) { - NGRegion region = (NGRegion)node; - javafx.scene.paint.Color color = new javafx.scene.paint.Color(.43f, .23f, .66f, 1f); - // I have to do this nasty reflection trickery because we don't have a Toolkit for creating - // the Prism Color that is the platform peer. - try { - Field platformPaint = color.getClass().getDeclaredField("platformPaint"); - platformPaint.setAccessible(true); - platformPaint.set(color, new Color(.43f, .23f, .66f, 1f)); - } catch (Exception e) { - e.printStackTrace(); - } - - region.updateBackground(new Background(new BackgroundFill[] { - new BackgroundFill( - color, - CornerRadii.EMPTY, Insets.EMPTY) - })); - } else { - throw new IllegalArgumentException("I don't know how to make the fill dirty on " + node); - } - } - @Override public String toString() { return "Pollute Fill"; } - }; - // This polluter will translate the test node in a positive direction - final Polluter pollutePositiveTranslation = new Polluter() { - { tx = BaseTransform.getTranslateInstance(50, 50); } - @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } - @Override public String toString() { return "Pollute Positive Translation"; } - }; - // This polluter will translate the test node in a negative direction - final Polluter polluteNegativeTranslation = new Polluter() { - { tx = BaseTransform.getTranslateInstance(-50, -50); } - @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } - @Override public String toString() { return "Pollute Negative Translation"; } - }; - // This polluter will give the test node a scale causing it to get bigger - final Polluter polluteBiggerScale = new Polluter() { - { tx = BaseTransform.getScaleInstance(2, 2); } - @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } - @Override public String toString() { return "Pollute Bigger Scale"; } - }; - // This polluter will give the test node a scale causing it to get smaller - final Polluter polluteSmallerScale = new Polluter() { - { tx = BaseTransform.getScaleInstance(.5, .5); } - @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } - @Override public String toString() { return "Pollute Smaller Scale"; } - }; - // This polluter will rotate the node about its center - final Polluter polluteRotate = new Polluter() { - @Override public void pollute(NGNode node) { - BaseBounds effectBounds = node.getEffectBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); - BaseTransform tx = BaseTransform.getRotateInstance(45, effectBounds.getWidth()/2f, effectBounds.getHeight()/2f); - DirtyRegionTestBase.transform(node, tx); - } - @Override public BaseBounds modifiedBounds(NGNode node) { - BaseBounds effectBounds = node.getEffectBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); - BaseTransform tx = BaseTransform.getRotateInstance(45, effectBounds.getWidth() / 2f, effectBounds.getHeight() / 2f); - return DirtyRegionTestBase.getWhatTransformedBoundsWouldBe(node, tx); - } - @Override public String toString() { return "Pollute Rotate"; } - }; - // This polluter will make the test node invisible - final Polluter polluteVisibility = new Polluter() { - @Override public void pollute(NGNode node) { - node.setVisible(false); - } - @Override public String toString() { return "Pollute Visibility"; } - }; - // This polluter will make an invisible node visible again - final Polluter restoreVisibility = new Polluter() { - @Override public void pollute(NGNode node) { - // I need to hide the node, and then clean up all the dirty - // state associated with it, and then make it visible again. - // This simulates making it invisible, painting, and then - // making it visible again. - node.setVisible(false); - NGNode parent = node; - while(parent.getParent() != null) parent = parent.getParent(); - parent.render(TestGraphics.TEST_GRAPHICS); - // Now we can go ahead and set the opacity - node.setVisible(true); - } - @Override public String toString() { return "Restore Visibility"; } - }; - - // We will populate this list with the parameters with which we will test. - // Each Object[] within the params is composed of a Creator and a Polluter. - List params = new ArrayList(); - // A standard list of polluters which applies to all tests - List polluters = Arrays.asList(new Polluter[]{ - polluteRotate, - polluteOpacity, - restoreOpacity, - polluteVisibility, - restoreVisibility, - polluteSmallerScale, - polluteNegativeTranslation, - polluteBiggerScale, - pollutePositiveTranslation - }); - // Construct the Creator / Polluter pair for Groups - for (final Polluter polluter : polluters) { - params.add(new Object[] {new Creator() { - @Override public NGNode create() { return createGroup(createRectangle(0, 0, 100, 100)); } - @Override public String toString() { return "Group with one Rectangle"; } - }, polluter}); - } - // Construct the Creator / Polluter pair for Rectangles - List rectanglePolluters = new ArrayList(polluters); - rectanglePolluters.add(new Polluter() { - @Override public void pollute(NGNode node) { - NGRectangle rect = (NGRectangle)node; - BaseBounds bounds = rect.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); - rect.updateRectangle(bounds.getMinX(), bounds.getMinY(), 25, 25, 0, 0); - } - @Override public String toString() { return "Pollute Rectangle Geometry"; } - }); - for (final Polluter polluter : rectanglePolluters) { - params.add(new Object[] {new Creator() { - @Override public NGNode create() { return createRectangle(0, 0, 100, 100); } - @Override public String toString() { return "Rectangle"; } - }, polluter}); - } - // Construct the Creator / Polluter pair for Circles - List circlePolluters = new ArrayList(polluters); - circlePolluters.add(new Polluter() { - @Override public void pollute(NGNode node) { - NGCircle c = (NGCircle)node; - BaseBounds bounds = c.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); - c.updateCircle( - bounds.getMinX() + (bounds.getWidth()/2f), - bounds.getMinY() + (bounds.getHeight()/2f), - 10); - } - @Override public String toString() { return "Pollute Circle Geometry"; } - }); - for (final Polluter polluter : circlePolluters) { - params.add(new Object[] {new Creator() { - @Override public NGNode create() { return createCircle(50, 50, 50); } - @Override public String toString() { return "Circle"; } - }, polluter}); - } - // Return the populated params collection - return params; - } - - /** - * The test node creator. This is called from within the "setUp" method in each - * subclass to create the nodes that are going to be tested. - */ - protected Creator creator; - - /** - * The polluter. Subclasses will use the polluter to make a node dirty at the - * appropriate time in the test method. - */ - protected Polluter polluter; - - /** - * The root node. This must be created during the "setUp" method in each sub - * class. The root is needed for actually accumulating dirty regions. - */ - protected TestNGGroup root; - - /** - * The clip to use when accumulating dirty regions. By default it is - * ridiculously large, such that none of the tests will ever bump up - * against the clip. Subclasses should however implement some tests in - * which they will set the clip to a specific value, and then test - * whether accumulating dirty regions takes the clip into account. - */ - protected RectBounds windowClip = new RectBounds(-100000, -100000, 100000, 10000); - - /** - * Creates a new DirtyRegionTestBase. Each subclass must have an identical - * constructor which simply passes the creator and polluter to this - * constructor. These instances are passed to the constructor by JUnit, - * so sub classes don't need to worry about creating these instances - * (and in fact must not do so). - */ - protected DirtyRegionTestBase(Creator creator, Polluter polluter) { - this.creator = creator; - this.polluter = polluter; - } - - /** - * Helper method for asserting that the dirty region of the node indicated - * (start) matches the dirty region which is expected. This method will - * invoke the accumulateDirtyRegions method on the start node. Accumulating - * dirty regions requires a clip to be sent along as well. The windowClip is - * specified on DirtyRegionTestBase (by default it is ridiculously large) - * but sub classes can change the clip at any time. - * - */ - protected void assertDirtyRegionEquals(NGNode start, RectBounds expected) { - // TODO The root might have changes to its bounds and we should reset these. (RT-26928) - //DirtyRegionTestBase.resetGroupBounds(root); - // Accumulate the dirty region, using the windowClip. - // TODO if we wanted to, we could also make the device space transform parameterized - // such that we could test that the dirty region accumulation logic all works - // correctly even in the presence of a non-identity device space transform - // (RT-26928) - DirtyRegionPool pool = new DirtyRegionPool(1); - DirtyRegionContainer drc = pool.checkOut(); - int status = start.accumulateDirtyRegions( - windowClip, - new RectBounds(), pool, - drc, - BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - - RectBounds dirtyRegion = drc.getDirtyRegion(0) ; - - // The accumulation of dirty regions ends up with a slightly - // padded dirty region, just to make up for any error when - // transforming. Its quick and dirty but does the job. - // Perhaps we could avoid adding the slop in the case where - // there is no rotation or skew involved, but for now we - // don't. I don't want to populate all my tests with this - // assumption though in case it ever changes. So I am going - // to pad the expected here. - expected = new RectBounds( - Math.max(expected.getMinX() - 1, dirtyRegion.getMinX()), - Math.max(expected.getMinY() - 1, dirtyRegion.getMinY()), - Math.min(expected.getMaxX() + 1, dirtyRegion.getMaxX()), - Math.min(expected.getMaxY() + 1, dirtyRegion.getMaxY())); - // Now make the check, and print useful error information in case it fails. - assertEquals("creator=" + creator + ", polluter=" + polluter, expected, dirtyRegion); - } - - /** - * Helper method for asserting that the dirty region of the node indicated - * (start) contains the windowClip and matches the dirty region which is - * expected. This method will invoke the accumulateDirtyRegions method - * on the start node. Accumulating dirty regions requires a clip to be sent - * along as well. The windowClip is specified on DirtyRegionTestBase - * (by default it is ridiculously large) but sub classes can change the clip - * at any time. - */ - protected void assertContainsClip(NGNode start, RectBounds expectedDirtyRegion, int expectedStatus) { - DirtyRegionPool pool = new DirtyRegionPool(1); - DirtyRegionContainer drc = pool.checkOut(); - int status = start.accumulateDirtyRegions( - windowClip, - new RectBounds(), pool, - drc, - BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - - assertEquals(expectedStatus, status); - - if (status == DirtyRegionContainer.DTR_OK) { - assertDirtyRegionEquals(start, expectedDirtyRegion); - } - } - - /** - * Accumulates the dirty region, and checks to make sure the the accumulateDirtyRegion - * method was only called on the nodes supplied. If any node in the tree (starting with - * and including root) have had accumulateDirtyRegion called and they are NOT in this - * list of expected nodes, then the assertion fails. - *

- * This assertion is used to make sure that various performance optimizations are - * implemented correctly, such that we are not asking nodes to accumulate dirty regions - * who have no hope of being in the dirty region (such as children of a clean group). - * - * @param nodes A non-null array of nodes. - */ - protected void assertOnlyTheseNodesAreAskedToAccumulateDirtyRegions(NGNode... nodes) { - accumulateDirtyRegions(); - Set set = new HashSet(Arrays.asList(nodes)); - assertOnlyTheseNodesWereAskedToAccumulateDirtyRegions(root, set); - } - - /** - * Accumulates the dirty region, and checks to make sure that the dirty region - * computation methods (accumulateNodeDirtyRegion, computeDirtyRegion, - * accumulateGroupDirtyRegion) are only called on the nodes supplied. If any - * node in the tree (starting with and including the root) has had one or more - * of these methods called and they are NOT in the array of expected nodes, then - * the assertion fails. - *

- * This assertion is used to make sure various performance optimizations are - * implemented correctly, such that even if a node is asked to accumulate its - * dirty region, it doesn't actually do any work if the node is actually clean. - * - * @param nodes A non-null array of nodes. - */ - protected void assertOnlyTheseNodesAreAskedToComputeDirtyRegions(NGNode... nodes) { - accumulateDirtyRegions(); - Set set = new HashSet(Arrays.asList(nodes)); - assertOnlyTheseNodesWereAskedToComputeDirtyRegions(root, set); - } - - /** - * Helper method which will reset the group bounds of the root prior to accumulating - * dirty regions. The root node might have new bounds due to changes in its children, - * such as transforms or geometry changes. - */ - private void accumulateDirtyRegions() { - DirtyRegionPool pool = new DirtyRegionPool(1); - DirtyRegionTestBase.resetGroupBounds(root); - root.accumulateDirtyRegions( - new RectBounds(0, 0, 800, 600), - new RectBounds(), pool, - pool.checkOut(), - BaseTransform.IDENTITY_TRANSFORM, - new GeneralTransform3D()); - } - - /** - * Helper which walks down the tree checking to see if accumulateDirtyRegion has been - * called, and throws an exception if it was not expected. - */ - private void assertOnlyTheseNodesWereAskedToAccumulateDirtyRegions(NGNode start, Set nodes) { - assertEquals( - "creator=" + creator + ", polluter=" + polluter, - nodes.contains(start), ((TestNGNode)start).askedToAccumulateDirtyRegion()); - if (start instanceof NGGroup) { - for (NGNode child : ((NGGroup)start).getChildren()) { - assertOnlyTheseNodesWereAskedToAccumulateDirtyRegions(child, nodes); - } - } - } - - /** - * Helper which walks down the tree checking to see if any of the methods which actually - * compute the dirty region have been called, and throws an exception if it was not expected. - */ - private void assertOnlyTheseNodesWereAskedToComputeDirtyRegions(NGNode start, Set nodes) { - assertEquals( - "creator=" + creator + ", polluter=" + polluter, - nodes.contains(start), ((TestNGNode)start).computedDirtyRegion()); - if (start instanceof NGGroup) { - for (NGNode child : ((NGGroup)start).getChildren()) { - assertOnlyTheseNodesWereAskedToComputeDirtyRegions(child, nodes); - } - } - } - - static protected void resetGroupBounds(NGGroup group) { - BaseBounds contentBounds = new RectBounds(); - for (NGNode child : group.getChildren()) { - contentBounds = contentBounds.deriveWithUnion( - child.getCompleteBounds( - new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - } - BaseBounds currentContentBounds = group.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); - if (!contentBounds.equals(currentContentBounds)) { - System.out.println("CurrentContentBounds=" + currentContentBounds + ", bounds=" + contentBounds); - group.setContentBounds(contentBounds); - group.setTransformedBounds(group.getEffectBounds(new RectBounds(), group.getTransform()), false); - } - } - - /** - * Sort of a non-applying version of the transform method. This method will - * compute and return what the transformed bounds of the given node would - * be if the transform were applied to it. - */ - static protected BaseBounds getWhatTransformedBoundsWouldBe(NGNode node, BaseTransform tx) { - BaseTransform existing = BaseTransform.IDENTITY_TRANSFORM.deriveWithNewTransform(node.getTransform()); - tx = existing.deriveWithConcatenation(tx); - return node.getEffectBounds(new RectBounds(), tx); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/DirtyRegionTestBase.java 2015-09-11 21:24:27.565286954 -0400 @@ -0,0 +1,480 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import javafx.geometry.Insets; +import javafx.scene.layout.Background; +import javafx.scene.layout.BackgroundFill; +import javafx.scene.layout.CornerRadii; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.DirtyRegionPool; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; +import com.sun.javafx.sg.prism.NGCircle; +import com.sun.javafx.sg.prism.NGGroup; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.javafx.sg.prism.NGRectangle; +import com.sun.javafx.sg.prism.NGRegion; +import com.sun.javafx.sg.prism.NGShape; +import com.sun.prism.paint.Color; +import org.junit.runners.Parameterized; +import static org.junit.Assert.assertEquals; + +/** + * A base class for all testing of the dirty regions. This class contains + * some useful infrastructure for testing dirty regions, such as the ability + * to assert that a dirty region matches the expected region; the ability to + * manage the state on an NG node appropriately (ensuring that the transform, + * transformed bounds, effect, etc are all managed correctly); and ensuring + * that all test are run over a set of common parameters, such as when a + * Node becomes dirty due to opacity changing, visibility changing, geometry + * changing, and so forth. + *

+ * The DirtyRegionTestBase is parametrized, using different node types + * (rectangle, ellipse, group) and different methods for becoming dirty + * (visibility change, geometry change, etc). The cross product of these + * forms the parameters for the test. Each test method is called using the + * combination of a node type & dirty method. + */ +public class DirtyRegionTestBase extends NGTestBase { + /** + * Gets the test parameters to use when running these tests. The parameters + * are a combination of a Polluter and a Creator. The Creator is used to + * create the node to be tested (might be a rectangle, or Group, or something + * more complex), while the Polluter is responsible for making the test node + * dirty by some means. Since the Polluter knows what it did to make the node + * dirty, it is also responsible for computing and returning what the expected + * change to the node's geometry is, such that the test code can create the + * union and test for the appropriate dirty region for this specific node. + */ + @Parameterized.Parameters + public static Collection createParameters() { + // This polluter will change the opacity of the test node + final Polluter polluteOpacity = new Polluter() { + @Override public void pollute(NGNode node) { node.setOpacity(.5f); } + @Override public String toString() { return "Pollute Opacity"; } + }; + // This polluter will restore the opacity of the test node. That is, + // the test node did have 0 opacity and now it is going to be changed + // to an opacity of 1. + final Polluter restoreOpacity = new Polluter() { + @Override public void pollute(NGNode node) { + // I need to hide the node, and then clean up all the dirty + // state associated with it, and then make it visible again. + // This simulates making it invisible, painting, and then + // making it visible again. + node.setOpacity(0f); + NGNode parent = node; + while(parent.getParent() != null) parent = parent.getParent(); + parent.render(TestGraphics.TEST_GRAPHICS); + // Now we can go ahead and set the opacity + node.setOpacity(1f); + } + @Override public String toString() { return "Restore Opacity"; } + }; + // This polluter will change the fill of the node. This only works if + // the test node is of a shape type (the code which creates the test + // parameters will make sure to only use polluteFill with creators + // which are create Shapes) + final Polluter polluteFill = new Polluter() { + @Override public void pollute(NGNode node) { + if (node instanceof NGShape) { + com.sun.javafx.sg.prism.NGShape shape = (NGShape)node; + shape.setFillPaint(new Color(.43f, .23f, .66f, 1f)); + } else if (node instanceof NGRegion) { + NGRegion region = (NGRegion)node; + javafx.scene.paint.Color color = new javafx.scene.paint.Color(.43f, .23f, .66f, 1f); + // I have to do this nasty reflection trickery because we don't have a Toolkit for creating + // the Prism Color that is the platform peer. + try { + Field platformPaint = color.getClass().getDeclaredField("platformPaint"); + platformPaint.setAccessible(true); + platformPaint.set(color, new Color(.43f, .23f, .66f, 1f)); + } catch (Exception e) { + e.printStackTrace(); + } + + region.updateBackground(new Background(new BackgroundFill[] { + new BackgroundFill( + color, + CornerRadii.EMPTY, Insets.EMPTY) + })); + } else { + throw new IllegalArgumentException("I don't know how to make the fill dirty on " + node); + } + } + @Override public String toString() { return "Pollute Fill"; } + }; + // This polluter will translate the test node in a positive direction + final Polluter pollutePositiveTranslation = new Polluter() { + { tx = BaseTransform.getTranslateInstance(50, 50); } + @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } + @Override public String toString() { return "Pollute Positive Translation"; } + }; + // This polluter will translate the test node in a negative direction + final Polluter polluteNegativeTranslation = new Polluter() { + { tx = BaseTransform.getTranslateInstance(-50, -50); } + @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } + @Override public String toString() { return "Pollute Negative Translation"; } + }; + // This polluter will give the test node a scale causing it to get bigger + final Polluter polluteBiggerScale = new Polluter() { + { tx = BaseTransform.getScaleInstance(2, 2); } + @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } + @Override public String toString() { return "Pollute Bigger Scale"; } + }; + // This polluter will give the test node a scale causing it to get smaller + final Polluter polluteSmallerScale = new Polluter() { + { tx = BaseTransform.getScaleInstance(.5, .5); } + @Override public void pollute(NGNode node) { DirtyRegionTestBase.transform(node, tx); } + @Override public String toString() { return "Pollute Smaller Scale"; } + }; + // This polluter will rotate the node about its center + final Polluter polluteRotate = new Polluter() { + @Override public void pollute(NGNode node) { + BaseBounds effectBounds = node.getEffectBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); + BaseTransform tx = BaseTransform.getRotateInstance(45, effectBounds.getWidth()/2f, effectBounds.getHeight()/2f); + DirtyRegionTestBase.transform(node, tx); + } + @Override public BaseBounds modifiedBounds(NGNode node) { + BaseBounds effectBounds = node.getEffectBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); + BaseTransform tx = BaseTransform.getRotateInstance(45, effectBounds.getWidth() / 2f, effectBounds.getHeight() / 2f); + return DirtyRegionTestBase.getWhatTransformedBoundsWouldBe(node, tx); + } + @Override public String toString() { return "Pollute Rotate"; } + }; + // This polluter will make the test node invisible + final Polluter polluteVisibility = new Polluter() { + @Override public void pollute(NGNode node) { + node.setVisible(false); + } + @Override public String toString() { return "Pollute Visibility"; } + }; + // This polluter will make an invisible node visible again + final Polluter restoreVisibility = new Polluter() { + @Override public void pollute(NGNode node) { + // I need to hide the node, and then clean up all the dirty + // state associated with it, and then make it visible again. + // This simulates making it invisible, painting, and then + // making it visible again. + node.setVisible(false); + NGNode parent = node; + while(parent.getParent() != null) parent = parent.getParent(); + parent.render(TestGraphics.TEST_GRAPHICS); + // Now we can go ahead and set the opacity + node.setVisible(true); + } + @Override public String toString() { return "Restore Visibility"; } + }; + + // We will populate this list with the parameters with which we will test. + // Each Object[] within the params is composed of a Creator and a Polluter. + List params = new ArrayList(); + // A standard list of polluters which applies to all tests + List polluters = Arrays.asList(new Polluter[]{ + polluteRotate, + polluteOpacity, + restoreOpacity, + polluteVisibility, + restoreVisibility, + polluteSmallerScale, + polluteNegativeTranslation, + polluteBiggerScale, + pollutePositiveTranslation + }); + // Construct the Creator / Polluter pair for Groups + for (final Polluter polluter : polluters) { + params.add(new Object[] {new Creator() { + @Override public NGNode create() { return createGroup(createRectangle(0, 0, 100, 100)); } + @Override public String toString() { return "Group with one Rectangle"; } + }, polluter}); + } + // Construct the Creator / Polluter pair for Rectangles + List rectanglePolluters = new ArrayList(polluters); + rectanglePolluters.add(new Polluter() { + @Override public void pollute(NGNode node) { + NGRectangle rect = (NGRectangle)node; + BaseBounds bounds = rect.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); + rect.updateRectangle(bounds.getMinX(), bounds.getMinY(), 25, 25, 0, 0); + } + @Override public String toString() { return "Pollute Rectangle Geometry"; } + }); + for (final Polluter polluter : rectanglePolluters) { + params.add(new Object[] {new Creator() { + @Override public NGNode create() { return createRectangle(0, 0, 100, 100); } + @Override public String toString() { return "Rectangle"; } + }, polluter}); + } + // Construct the Creator / Polluter pair for Circles + List circlePolluters = new ArrayList(polluters); + circlePolluters.add(new Polluter() { + @Override public void pollute(NGNode node) { + NGCircle c = (NGCircle)node; + BaseBounds bounds = c.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); + c.updateCircle( + bounds.getMinX() + (bounds.getWidth()/2f), + bounds.getMinY() + (bounds.getHeight()/2f), + 10); + } + @Override public String toString() { return "Pollute Circle Geometry"; } + }); + for (final Polluter polluter : circlePolluters) { + params.add(new Object[] {new Creator() { + @Override public NGNode create() { return createCircle(50, 50, 50); } + @Override public String toString() { return "Circle"; } + }, polluter}); + } + // Return the populated params collection + return params; + } + + /** + * The test node creator. This is called from within the "setUp" method in each + * subclass to create the nodes that are going to be tested. + */ + protected Creator creator; + + /** + * The polluter. Subclasses will use the polluter to make a node dirty at the + * appropriate time in the test method. + */ + protected Polluter polluter; + + /** + * The root node. This must be created during the "setUp" method in each sub + * class. The root is needed for actually accumulating dirty regions. + */ + protected TestNGGroup root; + + /** + * The clip to use when accumulating dirty regions. By default it is + * ridiculously large, such that none of the tests will ever bump up + * against the clip. Subclasses should however implement some tests in + * which they will set the clip to a specific value, and then test + * whether accumulating dirty regions takes the clip into account. + */ + protected RectBounds windowClip = new RectBounds(-100000, -100000, 100000, 10000); + + /** + * Creates a new DirtyRegionTestBase. Each subclass must have an identical + * constructor which simply passes the creator and polluter to this + * constructor. These instances are passed to the constructor by JUnit, + * so sub classes don't need to worry about creating these instances + * (and in fact must not do so). + */ + protected DirtyRegionTestBase(Creator creator, Polluter polluter) { + this.creator = creator; + this.polluter = polluter; + } + + /** + * Helper method for asserting that the dirty region of the node indicated + * (start) matches the dirty region which is expected. This method will + * invoke the accumulateDirtyRegions method on the start node. Accumulating + * dirty regions requires a clip to be sent along as well. The windowClip is + * specified on DirtyRegionTestBase (by default it is ridiculously large) + * but sub classes can change the clip at any time. + * + */ + protected void assertDirtyRegionEquals(NGNode start, RectBounds expected) { + // TODO The root might have changes to its bounds and we should reset these. (RT-26928) + //DirtyRegionTestBase.resetGroupBounds(root); + // Accumulate the dirty region, using the windowClip. + // TODO if we wanted to, we could also make the device space transform parameterized + // such that we could test that the dirty region accumulation logic all works + // correctly even in the presence of a non-identity device space transform + // (RT-26928) + DirtyRegionPool pool = new DirtyRegionPool(1); + DirtyRegionContainer drc = pool.checkOut(); + int status = start.accumulateDirtyRegions( + windowClip, + new RectBounds(), pool, + drc, + BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + + RectBounds dirtyRegion = drc.getDirtyRegion(0) ; + + // The accumulation of dirty regions ends up with a slightly + // padded dirty region, just to make up for any error when + // transforming. Its quick and dirty but does the job. + // Perhaps we could avoid adding the slop in the case where + // there is no rotation or skew involved, but for now we + // don't. I don't want to populate all my tests with this + // assumption though in case it ever changes. So I am going + // to pad the expected here. + expected = new RectBounds( + Math.max(expected.getMinX() - 1, dirtyRegion.getMinX()), + Math.max(expected.getMinY() - 1, dirtyRegion.getMinY()), + Math.min(expected.getMaxX() + 1, dirtyRegion.getMaxX()), + Math.min(expected.getMaxY() + 1, dirtyRegion.getMaxY())); + // Now make the check, and print useful error information in case it fails. + assertEquals("creator=" + creator + ", polluter=" + polluter, expected, dirtyRegion); + } + + /** + * Helper method for asserting that the dirty region of the node indicated + * (start) contains the windowClip and matches the dirty region which is + * expected. This method will invoke the accumulateDirtyRegions method + * on the start node. Accumulating dirty regions requires a clip to be sent + * along as well. The windowClip is specified on DirtyRegionTestBase + * (by default it is ridiculously large) but sub classes can change the clip + * at any time. + */ + protected void assertContainsClip(NGNode start, RectBounds expectedDirtyRegion, int expectedStatus) { + DirtyRegionPool pool = new DirtyRegionPool(1); + DirtyRegionContainer drc = pool.checkOut(); + int status = start.accumulateDirtyRegions( + windowClip, + new RectBounds(), pool, + drc, + BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + + assertEquals(expectedStatus, status); + + if (status == DirtyRegionContainer.DTR_OK) { + assertDirtyRegionEquals(start, expectedDirtyRegion); + } + } + + /** + * Accumulates the dirty region, and checks to make sure the the accumulateDirtyRegion + * method was only called on the nodes supplied. If any node in the tree (starting with + * and including root) have had accumulateDirtyRegion called and they are NOT in this + * list of expected nodes, then the assertion fails. + *

+ * This assertion is used to make sure that various performance optimizations are + * implemented correctly, such that we are not asking nodes to accumulate dirty regions + * who have no hope of being in the dirty region (such as children of a clean group). + * + * @param nodes A non-null array of nodes. + */ + protected void assertOnlyTheseNodesAreAskedToAccumulateDirtyRegions(NGNode... nodes) { + accumulateDirtyRegions(); + Set set = new HashSet(Arrays.asList(nodes)); + assertOnlyTheseNodesWereAskedToAccumulateDirtyRegions(root, set); + } + + /** + * Accumulates the dirty region, and checks to make sure that the dirty region + * computation methods (accumulateNodeDirtyRegion, computeDirtyRegion, + * accumulateGroupDirtyRegion) are only called on the nodes supplied. If any + * node in the tree (starting with and including the root) has had one or more + * of these methods called and they are NOT in the array of expected nodes, then + * the assertion fails. + *

+ * This assertion is used to make sure various performance optimizations are + * implemented correctly, such that even if a node is asked to accumulate its + * dirty region, it doesn't actually do any work if the node is actually clean. + * + * @param nodes A non-null array of nodes. + */ + protected void assertOnlyTheseNodesAreAskedToComputeDirtyRegions(NGNode... nodes) { + accumulateDirtyRegions(); + Set set = new HashSet(Arrays.asList(nodes)); + assertOnlyTheseNodesWereAskedToComputeDirtyRegions(root, set); + } + + /** + * Helper method which will reset the group bounds of the root prior to accumulating + * dirty regions. The root node might have new bounds due to changes in its children, + * such as transforms or geometry changes. + */ + private void accumulateDirtyRegions() { + DirtyRegionPool pool = new DirtyRegionPool(1); + DirtyRegionTestBase.resetGroupBounds(root); + root.accumulateDirtyRegions( + new RectBounds(0, 0, 800, 600), + new RectBounds(), pool, + pool.checkOut(), + BaseTransform.IDENTITY_TRANSFORM, + new GeneralTransform3D()); + } + + /** + * Helper which walks down the tree checking to see if accumulateDirtyRegion has been + * called, and throws an exception if it was not expected. + */ + private void assertOnlyTheseNodesWereAskedToAccumulateDirtyRegions(NGNode start, Set nodes) { + assertEquals( + "creator=" + creator + ", polluter=" + polluter, + nodes.contains(start), ((TestNGNode)start).askedToAccumulateDirtyRegion()); + if (start instanceof NGGroup) { + for (NGNode child : ((NGGroup)start).getChildren()) { + assertOnlyTheseNodesWereAskedToAccumulateDirtyRegions(child, nodes); + } + } + } + + /** + * Helper which walks down the tree checking to see if any of the methods which actually + * compute the dirty region have been called, and throws an exception if it was not expected. + */ + private void assertOnlyTheseNodesWereAskedToComputeDirtyRegions(NGNode start, Set nodes) { + assertEquals( + "creator=" + creator + ", polluter=" + polluter, + nodes.contains(start), ((TestNGNode)start).computedDirtyRegion()); + if (start instanceof NGGroup) { + for (NGNode child : ((NGGroup)start).getChildren()) { + assertOnlyTheseNodesWereAskedToComputeDirtyRegions(child, nodes); + } + } + } + + static protected void resetGroupBounds(NGGroup group) { + BaseBounds contentBounds = new RectBounds(); + for (NGNode child : group.getChildren()) { + contentBounds = contentBounds.deriveWithUnion( + child.getCompleteBounds( + new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); + } + BaseBounds currentContentBounds = group.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); + if (!contentBounds.equals(currentContentBounds)) { + System.out.println("CurrentContentBounds=" + currentContentBounds + ", bounds=" + contentBounds); + group.setContentBounds(contentBounds); + group.setTransformedBounds(group.getEffectBounds(new RectBounds(), group.getTransform()), false); + } + } + + /** + * Sort of a non-applying version of the transform method. This method will + * compute and return what the transformed bounds of the given node would + * be if the transform were applied to it. + */ + static protected BaseBounds getWhatTransformedBoundsWouldBe(NGNode node, BaseTransform tx) { + BaseTransform existing = BaseTransform.IDENTITY_TRANSFORM.deriveWithNewTransform(node.getTransform()); + tx = existing.deriveWithConcatenation(tx); + return node.getEffectBounds(new RectBounds(), tx); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/EffectDirtyRegionTest.java 2015-09-11 21:24:28.509286944 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,511 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import javafx.scene.Group; -import javafx.scene.Node; -import javafx.scene.Scene; -import javafx.scene.shape.Rectangle; -import com.sun.javafx.geom.BaseBounds; -import com.sun.javafx.geom.DirtyRegionContainer; -import com.sun.javafx.geom.DirtyRegionPool; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.javafx.sg.prism.NGNode; -import com.sun.scenario.effect.Blend; -import com.sun.scenario.effect.Bloom; -import com.sun.scenario.effect.BoxBlur; -import com.sun.scenario.effect.BoxShadow; -import com.sun.scenario.effect.ColorAdjust; -import com.sun.scenario.effect.Crop; -import com.sun.scenario.effect.DropShadow; -import com.sun.scenario.effect.Effect; -import com.sun.scenario.effect.GaussianBlur; -import com.sun.scenario.effect.GeneralShadow; -import com.sun.scenario.effect.Glow; -import com.sun.scenario.effect.InnerShadow; -import com.sun.scenario.effect.MotionBlur; -import com.sun.scenario.effect.Offset; -import com.sun.scenario.effect.SepiaTone; -import junit.framework.Assert; -import org.junit.Test; - -public class EffectDirtyRegionTest { - - DirtyRegionContainer drc; - DirtyRegionContainer drcExpected; - DirtyRegionPool drp; - Effect effect; - NGNode g1bn; - NGNode gbn; - - @Test - public void dropShadowTest() { - setupTest(); - - effect = new DropShadow(); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(40, 40, 70, 70) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(30, 30, 90, 90) - }); - compareResult(drcExpected, drc); - } - - @Test - public void colorAdjustTest() { - setupTest(); - - effect = new ColorAdjust(); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60), - new RectBounds(70, 70, 80, 80) - }); - compareResult(drcExpected, drc); - } - - @Test - public void bloomTest() { - setupTest(); - - effect = new Bloom(); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 80, 80) - }); - compareResult(drcExpected, drc); - } - - @Test - public void blendTest() { - setupTest(); - - effect = new Blend(Blend.Mode.ADD, new DropShadow(), new ColorAdjust()); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(40, 40, 70, 70) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(30, 30, 90, 90) - }); - compareResult(drcExpected, drc); - } - - @Test - public void boxBlurTest() { - setupTest(); - - effect = new BoxBlur(10, 5, 3); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(36, 44, 74, 66) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(22, 38, 88, 72), - new RectBounds(56, 64, 94, 86) - }); - compareResult(drcExpected, drc); - } - - @Test - public void gausianBlurTest() { - setupTest(); - - effect = new GaussianBlur(5); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(45, 45, 65, 65) - }); - compareResult(drcExpected, drc); - - ((GaussianBlur)effect).setRadius(2); - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(43, 43, 67, 67), - new RectBounds(68, 68, 82, 82) - }); - compareResult(drcExpected, drc); - } - - @Test - public void glowTest() { - setupTest(); - - effect = new Glow(); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 80, 80) - }); - compareResult(drcExpected, drc); - } - - @Test - public void innerShadowTest() { - setupTest(); - - effect = new InnerShadow(); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(40, 40, 70, 70) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(30, 30, 90, 90) - }); - compareResult(drcExpected, drc); - } - - @Test - public void motionBlurTest() { - setupTest(); - - effect = new MotionBlur(); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(40, 50, 70, 60) - }); - compareResult(drcExpected, drc); - - ((MotionBlur)effect).setAngle((float) Math.toRadians(90)); - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(39, 40, 71, 70), - new RectBounds(69, 60, 81, 90) - }); - compareResult(drcExpected, drc); - } - - @Test - public void sepiaToneTest() { - setupTest(); - - effect = new SepiaTone(); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60), - new RectBounds(70, 70, 80, 80) - }); - compareResult(drcExpected, drc); - } - - @Test - public void boxShadowTest() { - setupTest(); - - effect = new BoxShadow(); - ((BoxShadow) effect).setHorizontalSize(10); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(45, 50, 65, 60) - }); - compareResult(drcExpected, drc); - - ((BoxShadow) effect).setHorizontalSize(0); - ((BoxShadow) effect).setVerticalSize(10); - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(45, 45, 65, 65), - new RectBounds(70, 65, 80, 85) - }); - compareResult(drcExpected, drc); - } - - @Test - public void generalShadowTest() { - setupTest(); - - effect = new GeneralShadow(); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(40, 40, 70, 70) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(30, 30, 90, 90) - }); - compareResult(drcExpected, drc); - } - - @Test - public void cropTest() { - setupTest(); - - effect = new Crop(new DropShadow()); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 80, 80) - }); - compareResult(drcExpected, drc); - } - - @Test - public void offsetTest() { - setupTest(); - - effect = new Offset(10, -10, new DropShadow()); - - drc.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 50, 60, 60) - }); - g1bn.setEffect(effect); - g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 30, 80, 60) - }); - compareResult(drcExpected, drc); - - drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); - gbn.setEffect(effect); - gbn.applyEffect(gbn.getEffectFilter(), drc, drp); - drcExpected.deriveWithNewRegions(new RectBounds[] - { - new RectBounds(50, 10, 100, 80) - }); - compareResult(drcExpected, drc); - } - - private void setupTest() { - drc = new DirtyRegionContainer(6); - drcExpected = new DirtyRegionContainer(6); - drp = new DirtyRegionPool(4); - - Node g1 = group(new Rectangle(50, 50, 10, 10)); - g1bn = getBaseNode(g1); - Node g = group(g1, new Rectangle(70, 70, 10, 10)); - gbn = getBaseNode(g); - } - - private void compareResult(DirtyRegionContainer expected, DirtyRegionContainer computed) { - for (int i = 0; i < computed.size(); i++) { - Assert.assertEquals(expected.getDirtyRegion(i), computed.getDirtyRegion(i)); - } - } - - public static NGNode getBaseNode(Node n) { - Scene.impl_setAllowPGAccess(true); - // Eeek, this is gross! I have to use reflection to invoke this - // method so that bounds are updated... - try { - java.lang.reflect.Method method = Node.class.getDeclaredMethod("updateBounds"); - method.setAccessible(true); - method.invoke(n); - } catch (Exception e) { - throw new RuntimeException("Failed to update bounds", e); - } - n.impl_updatePeer(); - NGNode bn = n.impl_getPeer(); - Scene.impl_setAllowPGAccess(false); - return bn; - } - - public static Node group(Node... n) { - Group g = new Group(n); - return g; - } - - public static BaseBounds getBounds(Node n, BaseTransform tx) { - NGNode pgn = getBaseNode(n); - return pgn.getContentBounds(new RectBounds(), tx); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/EffectDirtyRegionTest.java 2015-09-11 21:24:28.365286945 -0400 @@ -0,0 +1,512 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import javafx.scene.Group; +import javafx.scene.Node; +import javafx.scene.Scene; +import javafx.scene.shape.Rectangle; +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.DirtyRegionPool; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.scenario.effect.Blend; +import com.sun.scenario.effect.Bloom; +import com.sun.scenario.effect.BoxBlur; +import com.sun.scenario.effect.BoxShadow; +import com.sun.scenario.effect.ColorAdjust; +import com.sun.scenario.effect.Crop; +import com.sun.scenario.effect.DropShadow; +import com.sun.scenario.effect.Effect; +import com.sun.scenario.effect.GaussianBlur; +import com.sun.scenario.effect.GeneralShadow; +import com.sun.scenario.effect.Glow; +import com.sun.scenario.effect.InnerShadow; +import com.sun.scenario.effect.MotionBlur; +import com.sun.scenario.effect.Offset; +import com.sun.scenario.effect.SepiaTone; +import junit.framework.Assert; +import org.junit.Test; + +public class EffectDirtyRegionTest { + + DirtyRegionContainer drc; + DirtyRegionContainer drcExpected; + DirtyRegionPool drp; + Effect effect; + NGNode g1bn; + NGNode gbn; + + @Test + public void dropShadowTest() { + setupTest(); + + effect = new DropShadow(); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(40, 40, 70, 70) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(30, 30, 90, 90) + }); + compareResult(drcExpected, drc); + } + + @Test + public void colorAdjustTest() { + setupTest(); + + effect = new ColorAdjust(); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60), + new RectBounds(70, 70, 80, 80) + }); + compareResult(drcExpected, drc); + } + + @Test + public void bloomTest() { + setupTest(); + + effect = new Bloom(); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 80, 80) + }); + compareResult(drcExpected, drc); + } + + @Test + public void blendTest() { + setupTest(); + + effect = new Blend(Blend.Mode.ADD, new DropShadow(), new ColorAdjust()); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(40, 40, 70, 70) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(30, 30, 90, 90) + }); + compareResult(drcExpected, drc); + } + + @Test + public void boxBlurTest() { + setupTest(); + + effect = new BoxBlur(10, 5, 3); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(36, 44, 74, 66) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(22, 38, 88, 72), + new RectBounds(56, 64, 94, 86) + }); + compareResult(drcExpected, drc); + } + + @Test + public void gausianBlurTest() { + setupTest(); + + effect = new GaussianBlur(5); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(45, 45, 65, 65) + }); + compareResult(drcExpected, drc); + + ((GaussianBlur)effect).setRadius(2); + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(43, 43, 67, 67), + new RectBounds(68, 68, 82, 82) + }); + compareResult(drcExpected, drc); + } + + @Test + public void glowTest() { + setupTest(); + + effect = new Glow(); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 80, 80) + }); + compareResult(drcExpected, drc); + } + + @Test + public void innerShadowTest() { + setupTest(); + + effect = new InnerShadow(); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(40, 40, 70, 70) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(30, 30, 90, 90) + }); + compareResult(drcExpected, drc); + } + + @Test + public void motionBlurTest() { + setupTest(); + + effect = new MotionBlur(); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(40, 50, 70, 60) + }); + compareResult(drcExpected, drc); + + ((MotionBlur)effect).setAngle((float) Math.toRadians(90)); + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(39, 40, 71, 70), + new RectBounds(69, 60, 81, 90) + }); + compareResult(drcExpected, drc); + } + + @Test + public void sepiaToneTest() { + setupTest(); + + effect = new SepiaTone(); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60), + new RectBounds(70, 70, 80, 80) + }); + compareResult(drcExpected, drc); + } + + @Test + public void boxShadowTest() { + setupTest(); + + effect = new BoxShadow(); + ((BoxShadow) effect).setHorizontalSize(10); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(45, 50, 65, 60) + }); + compareResult(drcExpected, drc); + + ((BoxShadow) effect).setHorizontalSize(0); + ((BoxShadow) effect).setVerticalSize(10); + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(45, 45, 65, 65), + new RectBounds(70, 65, 80, 85) + }); + compareResult(drcExpected, drc); + } + + @Test + public void generalShadowTest() { + setupTest(); + + effect = new GeneralShadow(); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(40, 40, 70, 70) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(30, 30, 90, 90) + }); + compareResult(drcExpected, drc); + } + + @Test + public void cropTest() { + setupTest(); + + effect = new Crop(new DropShadow()); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 80, 80) + }); + compareResult(drcExpected, drc); + } + + @Test + public void offsetTest() { + setupTest(); + + effect = new Offset(10, -10, new DropShadow()); + + drc.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 50, 60, 60) + }); + g1bn.setEffect(effect); + g1bn.applyEffect(g1bn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 30, 80, 60) + }); + compareResult(drcExpected, drc); + + drc.addDirtyRegion(new RectBounds(70, 70, 80, 80)); + gbn.setEffect(effect); + gbn.applyEffect(gbn.getEffectFilter(), drc, drp); + drcExpected.deriveWithNewRegions(new RectBounds[] + { + new RectBounds(50, 10, 100, 80) + }); + compareResult(drcExpected, drc); + } + + private void setupTest() { + drc = new DirtyRegionContainer(6); + drcExpected = new DirtyRegionContainer(6); + drp = new DirtyRegionPool(4); + + Node g1 = group(new Rectangle(50, 50, 10, 10)); + g1bn = getBaseNode(g1); + Node g = group(g1, new Rectangle(70, 70, 10, 10)); + gbn = getBaseNode(g); + } + + private void compareResult(DirtyRegionContainer expected, DirtyRegionContainer computed) { + for (int i = 0; i < computed.size(); i++) { + Assert.assertEquals(expected.getDirtyRegion(i), computed.getDirtyRegion(i)); + } + } + + public static NGNode getBaseNode(Node n) { + Scene.impl_setAllowPGAccess(true); + // Eeek, this is gross! I have to use reflection to invoke this + // method so that bounds are updated... + try { + java.lang.reflect.Method method = Node.class.getDeclaredMethod("updateBounds"); + method.setAccessible(true); + method.invoke(n); + } catch (Exception e) { + throw new RuntimeException("Failed to update bounds", e); + } + n.impl_updatePeer(); + NGNode bn = n.impl_getPeer(); + Scene.impl_setAllowPGAccess(false); + return bn; + } + + public static Node group(Node... n) { + Group g = new Group(n); + return g; + } + + public static BaseBounds getBounds(Node n, BaseTransform tx) { + NGNode pgn = getBaseNode(n); + return pgn.getContentBounds(new RectBounds(), tx); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/GridDirtyRegionTest.java 2015-09-11 21:24:29.129286937 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,238 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import java.util.ArrayList; -import java.util.List; -import com.sun.javafx.geom.BaseBounds; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.scenario.effect.DropShadow; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -/** - * A series of tests where we are checking for the dirty region on a grid - * of nodes. This is a parameterized test (based on its base class). - * Each time the test is run, it will be given a way to create nodes, - * and a way to make them dirty. Each test then only has to invoke the - * creator to make nodes and the polluter to make them dirty, and then - * check that the right methods were called and the right dirty regions - * computed. There is some magic here -- every node created by the creator - * must implement TestNGNode; the base class must set the "root" in the - * parent class. - */ -@RunWith(Parameterized.class) -public class GridDirtyRegionTest extends DirtyRegionTestBase { - /** - * Specified to avoid magic numbers. There are several places where we - * translate the root in order to make it dirty. - */ - private static final float TRANSLATE_DELTA = 50; - - /** - * Creates a new instance of the GridDirtyRegionTest. Since this is a - * parameterized test, we are passed the node creator and polluter. - */ - public GridDirtyRegionTest(Creator creator, Polluter polluter) { - super(creator, polluter); - } - - /** - * Constructs a non-overlapping grid of nodes. Each node is a direct child - * of the root node. They may end up overlapping when they become dirty, - * but they don't start out that way! Each node is placed where it belongs - * in the grid by translating them into place. - */ - @Before public void setUp() { - // create the grid - NGNode[] content = new NGNode[9]; - for (int row=0; row<3; row++) { - for (int col=0; col<3; col++) { - NGNode node = creator.create(); - BaseTransform tx = BaseTransform.IDENTITY_TRANSFORM; - tx = tx.deriveWithTranslation((col * 110), (row * 110)); - transform(node, tx); - content[(row * 3) + col] = node; - } - } - root = createGroup(content); - - // The grid is created & populated. We'll now go through and manually - // clean them all up so that when we perform the test, it is from the - // starting point of a completely cleaned tree - root.render(TestGraphics.TEST_GRAPHICS); - } - - @Test public void sanityCheck() { - NGNode node = root.getChildren().get(0); - assertEquals(new RectBounds(0, 0, 100, 100), node.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - assertEquals(new RectBounds(0, 0, 100, 100), node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - - node = root.getChildren().get(1); - assertEquals(new RectBounds(0, 0, 100, 100), node.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - assertEquals(new RectBounds(110, 0, 210, 100), node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - - node = root.getChildren().get(3); - assertEquals(new RectBounds(0, 0, 100, 100), node.getContentBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - assertEquals(new RectBounds(0, 110, 100, 210), node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - } - - @Test public void cleanNodesShouldNotContributeToDirtyRegion() { - // By default the scene should be clean - assertDirtyRegionEquals(root, new RectBounds()); - } - - @Test public void cleanChildNodesOnADirtyParentShouldNotContributeToDirtyRegion() { - // Now if I translate the root, none of the child nodes - // should contribute to the dirty region - translate(root, TRANSLATE_DELTA, TRANSLATE_DELTA); - for (NGNode child : root.getChildren()) { - assertDirtyRegionEquals(child, new RectBounds()); - } - } - - @Test public void whenOnlyTheRootIsDirtyOnlyTheRootShouldBeAskedToAccumulateDirtyRegions() { - translate(root, TRANSLATE_DELTA, TRANSLATE_DELTA); - assertOnlyTheseNodesAreAskedToAccumulateDirtyRegions(root); - } - - @Test public void cleanChildNodesOnACleanParentShouldNotContributeToDirtyRegion() { - // If I make one of the children dirty, then the child should contribute - // to the dirty region, but none of the other nodes should. This test just - // checks this second part -- that none of the other child nodes contribute. - NGNode middleChild = root.getChildren().get(root.getChildren().size()/2); - polluter.pollute(middleChild); - for (NGNode child : root.getChildren()) { - if (child != middleChild) { // skip the dirty node - assertDirtyRegionEquals(child, new RectBounds()); - } - } - } - - @Test public void whenOnlyASingleChildIsDirtyThenParentAndAllChildrenAreAskedToAccumulateDirtyRegions() { - NGNode middleChild = root.getChildren().get(root.getChildren().size()/2); - polluter.pollute(middleChild); - List nodes = new ArrayList<>(root.getChildren()); - nodes.add(root); - NGNode[] arr = new NGNode[nodes.size()]; - for (int i=0; i nodes = new ArrayList<>(root.getChildren()); + nodes.add(root); + NGNode[] arr = new NGNode[nodes.size()]; + for (int i=0; i= i); - assertTrue(gdb.objectCapacity() >= i); - } - } - - @Test public void testWriteAndReadValues() { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); - fill(gdb, true, false); - assertTrue(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - test(gdb, true, false); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } - - @Test public void testWriteAndReadUbytes() { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); - putUBytes(gdb); - assertTrue(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - getUBytes(gdb); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } - - @Test public void testWriteAndReadObjects() { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); - fill(gdb, false, true); - assertFalse(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - test(gdb, false, true); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } - - @Test public void testWriteAndReadValuesAndObjects() { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); - fill(gdb, true, true); - assertTrue(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - test(gdb, true, true); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } - - @Test public void testWriteAndReadGrowableValues() { - for (int i = 0; i < NUM_BYTES; i++) { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(i, NUM_VALUES); - fill(gdb, true, false); - assertTrue(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - test(gdb, true, false); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } - } - - @Test public void testWriteAndReadGrowableObjects() { - for (int i = 0; i < NUM_VALUES; i++) { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, i); - fill(gdb, false, true); - assertFalse(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - test(gdb, false, true); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } - } - - @Test public void testWriteAndMultipleReads() { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); - fill(gdb, true, true); - assertTrue(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - gdb.save(); - assertTrue(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - test(gdb, true, true); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - gdb.restore(); - assertTrue(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - test(gdb, true, true); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } - - @Test public void testPeekValues() { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); - fill(gdb, true, false); - assertTrue(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - for (int i = 0; i < gdb.writeValuePosition(); i++) { - gdb.peekByte(i); - } - assertTrue(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } - - @Test public void testPeekObjects() { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); - fill(gdb, false, true); - assertFalse(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - for (int i = 0; i < gdb.writeValuePosition(); i++) { - gdb.peekByte(i); - } - assertFalse(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - } - - @Test public void testAppend() { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); - fill(gdb, true, true); - GrowableDataBuffer gdb2 = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); - fill(gdb2, true, true); - gdb.append(gdb2); - assertTrue(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - test(gdb, true, true); - assertTrue(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - test(gdb, true, true); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } - - @Test public void testReset() { - GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(0, 0); - fill(gdb, true, true); - assertTrue(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - int valcapacity = gdb.valueCapacity(); - int objcapacity = gdb.objectCapacity(); - for (int i = 0; i < 5; i++) { - gdb.reset(); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - fill(gdb, true, true); - assertTrue(gdb.hasValues()); - assertTrue(gdb.hasObjects()); - } - assertTrue(gdb.valueCapacity() == valcapacity); - assertTrue(gdb.objectCapacity() == objcapacity); - test(gdb, true, true); - assertFalse(gdb.hasValues()); - assertFalse(gdb.hasObjects()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/GrowableDataBufferTest.java 2015-09-11 21:24:29.841286929 -0400 @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.sg.prism.GrowableDataBuffer; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + */ +public class GrowableDataBufferTest { + + public boolean encodableBooleans[] = { + false, true + }; + + public char encodableChars[] = { + ' ', 'A', 'Z', 'a', 'z', '0', '9' + }; + + public byte encodableBytes[] = { + -1, 0, 1, Byte.MIN_VALUE, Byte.MAX_VALUE + }; + + public short encodableShorts[] = { + -1, 0, 1, Short.MIN_VALUE, Short.MAX_VALUE + }; + + public int encodableInts[] = { + -1, 0, 1, Integer.MIN_VALUE, Integer.MAX_VALUE + }; + + public long encodableLongs[] = { + -1L, 0L, 1L, Long.MIN_VALUE, Long.MAX_VALUE + }; + + public float encodableFloats[] = { + -1.0f, 0.0f, 1.0f, Float.MIN_VALUE, Float.MAX_VALUE, + Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY + }; + + public double encodableDoubles[] = { + -1.0, 0.0, 1.0, Double.MIN_VALUE, Double.MAX_VALUE, + Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY + }; + + int NUM_VALUES = + encodableBooleans.length + + encodableChars.length + + encodableBytes.length + + encodableShorts.length + + encodableInts.length + + encodableLongs.length + + encodableFloats.length + + encodableDoubles.length; + int NUM_BYTES = + encodableBooleans.length + + encodableChars.length * 2 + + encodableBytes.length + + encodableShorts.length * 2 + + encodableInts.length * 4 + + encodableLongs.length * 8 + + encodableFloats.length * 4 + + encodableDoubles.length * 8; + + void putBooleans(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + for (boolean b : encodableBooleans) { + if (putPrim) gdb.putBoolean(b); + if (putObj) gdb.putObject(Boolean.valueOf(b)); + } + } + + void getBooleans(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + for (boolean b : encodableBooleans) { + if (getPrim) assertTrue(gdb.getBoolean() == b); + if (getObj) assertTrue(gdb.getObject().equals(Boolean.valueOf(b))); + } + } + + void putChars(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + for (char c : encodableChars) { + if (putPrim) gdb.putChar(c); + if (putObj) gdb.putObject(Character.valueOf(c)); + } + } + + void getChars(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + for (char c : encodableChars) { + if (getPrim) assertTrue(gdb.getChar() == c); + if (getObj) assertTrue(gdb.getObject().equals(Character.valueOf(c))); + } + } + + void putBytes(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + for (byte b : encodableBytes) { + if (putPrim) gdb.putByte(b); + if (putObj) gdb.putObject(Byte.valueOf(b)); + } + } + + void getBytes(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + for (byte b : encodableBytes) { + if (getPrim) assertTrue(gdb.getByte() == b); + if (getObj) assertTrue(gdb.getObject().equals(Byte.valueOf(b))); + } + } + + void putUBytes(GrowableDataBuffer gdb) { + for (byte b : encodableBytes) { + gdb.putByte(b); + } + } + + void getUBytes(GrowableDataBuffer gdb) { + for (byte b : encodableBytes) { + assertTrue(gdb.getUByte() == (b & 0xff)); + } + } + + void putShorts(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + for (short s : encodableShorts) { + if (putPrim) gdb.putShort(s); + if (putObj) gdb.putObject(Short.valueOf(s)); + } + } + + void getShorts(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + for (short s : encodableShorts) { + if (getPrim) assertTrue(gdb.getShort() == s); + if (getObj) assertTrue(gdb.getObject().equals(Short.valueOf(s))); + } + } + + void putInts(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + for (int i : encodableInts) { + if (putPrim) gdb.putInt(i); + if (putObj) gdb.putObject(Integer.valueOf(i)); + } + } + + void getInts(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + for (int i : encodableInts) { + if (getPrim) assertTrue(gdb.getInt() == i); + if (getObj) assertTrue(gdb.getObject().equals(Integer.valueOf(i))); + } + } + + void putLongs(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + for (long l : encodableLongs) { + if (putPrim) gdb.putLong(l); + if (putObj) gdb.putObject(Long.valueOf(l)); + } + } + + void getLongs(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + for (long c : encodableLongs) { + if (getPrim) assertTrue(gdb.getLong() == c); + if (getObj) assertTrue(gdb.getObject().equals(Long.valueOf(c))); + } + } + + void putFloats(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + for (float f : encodableFloats) { + if (putPrim) gdb.putFloat(f); + if (putObj) gdb.putObject(Float.valueOf(f)); + } + } + + void getFloats(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + for (float f : encodableFloats) { + if (getPrim) assertTrue(gdb.getFloat() == f); + if (getObj) assertTrue(gdb.getObject().equals(Float.valueOf(f))); + } + } + + void putFloatNaN(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + if (putPrim) gdb.putFloat(Float.NaN); + if (putObj) gdb.putObject(Float.valueOf(Float.NaN)); + } + + void getFloatNaN(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + if (getPrim) assertTrue(Float.isNaN(gdb.getFloat())); + if (getObj) assertTrue(gdb.getObject().equals(Float.valueOf(Float.NaN))); + } + + void putDoubles(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + for (double d : encodableDoubles) { + if (putPrim) gdb.putDouble(d); + if (putObj) gdb.putObject(Double.valueOf(d)); + } + } + + void getDoubles(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + for (double d : encodableDoubles) { + if (getPrim) assertTrue(gdb.getDouble() == d); + if (getObj) assertTrue(gdb.getObject().equals(Double.valueOf(d))); + } + } + + void putDoubleNaN(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + if (putPrim) gdb.putDouble(Double.NaN); + if (putObj) gdb.putObject(Double.valueOf(Double.NaN)); + } + + void getDoubleNaN(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + if (getPrim) assertTrue(Double.isNaN(gdb.getDouble())); + if (getObj) assertTrue(gdb.getObject().equals(Double.valueOf(Double.NaN))); + } + + void fill(GrowableDataBuffer gdb, boolean putPrim, boolean putObj) { + putBooleans(gdb, putPrim, putObj); + putChars(gdb, putPrim, putObj); + putBytes(gdb, putPrim, putObj); + putShorts(gdb, putPrim, putObj); + putInts(gdb, putPrim, putObj); + putLongs(gdb, putPrim, putObj); + putFloats(gdb, putPrim, putObj); + putFloatNaN(gdb, putPrim, putObj); + putDoubles(gdb, putPrim, putObj); + putDoubleNaN(gdb, putPrim, putObj); + } + + void test(GrowableDataBuffer gdb, boolean getPrim, boolean getObj) { + getBooleans(gdb, getPrim, getObj); + getChars(gdb, getPrim, getObj); + getBytes(gdb, getPrim, getObj); + getShorts(gdb, getPrim, getObj); + getInts(gdb, getPrim, getObj); + getLongs(gdb, getPrim, getObj); + getFloats(gdb, getPrim, getObj); + getFloatNaN(gdb, getPrim, getObj); + getDoubles(gdb, getPrim, getObj); + getDoubleNaN(gdb, getPrim, getObj); + } + + @Test public void testCapacities() { + for (int i = 1; i < 100000; i += 100) { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(i, i); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + assertTrue(gdb.isEmpty()); + assertTrue(gdb.valueCapacity() >= i); + assertTrue(gdb.objectCapacity() >= i); + } + } + + @Test public void testWriteAndReadValues() { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); + fill(gdb, true, false); + assertTrue(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + test(gdb, true, false); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } + + @Test public void testWriteAndReadUbytes() { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); + putUBytes(gdb); + assertTrue(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + getUBytes(gdb); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } + + @Test public void testWriteAndReadObjects() { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); + fill(gdb, false, true); + assertFalse(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + test(gdb, false, true); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } + + @Test public void testWriteAndReadValuesAndObjects() { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); + fill(gdb, true, true); + assertTrue(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + test(gdb, true, true); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } + + @Test public void testWriteAndReadGrowableValues() { + for (int i = 0; i < NUM_BYTES; i++) { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(i, NUM_VALUES); + fill(gdb, true, false); + assertTrue(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + test(gdb, true, false); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } + } + + @Test public void testWriteAndReadGrowableObjects() { + for (int i = 0; i < NUM_VALUES; i++) { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, i); + fill(gdb, false, true); + assertFalse(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + test(gdb, false, true); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } + } + + @Test public void testWriteAndMultipleReads() { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); + fill(gdb, true, true); + assertTrue(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + gdb.save(); + assertTrue(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + test(gdb, true, true); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + gdb.restore(); + assertTrue(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + test(gdb, true, true); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } + + @Test public void testPeekValues() { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); + fill(gdb, true, false); + assertTrue(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + for (int i = 0; i < gdb.writeValuePosition(); i++) { + gdb.peekByte(i); + } + assertTrue(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } + + @Test public void testPeekObjects() { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); + fill(gdb, false, true); + assertFalse(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + for (int i = 0; i < gdb.writeValuePosition(); i++) { + gdb.peekByte(i); + } + assertFalse(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + } + + @Test public void testAppend() { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); + fill(gdb, true, true); + GrowableDataBuffer gdb2 = GrowableDataBuffer.getBuffer(NUM_BYTES, NUM_VALUES); + fill(gdb2, true, true); + gdb.append(gdb2); + assertTrue(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + test(gdb, true, true); + assertTrue(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + test(gdb, true, true); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } + + @Test public void testReset() { + GrowableDataBuffer gdb = GrowableDataBuffer.getBuffer(0, 0); + fill(gdb, true, true); + assertTrue(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + int valcapacity = gdb.valueCapacity(); + int objcapacity = gdb.objectCapacity(); + for (int i = 0; i < 5; i++) { + gdb.reset(); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + fill(gdb, true, true); + assertTrue(gdb.hasValues()); + assertTrue(gdb.hasObjects()); + } + assertTrue(gdb.valueCapacity() == valcapacity); + assertTrue(gdb.objectCapacity() == objcapacity); + test(gdb, true, true); + assertFalse(gdb.hasValues()); + assertFalse(gdb.hasObjects()); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGCircleTest.java 2015-09-11 21:24:30.829286918 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import com.sun.javafx.geom.RectBounds; -import com.sun.prism.paint.Color; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - */ -public class NGCircleTest extends NGTestBase { - - NGCircle circle; - - @Before public void setup() { - circle = new NGCircle(); - circle.setFillPaint(Color.RED); - circle.updateCircle(10, 10, 5); - } - - @Test - public void testSupportsOpaqueRegion() { - assertTrue(circle.supportsOpaqueRegions()); - } - - @Test - public void hasOpaqueRegionIfRadiusIsGreaterThanZero() { - assertTrue(circle.hasOpaqueRegion()); - circle.updateCircle(10, 10, 0); - assertFalse(circle.hasOpaqueRegion()); - circle.updateCircle(10, 10, .0001f); - assertTrue(circle.hasOpaqueRegion()); - } - - @Test - public void opaqueRegionLiesWithinCircle() { - RectBounds or = new RectBounds(); - // Just sort of try a range of values. They should all be good. - final float[] radiusValues = new float[] { - .001f, - 1f/3f, - (float) Math.E, - (float) Math.PI, - 10f, - 13.321f // some random number - }; - for (float r : radiusValues) { - circle.updateCircle(10, 10, r); - or = circle.computeOpaqueRegion(or); - assertNotNull(or); - assertTrue(circle.getShape().contains(or.getMinX(), or.getMinY(), or.getWidth(), or.getHeight())); - } - } - - /** - * Perform a simple test to be sure that the opaque region is just - * about as large as it could possibly be without going outside the - * bounds of the ellipse. This is basically using the same math as - * the implementation, except that we use the more precise math here - * than what the implementation uses. So I will compute the wider box - * and a narrower box and make sure the implementation is between the two. - */ - @Test - public void testComputeOpaqueRegion() { - RectBounds or = circle.computeOpaqueRegion(new RectBounds()); - - // First we will compute with the highest precision we can. - float r = 5; // same as the ellipse - float side = 2*r / (float) Math.sqrt(2); - float halfSide = side / 2f; - float x1 = 10 - halfSide; // centerX = 10 - float y1 = 10 - halfSide; // centerY = 10 - float x2 = 10 + halfSide; - float y2 = 10 + halfSide; - // Less than really accurate - assertTrue(x1 < or.getMinX()); - assertTrue(y1 < or.getMinY()); - assertTrue(x2 > or.getMaxX()); - assertTrue(y2 > or.getMaxY()); - // But not too far off - assertEquals(x1, or.getMinX(), .1f); - assertEquals(y1, or.getMinY(), .1f); - assertEquals(x2, or.getMaxX(), .1f); - assertEquals(y2, or.getMaxY(), .1f); - - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/NGCircleTest.java 2015-09-11 21:24:30.621286920 -0400 @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.sg.prism.NGCircle; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.prism.paint.Color; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + */ +public class NGCircleTest extends NGTestBase { + + NGCircle circle; + + @Before public void setup() { + circle = new NGCircle(); + circle.setFillPaint(Color.RED); + circle.updateCircle(10, 10, 5); + } + + @Test + public void testSupportsOpaqueRegion() { + assertTrue(NGNodeShim.supportsOpaqueRegions(circle)); + } + + @Test + public void hasOpaqueRegionIfRadiusIsGreaterThanZero() { + assertTrue(NGNodeShim.hasOpaqueRegion(circle)); + circle.updateCircle(10, 10, 0); + assertFalse(NGNodeShim.hasOpaqueRegion(circle)); + circle.updateCircle(10, 10, .0001f); + assertTrue(NGNodeShim.hasOpaqueRegion(circle)); + } + + @Test + public void opaqueRegionLiesWithinCircle() { + RectBounds or = new RectBounds(); + // Just sort of try a range of values. They should all be good. + final float[] radiusValues = new float[] { + .001f, + 1f/3f, + (float) Math.E, + (float) Math.PI, + 10f, + 13.321f // some random number + }; + for (float r : radiusValues) { + circle.updateCircle(10, 10, r); + or = NGNodeShim.computeOpaqueRegion(circle, or); + assertNotNull(or); + assertTrue(circle.getShape().contains(or.getMinX(), or.getMinY(), or.getWidth(), or.getHeight())); + } + } + + /** + * Perform a simple test to be sure that the opaque region is just + * about as large as it could possibly be without going outside the + * bounds of the ellipse. This is basically using the same math as + * the implementation, except that we use the more precise math here + * than what the implementation uses. So I will compute the wider box + * and a narrower box and make sure the implementation is between the two. + */ + @Test + public void testComputeOpaqueRegion() { + RectBounds or = NGNodeShim.computeOpaqueRegion(circle, new RectBounds()); + + // First we will compute with the highest precision we can. + float r = 5; // same as the ellipse + float side = 2*r / (float) Math.sqrt(2); + float halfSide = side / 2f; + float x1 = 10 - halfSide; // centerX = 10 + float y1 = 10 - halfSide; // centerY = 10 + float x2 = 10 + halfSide; + float y2 = 10 + halfSide; + // Less than really accurate + assertTrue(x1 < or.getMinX()); + assertTrue(y1 < or.getMinY()); + assertTrue(x2 > or.getMaxX()); + assertTrue(y2 > or.getMaxY()); + // But not too far off + assertEquals(x1, or.getMinX(), .1f); + assertEquals(y1, or.getMinY(), .1f); + assertEquals(x2, or.getMaxX(), .1f); + assertEquals(y2, or.getMaxY(), .1f); + + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGEllipseTest.java 2015-09-11 21:24:31.453286911 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import com.sun.javafx.geom.RectBounds; -import com.sun.prism.paint.Color; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - */ -public class NGEllipseTest extends NGTestBase { - - NGEllipse ellipse; - - @Before - public void setup() { - ellipse = new NGEllipse(); - ellipse.setFillPaint(Color.RED); - ellipse.updateEllipse(10, 10, 3, 4); - } - - @Test - public void testSupportsOpaqueRegion() { - assertTrue(ellipse.supportsOpaqueRegions()); - } - - @Test - public void hasOpaqueRegionIfRadiusIsGreaterThanZero() { - assertTrue(ellipse.hasOpaqueRegion()); - ellipse.updateEllipse(10, 10, 0, 10); - assertFalse(ellipse.hasOpaqueRegion()); - ellipse.updateEllipse(10, 10, 10, 0); - assertFalse(ellipse.hasOpaqueRegion()); - ellipse.updateEllipse(10, 10, .0001f, .0001f); - assertTrue(ellipse.hasOpaqueRegion()); - } - - @Test - public void opaqueRegionLiesWithinCircle() { - RectBounds or = new RectBounds(); - // Just sort of try a range of values. They should all be good. - final float[] radiusValues = new float[] { - .001f, - 1f/3f, - (float) Math.E, - (float) Math.PI, - 10f, - 13.321f // some random number - }; - for (int i=0; i or.getMaxX()); - assertTrue(y2 > or.getMaxY()); - // But not too far off - assertEquals(x1, or.getMinX(), .1f); - assertEquals(y1, or.getMinY(), .1f); - assertEquals(x2, or.getMaxX(), .1f); - assertEquals(y2, or.getMaxY(), .1f); - - } -} - --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/NGEllipseTest.java 2015-09-11 21:24:31.317286912 -0400 @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.sg.prism.NGEllipse; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.prism.paint.Color; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + */ +public class NGEllipseTest extends NGTestBase { + + NGEllipse ellipse; + + @Before + public void setup() { + ellipse = new NGEllipse(); + ellipse.setFillPaint(Color.RED); + ellipse.updateEllipse(10, 10, 3, 4); + } + + @Test + public void testSupportsOpaqueRegion() { + assertTrue(NGNodeShim.supportsOpaqueRegions(ellipse)); + } + + @Test + public void hasOpaqueRegionIfRadiusIsGreaterThanZero() { + assertTrue(NGNodeShim.hasOpaqueRegion(ellipse)); + ellipse.updateEllipse(10, 10, 0, 10); + assertFalse(NGNodeShim.hasOpaqueRegion(ellipse)); + ellipse.updateEllipse(10, 10, 10, 0); + assertFalse(NGNodeShim.hasOpaqueRegion(ellipse)); + ellipse.updateEllipse(10, 10, .0001f, .0001f); + assertTrue(NGNodeShim.hasOpaqueRegion(ellipse)); + } + + @Test + public void opaqueRegionLiesWithinCircle() { + RectBounds or = new RectBounds(); + // Just sort of try a range of values. They should all be good. + final float[] radiusValues = new float[] { + .001f, + 1f/3f, + (float) Math.E, + (float) Math.PI, + 10f, + 13.321f // some random number + }; + for (int i=0; i or.getMaxX()); + assertTrue(y2 > or.getMaxY()); + // But not too far off + assertEquals(x1, or.getMinX(), .1f); + assertEquals(y1, or.getMinY(), .1f); + assertEquals(x2, or.getMaxX(), .1f); + assertEquals(y2, or.getMaxY(), .1f); + + } +} + --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGImageViewTest.java 2015-09-11 21:24:32.129286903 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import com.sun.javafx.geom.RectBounds; -import com.sun.prism.Image; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - */ -public class NGImageViewTest extends NGTestBase { - static final byte[] ICON_PIXELS = new byte[16*16]; - static final Image ICON = Image.fromByteRgbData(ICON_PIXELS, 16, 16); - - NGImageView imageView; - - @Before - public void setup() { - imageView = new NGImageView(); - imageView.setImage(ICON); - imageView.setX(10); - imageView.setY(10); - imageView.setViewport(0, 0, 0, 0, 16, 16); - } - - /** - * ImageView always reports true for this - */ - @Test - public void testSupportsOpaqueRegion() { - assertTrue(imageView.supportsOpaqueRegions()); - } - - /** - * In the configured state it should report true - */ - @Test - public void hasOpaqueRegionWithNonEmptyImage() { - assertTrue(imageView.hasOpaqueRegion()); - } - - /** - * Tests when the view port is modified (not sure if I'm modifying the - * view port exactly correctly...) - */ - @Test - public void hasOpaqueRegionIfViewPortGreaterThanOne() { - assertTrue(imageView.hasOpaqueRegion()); - imageView.setViewport(0, 0, 2, 2, 16, 16); - assertTrue(imageView.hasOpaqueRegion()); - imageView.setViewport(0, 0, 1, 1, 16, 16); - assertTrue(imageView.hasOpaqueRegion()); - imageView.setViewport(0, 0, 0, 0, .1f, .1f); - assertFalse(imageView.hasOpaqueRegion()); - } - - /** - * Null images should return false for hasOpaqueImage - */ - @Test - public void doesNotHaveOpaqueRegionForNullImage() { - imageView.setImage(null); - assertFalse(imageView.hasOpaqueRegion()); - } - - /** - * Simple test should match bounds for opaque image - */ - @Test - public void computeOpaqueRegionForWholeNumbers() { - assertEquals(new RectBounds(10, 10, 26, 26), imageView.computeOpaqueRegion(new RectBounds())); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/NGImageViewTest.java 2015-09-11 21:24:31.989286905 -0400 @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.sg.prism.NGImageView; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.prism.Image; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + */ +public class NGImageViewTest extends NGTestBase { + static final byte[] ICON_PIXELS = new byte[16*16]; + static final Image ICON = Image.fromByteRgbData(ICON_PIXELS, 16, 16); + + NGImageView imageView; + + @Before + public void setup() { + imageView = new NGImageView(); + imageView.setImage(ICON); + imageView.setX(10); + imageView.setY(10); + imageView.setViewport(0, 0, 0, 0, 16, 16); + } + + /** + * ImageView always reports true for this + */ + @Test + public void testSupportsOpaqueRegion() { + assertTrue(NGNodeShim.supportsOpaqueRegions(imageView)); + } + + /** + * In the configured state it should report true + */ + @Test + public void hasOpaqueRegionWithNonEmptyImage() { + assertTrue(NGNodeShim.hasOpaqueRegion(imageView)); + } + + /** + * Tests when the view port is modified (not sure if I'm modifying the + * view port exactly correctly...) + */ + @Test + public void hasOpaqueRegionIfViewPortGreaterThanOne() { + assertTrue(NGNodeShim.hasOpaqueRegion(imageView)); + imageView.setViewport(0, 0, 2, 2, 16, 16); + assertTrue(NGNodeShim.hasOpaqueRegion(imageView)); + imageView.setViewport(0, 0, 1, 1, 16, 16); + assertTrue(NGNodeShim.hasOpaqueRegion(imageView)); + imageView.setViewport(0, 0, 0, 0, .1f, .1f); + assertFalse(NGNodeShim.hasOpaqueRegion(imageView)); + } + + /** + * Null images should return false for hasOpaqueImage + */ + @Test + public void doesNotHaveOpaqueRegionForNullImage() { + imageView.setImage(null); + assertFalse(NGNodeShim.hasOpaqueRegion(imageView)); + } + + /** + * Simple test should match bounds for opaque image + */ + @Test + public void computeOpaqueRegionForWholeNumbers() { + assertEquals(new RectBounds(10, 10, 26, 26), + NGNodeShim.computeOpaqueRegion(imageView, new RectBounds())); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGNodeTest.java 2015-09-11 21:24:32.753286896 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,645 +0,0 @@ -/* - * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import com.sun.javafx.geom.BaseBounds; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.Rectangle; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.prism.Graphics; -import com.sun.prism.paint.Color; -import com.sun.scenario.effect.Blend; -import com.sun.scenario.effect.Effect; -import com.sun.scenario.effect.FilterContext; -import com.sun.scenario.effect.ImageData; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -/** - */ -public class NGNodeTest extends NGTestBase { - NGNodeMock n; - - @Before - public void setup() { - n = new NGNodeMock(); - } - - /************************************************************************** - * * - * Various tests for hasOpaqueRegion * - * * - *************************************************************************/ - - @Test - public void hasOpaqueRegionIsFalseIfOpacityIsLessThanOne() { - n.setOpacity(1); - assertTrue(n.hasOpaqueRegion()); - - n.setOpacity(.5f); - assertFalse(n.hasOpaqueRegion()); - - n.setOpacity(0); - assertFalse(n.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionIsFalseIfEffectIsNotNullAndEffect_reducesOpaquePixels_returnsFalse() { - n.setEffect(new TransparentEffect()); - assertFalse(n.hasOpaqueRegion()); - n.setEffect(null); - assertTrue(n.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionIsTrueIfEffectIsNotNullAndEffect_reducesOpaquePixels_returnsTrue() { - n.setEffect(new OpaqueEffect()); - assertTrue(n.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionIsTrueIfClipIsNullOrHappy() { - n.setClipNode(null); - assertTrue(n.hasOpaqueRegion()); - - NGRectangle r = new NGRectangle(); - r.updateRectangle(0, 0, 10, 10, 0, 0); - r.setFillPaint(Color.BLACK); - n.setClipNode(r); - - assertTrue(n.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionIsFalseIfClipDoesNotSupportOpaqueRegions() { - n.setClipNode(new NGPath()); - assertFalse(n.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionIsFalseIfClipDoesNotHaveAnOpaqueRegion() { - NGRectangle r = new NGRectangle(); - n.setClipNode(r); - assertFalse(n.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionIsFalseIfBlendModeIsNotNullOrSRC_OVER() { - for (Blend.Mode mode : Blend.Mode.values()) { - // Set blend mode - n.setNodeBlendMode(mode); - if (mode == Blend.Mode.SRC_OVER) { - assertTrue(n.hasOpaqueRegion()); - } else { - assertFalse(n.hasOpaqueRegion()); - } - } - n.setNodeBlendMode(null); - assertTrue(n.hasOpaqueRegion()); - } - - /************************************************************************** - * * - * Various tests for opaque region caching and invalidation * - * * - *************************************************************************/ - - /** - * The same opaqueRegion instance should be reused every time, unless - * we transition to a state where opaqueRegion is not true, in which case - * opaqueRegion will be null. - */ - @Test - public void opaqueRegionCached() { - RectBounds or = n.getOpaqueRegion(); - assertNotNull(or); - - // Simulating changing state that would result in a different opaque region - // but should be the same instance - n.changeOpaqueRegion(10, 10, 100, 100); - assertSame(or, n.getOpaqueRegion()); - - // Changing to something that will cause the hasOpaqueRegions to return false - n.setEffect(new TransparentEffect()); - assertNull(n.getOpaqueRegion()); - - // Change back to something that will work and get a different instance - n.setEffect(null); - assertNotSame(or, n.getOpaqueRegion()); - } - - /** - * Test that as long as the opaque region is valid, that we don't - * try to compute a new one - */ - @Test - public void opaqueRegionCached2() { - // Cause it to be cached - n.getOpaqueRegion(); - n.opaqueRegionRecomputed = false; - - // Just calling it again should do nothing - n.getOpaqueRegion(); - assertFalse(n.opaqueRegionRecomputed); - } - - /** - * If the transform is changed, we need to recompute the opaque region. But - * if the transform is not changed, then we shouldn't. Since NGNode doesn't keep - * a reference to the last transform object it was passed and doesn't perform - * any kind of check, we're going to invalidate the opaque region every time - * it is called. If we change that behavior later, this test will need to be - * updated accordingly. - */ - @Test - public void opaqueRegionRecomputedWhenTransformChanges() { - n.getOpaqueRegion(); - - n.opaqueRegionRecomputed = false; - n.setTransformMatrix(BaseTransform.getTranslateInstance(1, 1)); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - n.opaqueRegionRecomputed = false; - n.setTransformMatrix(BaseTransform.getTranslateInstance(1, 1)); - n.getOpaqueRegion(); - assertFalse(n.opaqueRegionRecomputed); - - n.opaqueRegionRecomputed = false; - n.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - n.opaqueRegionRecomputed = false; - n.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); - n.getOpaqueRegion(); - assertFalse(n.opaqueRegionRecomputed); - } - - /** - * If we change references to the clip node, then we must recompute the - * opaque region, regardless of whether we set the reference to a - * different equivalent guy (since we don't check for equals and without - * doing deep equals it would fail anyway) - */ - @Test - public void opaqueRegionRecomputedWhenClipNodeReferenceChanges() { - n.getOpaqueRegion(); - - // I'm setting a clip, and even though the clip isn't opaque, - // I will have to ask the hasOpaqueRegions question again - n.opaqueRegionRecomputed = false; - NGRectangle clip = new NGRectangle(); - n.setClipNode(clip); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set the same clip instance again, which should have no effect - n.opaqueRegionRecomputed = false; - n.setClipNode(clip); - n.getOpaqueRegion(); - assertFalse(n.opaqueRegionRecomputed); - - // Try out a nice clip, this time with a nice opaque region. - n.opaqueRegionRecomputed = false; - clip = new NGRectangle(); - clip.updateRectangle(0, 0, 10, 10, 0, 0); - clip.setFillPaint(Color.BLACK); - n.setClipNode(clip); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Try out an equivalent, but different instance, clip. - n.opaqueRegionRecomputed = false; - clip = new NGRectangle(); - clip.updateRectangle(0, 0, 10, 10, 0, 0); - clip.setFillPaint(Color.BLACK); - n.setClipNode(clip); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set it to null - n.opaqueRegionRecomputed = false; - n.setClipNode(null); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set it to null again, which should have no effect - n.opaqueRegionRecomputed = false; - n.setClipNode(null); - n.getOpaqueRegion(); - assertFalse(n.opaqueRegionRecomputed); - } - - /************************************************************************** - * * - * Various tests for opaque region caching and invalidation * - * * - *************************************************************************/ - - /** - * If one of the inputs to the "hasOpaqueRegions" changes in such a way - * that we have to recompute the opaque region for the clip, then we - * also need to recompute the opaque region of the node being clipped! - */ - @Test - public void opaqueRegionRecomputedWhenClipNodeHasOpaqueRegionChanges() { - n.getOpaqueRegion(); - - // Start off with a clip which supports an opaque region - n.opaqueRegionRecomputed = false; - NGRectangle clip = new NGRectangle(); - clip.updateRectangle(0, 0, 10, 10, 0, 0); - clip.setFillPaint(Color.BLACK); - n.setClipNode(clip); - n.getOpaqueRegion(); - - // Switch the clip so that it doesn't any longer - n.opaqueRegionRecomputed = false; - clip.setFillPaint(null); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Switch back to the clip so that it does - n.opaqueRegionRecomputed = false; - clip.setFillPaint(Color.WHITE); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - } - - /** - * If the opacity switches from 1 to a value < 1, then we must recompute - * the opaque region (the answer will always be false! I guess if we were - * really clever we could just set opaque region to null in this case and - * set "invalid" to false!) - */ - @Test - public void opaqueRegionRecomputedWhenOpacityGoesFromOneToLessThanOne() { - n.getOpaqueRegion(); - - // Change to less than one - n.opaqueRegionRecomputed = false; - n.setOpacity(.9f); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Change to one again - n.opaqueRegionRecomputed = false; - n.setOpacity(1f); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Change to one again! - n.opaqueRegionRecomputed = false; - n.setOpacity(1f); - n.getOpaqueRegion(); - assertFalse(n.opaqueRegionRecomputed); - - // Change to zero. Note that changing to 0 doesn't mean that we have - // to invalidate the opaque region, because a 0 opacity node will never - // be asked for its opaque region, but we do it anyway :-(. - n.opaqueRegionRecomputed = false; - n.setOpacity(0f); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - } - - /** - * Tests for handling what happens as we toggle between Zero and other values. - */ - @Test - public void opaqueRegionRecomputedWhenOpacityGoesFromZeroToMoreThanZero() { - n.setOpacity(0f); - n.getOpaqueRegion(); - - // Change to > 0 and < 1 - n.opaqueRegionRecomputed = false; - n.setOpacity(.9f); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Change to zero again - n.opaqueRegionRecomputed = false; - n.setOpacity(0f); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Change to zero again! - n.opaqueRegionRecomputed = false; - n.setOpacity(0f); - n.getOpaqueRegion(); - assertFalse(n.opaqueRegionRecomputed); - - // Change to one - n.opaqueRegionRecomputed = false; - n.setOpacity(1f); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - } - - /** - * If the opacity changes between 0 and 1, there is no point invalidating the - * opaqueRegion since it will always remain disabled in this range. - */ - @Test - public void opaqueRegionNotRecomputedWhenOpacityNeverGoesToOneOrZero() { - n.setOpacity(.1f); - n.getOpaqueRegion(); - - for (float f=.1f; f<.9f; f+=.1) { - // Change to > 0 and < 1 - n.opaqueRegionRecomputed = false; - n.setOpacity(f); - n.getOpaqueRegion(); - assertFalse(n.opaqueRegionRecomputed); - } - } - - // Note that when depth buffer is enabled we should NEVER be asking for the opaque - // region, so we don't do anything special in terms of invalidating the opaque region - - @Test - public void opaqueRegionRecomputedWhenBlendModeChanges() { - n.getOpaqueRegion(); - - for (Blend.Mode mode : Blend.Mode.values()) { - // Set blend mode - n.opaqueRegionRecomputed = false; - n.setNodeBlendMode(mode); - n.getOpaqueRegion(); - if (mode == Blend.Mode.SRC_OVER) continue; - assertTrue(n.opaqueRegionRecomputed); - - // Set back to null - n.opaqueRegionRecomputed = false; - n.setNodeBlendMode(null); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set to SRC_OVER (should recompute even though it may be a NOP) - // For leaf nodes it is a NOP, but for groups there is a difference - n.opaqueRegionRecomputed = false; - n.setNodeBlendMode(Blend.Mode.SRC_OVER); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set to blend mode (should do it) - n.opaqueRegionRecomputed = false; - n.setNodeBlendMode(mode); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set back to SRC_OVER (should do it) - n.opaqueRegionRecomputed = false; - n.setNodeBlendMode(Blend.Mode.SRC_OVER); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set back to null - n.opaqueRegionRecomputed = false; - n.setNodeBlendMode(null); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - } - } - - /** - * If we change references to the effect, we're might have to - * figure things out again. Right now, we only pay attention to changes - * from null to not-null (and vice versa). To enable opaque regions for - * effects, we need to be notified by the effect whenever the effect - * changes in such a way as to impact whether it can participate in - * opaque regions. - */ - @Test - public void opaqueRegionNotRecomputedWhenEffectReferenceChanges() { - n.getOpaqueRegion(); - - // Set some effect (was null) - n.opaqueRegionRecomputed = false; - n.setEffect(new TransparentEffect()); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Change to some effect which messes with alpha. - n.opaqueRegionRecomputed = false; - n.setEffect(new TransparentEffect()); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Change to null. - n.opaqueRegionRecomputed = false; - n.setEffect(null); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Change to some effect that messes with alpha - n.opaqueRegionRecomputed = false; - Effect effect = new TransparentEffect(); - n.setEffect(effect); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set the same effect again! Right now we simply recompute - // every time if an effect may mess with alpha - n.opaqueRegionRecomputed = false; - n.setEffect(effect); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set the effect to be one that will never mess with alpha - n.opaqueRegionRecomputed = false; - effect = new OpaqueEffect(); - n.setEffect(effect); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set it to the same instance. Right now we simply recompute - // every time if an effect may mess with alpha - n.opaqueRegionRecomputed = false; - n.setEffect(effect); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - - // Set it to another instance that also doesn't mess with alpha. - // Right now we simply recompute every time if an effect may mess with alpha - n.opaqueRegionRecomputed = false; - n.setEffect(new OpaqueEffect()); - n.getOpaqueRegion(); - assertTrue(n.opaqueRegionRecomputed); - } - - /************************************************************************** - * * - * getOpaqueRegion tests * - * * - *************************************************************************/ - - @Test - public void testGetOpaqueRegionReturnsNullIf_supportsOpaqueRegion_returnsFalse() { - NGPath path = new NGPath(); - path.setFillPaint(Color.BLACK); - assertNull(path.getOpaqueRegion()); - } - - @Test public void testGetOpaqueRegionReturnsNullIf_hasOpaqueRegion_returnsFalse() { - n.setEffect(new TransparentEffect()); - assertNull(n.getOpaqueRegion()); - } - - @Test public void testGetOpaqueRegionWithNoClip() { - assertEquals(new RectBounds(0, 0, 10, 10), n.getOpaqueRegion()); - } - - @Test public void testGetOpaqueRegionWithSimpleRectangleClip() { - NGRectangle clip = new NGRectangle(); - clip.setFillPaint(Color.BLACK); - clip.updateRectangle(3, 3, 4, 4, 0, 0); - n.setClipNode(clip); - assertEquals(new RectBounds(3, 3, 7, 7), n.getOpaqueRegion()); - } - - @Test public void testGetOpaqueRegionWithSimpleRectangleClipWithNoFill() { - NGRectangle clip = new NGRectangle(); - clip.updateRectangle(3, 3, 4, 4, 0, 0); - n.setClipNode(clip); - assertNull(n.getOpaqueRegion()); - } - - @Test public void testGetOpaqueRegionWithTranslatedRectangleClip() { - NGRectangle clip = new NGRectangle(); - clip.setFillPaint(Color.BLACK); - clip.updateRectangle(0, 0, 4, 4, 0, 0); - clip.setTransformMatrix(BaseTransform.getTranslateInstance(2, 2)); - n.setClipNode(clip); - assertEquals(new RectBounds(2, 2, 6, 6), n.getOpaqueRegion()); - } - - @Test public void testGetOpaqueRegionWithScaledRectangleClip() { - NGRectangle clip = new NGRectangle(); - clip.setFillPaint(Color.BLACK); - clip.updateRectangle(0, 0, 4, 4, 0, 0); - clip.setTransformMatrix(BaseTransform.getScaleInstance(.5, .5)); - n.setClipNode(clip); - assertEquals(new RectBounds(0, 0, 2, 2), n.getOpaqueRegion()); - } - - @Test public void testGetOpaqueRegionWithTranslatedAndScaledRectangleClip() { - NGRectangle clip = new NGRectangle(); - clip.setFillPaint(Color.BLACK); - clip.updateRectangle(0, 0, 4, 4, 0, 0); - clip.setTransformMatrix( - BaseTransform.getTranslateInstance(2, 2).deriveWithConcatenation( - BaseTransform.getScaleInstance(.5, .5))); - n.setClipNode(clip); - assertEquals(new RectBounds(2, 2, 4, 4), n.getOpaqueRegion()); - } - - @Test public void testGetOpaqueRegionWithRotatedRectangleClip() { - NGRectangle clip = new NGRectangle(); - clip.setFillPaint(Color.BLACK); - clip.updateRectangle(0, 0, 4, 4, 0, 0); - clip.setTransformMatrix(BaseTransform.getRotateInstance(45, 5, 5)); - n.setClipNode(clip); - assertNull(n.getOpaqueRegion()); - } - - class NGNodeMock extends NGNode { - boolean opaqueRegionRecomputed = false; - RectBounds computedOpaqueRegion = new RectBounds(0, 0, 10, 10); - - void changeOpaqueRegion(float x, float y, float x2, float y2) { - computedOpaqueRegion = new RectBounds(x, y, x2, y2); - geometryChanged(); - } - - @Override - protected boolean hasOpaqueRegion() { - opaqueRegionRecomputed = true; - return super.hasOpaqueRegion() && computedOpaqueRegion != null; - } - - @Override - protected RectBounds computeOpaqueRegion(RectBounds opaqueRegion) { - opaqueRegionRecomputed = true; - assert computedOpaqueRegion != null; - return (RectBounds) opaqueRegion.deriveWithNewBounds(computedOpaqueRegion); - } - - @Override - protected void renderContent(Graphics g) { } - - @Override - protected boolean hasOverlappingContents() { - return false; - } - - @Override - protected boolean supportsOpaqueRegions() { - return true; - } - } - - static abstract class MockEffect extends Effect { - - @Override - public ImageData filter(FilterContext fctx, BaseTransform transform, Rectangle outputClip, Object renderHelper, Effect defaultInput) { - return null; - } - - @Override - public BaseBounds getBounds(BaseTransform transform, Effect defaultInput) { - return null; - } - - @Override - public AccelType getAccelType(FilterContext fctx) { - return AccelType.OPENGL; - } - } - - class TransparentEffect extends MockEffect { - @Override - public boolean reducesOpaquePixels() { - return true; - } - } - - class OpaqueEffect extends MockEffect { - @Override - public boolean reducesOpaquePixels() { - return false; - } - - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/NGNodeTest.java 2015-09-11 21:24:32.617286898 -0400 @@ -0,0 +1,650 @@ +/* + * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.Rectangle; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.javafx.sg.prism.NGPath; +import com.sun.javafx.sg.prism.NGRectangle; +import com.sun.prism.Graphics; +import com.sun.prism.paint.Color; +import com.sun.scenario.effect.Blend; +import com.sun.scenario.effect.Effect; +import com.sun.scenario.effect.FilterContext; +import com.sun.scenario.effect.ImageData; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + */ +public class NGNodeTest extends NGTestBase { + NGNodeMock n; + + @Before + public void setup() { + n = new NGNodeMock(); + } + + /************************************************************************** + * * + * Various tests for hasOpaqueRegion * + * * + *************************************************************************/ + + @Test + public void hasOpaqueRegionIsFalseIfOpacityIsLessThanOne() { + n.setOpacity(1); + assertTrue(n.hasOpaqueRegion()); + + n.setOpacity(.5f); + assertFalse(n.hasOpaqueRegion()); + + n.setOpacity(0); + assertFalse(n.hasOpaqueRegion()); + } + + @Test + public void hasOpaqueRegionIsFalseIfEffectIsNotNullAndEffect_reducesOpaquePixels_returnsFalse() { + n.setEffect(new TransparentEffect()); + assertFalse(n.hasOpaqueRegion()); + n.setEffect(null); + assertTrue(n.hasOpaqueRegion()); + } + + @Test + public void hasOpaqueRegionIsTrueIfEffectIsNotNullAndEffect_reducesOpaquePixels_returnsTrue() { + n.setEffect(new OpaqueEffect()); + assertTrue(n.hasOpaqueRegion()); + } + + @Test + public void hasOpaqueRegionIsTrueIfClipIsNullOrHappy() { + n.setClipNode(null); + assertTrue(n.hasOpaqueRegion()); + + NGRectangle r = new NGRectangle(); + r.updateRectangle(0, 0, 10, 10, 0, 0); + r.setFillPaint(Color.BLACK); + n.setClipNode(r); + + assertTrue(n.hasOpaqueRegion()); + } + + @Test + public void hasOpaqueRegionIsFalseIfClipDoesNotSupportOpaqueRegions() { + n.setClipNode(new NGPath()); + assertFalse(n.hasOpaqueRegion()); + } + + @Test + public void hasOpaqueRegionIsFalseIfClipDoesNotHaveAnOpaqueRegion() { + NGRectangle r = new NGRectangle(); + n.setClipNode(r); + assertFalse(n.hasOpaqueRegion()); + } + + @Test + public void hasOpaqueRegionIsFalseIfBlendModeIsNotNullOrSRC_OVER() { + for (Blend.Mode mode : Blend.Mode.values()) { + // Set blend mode + n.setNodeBlendMode(mode); + if (mode == Blend.Mode.SRC_OVER) { + assertTrue(n.hasOpaqueRegion()); + } else { + assertFalse(n.hasOpaqueRegion()); + } + } + n.setNodeBlendMode(null); + assertTrue(n.hasOpaqueRegion()); + } + + /************************************************************************** + * * + * Various tests for opaque region caching and invalidation * + * * + *************************************************************************/ + + /** + * The same opaqueRegion instance should be reused every time, unless + * we transition to a state where opaqueRegion is not true, in which case + * opaqueRegion will be null. + */ + @Test + public void opaqueRegionCached() { + RectBounds or = n.getOpaqueRegion(); + assertNotNull(or); + + // Simulating changing state that would result in a different opaque region + // but should be the same instance + n.changeOpaqueRegion(10, 10, 100, 100); + assertSame(or, n.getOpaqueRegion()); + + // Changing to something that will cause the hasOpaqueRegions to return false + n.setEffect(new TransparentEffect()); + assertNull(n.getOpaqueRegion()); + + // Change back to something that will work and get a different instance + n.setEffect(null); + assertNotSame(or, n.getOpaqueRegion()); + } + + /** + * Test that as long as the opaque region is valid, that we don't + * try to compute a new one + */ + @Test + public void opaqueRegionCached2() { + // Cause it to be cached + n.getOpaqueRegion(); + n.opaqueRegionRecomputed = false; + + // Just calling it again should do nothing + n.getOpaqueRegion(); + assertFalse(n.opaqueRegionRecomputed); + } + + /** + * If the transform is changed, we need to recompute the opaque region. But + * if the transform is not changed, then we shouldn't. Since NGNode doesn't keep + * a reference to the last transform object it was passed and doesn't perform + * any kind of check, we're going to invalidate the opaque region every time + * it is called. If we change that behavior later, this test will need to be + * updated accordingly. + */ + @Test + public void opaqueRegionRecomputedWhenTransformChanges() { + n.getOpaqueRegion(); + + n.opaqueRegionRecomputed = false; + n.setTransformMatrix(BaseTransform.getTranslateInstance(1, 1)); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + n.opaqueRegionRecomputed = false; + n.setTransformMatrix(BaseTransform.getTranslateInstance(1, 1)); + n.getOpaqueRegion(); + assertFalse(n.opaqueRegionRecomputed); + + n.opaqueRegionRecomputed = false; + n.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + n.opaqueRegionRecomputed = false; + n.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); + n.getOpaqueRegion(); + assertFalse(n.opaqueRegionRecomputed); + } + + /** + * If we change references to the clip node, then we must recompute the + * opaque region, regardless of whether we set the reference to a + * different equivalent guy (since we don't check for equals and without + * doing deep equals it would fail anyway) + */ + @Test + public void opaqueRegionRecomputedWhenClipNodeReferenceChanges() { + n.getOpaqueRegion(); + + // I'm setting a clip, and even though the clip isn't opaque, + // I will have to ask the hasOpaqueRegions question again + n.opaqueRegionRecomputed = false; + NGRectangle clip = new NGRectangle(); + n.setClipNode(clip); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set the same clip instance again, which should have no effect + n.opaqueRegionRecomputed = false; + n.setClipNode(clip); + n.getOpaqueRegion(); + assertFalse(n.opaqueRegionRecomputed); + + // Try out a nice clip, this time with a nice opaque region. + n.opaqueRegionRecomputed = false; + clip = new NGRectangle(); + clip.updateRectangle(0, 0, 10, 10, 0, 0); + clip.setFillPaint(Color.BLACK); + n.setClipNode(clip); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Try out an equivalent, but different instance, clip. + n.opaqueRegionRecomputed = false; + clip = new NGRectangle(); + clip.updateRectangle(0, 0, 10, 10, 0, 0); + clip.setFillPaint(Color.BLACK); + n.setClipNode(clip); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set it to null + n.opaqueRegionRecomputed = false; + n.setClipNode(null); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set it to null again, which should have no effect + n.opaqueRegionRecomputed = false; + n.setClipNode(null); + n.getOpaqueRegion(); + assertFalse(n.opaqueRegionRecomputed); + } + + /************************************************************************** + * * + * Various tests for opaque region caching and invalidation * + * * + *************************************************************************/ + + /** + * If one of the inputs to the "hasOpaqueRegions" changes in such a way + * that we have to recompute the opaque region for the clip, then we + * also need to recompute the opaque region of the node being clipped! + */ + @Test + public void opaqueRegionRecomputedWhenClipNodeHasOpaqueRegionChanges() { + n.getOpaqueRegion(); + + // Start off with a clip which supports an opaque region + n.opaqueRegionRecomputed = false; + NGRectangle clip = new NGRectangle(); + clip.updateRectangle(0, 0, 10, 10, 0, 0); + clip.setFillPaint(Color.BLACK); + n.setClipNode(clip); + n.getOpaqueRegion(); + + // Switch the clip so that it doesn't any longer + n.opaqueRegionRecomputed = false; + clip.setFillPaint(null); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Switch back to the clip so that it does + n.opaqueRegionRecomputed = false; + clip.setFillPaint(Color.WHITE); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + } + + /** + * If the opacity switches from 1 to a value < 1, then we must recompute + * the opaque region (the answer will always be false! I guess if we were + * really clever we could just set opaque region to null in this case and + * set "invalid" to false!) + */ + @Test + public void opaqueRegionRecomputedWhenOpacityGoesFromOneToLessThanOne() { + n.getOpaqueRegion(); + + // Change to less than one + n.opaqueRegionRecomputed = false; + n.setOpacity(.9f); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Change to one again + n.opaqueRegionRecomputed = false; + n.setOpacity(1f); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Change to one again! + n.opaqueRegionRecomputed = false; + n.setOpacity(1f); + n.getOpaqueRegion(); + assertFalse(n.opaqueRegionRecomputed); + + // Change to zero. Note that changing to 0 doesn't mean that we have + // to invalidate the opaque region, because a 0 opacity node will never + // be asked for its opaque region, but we do it anyway :-(. + n.opaqueRegionRecomputed = false; + n.setOpacity(0f); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + } + + /** + * Tests for handling what happens as we toggle between Zero and other values. + */ + @Test + public void opaqueRegionRecomputedWhenOpacityGoesFromZeroToMoreThanZero() { + n.setOpacity(0f); + n.getOpaqueRegion(); + + // Change to > 0 and < 1 + n.opaqueRegionRecomputed = false; + n.setOpacity(.9f); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Change to zero again + n.opaqueRegionRecomputed = false; + n.setOpacity(0f); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Change to zero again! + n.opaqueRegionRecomputed = false; + n.setOpacity(0f); + n.getOpaqueRegion(); + assertFalse(n.opaqueRegionRecomputed); + + // Change to one + n.opaqueRegionRecomputed = false; + n.setOpacity(1f); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + } + + /** + * If the opacity changes between 0 and 1, there is no point invalidating the + * opaqueRegion since it will always remain disabled in this range. + */ + @Test + public void opaqueRegionNotRecomputedWhenOpacityNeverGoesToOneOrZero() { + n.setOpacity(.1f); + n.getOpaqueRegion(); + + for (float f=.1f; f<.9f; f+=.1) { + // Change to > 0 and < 1 + n.opaqueRegionRecomputed = false; + n.setOpacity(f); + n.getOpaqueRegion(); + assertFalse(n.opaqueRegionRecomputed); + } + } + + // Note that when depth buffer is enabled we should NEVER be asking for the opaque + // region, so we don't do anything special in terms of invalidating the opaque region + + @Test + public void opaqueRegionRecomputedWhenBlendModeChanges() { + n.getOpaqueRegion(); + + for (Blend.Mode mode : Blend.Mode.values()) { + // Set blend mode + n.opaqueRegionRecomputed = false; + n.setNodeBlendMode(mode); + n.getOpaqueRegion(); + if (mode == Blend.Mode.SRC_OVER) continue; + assertTrue(n.opaqueRegionRecomputed); + + // Set back to null + n.opaqueRegionRecomputed = false; + n.setNodeBlendMode(null); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set to SRC_OVER (should recompute even though it may be a NOP) + // For leaf nodes it is a NOP, but for groups there is a difference + n.opaqueRegionRecomputed = false; + n.setNodeBlendMode(Blend.Mode.SRC_OVER); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set to blend mode (should do it) + n.opaqueRegionRecomputed = false; + n.setNodeBlendMode(mode); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set back to SRC_OVER (should do it) + n.opaqueRegionRecomputed = false; + n.setNodeBlendMode(Blend.Mode.SRC_OVER); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set back to null + n.opaqueRegionRecomputed = false; + n.setNodeBlendMode(null); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + } + } + + /** + * If we change references to the effect, we're might have to + * figure things out again. Right now, we only pay attention to changes + * from null to not-null (and vice versa). To enable opaque regions for + * effects, we need to be notified by the effect whenever the effect + * changes in such a way as to impact whether it can participate in + * opaque regions. + */ + @Test + public void opaqueRegionNotRecomputedWhenEffectReferenceChanges() { + n.getOpaqueRegion(); + + // Set some effect (was null) + n.opaqueRegionRecomputed = false; + n.setEffect(new TransparentEffect()); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Change to some effect which messes with alpha. + n.opaqueRegionRecomputed = false; + n.setEffect(new TransparentEffect()); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Change to null. + n.opaqueRegionRecomputed = false; + n.setEffect(null); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Change to some effect that messes with alpha + n.opaqueRegionRecomputed = false; + Effect effect = new TransparentEffect(); + n.setEffect(effect); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set the same effect again! Right now we simply recompute + // every time if an effect may mess with alpha + n.opaqueRegionRecomputed = false; + n.setEffect(effect); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set the effect to be one that will never mess with alpha + n.opaqueRegionRecomputed = false; + effect = new OpaqueEffect(); + n.setEffect(effect); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set it to the same instance. Right now we simply recompute + // every time if an effect may mess with alpha + n.opaqueRegionRecomputed = false; + n.setEffect(effect); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + + // Set it to another instance that also doesn't mess with alpha. + // Right now we simply recompute every time if an effect may mess with alpha + n.opaqueRegionRecomputed = false; + n.setEffect(new OpaqueEffect()); + n.getOpaqueRegion(); + assertTrue(n.opaqueRegionRecomputed); + } + + /************************************************************************** + * * + * getOpaqueRegion tests * + * * + *************************************************************************/ + + @Test + public void testGetOpaqueRegionReturnsNullIf_supportsOpaqueRegion_returnsFalse() { + NGPath path = new NGPath(); + path.setFillPaint(Color.BLACK); + assertNull(path.getOpaqueRegion()); + } + + @Test public void testGetOpaqueRegionReturnsNullIf_hasOpaqueRegion_returnsFalse() { + n.setEffect(new TransparentEffect()); + assertNull(n.getOpaqueRegion()); + } + + @Test public void testGetOpaqueRegionWithNoClip() { + assertEquals(new RectBounds(0, 0, 10, 10), n.getOpaqueRegion()); + } + + @Test public void testGetOpaqueRegionWithSimpleRectangleClip() { + NGRectangle clip = new NGRectangle(); + clip.setFillPaint(Color.BLACK); + clip.updateRectangle(3, 3, 4, 4, 0, 0); + n.setClipNode(clip); + assertEquals(new RectBounds(3, 3, 7, 7), n.getOpaqueRegion()); + } + + @Test public void testGetOpaqueRegionWithSimpleRectangleClipWithNoFill() { + NGRectangle clip = new NGRectangle(); + clip.updateRectangle(3, 3, 4, 4, 0, 0); + n.setClipNode(clip); + assertNull(n.getOpaqueRegion()); + } + + @Test public void testGetOpaqueRegionWithTranslatedRectangleClip() { + NGRectangle clip = new NGRectangle(); + clip.setFillPaint(Color.BLACK); + clip.updateRectangle(0, 0, 4, 4, 0, 0); + clip.setTransformMatrix(BaseTransform.getTranslateInstance(2, 2)); + n.setClipNode(clip); + assertEquals(new RectBounds(2, 2, 6, 6), n.getOpaqueRegion()); + } + + @Test public void testGetOpaqueRegionWithScaledRectangleClip() { + NGRectangle clip = new NGRectangle(); + clip.setFillPaint(Color.BLACK); + clip.updateRectangle(0, 0, 4, 4, 0, 0); + clip.setTransformMatrix(BaseTransform.getScaleInstance(.5, .5)); + n.setClipNode(clip); + assertEquals(new RectBounds(0, 0, 2, 2), n.getOpaqueRegion()); + } + + @Test public void testGetOpaqueRegionWithTranslatedAndScaledRectangleClip() { + NGRectangle clip = new NGRectangle(); + clip.setFillPaint(Color.BLACK); + clip.updateRectangle(0, 0, 4, 4, 0, 0); + clip.setTransformMatrix( + BaseTransform.getTranslateInstance(2, 2).deriveWithConcatenation( + BaseTransform.getScaleInstance(.5, .5))); + n.setClipNode(clip); + assertEquals(new RectBounds(2, 2, 4, 4), n.getOpaqueRegion()); + } + + @Test public void testGetOpaqueRegionWithRotatedRectangleClip() { + NGRectangle clip = new NGRectangle(); + clip.setFillPaint(Color.BLACK); + clip.updateRectangle(0, 0, 4, 4, 0, 0); + clip.setTransformMatrix(BaseTransform.getRotateInstance(45, 5, 5)); + n.setClipNode(clip); + assertNull(n.getOpaqueRegion()); + } + + class NGNodeMock extends NGNodeShim { + boolean opaqueRegionRecomputed = false; + RectBounds computedOpaqueRegion = new RectBounds(0, 0, 10, 10); + + void changeOpaqueRegion(float x, float y, float x2, float y2) { + computedOpaqueRegion = new RectBounds(x, y, x2, y2); + geometryChanged(); + } + + @Override + public boolean hasOpaqueRegion() { + opaqueRegionRecomputed = true; + return super.hasOpaqueRegion() + && computedOpaqueRegion != null; + } + + @Override + protected RectBounds computeOpaqueRegion(RectBounds opaqueRegion) { + opaqueRegionRecomputed = true; + assert computedOpaqueRegion != null; + return (RectBounds) opaqueRegion.deriveWithNewBounds(computedOpaqueRegion); + } + + @Override + protected void renderContent(Graphics g) { } + + @Override + protected boolean hasOverlappingContents() { + return false; + } + + @Override + protected boolean supportsOpaqueRegions() { + return true; + } + } + + static abstract class MockEffect extends Effect { + + @Override + public ImageData filter(FilterContext fctx, BaseTransform transform, Rectangle outputClip, Object renderHelper, Effect defaultInput) { + return null; + } + + @Override + public BaseBounds getBounds(BaseTransform transform, Effect defaultInput) { + return null; + } + + @Override + public AccelType getAccelType(FilterContext fctx) { + return AccelType.OPENGL; + } + } + + class TransparentEffect extends MockEffect { + @Override + public boolean reducesOpaquePixels() { + return true; + } + } + + class OpaqueEffect extends MockEffect { + @Override + public boolean reducesOpaquePixels() { + return false; + } + + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGRectangleTest.java 2015-09-11 21:24:33.529286887 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import com.sun.javafx.geom.RectBounds; -import com.sun.prism.paint.Color; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * Tests for NGRectangle class - */ -public class NGRectangleTest extends NGTestBase { - NGRectangleMock r; - - @Before - public void setup() { - r = new NGRectangleMock(); - r.updateRectangle(0, 0, 100, 100, 0, 0); - r.setFillPaint(Color.BLACK); - } - - /** - * NGRectangle supports opaque regions - */ - @Test - public void testSupportsOpaqueRegions() { - assertTrue(r.supportsOpaqueRegions()); - } - - /** - * The default rectangle with a fill and size should have an opaque region - */ - @Test - public void testHasOpaqueRegion() { - assertTrue(r.hasOpaqueRegion()); - } - - /** - * If there's no fill, there is no opaque region because - * we don't yet support strokes as being part of our - * opaque region computation. - */ - @Test - public void testHasOpaqueRegion_NoFill() { - r.setFillPaint(null); - assertFalse(r.hasOpaqueRegion()); - } - - /** - * If we have no width, we won't have any opaque region. - */ - @Test - public void testHasOpaqueRegion_NoWidth() { - r.updateRectangle(0, 0, 0, 100, 0, 0); - assertFalse(r.hasOpaqueRegion()); - } - - /** - * If we have no height, we won't have any opaque region. - */ - @Test - public void testHasOpaqueRegion_NoHeight() { - r.updateRectangle(0, 0, 100, 0, 0, 0); - assertFalse(r.hasOpaqueRegion()); - } - - /** - * In this case we still compute opaque insets, - * based on the same logic as we'd use with - * an ellipse. - */ - @Test - public void testHasOpaqueRegion_ArcWidthSoBig() { - r.updateRectangle(0, 0, 100, 100, 100, 100); - assertTrue(r.hasOpaqueRegion()); - } - - @Test - public void computeOpaqueRegion_NoArc() { - assertEquals(new RectBounds(0, 0, 100, 100), r.computeOpaqueRegion(new RectBounds())); - } - - class NGRectangleMock extends NGRectangle { - boolean opaqueRegionRecomputed = false; - - @Override - protected boolean hasOpaqueRegion() { - opaqueRegionRecomputed = true; - return super.hasOpaqueRegion(); - } - - @Override - protected RectBounds computeOpaqueRegion(RectBounds opaqueRegion) { - opaqueRegionRecomputed = true; - return super.computeOpaqueRegion(opaqueRegion); - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/NGRectangleTest.java 2015-09-11 21:24:33.313286890 -0400 @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.javafx.sg.prism.NGRectangle; +import com.sun.prism.paint.Color; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Tests for NGRectangle class + */ +public class NGRectangleTest extends NGTestBase { + NGRectangleMock r; + + @Before + public void setup() { + r = new NGRectangleMock(); + r.updateRectangle(0, 0, 100, 100, 0, 0); + r.setFillPaint(Color.BLACK); + } + + /** + * NGRectangle supports opaque regions + */ + @Test + public void testSupportsOpaqueRegions() { + assertTrue(NGNodeShim.supportsOpaqueRegions(r)); + } + + /** + * The default rectangle with a fill and size should have an opaque region + */ + @Test + public void testHasOpaqueRegion() { + assertTrue(r.hasOpaqueRegion()); + } + + /** + * If there's no fill, there is no opaque region because + * we don't yet support strokes as being part of our + * opaque region computation. + */ + @Test + public void testHasOpaqueRegion_NoFill() { + r.setFillPaint(null); + assertFalse(r.hasOpaqueRegion()); + } + + /** + * If we have no width, we won't have any opaque region. + */ + @Test + public void testHasOpaqueRegion_NoWidth() { + r.updateRectangle(0, 0, 0, 100, 0, 0); + assertFalse(r.hasOpaqueRegion()); + } + + /** + * If we have no height, we won't have any opaque region. + */ + @Test + public void testHasOpaqueRegion_NoHeight() { + r.updateRectangle(0, 0, 100, 0, 0, 0); + assertFalse(r.hasOpaqueRegion()); + } + + /** + * In this case we still compute opaque insets, + * based on the same logic as we'd use with + * an ellipse. + */ + @Test + public void testHasOpaqueRegion_ArcWidthSoBig() { + r.updateRectangle(0, 0, 100, 100, 100, 100); + assertTrue(r.hasOpaqueRegion()); + } + + @Test + public void computeOpaqueRegion_NoArc() { + assertEquals(new RectBounds(0, 0, 100, 100), r.computeOpaqueRegion(new RectBounds())); + } + + class NGRectangleMock extends NGRectangle { + boolean opaqueRegionRecomputed = false; + + @Override + public boolean hasOpaqueRegion() { + opaqueRegionRecomputed = true; + return super.hasOpaqueRegion(); + } + + @Override + protected RectBounds computeOpaqueRegion(RectBounds opaqueRegion) { + opaqueRegionRecomputed = true; + return super.computeOpaqueRegion(opaqueRegion); + } + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGRegionTest.java 2015-09-11 21:24:34.313286878 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import javafx.geometry.Insets; -import javafx.scene.layout.Background; -import javafx.scene.layout.BackgroundFill; -import javafx.scene.layout.Region; -import javafx.scene.paint.Color; -import javafx.scene.shape.ClosePath; -import javafx.scene.shape.LineTo; -import javafx.scene.shape.MoveTo; -import javafx.scene.shape.Path; -import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - */ -public class NGRegionTest { - @Test public void setOpaqueInsetsInvalidatesOpaqueRegion() { - NGRegion r = new NGRegion(); - r.getOpaqueRegion(); // Forces to validate the opaque region - assertFalse(r.isOpaqueRegionInvalid()); // sanity check - r.setOpaqueInsets(0, 0, 0, 0); - assertTrue(r.isOpaqueRegionInvalid()); - } - - @Test public void updateShapeInvalidatesOpaqueRegion() { - NGRegion r = new NGRegion(); - r.getOpaqueRegion(); // Forces to validate the opaque region - assertFalse(r.isOpaqueRegionInvalid()); // sanity check - r.updateShape(null, true, false, false); // Actual values don't matter - assertTrue(r.isOpaqueRegionInvalid()); - } - - // RT-13820: We change the shape internally and call this same method, so it - // needs to invalidate the opaque region. - @Test public void updateShapeToSameInstanceInvalidatesOpaqueRegion() { - LineTo lineTo; - Path p = new Path( - new MoveTo(10, 20), - lineTo = new LineTo(100, 100), - new ClosePath() - ); - - NGRegion r = new NGRegion(); - r.updateShape(p, true, true, true); - r.getOpaqueRegion(); // Forces to validate the opaque region - assertFalse(r.isOpaqueRegionInvalid()); // sanity check - lineTo.setX(200); - r.updateShape(p, true, true, true); - assertTrue(r.isOpaqueRegionInvalid()); - } - - @Test public void setSizeInvalidatesOpaqueRegion() { - NGRegion r = new NGRegion(); - r.getOpaqueRegion(); // Forces to validate the opaque region - assertFalse(r.isOpaqueRegionInvalid()); // sanity check - r.setSize(100, 100); - assertTrue(r.isOpaqueRegionInvalid()); - } - - // Note: These tests are using a Region and doing a sync because it was found that - // doing the check directly on the updateBackground method itself gave incorrect - // results, but doing so via Region's sync worked correctly (because every time a - // background is changed on the Region, setOpaqueInsets is called which invalidates - // the opaque region). - - @Test public void updateBackgroundWithSameSizeButTransparentFillInvalidatesOpaqueInsets() { - Region r = new Region(); - NGRegion peer = r.impl_getPeer(); - r.setBackground(new Background(new BackgroundFill(Color.RED, null, null))); - r.impl_updatePeer(); - peer.getOpaqueRegion(); // Forces to validate the opaque region - assertFalse(peer.isOpaqueRegionInvalid()); // sanity check - r.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, null))); - r.impl_updatePeer(); - assertTrue(peer.isOpaqueRegionInvalid()); - } - - @Test public void updateBackgroundWithDifferentSizeBackgroundInvalidatesOpaqueInsets() { - Region r = new Region(); - NGRegion peer = r.impl_getPeer(); - r.setBackground(new Background(new BackgroundFill(Color.RED, null, null))); - r.impl_updatePeer(); - peer.getOpaqueRegion(); // Forces to validate the opaque region - assertFalse(peer.isOpaqueRegionInvalid()); // sanity check - r.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, new Insets(10)))); - r.impl_updatePeer(); - assertTrue(peer.isOpaqueRegionInvalid()); - } - - @Test public void updateBackgroundWithDifferentSizeBackgroundInvalidatesOpaqueInsets2() { - Region r = new Region(); - NGRegion peer = r.impl_getPeer(); - r.setBackground(new Background(new BackgroundFill(Color.RED, null, null))); - r.impl_updatePeer(); - peer.getOpaqueRegion(); // Forces to validate the opaque region - assertFalse(peer.isOpaqueRegionInvalid()); // sanity check - r.setBackground(new Background(new BackgroundFill(Color.RED, null, new Insets(10)))); - r.impl_updatePeer(); - assertTrue(peer.isOpaqueRegionInvalid()); - } - - @Test public void updateBackgroundWithDifferentSizeBackgroundInvalidatesOpaqueInsets3() { - Region r = new Region(); - NGRegion peer = r.impl_getPeer(); - r.setBackground(new Background(new BackgroundFill(Color.RED, null, null))); - r.impl_updatePeer(); - peer.getOpaqueRegion(); // Forces to validate the opaque region - assertFalse(peer.isOpaqueRegionInvalid()); // sanity check - r.setBackground(new Background(new BackgroundFill(Color.RED, null, new Insets(-10)))); - r.impl_updatePeer(); - assertTrue(peer.isOpaqueRegionInvalid()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/NGRegionTest.java 2015-09-11 21:24:34.117286881 -0400 @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.javafx.sg.prism.NGRegion; +import javafx.geometry.Insets; +import javafx.scene.layout.Background; +import javafx.scene.layout.BackgroundFill; +import javafx.scene.layout.Region; +import javafx.scene.paint.Color; +import javafx.scene.shape.ClosePath; +import javafx.scene.shape.LineTo; +import javafx.scene.shape.MoveTo; +import javafx.scene.shape.Path; +import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + */ +public class NGRegionTest { + @Test public void setOpaqueInsetsInvalidatesOpaqueRegion() { + NGRegion r = new NGRegion(); + r.getOpaqueRegion(); // Forces to validate the opaque region + assertFalse(NGNodeShim.isOpaqueRegionInvalid(r)); // sanity check + r.setOpaqueInsets(0, 0, 0, 0); + assertTrue(NGNodeShim.isOpaqueRegionInvalid(r)); + } + + @Test public void updateShapeInvalidatesOpaqueRegion() { + NGRegion r = new NGRegion(); + r.getOpaqueRegion(); // Forces to validate the opaque region + assertFalse(NGNodeShim.isOpaqueRegionInvalid(r)); // sanity check + r.updateShape(null, true, false, false); // Actual values don't matter + assertTrue(NGNodeShim.isOpaqueRegionInvalid(r)); + } + + // RT-13820: We change the shape internally and call this same method, so it + // needs to invalidate the opaque region. + @Test public void updateShapeToSameInstanceInvalidatesOpaqueRegion() { + LineTo lineTo; + Path p = new Path( + new MoveTo(10, 20), + lineTo = new LineTo(100, 100), + new ClosePath() + ); + + NGRegion r = new NGRegion(); + r.updateShape(p, true, true, true); + r.getOpaqueRegion(); // Forces to validate the opaque region + assertFalse(NGNodeShim.isOpaqueRegionInvalid(r)); // sanity check + lineTo.setX(200); + r.updateShape(p, true, true, true); + assertTrue(NGNodeShim.isOpaqueRegionInvalid(r)); + } + + @Test public void setSizeInvalidatesOpaqueRegion() { + NGRegion r = new NGRegion(); + r.getOpaqueRegion(); // Forces to validate the opaque region + assertFalse(NGNodeShim.isOpaqueRegionInvalid(r)); // sanity check + r.setSize(100, 100); + assertTrue(NGNodeShim.isOpaqueRegionInvalid(r)); + } + + // Note: These tests are using a Region and doing a sync because it was found that + // doing the check directly on the updateBackground method itself gave incorrect + // results, but doing so via Region's sync worked correctly (because every time a + // background is changed on the Region, setOpaqueInsets is called which invalidates + // the opaque region). + + @Test public void updateBackgroundWithSameSizeButTransparentFillInvalidatesOpaqueInsets() { + Region r = new Region(); + NGRegion peer = r.impl_getPeer(); + r.setBackground(new Background(new BackgroundFill(Color.RED, null, null))); + r.impl_updatePeer(); + peer.getOpaqueRegion(); // Forces to validate the opaque region + assertFalse(NGNodeShim.isOpaqueRegionInvalid(peer)); // sanity check + r.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, null))); + r.impl_updatePeer(); + assertTrue(NGNodeShim.isOpaqueRegionInvalid(peer)); + } + + @Test public void updateBackgroundWithDifferentSizeBackgroundInvalidatesOpaqueInsets() { + Region r = new Region(); + NGRegion peer = r.impl_getPeer(); + r.setBackground(new Background(new BackgroundFill(Color.RED, null, null))); + r.impl_updatePeer(); + peer.getOpaqueRegion(); // Forces to validate the opaque region + assertFalse(NGNodeShim.isOpaqueRegionInvalid(peer)); // sanity check + r.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, new Insets(10)))); + r.impl_updatePeer(); + assertTrue(NGNodeShim.isOpaqueRegionInvalid(peer)); + } + + @Test public void updateBackgroundWithDifferentSizeBackgroundInvalidatesOpaqueInsets2() { + Region r = new Region(); + NGRegion peer = r.impl_getPeer(); + r.setBackground(new Background(new BackgroundFill(Color.RED, null, null))); + r.impl_updatePeer(); + peer.getOpaqueRegion(); // Forces to validate the opaque region + assertFalse(NGNodeShim.isOpaqueRegionInvalid(peer)); // sanity check + r.setBackground(new Background(new BackgroundFill(Color.RED, null, new Insets(10)))); + r.impl_updatePeer(); + assertTrue(NGNodeShim.isOpaqueRegionInvalid(peer)); + } + + @Test public void updateBackgroundWithDifferentSizeBackgroundInvalidatesOpaqueInsets3() { + Region r = new Region(); + NGRegion peer = r.impl_getPeer(); + r.setBackground(new Background(new BackgroundFill(Color.RED, null, null))); + r.impl_updatePeer(); + peer.getOpaqueRegion(); // Forces to validate the opaque region + assertFalse(NGNodeShim.isOpaqueRegionInvalid(peer)); // sanity check + r.setBackground(new Background(new BackgroundFill(Color.RED, null, new Insets(-10)))); + r.impl_updatePeer(); + assertTrue(NGNodeShim.isOpaqueRegionInvalid(peer)); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGShapeTest.java 2015-09-11 21:24:35.077286870 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import java.util.Arrays; -import com.sun.javafx.geom.Ellipse2D; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.Shape; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.prism.paint.Color; -import com.sun.prism.paint.LinearGradient; -import com.sun.prism.paint.Stop; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - */ -public class NGShapeTest extends NGTestBase { - private NGShape shape; - - @Before - public void setup() { - shape = new NGShape() { - @Override - public Shape getShape() { - return new Ellipse2D(10, 10, 10, 10); - } - - @Override - protected boolean supportsOpaqueRegions() { - return true; - } - - @Override - protected RectBounds computeOpaqueRegion(RectBounds opaqueRegion) { - // For the sake of the tests in this class we actually don't care - // what the opaque region is, so I just make something up - opaqueRegion.setBounds(0, 0, 20, 20); - return opaqueRegion; - } - }; - shape.setDrawPaint(Color.WHITE); - shape.setFillPaint(Color.BLACK); - } - - @Test - public void hasOpaqueRegionReturnsFalseIfModeIsStroke() { - shape.setMode(NGShape.Mode.STROKE); - assertFalse(shape.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionReturnsFalseIfModeIsEmpty() { - shape.setMode(NGShape.Mode.EMPTY); - assertFalse(shape.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionReturnsFalseIfFillPaintIsNull() { - shape.setFillPaint(null); - assertFalse(shape.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionReturnsFalseIfFillPaintIsNotOpaque() { - shape.setFillPaint(new LinearGradient(0, 0, 1, 1, BaseTransform.IDENTITY_TRANSFORM, true, 0, Arrays.asList( - new Stop(Color.BLACK, 0), new Stop(Color.TRANSPARENT, 1)))); - assertFalse(shape.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionReturnsTrueIfModeIsSTROKE_FILE() { - shape.setMode(NGShape.Mode.STROKE_FILL); - assertTrue(shape.hasOpaqueRegion()); - } - - @Test - public void hasOpaqueRegionReturnsTrueIfModeIsFILL() { - assertTrue(shape.hasOpaqueRegion()); - } - - @Test - public void getOpaqueRegionChangesWhenFillChanged() { - RectBounds or = shape.getOpaqueRegion(); - assertNotNull(or); - - shape.setFillPaint(null); - assertNull(shape.getOpaqueRegion()); - - shape.setFillPaint(Color.BLACK); - assertNotNull(shape.getOpaqueRegion()); - assertEquals(or, shape.getOpaqueRegion()); - } - - @Test - public void getOpaqueRegionChangesWhenModeChanged() { - RectBounds or = shape.getOpaqueRegion(); - assertNotNull(or); - - shape.setMode(NGShape.Mode.EMPTY); - assertNull(shape.getOpaqueRegion()); - - shape.setMode(NGShape.Mode.FILL); - assertNotNull(shape.getOpaqueRegion()); - assertEquals(or, shape.getOpaqueRegion()); - - shape.setMode(NGShape.Mode.STROKE); - assertNull(shape.getOpaqueRegion()); - - shape.setMode(NGShape.Mode.STROKE_FILL); - assertNotNull(shape.getOpaqueRegion()); - assertEquals(or, shape.getOpaqueRegion()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/NGShapeTest.java 2015-09-11 21:24:34.869286872 -0400 @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import java.util.Arrays; +import com.sun.javafx.geom.Ellipse2D; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.Shape; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.javafx.sg.prism.NGShape; +import com.sun.prism.paint.Color; +import com.sun.prism.paint.LinearGradient; +import com.sun.prism.paint.Stop; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + */ +public class NGShapeTest extends NGTestBase { + private NGShape shape; + + @Before + public void setup() { + shape = new NGShape() { + @Override + public Shape getShape() { + return new Ellipse2D(10, 10, 10, 10); + } + + @Override + protected boolean supportsOpaqueRegions() { + return true; + } + + @Override + protected RectBounds computeOpaqueRegion(RectBounds opaqueRegion) { + // For the sake of the tests in this class we actually don't care + // what the opaque region is, so I just make something up + opaqueRegion.setBounds(0, 0, 20, 20); + return opaqueRegion; + } + }; + shape.setDrawPaint(Color.WHITE); + shape.setFillPaint(Color.BLACK); + } + + @Test + public void hasOpaqueRegionReturnsFalseIfModeIsStroke() { + shape.setMode(NGShape.Mode.STROKE); + assertFalse(NGNodeShim.hasOpaqueRegion(shape)); + } + + @Test + public void hasOpaqueRegionReturnsFalseIfModeIsEmpty() { + shape.setMode(NGShape.Mode.EMPTY); + assertFalse(NGNodeShim.hasOpaqueRegion(shape)); + } + + @Test + public void hasOpaqueRegionReturnsFalseIfFillPaintIsNull() { + shape.setFillPaint(null); + assertFalse(NGNodeShim.hasOpaqueRegion(shape)); + } + + @Test + public void hasOpaqueRegionReturnsFalseIfFillPaintIsNotOpaque() { + shape.setFillPaint(new LinearGradient(0, 0, 1, 1, BaseTransform.IDENTITY_TRANSFORM, true, 0, Arrays.asList( + new Stop(Color.BLACK, 0), new Stop(Color.TRANSPARENT, 1)))); + assertFalse(NGNodeShim.hasOpaqueRegion(shape)); + } + + @Test + public void hasOpaqueRegionReturnsTrueIfModeIsSTROKE_FILE() { + shape.setMode(NGShape.Mode.STROKE_FILL); + assertTrue(NGNodeShim.hasOpaqueRegion(shape)); + } + + @Test + public void hasOpaqueRegionReturnsTrueIfModeIsFILL() { + assertTrue(NGNodeShim.hasOpaqueRegion(shape)); + } + + @Test + public void getOpaqueRegionChangesWhenFillChanged() { + RectBounds or = shape.getOpaqueRegion(); + assertNotNull(or); + + shape.setFillPaint(null); + assertNull(shape.getOpaqueRegion()); + + shape.setFillPaint(Color.BLACK); + assertNotNull(shape.getOpaqueRegion()); + assertEquals(or, shape.getOpaqueRegion()); + } + + @Test + public void getOpaqueRegionChangesWhenModeChanged() { + RectBounds or = shape.getOpaqueRegion(); + assertNotNull(or); + + shape.setMode(NGShape.Mode.EMPTY); + assertNull(shape.getOpaqueRegion()); + + shape.setMode(NGShape.Mode.FILL); + assertNotNull(shape.getOpaqueRegion()); + assertEquals(or, shape.getOpaqueRegion()); + + shape.setMode(NGShape.Mode.STROKE); + assertNull(shape.getOpaqueRegion()); + + shape.setMode(NGShape.Mode.STROKE_FILL); + assertNotNull(shape.getOpaqueRegion()); + assertEquals(or, shape.getOpaqueRegion()); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGTestBase.java 2015-09-11 21:24:35.841286861 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,321 +0,0 @@ -/* - * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import javafx.geometry.Insets; -import javafx.scene.layout.Background; -import javafx.scene.layout.BackgroundFill; -import javafx.scene.layout.CornerRadii; -import java.lang.reflect.Field; -import com.sun.javafx.geom.BaseBounds; -import com.sun.javafx.geom.BoxBounds; -import com.sun.javafx.geom.DirtyRegionContainer; -import com.sun.javafx.geom.DirtyRegionPool; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.javafx.geom.transform.GeneralTransform3D; -import com.sun.prism.Graphics; -import com.sun.prism.paint.Color; -import com.sun.scenario.effect.Effect; - -/** - * Base class for all tests in this package. The tests in this package are all about - * testing the NGNode and associated classes. These tests all need to be able to work - * directly against the NGNodes and not rely on the upper level scene graph nodes. - * However Node and the other classes do manage a lot of tasks (like setting up the bounds - * and transforms appropriately) during synchronization. This class contains all of the - * useful convenience methods for creating scene graphs of NG nodes and manipulating them - * so that we can test the NG nodes. - */ -public class NGTestBase { - - /** Transforms the given node by the specified transform. */ - protected static void transform(N node, BaseTransform tx) { - // Concatenate this transform with the one already on the node - tx = node.getTransform().copy().deriveWithConcatenation(tx); - // Compute & set the new transformed bounds for the node - node.setTransformedBounds(node.getEffectBounds(new RectBounds(), tx), false); - // Set the transform matrix - node.setTransformMatrix(tx); - } - - /** Translate the given node by the specified amount */ - protected static void translate(N node, double tx, double ty) { - transform(node, BaseTransform.getTranslateInstance(tx, ty)); - } - - /** Set the given effect on the node. effect must not be null. */ - protected static void setEffect(N node, Effect effect) { - node.setEffect(null); // so that when we ask for the getEffectBounds, it won't include an old effect - BaseBounds effectBounds = new RectBounds(); - effectBounds = effectBounds.deriveWithNewBounds(effect.getBounds(BaseTransform.IDENTITY_TRANSFORM, new NodeEffectInput(node))); - BaseBounds clippedBounds = node.getEffectBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); - node.setEffect(effect); - // The new transformed bounds should be the union of the old effect bounds, new effect bounds, and - // then transform those bounds. The reason I'm doing it this way is to expose any bugs in the - // getEffectBounds() implementation when an effect is present. - effectBounds = effectBounds.deriveWithUnion(clippedBounds); - node.setTransformedBounds(node.getTransform().transform(effectBounds, effectBounds), false); - } - - public static TestNGRectangle createRectangle(int x, int y, int width, int height) { - TestNGRectangle rect = new TestNGRectangle(); - rect.updateRectangle(x, y, width, height, 0, 0); - final RectBounds bounds = new RectBounds(x, y, x + width, y + height); - rect.setContentBounds(bounds); - rect.setFillPaint(new Color(0, 0, 0, 1.0f)); - rect.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); - rect.setTransformedBounds(bounds, false); - return rect; - } - - public static TestNGCircle createCircle(int cx, int cy, int radius) { - TestNGCircle c = new TestNGCircle(); - c.updateCircle(cx, cy, radius); - final RectBounds bounds = new RectBounds(cx - radius, cy - radius, cx + radius, cy + radius); - c.setContentBounds(bounds); - c.setFillPaint(new Color(0, 0, 0, 1.0f)); - c.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); - c.setTransformedBounds(bounds, false); - return c; - } - - public static TestNGRegion createOpaqueRegion(int x, int y, int width, int height, NGNode... children) { - TestNGRegion r = createTransparentRegion(x, y, width, height, children); - r.updateBackground(new Background(new BackgroundFill(javafx.scene.paint.Color.BLACK, null, null))); - r.setOpaqueInsets(0, 0, 0, 0); - return r; - } - - public static TestNGRegion createTransparentRegion(int x, int y, int width, int height, NGNode... children) { - TestNGRegion r = new TestNGRegion(); - for (NGNode child : children) { - r.add(-1, child); - } - r.setSize(width, height); - final RectBounds bounds = new RectBounds(0, 0, width, height); - r.setContentBounds(bounds); - if (x != 0 || y != 0) { - r.setTransformMatrix(BaseTransform.getTranslateInstance(x, y)); - r.setTransformedBounds(r.getTransform().transform(bounds, new RectBounds()), true); - } else { - r.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); - r.setTransformedBounds(bounds, false); - } - return r; - } - - public static TestNGGroup createGroup(NGNode... children) { - TestNGGroup group = new TestNGGroup(); - BaseBounds contentBounds = new RectBounds(); - for (NGNode child : children) { - contentBounds = contentBounds.deriveWithUnion( - child.getCompleteBounds( - new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - group.add(-1, child); - } - group.setContentBounds(contentBounds); - group.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); - group.setTransformedBounds(contentBounds, false); - return group; - } - - public static TestNGRegion createRegion(int w, int h, NGNode... children) { - TestNGRegion region = new TestNGRegion(); - BaseBounds contentBounds = new RectBounds(); - for (NGNode child : children) { - contentBounds = contentBounds.deriveWithUnion( - child.getCompleteBounds( - new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); - region.add(-1, child); - } - region.setContentBounds(contentBounds); - region.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); - region.setTransformedBounds(contentBounds, false); - region.setSize(w, h); - - // I have to do this nasty reflection trickery because we don't have a Toolkit for creating - // the Prism Color that is the platform peer. - javafx.scene.paint.Color color = new javafx.scene.paint.Color(0, 0, 0, 1); - try { - Field platformPaint = color.getClass().getDeclaredField("platformPaint"); - platformPaint.setAccessible(true); - platformPaint.set(color, new Color(0f, 0f, 0f, 1f)); - } catch (Exception e) { - e.printStackTrace(); - } - Background background = new Background(new BackgroundFill[] { - new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY)}, null); - region.updateBackground(background); - region.setOpaqueInsets(0, 0, 0, 0); - return region; - } - - - public static final class TestNGGroup extends NGGroup implements TestNGNode { - private boolean askedToAccumulateDirtyRegion; - private boolean computedDirtyRegion; - private boolean rendered; - - @Override - protected void renderContent(Graphics g) { - super.renderContent(g); - rendered = true; - } - - @Override public int accumulateDirtyRegions(final RectBounds clip, - RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) { - askedToAccumulateDirtyRegion = true; - return super.accumulateDirtyRegions(clip, dirtyRegion, pool, drc, tx, pvTx); - } - @Override protected int accumulateGroupDirtyRegion( - final RectBounds clip, RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) - { - computedDirtyRegion = true; - return super.accumulateGroupDirtyRegion(clip, dirtyRegion, pool, drc, tx, pvTx); - } - @Override protected int accumulateNodeDirtyRegion( - final RectBounds clip, RectBounds dirtyRegion, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) - { - computedDirtyRegion = true; - return super.accumulateNodeDirtyRegion(clip, dirtyRegion, drc, tx, pvTx); - } - @Override public boolean askedToAccumulateDirtyRegion() { return askedToAccumulateDirtyRegion; } - @Override public boolean computedDirtyRegion() { return computedDirtyRegion; } - @Override public boolean rendered() { return rendered; } - } - - public static final class TestNGRegion extends NGRegion implements TestNGNode { - private boolean askedToAccumulateDirtyRegion; - private boolean computedDirtyRegion; - private boolean rendered; - - @Override - protected void renderContent(Graphics g) { - super.renderContent(g); - rendered = true; - } - - @Override public int accumulateDirtyRegions(final RectBounds clip, - RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) { - askedToAccumulateDirtyRegion = true; - return super.accumulateDirtyRegions(clip, dirtyRegion, pool, drc, tx, pvTx); - } - @Override protected int accumulateGroupDirtyRegion( - final RectBounds clip, RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) - { - computedDirtyRegion = true; - return super.accumulateGroupDirtyRegion(clip, dirtyRegion, pool, drc, tx, pvTx); - } - @Override protected int accumulateNodeDirtyRegion( - final RectBounds clip, RectBounds dirtyRegion, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) - { - computedDirtyRegion = true; - return super.accumulateNodeDirtyRegion(clip, dirtyRegion, drc, tx, pvTx); - } - @Override public boolean askedToAccumulateDirtyRegion() { return askedToAccumulateDirtyRegion; } - @Override public boolean computedDirtyRegion() { return computedDirtyRegion; } - @Override public boolean rendered() { return rendered; } - } - - public static final class TestNGRectangle extends NGRectangle implements TestNGNode { - private boolean askedToAccumulateDirtyRegion; - private boolean computedDirtyRegion; - private boolean rendered; - - @Override - protected void renderContent(Graphics g) { - rendered = true; - } - - @Override public int accumulateDirtyRegions(final RectBounds clip, - RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) { - askedToAccumulateDirtyRegion = true; - return super.accumulateDirtyRegions(clip, dirtyRegion, pool, drc, tx, pvTx); - } - @Override protected int accumulateNodeDirtyRegion( - final RectBounds clip, RectBounds dirtyRegion, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) - { - computedDirtyRegion = true; - return super.accumulateNodeDirtyRegion(clip, dirtyRegion, drc, tx, pvTx); - } - @Override public boolean askedToAccumulateDirtyRegion() { return askedToAccumulateDirtyRegion; } - @Override public boolean computedDirtyRegion() { return computedDirtyRegion; } - @Override public boolean rendered() { return rendered; } - } - - public static final class TestNGCircle extends NGCircle implements TestNGNode { - private boolean askedToAccumulateDirtyRegion; - private boolean computedDirtyRegion; - private boolean rendered; - - @Override - protected void renderContent(Graphics g) { - rendered = true; - } - - @Override public int accumulateDirtyRegions(final RectBounds clip, - RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) { - askedToAccumulateDirtyRegion = true; - return super.accumulateDirtyRegions(clip, dirtyRegion, pool, drc, tx, pvTx); - } - @Override protected int accumulateNodeDirtyRegion( - final RectBounds clip, RectBounds dirtyRegion, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) - { - computedDirtyRegion = true; - return super.accumulateNodeDirtyRegion(clip, dirtyRegion, drc,tx, pvTx); - } - @Override public boolean askedToAccumulateDirtyRegion() { return askedToAccumulateDirtyRegion; } - @Override public boolean computedDirtyRegion() { return computedDirtyRegion; } - @Override public boolean rendered() { return rendered; } - - } - - public interface TestNGNode { - public boolean askedToAccumulateDirtyRegion(); - public boolean computedDirtyRegion(); - public boolean rendered(); - } - - public static abstract class Creator { - public abstract N create(); - } - - public static abstract class Polluter { - protected BaseTransform tx = BaseTransform.IDENTITY_TRANSFORM; - protected abstract void pollute(NGNode node); - protected BaseBounds modifiedBounds(NGNode node) { - return DirtyRegionTestBase.getWhatTransformedBoundsWouldBe(node, tx); - } - public RectBounds polluteAndGetExpectedBounds(NGNode node) { - BaseBounds originalBounds = node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); - BaseBounds modifiedBounds = modifiedBounds(node); - BaseBounds expected = originalBounds.deriveWithUnion(modifiedBounds); - pollute(node); - return (RectBounds)expected; - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/NGTestBase.java 2015-09-11 21:24:35.645286864 -0400 @@ -0,0 +1,327 @@ +/* + * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import javafx.geometry.Insets; +import javafx.scene.layout.Background; +import javafx.scene.layout.BackgroundFill; +import javafx.scene.layout.CornerRadii; +import java.lang.reflect.Field; +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.DirtyRegionPool; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; +import com.sun.javafx.sg.prism.NGCircleShim; +import com.sun.javafx.sg.prism.NGGroupShim; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.javafx.sg.prism.NGRectangleShim; +import com.sun.javafx.sg.prism.NGRegionShim; +import com.sun.javafx.sg.prism.NodeEffectInput; +import com.sun.prism.Graphics; +import com.sun.prism.paint.Color; +import com.sun.scenario.effect.Effect; + +/** + * Base class for all tests in this package. The tests in this package are all about + * testing the NGNode and associated classes. These tests all need to be able to work + * directly against the NGNodes and not rely on the upper level scene graph nodes. + * However Node and the other classes do manage a lot of tasks (like setting up the bounds + * and transforms appropriately) during synchronization. This class contains all of the + * useful convenience methods for creating scene graphs of NG nodes and manipulating them + * so that we can test the NG nodes. + */ +public class NGTestBase { + + /** Transforms the given node by the specified transform. */ + protected static void transform(N node, BaseTransform tx) { + // Concatenate this transform with the one already on the node + tx = node.getTransform().copy().deriveWithConcatenation(tx); + // Compute & set the new transformed bounds for the node + node.setTransformedBounds(node.getEffectBounds(new RectBounds(), tx), false); + // Set the transform matrix + node.setTransformMatrix(tx); + } + + /** Translate the given node by the specified amount */ + protected static void translate(N node, double tx, double ty) { + transform(node, BaseTransform.getTranslateInstance(tx, ty)); + } + + /** Set the given effect on the node. effect must not be null. */ + protected static void setEffect(N node, Effect effect) { + node.setEffect(null); // so that when we ask for the getEffectBounds, it won't include an old effect + BaseBounds effectBounds = new RectBounds(); + effectBounds = effectBounds.deriveWithNewBounds(effect.getBounds(BaseTransform.IDENTITY_TRANSFORM, new NodeEffectInput(node))); + BaseBounds clippedBounds = node.getEffectBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); + node.setEffect(effect); + // The new transformed bounds should be the union of the old effect bounds, new effect bounds, and + // then transform those bounds. The reason I'm doing it this way is to expose any bugs in the + // getEffectBounds() implementation when an effect is present. + effectBounds = effectBounds.deriveWithUnion(clippedBounds); + node.setTransformedBounds(node.getTransform().transform(effectBounds, effectBounds), false); + } + + public static TestNGRectangle createRectangle(int x, int y, int width, int height) { + TestNGRectangle rect = new TestNGRectangle(); + rect.updateRectangle(x, y, width, height, 0, 0); + final RectBounds bounds = new RectBounds(x, y, x + width, y + height); + rect.setContentBounds(bounds); + rect.setFillPaint(new Color(0, 0, 0, 1.0f)); + rect.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); + rect.setTransformedBounds(bounds, false); + return rect; + } + + public static TestNGCircle createCircle(int cx, int cy, int radius) { + TestNGCircle c = new TestNGCircle(); + c.updateCircle(cx, cy, radius); + final RectBounds bounds = new RectBounds(cx - radius, cy - radius, cx + radius, cy + radius); + c.setContentBounds(bounds); + c.setFillPaint(new Color(0, 0, 0, 1.0f)); + c.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); + c.setTransformedBounds(bounds, false); + return c; + } + + public static TestNGRegion createOpaqueRegion(int x, int y, int width, int height, NGNode... children) { + TestNGRegion r = createTransparentRegion(x, y, width, height, children); + r.updateBackground(new Background(new BackgroundFill(javafx.scene.paint.Color.BLACK, null, null))); + r.setOpaqueInsets(0, 0, 0, 0); + return r; + } + + public static TestNGRegion createTransparentRegion(int x, int y, int width, int height, NGNode... children) { + TestNGRegion r = new TestNGRegion(); + for (NGNode child : children) { + r.add(-1, child); + } + r.setSize(width, height); + final RectBounds bounds = new RectBounds(0, 0, width, height); + r.setContentBounds(bounds); + if (x != 0 || y != 0) { + r.setTransformMatrix(BaseTransform.getTranslateInstance(x, y)); + r.setTransformedBounds(r.getTransform().transform(bounds, new RectBounds()), true); + } else { + r.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); + r.setTransformedBounds(bounds, false); + } + return r; + } + + public static TestNGGroup createGroup(NGNode... children) { + TestNGGroup group = new TestNGGroup(); + BaseBounds contentBounds = new RectBounds(); + for (NGNode child : children) { + contentBounds = contentBounds.deriveWithUnion( + child.getCompleteBounds( + new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); + group.add(-1, child); + } + group.setContentBounds(contentBounds); + group.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); + group.setTransformedBounds(contentBounds, false); + return group; + } + + public static TestNGRegion createRegion(int w, int h, NGNode... children) { + TestNGRegion region = new TestNGRegion(); + BaseBounds contentBounds = new RectBounds(); + for (NGNode child : children) { + contentBounds = contentBounds.deriveWithUnion( + child.getCompleteBounds( + new RectBounds(), BaseTransform.IDENTITY_TRANSFORM)); + region.add(-1, child); + } + region.setContentBounds(contentBounds); + region.setTransformMatrix(BaseTransform.IDENTITY_TRANSFORM); + region.setTransformedBounds(contentBounds, false); + region.setSize(w, h); + + // I have to do this nasty reflection trickery because we don't have a Toolkit for creating + // the Prism Color that is the platform peer. + javafx.scene.paint.Color color = new javafx.scene.paint.Color(0, 0, 0, 1); + try { + Field platformPaint = color.getClass().getDeclaredField("platformPaint"); + platformPaint.setAccessible(true); + platformPaint.set(color, new Color(0f, 0f, 0f, 1f)); + } catch (Exception e) { + e.printStackTrace(); + } + Background background = new Background(new BackgroundFill[] { + new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY)}, null); + region.updateBackground(background); + region.setOpaqueInsets(0, 0, 0, 0); + return region; + } + + + public static final class TestNGGroup extends NGGroupShim implements TestNGNode { + private boolean askedToAccumulateDirtyRegion; + private boolean computedDirtyRegion; + private boolean rendered; + + @Override + protected void renderContent(Graphics g) { + super.renderContent(g); + rendered = true; + } + + @Override public int accumulateDirtyRegions(final RectBounds clip, + RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) { + askedToAccumulateDirtyRegion = true; + return super.accumulateDirtyRegions(clip, dirtyRegion, pool, drc, tx, pvTx); + } + @Override public int accumulateGroupDirtyRegion( + final RectBounds clip, RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) + { + computedDirtyRegion = true; + return super.accumulateGroupDirtyRegion(clip, dirtyRegion, pool, drc, tx, pvTx); + } + @Override public int accumulateNodeDirtyRegion( + final RectBounds clip, RectBounds dirtyRegion, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) + { + computedDirtyRegion = true; + return super.accumulateNodeDirtyRegion(clip, dirtyRegion, drc, tx, pvTx); + } + @Override public boolean askedToAccumulateDirtyRegion() { return askedToAccumulateDirtyRegion; } + @Override public boolean computedDirtyRegion() { return computedDirtyRegion; } + @Override public boolean rendered() { return rendered; } + } + + public static final class TestNGRegion extends NGRegionShim implements TestNGNode { + private boolean askedToAccumulateDirtyRegion; + private boolean computedDirtyRegion; + private boolean rendered; + + @Override + protected void renderContent(Graphics g) { + super.renderContent(g); + rendered = true; + } + + @Override public int accumulateDirtyRegions(final RectBounds clip, + RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) { + askedToAccumulateDirtyRegion = true; + return super.accumulateDirtyRegions(clip, dirtyRegion, pool, drc, tx, pvTx); + } + @Override public int accumulateGroupDirtyRegion( + final RectBounds clip, RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) + { + computedDirtyRegion = true; + return super.accumulateGroupDirtyRegion(clip, dirtyRegion, pool, drc, tx, pvTx); + } + @Override public int accumulateNodeDirtyRegion( + final RectBounds clip, RectBounds dirtyRegion, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) + { + computedDirtyRegion = true; + return super.accumulateNodeDirtyRegion(clip, dirtyRegion, drc, tx, pvTx); + } + @Override public boolean askedToAccumulateDirtyRegion() { return askedToAccumulateDirtyRegion; } + @Override public boolean computedDirtyRegion() { return computedDirtyRegion; } + @Override public boolean rendered() { return rendered; } + } + + public static final class TestNGRectangle extends NGRectangleShim implements TestNGNode { + private boolean askedToAccumulateDirtyRegion; + private boolean computedDirtyRegion; + private boolean rendered; + + @Override + protected void renderContent(Graphics g) { + rendered = true; + } + + @Override public int accumulateDirtyRegions(final RectBounds clip, + RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) { + askedToAccumulateDirtyRegion = true; + return super.accumulateDirtyRegions(clip, dirtyRegion, pool, drc, tx, pvTx); + } + @Override public int accumulateNodeDirtyRegion( + final RectBounds clip, RectBounds dirtyRegion, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) + { + computedDirtyRegion = true; + return super.accumulateNodeDirtyRegion(clip, dirtyRegion, drc, tx, pvTx); + } + @Override public boolean askedToAccumulateDirtyRegion() { return askedToAccumulateDirtyRegion; } + @Override public boolean computedDirtyRegion() { return computedDirtyRegion; } + @Override public boolean rendered() { return rendered; } + } + + public static final class TestNGCircle extends NGCircleShim implements TestNGNode { + private boolean askedToAccumulateDirtyRegion; + private boolean computedDirtyRegion; + private boolean rendered; + + @Override + protected void renderContent(Graphics g) { + rendered = true; + } + + @Override public int accumulateDirtyRegions(final RectBounds clip, + RectBounds dirtyRegion, DirtyRegionPool pool, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) { + askedToAccumulateDirtyRegion = true; + return super.accumulateDirtyRegions(clip, dirtyRegion, pool, drc, tx, pvTx); + } + @Override public int accumulateNodeDirtyRegion( + final RectBounds clip, RectBounds dirtyRegion, DirtyRegionContainer drc, BaseTransform tx, GeneralTransform3D pvTx) + { + computedDirtyRegion = true; + return super.accumulateNodeDirtyRegion(clip, dirtyRegion, drc,tx, pvTx); + } + @Override public boolean askedToAccumulateDirtyRegion() { return askedToAccumulateDirtyRegion; } + @Override public boolean computedDirtyRegion() { return computedDirtyRegion; } + @Override public boolean rendered() { return rendered; } + + } + + public interface TestNGNode { + public boolean askedToAccumulateDirtyRegion(); + public boolean computedDirtyRegion(); + public boolean rendered(); + } + + public static abstract class Creator { + public abstract N create(); + } + + public static abstract class Polluter { + public BaseTransform tx = BaseTransform.IDENTITY_TRANSFORM; + public abstract void pollute(NGNode node); + public BaseBounds modifiedBounds(NGNode node) { + return DirtyRegionTestBase.getWhatTransformedBoundsWouldBe(node, tx); + } + public RectBounds polluteAndGetExpectedBounds(NGNode node) { + BaseBounds originalBounds = node.getCompleteBounds(new RectBounds(), BaseTransform.IDENTITY_TRANSFORM); + BaseBounds modifiedBounds = modifiedBounds(node); + BaseBounds expected = originalBounds.deriveWithUnion(modifiedBounds); + pollute(node); + return (RectBounds)expected; + } + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/NGTriangleMeshTest.java 2015-09-11 21:24:36.533286854 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.sun.javafx.sg.prism; - -import com.sun.javafx.collections.FloatArraySyncer; -import com.sun.javafx.collections.IntegerArraySyncer; -import java.util.Arrays; -import static org.junit.Assert.assertArrayEquals; -import org.junit.Test; - -public class NGTriangleMeshTest { - - private static final float EPSILON_FLOAT = 1e-5f; - - /** - * Test of syncFaceSmoothingGroups method, of class NGTriangleMesh. - */ - @Test - public void testSyncFaceSmoothingGroups() { - final int[] faceSmoothingGroups = new int[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncFaceSmoothingGroups((array, fromAndLengthIndices) -> faceSmoothingGroups); - int[] actuals = instance.test_getFaceSmoothingGroups(); - int[] expecteds = new int[]{0, 1, 2, 3, 4, 5}; - assertArrayEquals(expecteds, actuals); - } - - /** - * Test of syncFaceSmoothingGroups method, of class NGTriangleMesh. - */ - @Test - public void testSyncFaceSmoothingGroups2() { - final int[] faceSmoothingGroups = new int[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncFaceSmoothingGroups((array, fromAndLengthIndices) -> faceSmoothingGroups); - instance.syncFaceSmoothingGroups((array, fromAndLengthIndices) -> { - Arrays.fill(array, 1, 1 + 4, 1); - return array; - }); - int[] actuals = instance.test_getFaceSmoothingGroups(); - int[] expecteds = new int[]{0, 1, 1, 1, 1, 5}; - assertArrayEquals(expecteds, actuals); - } - - /** - * Test of syncPoints method, of class NGTriangleMesh. - */ - @Test - public void testSyncPoints() { - final float[] points = new float[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncPoints((array, fromAndLengthIndices) -> points); - float[] actuals = instance.test_getPoints(); - float[] expecteds = new float[]{0, 1, 2, 3, 4, 5}; - assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); - } - - /** - * Test of syncPoints method, of class NGTriangleMesh. - */ - @Test - public void testSyncPoints2() { - final float[] points = new float[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncPoints((array, fromAndLengthIndices) -> points); - instance.syncPoints((array, fromAndLengthIndices) -> { - Arrays.fill(array, 1, 1 + 4, 1); - return array; - }); - float[] actuals = instance.test_getPoints(); - float[] expecteds = new float[]{0, 1, 1, 1, 1, 5}; - assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); - } - - /** - * Test of syncNormals method, of class NGTriangleMesh. - */ - @Test - public void testSyncNormals() { - final float[] normals = new float[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncNormals((array, fromAndLengthIndices) -> normals); - float[] actuals = instance.test_getNormals(); - float[] expecteds = new float[]{0, 1, 2, 3, 4, 5}; - assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); - } - - /** - * Test of syncNormals method, of class NGTriangleMesh. - */ - @Test - public void testSyncNormals2() { - final float[] normals = new float[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncNormals((array, fromAndLengthIndices) -> normals); - instance.syncNormals((array, fromAndLengthIndices) -> { - Arrays.fill(array, 1, 1 + 4, 1); - return array; - }); - float[] actuals = instance.test_getNormals(); - float[] expecteds = new float[]{0, 1, 1, 1, 1, 5}; - assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); - } - - /** - * Test of syncTexCoords method, of class NGTriangleMesh. - */ - @Test - public void testSyncTexCoords() { - final float[] texcoords = new float[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncTexCoords((array, fromAndLengthIndices) -> texcoords); - float[] actuals = instance.test_getTexCoords(); - float[] expecteds = new float[]{0, 1, 2, 3, 4, 5}; - assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); - } - - /** - * Test of syncTexCoords method, of class NGTriangleMesh. - */ - @Test - public void testSyncTexCoords2() { - final float[] texcoords = new float[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncTexCoords((array, fromAndLengthIndices) -> texcoords); - instance.syncTexCoords((array, fromAndLengthIndices) -> { - Arrays.fill(array, 1, 1 + 4, 1); - return array; - }); - float[] actuals = instance.test_getTexCoords(); - float[] expecteds = new float[]{0, 1, 1, 1, 1, 5}; - assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); - } - - /** - * Test of syncFaces method, of class NGTriangleMesh. - */ - @Test - public void testSyncFaces() { - final int[] faces = new int[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncFaces((array, fromAndLengthIndices) -> faces); - int[] actuals = instance.test_getFaces(); - int[] expecteds = new int[]{0, 1, 2, 3, 4, 5}; - assertArrayEquals(expecteds, actuals); - } - - /** - * Test of syncFaces method, of class NGTriangleMesh. - */ - @Test - public void testSyncFaces2() { - final int[] faces = new int[]{0, 1, 2, 3, 4, 5}; - NGTriangleMesh instance = new NGTriangleMesh(); - instance.syncFaces((array, fromAndLengthIndices) -> faces); - instance.syncFaces((array, fromAndLengthIndices) -> { - Arrays.fill(array, 1, 1 + 4, 1); - return array; - }); - int[] actuals = instance.test_getFaces(); - int[] expecteds = new int[]{0, 1, 1, 1, 1, 5}; - assertArrayEquals(expecteds, actuals); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/NGTriangleMeshTest.java 2015-09-11 21:24:36.321286856 -0400 @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.collections.FloatArraySyncer; +import com.sun.javafx.collections.IntegerArraySyncer; +import com.sun.javafx.sg.prism.NGTriangleMeshShim; +import java.util.Arrays; +import static org.junit.Assert.assertArrayEquals; +import org.junit.Test; + +public class NGTriangleMeshTest { + + private static final float EPSILON_FLOAT = 1e-5f; + + /** + * Test of syncFaceSmoothingGroups method, of class NGTriangleMesh. + */ + @Test + public void testSyncFaceSmoothingGroups() { + final int[] faceSmoothingGroups = new int[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncFaceSmoothingGroups((array, fromAndLengthIndices) -> faceSmoothingGroups); + int[] actuals = instance.test_getFaceSmoothingGroups(); + int[] expecteds = new int[]{0, 1, 2, 3, 4, 5}; + assertArrayEquals(expecteds, actuals); + } + + /** + * Test of syncFaceSmoothingGroups method, of class NGTriangleMesh. + */ + @Test + public void testSyncFaceSmoothingGroups2() { + final int[] faceSmoothingGroups = new int[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncFaceSmoothingGroups((array, fromAndLengthIndices) -> faceSmoothingGroups); + instance.syncFaceSmoothingGroups((array, fromAndLengthIndices) -> { + Arrays.fill(array, 1, 1 + 4, 1); + return array; + }); + int[] actuals = instance.test_getFaceSmoothingGroups(); + int[] expecteds = new int[]{0, 1, 1, 1, 1, 5}; + assertArrayEquals(expecteds, actuals); + } + + /** + * Test of syncPoints method, of class NGTriangleMesh. + */ + @Test + public void testSyncPoints() { + final float[] points = new float[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncPoints((array, fromAndLengthIndices) -> points); + float[] actuals = instance.test_getPoints(); + float[] expecteds = new float[]{0, 1, 2, 3, 4, 5}; + assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); + } + + /** + * Test of syncPoints method, of class NGTriangleMesh. + */ + @Test + public void testSyncPoints2() { + final float[] points = new float[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncPoints((array, fromAndLengthIndices) -> points); + instance.syncPoints((array, fromAndLengthIndices) -> { + Arrays.fill(array, 1, 1 + 4, 1); + return array; + }); + float[] actuals = instance.test_getPoints(); + float[] expecteds = new float[]{0, 1, 1, 1, 1, 5}; + assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); + } + + /** + * Test of syncNormals method, of class NGTriangleMesh. + */ + @Test + public void testSyncNormals() { + final float[] normals = new float[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncNormals((array, fromAndLengthIndices) -> normals); + float[] actuals = instance.test_getNormals(); + float[] expecteds = new float[]{0, 1, 2, 3, 4, 5}; + assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); + } + + /** + * Test of syncNormals method, of class NGTriangleMesh. + */ + @Test + public void testSyncNormals2() { + final float[] normals = new float[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncNormals((array, fromAndLengthIndices) -> normals); + instance.syncNormals((array, fromAndLengthIndices) -> { + Arrays.fill(array, 1, 1 + 4, 1); + return array; + }); + float[] actuals = instance.test_getNormals(); + float[] expecteds = new float[]{0, 1, 1, 1, 1, 5}; + assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); + } + + /** + * Test of syncTexCoords method, of class NGTriangleMesh. + */ + @Test + public void testSyncTexCoords() { + final float[] texcoords = new float[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncTexCoords((array, fromAndLengthIndices) -> texcoords); + float[] actuals = instance.test_getTexCoords(); + float[] expecteds = new float[]{0, 1, 2, 3, 4, 5}; + assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); + } + + /** + * Test of syncTexCoords method, of class NGTriangleMesh. + */ + @Test + public void testSyncTexCoords2() { + final float[] texcoords = new float[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncTexCoords((array, fromAndLengthIndices) -> texcoords); + instance.syncTexCoords((array, fromAndLengthIndices) -> { + Arrays.fill(array, 1, 1 + 4, 1); + return array; + }); + float[] actuals = instance.test_getTexCoords(); + float[] expecteds = new float[]{0, 1, 1, 1, 1, 5}; + assertArrayEquals(expecteds, actuals, EPSILON_FLOAT); + } + + /** + * Test of syncFaces method, of class NGTriangleMesh. + */ + @Test + public void testSyncFaces() { + final int[] faces = new int[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncFaces((array, fromAndLengthIndices) -> faces); + int[] actuals = instance.test_getFaces(); + int[] expecteds = new int[]{0, 1, 2, 3, 4, 5}; + assertArrayEquals(expecteds, actuals); + } + + /** + * Test of syncFaces method, of class NGTriangleMesh. + */ + @Test + public void testSyncFaces2() { + final int[] faces = new int[]{0, 1, 2, 3, 4, 5}; + NGTriangleMeshShim instance = new NGTriangleMeshShim(); + instance.syncFaces((array, fromAndLengthIndices) -> faces); + instance.syncFaces((array, fromAndLengthIndices) -> { + Arrays.fill(array, 1, 1 + 4, 1); + return array; + }); + int[] actuals = instance.test_getFaces(); + int[] expecteds = new int[]{0, 1, 1, 1, 1, 5}; + assertArrayEquals(expecteds, actuals); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/OcclusionCullingTest.java 2015-09-11 21:24:37.213286846 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,226 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.javafx.geom.transform.GeneralTransform3D; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -/** - * - */ -public class OcclusionCullingTest extends NGTestBase { - - - @Test - public void testRectangleOcclusion() { - final TestNGRectangle root = createRectangle(0, 0, 50, 50); - TestNGGroup group = createGroup( - createRectangle(0, 0, 100, 100), root); - NodePath rootPath = new NodePath(); - group.getRenderRoot(rootPath, new RectBounds(20, 20, 30, 30), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - TestGraphics g = new TestGraphics(); - g.setRenderRoot(rootPath); - group.render(g); - assertRoot(rootPath, root); - checkRootRendering(group, rootPath); - } - - @Test - public void testGroupOcclusion() { - final TestNGRectangle root = createRectangle(0, 0, 50, 50); - TestNGGroup group = createGroup(createGroup( - createRectangle(0, 0, 100, 100)), createGroup(root)); - NodePath rootPath = new NodePath(); - group.getRenderRoot(rootPath, new RectBounds(20, 20, 30, 30), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - TestGraphics g = new TestGraphics(); - g.setRenderRoot(rootPath); - group.render(g); - assertRoot(rootPath, root); - checkRootRendering(group, rootPath); - } - - @Test - public void testRegionOcclusion() { - final TestNGRegion root = createRegion(50, 50); - TestNGGroup group = createGroup( - createRegion(100, 100), root); - NodePath rootPath = new NodePath(); - group.getRenderRoot(rootPath, new RectBounds(20, 20, 30, 30), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - TestGraphics g = new TestGraphics(); - g.setRenderRoot(rootPath); - group.render(g); - assertRoot(rootPath, root); - checkRootRendering(group, rootPath); - } - - @Test - public void testPresetRegionOcclusion() { - final TestNGRegion root = createRegion(100, 100); - final TestNGRegion other = createRegion(50, 50); - TestNGGroup group = createGroup( - root, other); - other.setOpaqueInsets(30, 30, 0, 0); - NodePath rootPath = new NodePath(); - group.getRenderRoot(rootPath, new RectBounds(20, 20, 30, 30), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - TestGraphics g = new TestGraphics(); - g.setRenderRoot(rootPath); - group.render(g); - assertRoot(rootPath, root); - checkRootRendering(group, rootPath); - } - - @Test - public void test2SameRectanglesOcclusion() { - final TestNGRectangle root = createRectangle(10, 10, 100, 100); - TestNGGroup group = createGroup( - createGroup(createRectangle(10, 10, 100, 100), createRectangle(20, 20, 20, 20)), - createGroup(root)); - NodePath rootPath = new NodePath(); - group.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - TestGraphics g = new TestGraphics(); - g.setRenderRoot(rootPath); - group.render(g); - assertRoot(rootPath, root); - checkRootRendering(group, rootPath); - } - - @Test - public void test2SameRectanglesOcclusionWithRootNotDirty() { - final TestNGRectangle root = createRectangle(10, 10, 100, 100); - final TestNGGroup rootParent = createGroup(root); - TestNGGroup group = createGroup( - createGroup(createRectangle(10, 10, 100, 100), createRectangle(20, 20, 20, 20)), rootParent); - - group.dirty = NGNode.DirtyFlag.CLEAN; // need to clean default dirty flags - rootParent.dirty = NGNode.DirtyFlag.CLEAN; - rootParent.childDirty = false; - root.dirty = NGNode.DirtyFlag.CLEAN; - root.childDirty = false; - NodePath rootPath = new NodePath(); - group.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - assertTrue(rootPath.isEmpty()); - - final TestNGRectangle dirtySibling = createRectangle(0,0,10,10); - rootParent.add(-1, dirtySibling); - rootPath = new NodePath(); - group.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - assertRoot(rootPath, root); - } - - @Test - public void testTransparentRegionWithChildren() { - final TestNGRectangle root = createRectangle(10, 10, 100, 100); - final TestNGGroup rootParent = createGroup(root); - TestNGRegion region = createTransparentRegion(0, 0, 100, 100, - createGroup(createRectangle(10, 10, 100, 100), createRectangle(20, 20, 20, 20)), rootParent); - - region.dirty = NGNode.DirtyFlag.CLEAN; // need to clean default dirty flags - rootParent.dirty = NGNode.DirtyFlag.CLEAN; - rootParent.childDirty = false; - root.dirty = NGNode.DirtyFlag.CLEAN; - root.childDirty = false; - NodePath rootPath = new NodePath(); - region.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - assertTrue(rootPath.isEmpty()); - - final TestNGRectangle dirtySibling = createRectangle(0,0,10,10); - rootParent.add(-1,dirtySibling); - rootPath = new NodePath(); - region.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - assertRoot(rootPath, root); - } - - @Test - public void testOpaqueRegion() { - final TestNGRectangle rect = createRectangle(10, 10, 100, 100); - TestNGRegion region = createOpaqueRegion(0, 0, 200, 200, rect); - TestNGGroup root = createGroup(region); - - NodePath rootPath = new NodePath(); - root.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - assertRoot(rootPath, rect); - - rootPath.clear(); - root.getRenderRoot(rootPath, new RectBounds(5, 5, 150, 150), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - assertRoot(rootPath, region); - TestGraphics g = new TestGraphics(); - g.setRenderRoot(rootPath); - root.render(g); - checkRootRendering(root, rootPath); - - rootPath.clear(); - root.getRenderRoot(rootPath, new RectBounds(-5, -5, 150, 150), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); - assertRoot(rootPath, root); - } - - private void checkRootRendering(TestNGNode node, NodePath root) { - assertTrue(node.rendered()); - if (node instanceof TestNGGroup) { - if (root.hasNext()) { - boolean foundRoot = false; - root.next(); - for (NGNode p : ((TestNGGroup)node).getChildren()) { - TestNGNode n = (TestNGNode) p; - if (n == root.getCurrentNode()) { - foundRoot = true; - checkRootRendering(n, root); - continue; - } - checkRendered(n, foundRoot); - } - } else { - for (NGNode p : ((TestNGGroup)node).getChildren()) { - checkRendered((TestNGNode)p, true); - } - } - } - } - - private void checkRendered(TestNGNode node, boolean rendered) { - assertEquals(rendered, node.rendered()); - if (node instanceof TestNGGroup) { - for (NGNode p : ((TestNGGroup)node).getChildren()) { - checkRendered((TestNGNode)p, rendered); - } - } - } - - private void assertRoot(NodePath rootPath, final NGNode root) { - rootPath.reset(); - while(rootPath.hasNext()) { - rootPath.next(); - } - assertSame(root, rootPath.getCurrentNode()); - rootPath.reset(); - } - - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/OcclusionCullingTest.java 2015-09-11 21:24:37.077286847 -0400 @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import test.com.sun.javafx.sg.prism.TestGraphics; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.javafx.sg.prism.NodePath; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + * + */ +public class OcclusionCullingTest extends NGTestBase { + + + @Test + public void testRectangleOcclusion() { + final TestNGRectangle root = createRectangle(0, 0, 50, 50); + TestNGGroup group = createGroup( + createRectangle(0, 0, 100, 100), root); + NodePath rootPath = new NodePath(); + group.getRenderRoot(rootPath, new RectBounds(20, 20, 30, 30), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + TestGraphics g = new TestGraphics(); + g.setRenderRoot(rootPath); + group.render(g); + assertRoot(rootPath, root); + checkRootRendering(group, rootPath); + } + + @Test + public void testGroupOcclusion() { + final TestNGRectangle root = createRectangle(0, 0, 50, 50); + TestNGGroup group = createGroup(createGroup( + createRectangle(0, 0, 100, 100)), createGroup(root)); + NodePath rootPath = new NodePath(); + group.getRenderRoot(rootPath, new RectBounds(20, 20, 30, 30), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + TestGraphics g = new TestGraphics(); + g.setRenderRoot(rootPath); + group.render(g); + assertRoot(rootPath, root); + checkRootRendering(group, rootPath); + } + + @Test + public void testRegionOcclusion() { + final TestNGRegion root = createRegion(50, 50); + TestNGGroup group = createGroup( + createRegion(100, 100), root); + NodePath rootPath = new NodePath(); + group.getRenderRoot(rootPath, new RectBounds(20, 20, 30, 30), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + TestGraphics g = new TestGraphics(); + g.setRenderRoot(rootPath); + group.render(g); + assertRoot(rootPath, root); + checkRootRendering(group, rootPath); + } + + @Test + public void testPresetRegionOcclusion() { + final TestNGRegion root = createRegion(100, 100); + final TestNGRegion other = createRegion(50, 50); + TestNGGroup group = createGroup( + root, other); + other.setOpaqueInsets(30, 30, 0, 0); + NodePath rootPath = new NodePath(); + group.getRenderRoot(rootPath, new RectBounds(20, 20, 30, 30), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + TestGraphics g = new TestGraphics(); + g.setRenderRoot(rootPath); + group.render(g); + assertRoot(rootPath, root); + checkRootRendering(group, rootPath); + } + + @Test + public void test2SameRectanglesOcclusion() { + final TestNGRectangle root = createRectangle(10, 10, 100, 100); + TestNGGroup group = createGroup( + createGroup(createRectangle(10, 10, 100, 100), createRectangle(20, 20, 20, 20)), + createGroup(root)); + NodePath rootPath = new NodePath(); + group.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + TestGraphics g = new TestGraphics(); + g.setRenderRoot(rootPath); + group.render(g); + assertRoot(rootPath, root); + checkRootRendering(group, rootPath); + } + + @Test + public void test2SameRectanglesOcclusionWithRootNotDirty() { + final TestNGRectangle root = createRectangle(10, 10, 100, 100); + final TestNGGroup rootParent = createGroup(root); + TestNGGroup group = createGroup( + createGroup(createRectangle(10, 10, 100, 100), createRectangle(20, 20, 20, 20)), rootParent); + + NGNodeShim.set_dirty(group, NGNode.DirtyFlag.CLEAN); // need to clean default dirty flags + NGNodeShim.set_dirty(rootParent, NGNode.DirtyFlag.CLEAN); + NGNodeShim.set_childDirty(rootParent, false); + NGNodeShim.set_dirty(root, NGNode.DirtyFlag.CLEAN); + NGNodeShim.set_childDirty(root, false); + NodePath rootPath = new NodePath(); + group.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + assertTrue(rootPath.isEmpty()); + + final TestNGRectangle dirtySibling = createRectangle(0,0,10,10); + rootParent.add(-1, dirtySibling); + rootPath = new NodePath(); + group.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + assertRoot(rootPath, root); + } + + @Test + public void testTransparentRegionWithChildren() { + final TestNGRectangle root = createRectangle(10, 10, 100, 100); + final TestNGGroup rootParent = createGroup(root); + TestNGRegion region = createTransparentRegion(0, 0, 100, 100, + createGroup(createRectangle(10, 10, 100, 100), createRectangle(20, 20, 20, 20)), rootParent); + + NGNodeShim.set_dirty(region, NGNode.DirtyFlag.CLEAN); // need to clean default dirty flags + NGNodeShim.set_dirty(rootParent, NGNode.DirtyFlag.CLEAN); + NGNodeShim.set_childDirty(rootParent, false); + NGNodeShim.set_dirty(root, NGNode.DirtyFlag.CLEAN); + NGNodeShim.set_childDirty(root, false); + NodePath rootPath = new NodePath(); + region.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + assertTrue(rootPath.isEmpty()); + + final TestNGRectangle dirtySibling = createRectangle(0,0,10,10); + rootParent.add(-1,dirtySibling); + rootPath = new NodePath(); + region.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + assertRoot(rootPath, root); + } + + @Test + public void testOpaqueRegion() { + final TestNGRectangle rect = createRectangle(10, 10, 100, 100); + TestNGRegion region = createOpaqueRegion(0, 0, 200, 200, rect); + TestNGGroup root = createGroup(region); + + NodePath rootPath = new NodePath(); + root.getRenderRoot(rootPath, new RectBounds(10, 10, 100, 100), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + assertRoot(rootPath, rect); + + rootPath.clear(); + root.getRenderRoot(rootPath, new RectBounds(5, 5, 150, 150), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + assertRoot(rootPath, region); + TestGraphics g = new TestGraphics(); + g.setRenderRoot(rootPath); + root.render(g); + checkRootRendering(root, rootPath); + + rootPath.clear(); + root.getRenderRoot(rootPath, new RectBounds(-5, -5, 150, 150), -1, BaseTransform.IDENTITY_TRANSFORM, new GeneralTransform3D()); + assertRoot(rootPath, root); + } + + private void checkRootRendering(TestNGNode node, NodePath root) { + assertTrue(node.rendered()); + if (node instanceof TestNGGroup) { + if (root.hasNext()) { + boolean foundRoot = false; + root.next(); + for (NGNode p : ((TestNGGroup)node).getChildren()) { + TestNGNode n = (TestNGNode) p; + if (n == root.getCurrentNode()) { + foundRoot = true; + checkRootRendering(n, root); + continue; + } + checkRendered(n, foundRoot); + } + } else { + for (NGNode p : ((TestNGGroup)node).getChildren()) { + checkRendered((TestNGNode)p, true); + } + } + } + } + + private void checkRendered(TestNGNode node, boolean rendered) { + assertEquals(rendered, node.rendered()); + if (node instanceof TestNGGroup) { + for (NGNode p : ((TestNGGroup)node).getChildren()) { + checkRendered((TestNGNode)p, rendered); + } + } + } + + private void assertRoot(NodePath rootPath, final NGNode root) { + rootPath.reset(); + while(rootPath.hasNext()) { + rootPath.next(); + } + assertSame(root, rootPath.getCurrentNode()); + rootPath.reset(); + } + + +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/RenderRootTest.java 2015-09-11 21:24:37.893286838 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,431 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import com.sun.javafx.geom.DirtyRegionContainer; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.javafx.geom.transform.GeneralTransform3D; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -/** - * Tests for the computation of the render root of a graph - */ -public class RenderRootTest extends NGTestBase { - // NGNodes to test: NGRectangle, NGImageView, NGRegion, NGCircle, NGEllipse - // Also thrown in 3D transforms and 2D transforms other than BASE_TRANSFORM - // Structures to test: root, background, foreground - // - Foreground completely covers background. - // - Foreground partially overlaps background - // Test each node has exactly the expected opaque region, given: - // - stroke - // - effect - // - clip (dirty region should only include the intersection of the clip & bounds) - // - transforms (transform onto a pixel boundary, or transform into a pixel crack) - // - fill - // - opaque image / transparent image - // - opacity - // - blend mode - // - x / y position on partial pixel boundaries - // - others? - - private NGRectangle rect; - private NGGroup root; - - @Before - public void setup() { - rect = createRectangle(10, 10, 90, 90); - root = createGroup(rect); - } - - /** - * Helper method to get the render root. We have to run both the markCullRegions and getRenderRoot methods - * in order for getRenderRoot to return the correctly computed results. - * - * @param root The root node - * @param dirtyX The x coordinate of the dirty region - * @param dirtyY The y coordinate of the dirty region - * @param dirtyWidth The width of the dirty region - * @param dirtyHeight The height of the dirty region - * @return The NodePath, or null if there are no path elements - */ - private NodePath getRenderRoot(NGGroup root, int dirtyX, int dirtyY, int dirtyWidth, int dirtyHeight) { - final DirtyRegionContainer drc = new DirtyRegionContainer(1); - final RectBounds dirtyRegion = new RectBounds(dirtyX, dirtyY, dirtyX+dirtyWidth, dirtyY+dirtyHeight); - drc.addDirtyRegion(dirtyRegion); - final BaseTransform tx = BaseTransform.IDENTITY_TRANSFORM; - final GeneralTransform3D pvTx = new GeneralTransform3D(); - root.markCullRegions(drc, -1, tx, pvTx); - NodePath path = new NodePath(); - root.getRenderRoot(path, dirtyRegion, 0, tx, pvTx); - return path; - } - - /** - * A quick note about how the NodePath works. - * - * If it is empty, then it means that nothing - * needs to be painted (maybe there were some dirty nodes, but they were completely - * occluded, so we don't need to paint anything). - * - * If it contains *only* the root node, - * then either the root node itself is completely occluding the dirty region, or there was - * no other render root to be found, so we have to paint the whole scene. - * - * If it contains something more than just the root node, then it will be the path from - * the root node down to the render root child. - * - * This method takes the expected root (which may be null) and the rootPath (which can - * never be null). If expectedRoot is null, rootPath must be empty. Otherwise, - * expectedRoot must be the last item in rootPath. - */ - private void assertRenderRoot(NGNode expectedRoot, NodePath rootPath) { - if (expectedRoot == null) { - assertTrue(rootPath.isEmpty()); - } else { - // Get to the end - while (rootPath.hasNext()) rootPath.next(); - assertSame(expectedRoot, rootPath.getCurrentNode()); - } - } - - /** - * Tests the case where the dirty region is completely within the opaque region. - * The rect in this case is dirty. - */ - @Test - public void dirtyRegionWithinOpaqueRegion() { - NodePath rootPath = getRenderRoot(root, 20, 20, 70, 70); - assertRenderRoot(rect, rootPath); - } - - /** - * Tests the case where the dirty region is completely within the opaque region. - * The rect in this case is clean. - */ - @Test - public void dirtyRegionWithinOpaqueRegion_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 20, 20, 70, 70); - assertRenderRoot(null, rootPath); - } - - /** - * Tests the case where the dirty region exactly matches the opaque region. - * The rect is dirty. - */ - @Test - public void dirtyRegionMatchesOpaqueRegion() { - NodePath rootPath = getRenderRoot(root, 10, 10, 90, 90); - assertRenderRoot(rect, rootPath); - } - - /** - * Tests the case where the dirty region exactly matches the opaque region. - * The rect is clean. - */ - @Test - public void dirtyRegionMatchesOpaqueRegion_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 10, 10, 90, 90); - assertRenderRoot(null, rootPath); - } - - /** - * Tests the case where the dirty region is within the opaque region, but shares the - * same top edge. The rect is dirty. - */ - @Test - public void dirtyRegionWithinOpaqueRegionTouchesTop() { - NodePath rootPath = getRenderRoot(root, 20, 10, 70, 70); - assertRenderRoot(rect, rootPath); - } - - /** - * Tests the case where the dirty region is within the opaque region, but shares the - * same top edge. The rect is clean. - */ - @Test - public void dirtyRegionWithinOpaqueRegionTouchesTop_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 20, 10, 70, 70); - assertRenderRoot(null, rootPath); - } - - /** - * Tests the case where the dirty region is within the opaque region, but shares the - * same right edge. The rect is dirty. - */ - @Test - public void dirtyRegionWithinOpaqueRegionTouchesRight() { - NodePath rootPath = getRenderRoot(root, 20, 20, 80, 70); - assertRenderRoot(rect, rootPath); - } - /** - * Tests the case where the dirty region is within the opaque region, but shares the - * same right edge. The rect is clean. - */ - @Test - public void dirtyRegionWithinOpaqueRegionTouchesRight_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 20, 20, 80, 70); - assertRenderRoot(null, rootPath); - } - - /** - * Tests the case where the dirty region is within the opaque region, but shares the - * same bottom edge. The rect is dirty. - */ - @Test - public void dirtyRegionWithinOpaqueRegionTouchesBottom() { - NodePath rootPath = getRenderRoot(root, 20, 20, 70, 80); - assertRenderRoot(rect, rootPath); - } - - /** - * Tests the case where the dirty region is within the opaque region, but shares the - * same bottom edge. The rect is clean. - */ - @Test - public void dirtyRegionWithinOpaqueRegionTouchesBottom_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 20, 20, 70, 80); - assertRenderRoot(null, rootPath); - } - - /** - * Tests the case where the dirty region is within the opaque region, but shares the - * same left edge. The rect is dirty. - */ - @Test - public void dirtyRegionWithinOpaqueRegionTouchesLeft() { - NodePath rootPath = getRenderRoot(root, 10, 20, 70, 70); - assertRenderRoot(rect, rootPath); - } - - /** - * Tests the case where the dirty region is within the opaque region, but shares the - * same left edge. The rect is clean. - */ - @Test - public void dirtyRegionWithinOpaqueRegionTouchesLeft_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 10, 20, 70, 70); - assertRenderRoot(null, rootPath); - } - - @Test - public void opaqueRegionWithinDirtyRegion() { - NodePath rootPath = getRenderRoot(root, 0, 0, 110, 110); - assertRenderRoot(root, rootPath); - } - - @Test - public void opaqueRegionWithinDirtyRegion_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 0, 0, 110, 110); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionIntersectsOpaqueRegionTop() { - NodePath rootPath = getRenderRoot(root, 20, 0, 70, 30); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionIntersectsOpaqueRegionTop_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 20, 0, 70, 30); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionIntersectsOpaqueRegionRight() { - NodePath rootPath = getRenderRoot(root, 90, 20, 30, 70); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionIntersectsOpaqueRegionRight_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 90, 20, 30, 70); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionIntersectsOpaqueRegionBottom() { - NodePath rootPath = getRenderRoot(root, 20, 90, 70, 30); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionIntersectsOpaqueRegionBottom_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 20, 90, 70, 30); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionIntersectsOpaqueRegionLeft() { - NodePath rootPath = getRenderRoot(root, 0, 20, 30, 70); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionIntersectsOpaqueRegionLeft_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 0, 20, 30, 70); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionCompletelyOutsideOfOpaqueRegion() { - NodePath rootPath = getRenderRoot(root, 0, 0, 5, 5); - assertRenderRoot(root, rootPath); - } - - @Test - public void dirtyRegionCompletelyOutsideOfOpaqueRegion_Clean() { - root.clearDirtyTree(); - NodePath rootPath = getRenderRoot(root, 0, 0, 5, 5); - assertRenderRoot(root, rootPath); - } - - @Ignore("What is the right thing here? It seems that an empty dirty region should result in no rendering?") - @Test - public void emptyDirtyRegion() { - NodePath rootPath = getRenderRoot(root, 0, 0, -1, -1); - assertRenderRoot(root, rootPath); - } - - @Ignore("Currently fails because isEmpty doesn't take into account width == 0, height == 0") - @Test - public void zeroSizeDirtyRegionWithinOpaqueRegion() { - NodePath rootPath = getRenderRoot(root, 20, 20, 0, 0); - assertRenderRoot(root, rootPath); - } - - /** - * Tests that a clip works. Note that I send the dirty region to be the same - * size as what I expect the clip to be, so that the test will fail if the - * dirty region ends up being larger than the computed clip. - */ - @Test - public void withRectangularClip() { - NGRectangle clip = createRectangle(20, 20, 70, 70); - rect.setClipNode(clip); - NodePath rootPath = getRenderRoot(root, 20, 20, 70, 70); - assertRenderRoot(rect, rootPath); - } - - /** - * The negative test, where the clip is smaller than the dirty region - */ - @Test - public void withRectangularClip_negative() { - NGRectangle clip = createRectangle(20, 20, 70, 70); - rect.setClipNode(clip); - NodePath rootPath = getRenderRoot(root, 19, 20, 70, 70); - assertRenderRoot(root, rootPath); - } - - /** - * Tests that a clip works when translated. - */ - @Test - public void withRectangularClipTranslated() { - NGRectangle clip = createRectangle(20, 20, 70, 70); - clip.setTransformMatrix(BaseTransform.getTranslateInstance(10, 10)); - rect.setClipNode(clip); - NodePath rootPath = getRenderRoot(root, 30, 30, 70, 70); - assertRenderRoot(rect, rootPath); - } - - /** - * Tests that a clip works when translated. - */ - @Test - public void withRectangularClipTranslated_negative() { - NGRectangle clip = createRectangle(20, 20, 70, 70); - clip.setTransformMatrix(BaseTransform.getTranslateInstance(10, 10)); - rect.setClipNode(clip); - NodePath rootPath = getRenderRoot(root, 29, 30, 70, 70); - assertRenderRoot(root, rootPath); - } - - /** - * Note, scales about origin, not center - */ - @Test - public void withRectangularClipScaled() { - NGRectangle clip = createRectangle(20, 20, 70, 70); - clip.setTransformMatrix(BaseTransform.getScaleInstance(.5, .5)); - rect.setClipNode(clip); - NodePath rootPath = getRenderRoot(root, 10, 10, 35, 35); - assertRenderRoot(rect, rootPath); - } - - /** - * Note, scales about origin, not center - */ - @Test - public void withRectangularClipScaled_negative() { - NGRectangle clip = createRectangle(20, 20, 70, 70); - clip.setTransformMatrix(BaseTransform.getScaleInstance(.5, .5)); - rect.setClipNode(clip); - NodePath rootPath = getRenderRoot(root, 9, 10, 35, 35); - assertRenderRoot(root, rootPath); - } - - /** - * We can now easily use ellipse and ellipse and images etc as clips - * in addition to rect clips. Here I choose a dirty region that is - * clearly in the center of the ellipse's area so as to pass the test. - */ - @Test - public void withCircleClip() { - NGCircle clip = createCircle(50, 50, 45); - rect.setClipNode(clip); - NodePath rootPath = getRenderRoot(root, 40, 40, 20, 20); - assertRenderRoot(rect, rootPath); - } - - /** - * Make the dirty area larger than the clip so as to fail. - */ - @Test - public void withCircleClip_negative() { - NGCircle clip = createCircle(50, 50, 45); - rect.setClipNode(clip); - NodePath rootPath = getRenderRoot(root, 10, 10, 90, 90); - assertRenderRoot(root, rootPath); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/RenderRootTest.java 2015-09-11 21:24:37.757286840 -0400 @@ -0,0 +1,437 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import com.sun.javafx.geom.DirtyRegionContainer; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; +import com.sun.javafx.sg.prism.NGCircle; +import com.sun.javafx.sg.prism.NGGroup; +import com.sun.javafx.sg.prism.NGNode; +import com.sun.javafx.sg.prism.NGNodeShim; +import com.sun.javafx.sg.prism.NGRectangle; +import com.sun.javafx.sg.prism.NodePath; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + * Tests for the computation of the render root of a graph + */ +public class RenderRootTest extends NGTestBase { + // NGNodes to test: NGRectangle, NGImageView, NGRegion, NGCircle, NGEllipse + // Also thrown in 3D transforms and 2D transforms other than BASE_TRANSFORM + // Structures to test: root, background, foreground + // - Foreground completely covers background. + // - Foreground partially overlaps background + // Test each node has exactly the expected opaque region, given: + // - stroke + // - effect + // - clip (dirty region should only include the intersection of the clip & bounds) + // - transforms (transform onto a pixel boundary, or transform into a pixel crack) + // - fill + // - opaque image / transparent image + // - opacity + // - blend mode + // - x / y position on partial pixel boundaries + // - others? + + private NGRectangle rect; + private NGGroup root; + + @Before + public void setup() { + rect = createRectangle(10, 10, 90, 90); + root = createGroup(rect); + } + + /** + * Helper method to get the render root. We have to run both the markCullRegions and getRenderRoot methods + * in order for getRenderRoot to return the correctly computed results. + * + * @param root The root node + * @param dirtyX The x coordinate of the dirty region + * @param dirtyY The y coordinate of the dirty region + * @param dirtyWidth The width of the dirty region + * @param dirtyHeight The height of the dirty region + * @return The NodePath, or null if there are no path elements + */ + private NodePath getRenderRoot(NGGroup root, int dirtyX, int dirtyY, int dirtyWidth, int dirtyHeight) { + final DirtyRegionContainer drc = new DirtyRegionContainer(1); + final RectBounds dirtyRegion = new RectBounds(dirtyX, dirtyY, dirtyX+dirtyWidth, dirtyY+dirtyHeight); + drc.addDirtyRegion(dirtyRegion); + final BaseTransform tx = BaseTransform.IDENTITY_TRANSFORM; + final GeneralTransform3D pvTx = new GeneralTransform3D(); + NGNodeShim.markCullRegions(root, drc, -1, tx, pvTx); + NodePath path = new NodePath(); + root.getRenderRoot(path, dirtyRegion, 0, tx, pvTx); + return path; + } + + /** + * A quick note about how the NodePath works. + * + * If it is empty, then it means that nothing + * needs to be painted (maybe there were some dirty nodes, but they were completely + * occluded, so we don't need to paint anything). + * + * If it contains *only* the root node, + * then either the root node itself is completely occluding the dirty region, or there was + * no other render root to be found, so we have to paint the whole scene. + * + * If it contains something more than just the root node, then it will be the path from + * the root node down to the render root child. + * + * This method takes the expected root (which may be null) and the rootPath (which can + * never be null). If expectedRoot is null, rootPath must be empty. Otherwise, + * expectedRoot must be the last item in rootPath. + */ + private void assertRenderRoot(NGNode expectedRoot, NodePath rootPath) { + if (expectedRoot == null) { + assertTrue(rootPath.isEmpty()); + } else { + // Get to the end + while (rootPath.hasNext()) rootPath.next(); + assertSame(expectedRoot, rootPath.getCurrentNode()); + } + } + + /** + * Tests the case where the dirty region is completely within the opaque region. + * The rect in this case is dirty. + */ + @Test + public void dirtyRegionWithinOpaqueRegion() { + NodePath rootPath = getRenderRoot(root, 20, 20, 70, 70); + assertRenderRoot(rect, rootPath); + } + + /** + * Tests the case where the dirty region is completely within the opaque region. + * The rect in this case is clean. + */ + @Test + public void dirtyRegionWithinOpaqueRegion_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 20, 20, 70, 70); + assertRenderRoot(null, rootPath); + } + + /** + * Tests the case where the dirty region exactly matches the opaque region. + * The rect is dirty. + */ + @Test + public void dirtyRegionMatchesOpaqueRegion() { + NodePath rootPath = getRenderRoot(root, 10, 10, 90, 90); + assertRenderRoot(rect, rootPath); + } + + /** + * Tests the case where the dirty region exactly matches the opaque region. + * The rect is clean. + */ + @Test + public void dirtyRegionMatchesOpaqueRegion_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 10, 10, 90, 90); + assertRenderRoot(null, rootPath); + } + + /** + * Tests the case where the dirty region is within the opaque region, but shares the + * same top edge. The rect is dirty. + */ + @Test + public void dirtyRegionWithinOpaqueRegionTouchesTop() { + NodePath rootPath = getRenderRoot(root, 20, 10, 70, 70); + assertRenderRoot(rect, rootPath); + } + + /** + * Tests the case where the dirty region is within the opaque region, but shares the + * same top edge. The rect is clean. + */ + @Test + public void dirtyRegionWithinOpaqueRegionTouchesTop_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 20, 10, 70, 70); + assertRenderRoot(null, rootPath); + } + + /** + * Tests the case where the dirty region is within the opaque region, but shares the + * same right edge. The rect is dirty. + */ + @Test + public void dirtyRegionWithinOpaqueRegionTouchesRight() { + NodePath rootPath = getRenderRoot(root, 20, 20, 80, 70); + assertRenderRoot(rect, rootPath); + } + /** + * Tests the case where the dirty region is within the opaque region, but shares the + * same right edge. The rect is clean. + */ + @Test + public void dirtyRegionWithinOpaqueRegionTouchesRight_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 20, 20, 80, 70); + assertRenderRoot(null, rootPath); + } + + /** + * Tests the case where the dirty region is within the opaque region, but shares the + * same bottom edge. The rect is dirty. + */ + @Test + public void dirtyRegionWithinOpaqueRegionTouchesBottom() { + NodePath rootPath = getRenderRoot(root, 20, 20, 70, 80); + assertRenderRoot(rect, rootPath); + } + + /** + * Tests the case where the dirty region is within the opaque region, but shares the + * same bottom edge. The rect is clean. + */ + @Test + public void dirtyRegionWithinOpaqueRegionTouchesBottom_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 20, 20, 70, 80); + assertRenderRoot(null, rootPath); + } + + /** + * Tests the case where the dirty region is within the opaque region, but shares the + * same left edge. The rect is dirty. + */ + @Test + public void dirtyRegionWithinOpaqueRegionTouchesLeft() { + NodePath rootPath = getRenderRoot(root, 10, 20, 70, 70); + assertRenderRoot(rect, rootPath); + } + + /** + * Tests the case where the dirty region is within the opaque region, but shares the + * same left edge. The rect is clean. + */ + @Test + public void dirtyRegionWithinOpaqueRegionTouchesLeft_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 10, 20, 70, 70); + assertRenderRoot(null, rootPath); + } + + @Test + public void opaqueRegionWithinDirtyRegion() { + NodePath rootPath = getRenderRoot(root, 0, 0, 110, 110); + assertRenderRoot(root, rootPath); + } + + @Test + public void opaqueRegionWithinDirtyRegion_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 0, 0, 110, 110); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionIntersectsOpaqueRegionTop() { + NodePath rootPath = getRenderRoot(root, 20, 0, 70, 30); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionIntersectsOpaqueRegionTop_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 20, 0, 70, 30); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionIntersectsOpaqueRegionRight() { + NodePath rootPath = getRenderRoot(root, 90, 20, 30, 70); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionIntersectsOpaqueRegionRight_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 90, 20, 30, 70); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionIntersectsOpaqueRegionBottom() { + NodePath rootPath = getRenderRoot(root, 20, 90, 70, 30); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionIntersectsOpaqueRegionBottom_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 20, 90, 70, 30); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionIntersectsOpaqueRegionLeft() { + NodePath rootPath = getRenderRoot(root, 0, 20, 30, 70); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionIntersectsOpaqueRegionLeft_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 0, 20, 30, 70); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionCompletelyOutsideOfOpaqueRegion() { + NodePath rootPath = getRenderRoot(root, 0, 0, 5, 5); + assertRenderRoot(root, rootPath); + } + + @Test + public void dirtyRegionCompletelyOutsideOfOpaqueRegion_Clean() { + root.clearDirtyTree(); + NodePath rootPath = getRenderRoot(root, 0, 0, 5, 5); + assertRenderRoot(root, rootPath); + } + + @Ignore("What is the right thing here? It seems that an empty dirty region should result in no rendering?") + @Test + public void emptyDirtyRegion() { + NodePath rootPath = getRenderRoot(root, 0, 0, -1, -1); + assertRenderRoot(root, rootPath); + } + + @Ignore("Currently fails because isEmpty doesn't take into account width == 0, height == 0") + @Test + public void zeroSizeDirtyRegionWithinOpaqueRegion() { + NodePath rootPath = getRenderRoot(root, 20, 20, 0, 0); + assertRenderRoot(root, rootPath); + } + + /** + * Tests that a clip works. Note that I send the dirty region to be the same + * size as what I expect the clip to be, so that the test will fail if the + * dirty region ends up being larger than the computed clip. + */ + @Test + public void withRectangularClip() { + NGRectangle clip = createRectangle(20, 20, 70, 70); + rect.setClipNode(clip); + NodePath rootPath = getRenderRoot(root, 20, 20, 70, 70); + assertRenderRoot(rect, rootPath); + } + + /** + * The negative test, where the clip is smaller than the dirty region + */ + @Test + public void withRectangularClip_negative() { + NGRectangle clip = createRectangle(20, 20, 70, 70); + rect.setClipNode(clip); + NodePath rootPath = getRenderRoot(root, 19, 20, 70, 70); + assertRenderRoot(root, rootPath); + } + + /** + * Tests that a clip works when translated. + */ + @Test + public void withRectangularClipTranslated() { + NGRectangle clip = createRectangle(20, 20, 70, 70); + clip.setTransformMatrix(BaseTransform.getTranslateInstance(10, 10)); + rect.setClipNode(clip); + NodePath rootPath = getRenderRoot(root, 30, 30, 70, 70); + assertRenderRoot(rect, rootPath); + } + + /** + * Tests that a clip works when translated. + */ + @Test + public void withRectangularClipTranslated_negative() { + NGRectangle clip = createRectangle(20, 20, 70, 70); + clip.setTransformMatrix(BaseTransform.getTranslateInstance(10, 10)); + rect.setClipNode(clip); + NodePath rootPath = getRenderRoot(root, 29, 30, 70, 70); + assertRenderRoot(root, rootPath); + } + + /** + * Note, scales about origin, not center + */ + @Test + public void withRectangularClipScaled() { + NGRectangle clip = createRectangle(20, 20, 70, 70); + clip.setTransformMatrix(BaseTransform.getScaleInstance(.5, .5)); + rect.setClipNode(clip); + NodePath rootPath = getRenderRoot(root, 10, 10, 35, 35); + assertRenderRoot(rect, rootPath); + } + + /** + * Note, scales about origin, not center + */ + @Test + public void withRectangularClipScaled_negative() { + NGRectangle clip = createRectangle(20, 20, 70, 70); + clip.setTransformMatrix(BaseTransform.getScaleInstance(.5, .5)); + rect.setClipNode(clip); + NodePath rootPath = getRenderRoot(root, 9, 10, 35, 35); + assertRenderRoot(root, rootPath); + } + + /** + * We can now easily use ellipse and ellipse and images etc as clips + * in addition to rect clips. Here I choose a dirty region that is + * clearly in the center of the ellipse's area so as to pass the test. + */ + @Test + public void withCircleClip() { + NGCircle clip = createCircle(50, 50, 45); + rect.setClipNode(clip); + NodePath rootPath = getRenderRoot(root, 40, 40, 20, 20); + assertRenderRoot(rect, rootPath); + } + + /** + * Make the dirty area larger than the clip so as to fail. + */ + @Test + public void withCircleClip_negative() { + NGCircle clip = createCircle(50, 50, 45); + rect.setClipNode(clip); + NodePath rootPath = getRenderRoot(root, 10, 10, 90, 90); + assertRenderRoot(root, rootPath); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/sg/prism/TestGraphics.java 2015-09-11 21:24:38.521286831 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,323 +0,0 @@ -/* - * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.sg.prism; - -import java.nio.Buffer; -import com.sun.glass.ui.Screen; -import com.sun.javafx.font.FontStrike; -import com.sun.javafx.geom.RectBounds; -import com.sun.javafx.geom.Shape; -import com.sun.javafx.geom.transform.BaseTransform; -import com.sun.javafx.scene.text.GlyphList; -import com.sun.prism.BasicStroke; -import com.sun.prism.Graphics; -import com.sun.prism.Image; -import com.sun.prism.MediaFrame; -import com.sun.prism.Mesh; -import com.sun.prism.MeshView; -import com.sun.prism.PhongMaterial; -import com.sun.prism.PixelFormat; -import com.sun.prism.Presentable; -import com.sun.prism.PresentableState; -import com.sun.prism.RTTexture; -import com.sun.prism.RenderTarget; -import com.sun.prism.ResourceFactory; -import com.sun.prism.ResourceFactoryListener; -import com.sun.prism.Texture; -import com.sun.prism.Texture.WrapMode; -import com.sun.prism.impl.BaseContext; -import com.sun.prism.impl.BaseGraphics; -import com.sun.prism.impl.TextureResourcePool; -import com.sun.prism.impl.VertexBuffer; -import com.sun.prism.paint.Color; -import com.sun.prism.shape.ShapeRep; - - -/** - * - */ -public class TestGraphics extends BaseGraphics { - - public static final Graphics TEST_GRAPHICS = new TestGraphics(); - - public TestGraphics() { - super(new TestContext(), new TestRenderTarget()); - } - - @Override - protected void renderShape(Shape shape, BasicStroke stroke, float bx, float by, float bw, float bh) { - } - - public void clear(Color color) { - } - - public void clearQuad(float x1, float y1, float x2, float y2) { - } - - public void fillQuad(float x1, float y1, float x2, float y2) { - } - - public void fillRect(float x, float y, float width, float height) { - } - - public void fillRoundRect(float x, float y, float width, float height, float arcw, float arch) { - } - - public void fillEllipse(float x, float y, float width, float height) { - } - - public void drawLine(float x1, float y1, float x2, float y2) { - } - - public void drawRect(float x, float y, float width, float height) { - } - - public void drawRoundRect(float x, float y, float width, float height, float arcw, float arch) { - } - - public void drawEllipse(float x, float y, float width, float height) { - } - - public void setNodeBounds(RectBounds bounds) { - } - - @Override public void drawString(GlyphList gl, FontStrike strike, float x, float y, Color selectColor, int selectStart, int selectEnd) { - } - - @Override public void drawTexture(Texture tex, float x, float y, float w, float h) { - } - - @Override - public void drawTexture(Texture tex, float dx1, float dy1, float dx2, float dy2, float sx1, float sy1, float sx2, float sy2) { - } - - @Override - public void drawTexture3SliceH(Texture tex, float dx1, float dy1, float dx2, float dy2, float sx1, float sy1, float sx2, float sy2, float dh1, float dh2, float sh1, float sh2) { - } - - @Override - public void drawTexture3SliceV(Texture tex, float dx1, float dy1, float dx2, float dy2, float sx1, float sy1, float sx2, float sy2, float dv1, float dv2, float sv1, float sv2) { - } - - @Override - public void drawTexture9Slice(Texture tex, float dx1, float dy1, float dx2, float dy2, float sx1, float sy1, float sx2, float sy2, float dh1, float dv1, float dh2, float dv2, float sh1, float sv1, float sh2, float sv2) { - } - - public void sync() { - } - - @Override - public void setState3D(boolean flag) { - } - - @Override - public boolean isState3D() { - return false; - } - - public void setup3DRendering() { - } - - public void blit(RTTexture srcTex, RTTexture dstTex, int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1) { - } - - private static class TestContext extends BaseContext { - - public TestContext() { - super(null, new TestResourceFactory(), null); - } - - @Override - protected void setRenderTarget(RenderTarget target, NGCamera camera, boolean depthTest, boolean state3D) { - } - - @Override - public void validateClearOp(BaseGraphics g) { - } - - @Override - public void validatePaintOp(BaseGraphics g, BaseTransform xform, Texture maskTex, float bx, float by, float bw, float bh) { - } - - @Override - public void validateTextureOp(BaseGraphics g, BaseTransform xform, Texture src, PixelFormat format) { - } - - @Override - public RTTexture getLCDBuffer() { - return null; - } - } - - private static class TestResourceFactory implements ResourceFactory { - @Override public boolean isDeviceReady() { return true; } - - @Override public TextureResourcePool getTextureResourcePool() { return null; } - @Override public Texture createTexture(Image image, Texture.Usage usageHint, WrapMode wrapMode) { return null; } - @Override public Texture createTexture(Image image, Texture.Usage usageHint, Texture.WrapMode wrapMode, boolean useMipmap) { return null; } - @Override public Texture createTexture(PixelFormat formatHint, Texture.Usage usageHint, WrapMode wrapMode, int w, int h) { return null; } - @Override public Texture createTexture(PixelFormat formatHint, Texture.Usage usageHint, Texture.WrapMode wrapMode, int w, int h, boolean useMipmap) { return null; } - @Override public Texture createTexture(MediaFrame frame) { return null; } - @Override public boolean isCompatibleTexture(Texture tex) { return true; } - @Override public boolean isWrapModeSupported(Texture.WrapMode mode) { return true; } - @Override public Texture getCachedTexture(Image image, WrapMode wrapMode) { return null; } - @Override public Texture getCachedTexture(Image image, WrapMode wrapMode, boolean useMipmap) { return null; } - @Override public boolean isFormatSupported(PixelFormat format) { return false; } - @Override public int getMaximumTextureSize() { return 0; } - @Override public Texture createMaskTexture(int width, int height, Texture.WrapMode wrapMode) { return null; } - @Override public Texture createFloatTexture(int width, int height) { return null; } - @Override public int getRTTWidth(int w, WrapMode wrapMode) { return w; } - @Override public int getRTTHeight(int h, WrapMode wrapMode) { return h; } - @Override public RTTexture createRTTexture(final int width, final int height, Texture.WrapMode wrapMode) { - return createRTTexture(width, height, wrapMode, false); - } - @Override public RTTexture createRTTexture(final int width, final int height, Texture.WrapMode wrapMode, boolean msaa) { - return new RTTexture() { - @Override public int[] getPixels() { return new int[0]; } - @Override public boolean readPixels(Buffer pixels, int x, int y, int width, int height) { return false; } - @Override public boolean readPixels(Buffer pixels) { return false; } - @Override public boolean isVolatile() { return false; } - @Override public boolean isSurfaceLost() { return false; } - @Override public Screen getAssociatedScreen() { return null; } - @Override public Graphics createGraphics() { - return new TestGraphics(); - } - - @Override public Texture getSharedTexture(WrapMode altMode) { return null; } - @Override public boolean isOpaque() { return false; } - @Override public PixelFormat getPixelFormat() { return null; } - @Override public int getPhysicalWidth() { return width; } - @Override public int getPhysicalHeight() { return height; } - @Override public int getContentX() { return 0; } - @Override public int getContentY() { return 0; } - @Override public int getContentWidth() { return width; } - @Override public int getContentHeight() { return height; } - @Override public int getLastImageSerial() { return 0; } - @Override public void setLastImageSerial(int serial) { } - @Override public void update(Image img) { } - @Override public void update(Image img, int dstx, int dsty) { } - @Override public void update(Image img, int dstx, int dsty, int srcw, int srch) { } - @Override public void update(Image img, int dstx, int dsty, int srcw, int srch, boolean skipFlush) { } - @Override public void update(Buffer buffer, PixelFormat format, int dstx, int dsty, int srcx, int srcy, int srcw, int srch, int srcscan, boolean skipFlush) { } - @Override public void update(MediaFrame frame, boolean skipFlush) { } - @Override public WrapMode getWrapMode() { return null; } - @Override public boolean getLinearFiltering() { return false; } - @Override public void setLinearFiltering(boolean linear) { } - @Override public void dispose() { } - @Override public void lock() { } - @Override public void unlock() { } - @Override public boolean isLocked() { return true; } - @Override public int getLockCount() { return 1; } - @Override public void assertLocked() { } - @Override public void makePermanent() { } - @Override public void contentsUseful() { } - @Override public void contentsNotUseful() { } - @Override public void setOpaque(boolean opaque) { } - @Override public boolean isMSAA() { return false; } - @Override public int getMaxContentWidth() { return getPhysicalWidth(); } - @Override public int getMaxContentHeight() { return getPhysicalHeight(); } - @Override public void setContentWidth(int contentWidth) { } - @Override public void setContentHeight(int contentHeight) { } - @Override public boolean getUseMipmap() { return false; } - }; - } - @Override public Presentable createPresentable(PresentableState pstate) { return null; } - @Override public VertexBuffer createVertexBuffer(int maxQuads) { return null; } - @Override public ShapeRep createPathRep() { return null; } - @Override public ShapeRep createRoundRectRep() { return null; } - @Override public ShapeRep createEllipseRep() { return null; } - @Override public ShapeRep createArcRep() { return null; } - @Override public void addFactoryListener(ResourceFactoryListener l) { } - @Override public void removeFactoryListener(ResourceFactoryListener l) { } - @Override public void dispose() { } - - @Override public PhongMaterial createPhongMaterial() { return null; } - @Override public MeshView createMeshView(Mesh mesh) { return null; } - @Override public Mesh createMesh() { return null; } - @Override public void setRegionTexture(Texture texture) { } - @Override public Texture getRegionTexture() { return null; } - @Override public void setGlyphTexture(Texture texture) { } - @Override public Texture getGlyphTexture() { return null; } - @Override public boolean isSuperShaderAllowed() {return false; } - - } - - private static class TestRenderTarget implements RenderTarget { - - public Screen getAssociatedScreen() { - return null; - } - - public Graphics createGraphics() { - return null; - } - - public boolean isOpaque() { - return true; - } - - public void setOpaque(boolean opaque) { - } - - public int getPhysicalWidth() { - return 0; - } - - public int getPhysicalHeight() { - return 0; - } - - public int getContentX() { - return 0; - } - - public int getContentY() { - return 0; - } - - public int getContentWidth() { - return 0; - } - - public int getContentHeight() { - return 0; - } - - public boolean isMSAA() { - return false; - } - - } - - @Override - public void setLights(NGLightBase[] lights) { - } - - @Override - public NGLightBase[] getLights() { - return null; - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/sg/prism/TestGraphics.java 2015-09-11 21:24:38.381286833 -0400 @@ -0,0 +1,325 @@ +/* + * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.sg.prism; + +import java.nio.Buffer; +import com.sun.glass.ui.Screen; +import com.sun.javafx.font.FontStrike; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.Shape; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.scene.text.GlyphList; +import com.sun.javafx.sg.prism.NGCamera; +import com.sun.javafx.sg.prism.NGLightBase; +import com.sun.prism.BasicStroke; +import com.sun.prism.Graphics; +import com.sun.prism.Image; +import com.sun.prism.MediaFrame; +import com.sun.prism.Mesh; +import com.sun.prism.MeshView; +import com.sun.prism.PhongMaterial; +import com.sun.prism.PixelFormat; +import com.sun.prism.Presentable; +import com.sun.prism.PresentableState; +import com.sun.prism.RTTexture; +import com.sun.prism.RenderTarget; +import com.sun.prism.ResourceFactory; +import com.sun.prism.ResourceFactoryListener; +import com.sun.prism.Texture; +import com.sun.prism.Texture.WrapMode; +import com.sun.prism.impl.BaseContext; +import com.sun.prism.impl.BaseGraphics; +import com.sun.prism.impl.TextureResourcePool; +import com.sun.prism.impl.VertexBuffer; +import com.sun.prism.paint.Color; +import com.sun.prism.shape.ShapeRep; + + +/** + * + */ +public class TestGraphics extends BaseGraphics { + + public static final Graphics TEST_GRAPHICS = new TestGraphics(); + + public TestGraphics() { + super(new TestContext(), new TestRenderTarget()); + } + + @Override + protected void renderShape(Shape shape, BasicStroke stroke, float bx, float by, float bw, float bh) { + } + + public void clear(Color color) { + } + + public void clearQuad(float x1, float y1, float x2, float y2) { + } + + public void fillQuad(float x1, float y1, float x2, float y2) { + } + + public void fillRect(float x, float y, float width, float height) { + } + + public void fillRoundRect(float x, float y, float width, float height, float arcw, float arch) { + } + + public void fillEllipse(float x, float y, float width, float height) { + } + + public void drawLine(float x1, float y1, float x2, float y2) { + } + + public void drawRect(float x, float y, float width, float height) { + } + + public void drawRoundRect(float x, float y, float width, float height, float arcw, float arch) { + } + + public void drawEllipse(float x, float y, float width, float height) { + } + + public void setNodeBounds(RectBounds bounds) { + } + + @Override public void drawString(GlyphList gl, FontStrike strike, float x, float y, Color selectColor, int selectStart, int selectEnd) { + } + + @Override public void drawTexture(Texture tex, float x, float y, float w, float h) { + } + + @Override + public void drawTexture(Texture tex, float dx1, float dy1, float dx2, float dy2, float sx1, float sy1, float sx2, float sy2) { + } + + @Override + public void drawTexture3SliceH(Texture tex, float dx1, float dy1, float dx2, float dy2, float sx1, float sy1, float sx2, float sy2, float dh1, float dh2, float sh1, float sh2) { + } + + @Override + public void drawTexture3SliceV(Texture tex, float dx1, float dy1, float dx2, float dy2, float sx1, float sy1, float sx2, float sy2, float dv1, float dv2, float sv1, float sv2) { + } + + @Override + public void drawTexture9Slice(Texture tex, float dx1, float dy1, float dx2, float dy2, float sx1, float sy1, float sx2, float sy2, float dh1, float dv1, float dh2, float dv2, float sh1, float sv1, float sh2, float sv2) { + } + + public void sync() { + } + + @Override + public void setState3D(boolean flag) { + } + + @Override + public boolean isState3D() { + return false; + } + + public void setup3DRendering() { + } + + public void blit(RTTexture srcTex, RTTexture dstTex, int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1) { + } + + private static class TestContext extends BaseContext { + + public TestContext() { + super(null, new TestResourceFactory(), null); + } + + @Override + protected void setRenderTarget(RenderTarget target, NGCamera camera, boolean depthTest, boolean state3D) { + } + + @Override + public void validateClearOp(BaseGraphics g) { + } + + @Override + public void validatePaintOp(BaseGraphics g, BaseTransform xform, Texture maskTex, float bx, float by, float bw, float bh) { + } + + @Override + public void validateTextureOp(BaseGraphics g, BaseTransform xform, Texture src, PixelFormat format) { + } + + @Override + public RTTexture getLCDBuffer() { + return null; + } + } + + private static class TestResourceFactory implements ResourceFactory { + @Override public boolean isDeviceReady() { return true; } + + @Override public TextureResourcePool getTextureResourcePool() { return null; } + @Override public Texture createTexture(Image image, Texture.Usage usageHint, WrapMode wrapMode) { return null; } + @Override public Texture createTexture(Image image, Texture.Usage usageHint, Texture.WrapMode wrapMode, boolean useMipmap) { return null; } + @Override public Texture createTexture(PixelFormat formatHint, Texture.Usage usageHint, WrapMode wrapMode, int w, int h) { return null; } + @Override public Texture createTexture(PixelFormat formatHint, Texture.Usage usageHint, Texture.WrapMode wrapMode, int w, int h, boolean useMipmap) { return null; } + @Override public Texture createTexture(MediaFrame frame) { return null; } + @Override public boolean isCompatibleTexture(Texture tex) { return true; } + @Override public boolean isWrapModeSupported(Texture.WrapMode mode) { return true; } + @Override public Texture getCachedTexture(Image image, WrapMode wrapMode) { return null; } + @Override public Texture getCachedTexture(Image image, WrapMode wrapMode, boolean useMipmap) { return null; } + @Override public boolean isFormatSupported(PixelFormat format) { return false; } + @Override public int getMaximumTextureSize() { return 0; } + @Override public Texture createMaskTexture(int width, int height, Texture.WrapMode wrapMode) { return null; } + @Override public Texture createFloatTexture(int width, int height) { return null; } + @Override public int getRTTWidth(int w, WrapMode wrapMode) { return w; } + @Override public int getRTTHeight(int h, WrapMode wrapMode) { return h; } + @Override public RTTexture createRTTexture(final int width, final int height, Texture.WrapMode wrapMode) { + return createRTTexture(width, height, wrapMode, false); + } + @Override public RTTexture createRTTexture(final int width, final int height, Texture.WrapMode wrapMode, boolean msaa) { + return new RTTexture() { + @Override public int[] getPixels() { return new int[0]; } + @Override public boolean readPixels(Buffer pixels, int x, int y, int width, int height) { return false; } + @Override public boolean readPixels(Buffer pixels) { return false; } + @Override public boolean isVolatile() { return false; } + @Override public boolean isSurfaceLost() { return false; } + @Override public Screen getAssociatedScreen() { return null; } + @Override public Graphics createGraphics() { + return new TestGraphics(); + } + + @Override public Texture getSharedTexture(WrapMode altMode) { return null; } + @Override public boolean isOpaque() { return false; } + @Override public PixelFormat getPixelFormat() { return null; } + @Override public int getPhysicalWidth() { return width; } + @Override public int getPhysicalHeight() { return height; } + @Override public int getContentX() { return 0; } + @Override public int getContentY() { return 0; } + @Override public int getContentWidth() { return width; } + @Override public int getContentHeight() { return height; } + @Override public int getLastImageSerial() { return 0; } + @Override public void setLastImageSerial(int serial) { } + @Override public void update(Image img) { } + @Override public void update(Image img, int dstx, int dsty) { } + @Override public void update(Image img, int dstx, int dsty, int srcw, int srch) { } + @Override public void update(Image img, int dstx, int dsty, int srcw, int srch, boolean skipFlush) { } + @Override public void update(Buffer buffer, PixelFormat format, int dstx, int dsty, int srcx, int srcy, int srcw, int srch, int srcscan, boolean skipFlush) { } + @Override public void update(MediaFrame frame, boolean skipFlush) { } + @Override public WrapMode getWrapMode() { return null; } + @Override public boolean getLinearFiltering() { return false; } + @Override public void setLinearFiltering(boolean linear) { } + @Override public void dispose() { } + @Override public void lock() { } + @Override public void unlock() { } + @Override public boolean isLocked() { return true; } + @Override public int getLockCount() { return 1; } + @Override public void assertLocked() { } + @Override public void makePermanent() { } + @Override public void contentsUseful() { } + @Override public void contentsNotUseful() { } + @Override public void setOpaque(boolean opaque) { } + @Override public boolean isMSAA() { return false; } + @Override public int getMaxContentWidth() { return getPhysicalWidth(); } + @Override public int getMaxContentHeight() { return getPhysicalHeight(); } + @Override public void setContentWidth(int contentWidth) { } + @Override public void setContentHeight(int contentHeight) { } + @Override public boolean getUseMipmap() { return false; } + }; + } + @Override public Presentable createPresentable(PresentableState pstate) { return null; } + @Override public VertexBuffer createVertexBuffer(int maxQuads) { return null; } + @Override public ShapeRep createPathRep() { return null; } + @Override public ShapeRep createRoundRectRep() { return null; } + @Override public ShapeRep createEllipseRep() { return null; } + @Override public ShapeRep createArcRep() { return null; } + @Override public void addFactoryListener(ResourceFactoryListener l) { } + @Override public void removeFactoryListener(ResourceFactoryListener l) { } + @Override public void dispose() { } + + @Override public PhongMaterial createPhongMaterial() { return null; } + @Override public MeshView createMeshView(Mesh mesh) { return null; } + @Override public Mesh createMesh() { return null; } + @Override public void setRegionTexture(Texture texture) { } + @Override public Texture getRegionTexture() { return null; } + @Override public void setGlyphTexture(Texture texture) { } + @Override public Texture getGlyphTexture() { return null; } + @Override public boolean isSuperShaderAllowed() {return false; } + + } + + private static class TestRenderTarget implements RenderTarget { + + public Screen getAssociatedScreen() { + return null; + } + + public Graphics createGraphics() { + return null; + } + + public boolean isOpaque() { + return true; + } + + public void setOpaque(boolean opaque) { + } + + public int getPhysicalWidth() { + return 0; + } + + public int getPhysicalHeight() { + return 0; + } + + public int getContentX() { + return 0; + } + + public int getContentY() { + return 0; + } + + public int getContentWidth() { + return 0; + } + + public int getContentHeight() { + return 0; + } + + public boolean isMSAA() { + return false; + } + + } + + @Override + public void setLights(NGLightBase[] lights) { + } + + @Override + public NGLightBase[] getLights() { + return null; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/BBoxComparator.java 2015-09-11 21:24:39.005286826 -0400 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import javafx.geometry.Bounds; + +public class BBoxComparator extends ValueComparator { + + private double delta; + + public BBoxComparator(double delta) { + this.delta = delta; + } + + @Override + public boolean equals(Object expected, Object actual) { + if (expected == actual) { + return true; + } + + if (!(expected instanceof Bounds)) { + return false; + } + if (!(actual instanceof Bounds)) { + return false; + } + + Bounds bExpectend = (Bounds) expected; + Bounds bActual = (Bounds) actual; + + if (Math.abs(bExpectend.getMinX() - bActual.getMinX()) > delta) { + return false; + } + if (Math.abs(bExpectend.getMinY() - bActual.getMinY()) > delta) { + return false; + } + if (Math.abs(bExpectend.getMaxX() - bActual.getMaxX()) > delta) { + return false; + } + if (Math.abs(bExpectend.getMaxY() - bActual.getMaxY()) > delta) { + return false; + } + + return true; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/BindingHelper.java 2015-09-11 21:24:39.821286817 -0400 @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import java.lang.reflect.Method; + +import javafx.beans.property.SimpleStringProperty; +import javafx.beans.value.ObservableStringValue; +import javafx.beans.value.WritableObjectValue; + +import test.com.sun.javafx.test.binding.BindingProxy; +import test.com.sun.javafx.test.binding.BindingProxyRefImpl; +import test.com.sun.javafx.test.binding.ReflectionHelper; + +public final class BindingHelper { + private BindingHelper() { + } + + public static Object getPropertyModel( + final Object bean, + final PropertyReference propertyReference) { + final Method modelMethod = ReflectionHelper.getMethod( + bean.getClass(), + propertyReference.getPropertyName() + + "Property"); + + return ReflectionHelper.invokeMethod(bean, modelMethod); + } + + public static Object createVariable(final Object value) { + final Class typeClass = (value != null) ? value.getClass() + : Object.class; + final Object variable = createVariable(typeClass); + setWritableValue(typeClass, variable, value); + return variable; + } + + public static Object createVariable(final Class typeClass) { + final BindingProxy bindingProxy = getBindingProxy(typeClass); + return bindingProxy.getVariableFactory().createVariable(); + } + + public static Object getObservableValue(final Class typeClass, + final Object observableValue) { + final BindingProxy bindingProxy = getBindingProxy(typeClass); + return bindingProxy.getObservableValueProxy().getValue(observableValue); + } + + public static void setWritableValue(final Object writableValue, + final Object value) { + setWritableValue(value.getClass(), writableValue, value); + } + + public static void setWritableValue(final Class typeClass, + final Object writableValue, + final Object value) { + final BindingProxy bindingProxy = getBindingProxy(typeClass); + bindingProxy.getWritableValueProxy().setValue(writableValue, value); + } + + public static void bind(final Object bean, + final PropertyReference propertyReference, + final Object observableValue) { + final Object propertyModel = getPropertyModel(bean, propertyReference); + bind(propertyReference.getValueType(), propertyModel, observableValue); + } + + public static void bind( + final Class typeClass, + final Object propertyModel, + final Object observableValue) { + final BindingProxy bindingProxy = getBindingProxy(typeClass); + bindingProxy.getPropertyModelProxy().bind(propertyModel, + observableValue); + } + + public static void unbind(final Object bean, + final PropertyReference propertyReference) { + final Object propertyModel = getPropertyModel(bean, propertyReference); + unbind(propertyReference.getValueType(), propertyModel); + } + + public static void unbind(final Class typeClass, + final Object propertyModel) { + final BindingProxy bindingProxy = getBindingProxy(typeClass); + bindingProxy.getPropertyModelProxy().unbind(propertyModel); + } + + private static final BindingProxy[] BINDING_PROXY_LIST = { + BindingProxyRefImpl.autoLookup("Boolean"), + BindingProxyRefImpl.autoLookup("Integer"), + BindingProxyRefImpl.autoLookup("Long"), + BindingProxyRefImpl.autoLookup("Float"), + BindingProxyRefImpl.autoLookup("Double"), + // special handling of String + // (WritableStringValue is not defined) + new BindingProxyRefImpl(String.class, + ObservableStringValue.class, + WritableObjectValue.class, + SimpleStringProperty.class, + SimpleStringProperty.class), + BindingProxyRefImpl.autoLookup("Object") + }; + + private static BindingProxy getBindingProxy( + Class typeClass) { + if (typeClass.isPrimitive()) { + typeClass = getWrapperClassForPrimitiveType(typeClass); + } + + for (final BindingProxy proxy: BINDING_PROXY_LIST) { + if (proxy.getTypeClass().isAssignableFrom(typeClass)) { + return proxy; + } + } + + // won't happen + throw new RuntimeException(); + } + + private static Class getWrapperClassForPrimitiveType( + final Class typeClass) { + if (typeClass == boolean.class) { + return Boolean.class; + } else if (typeClass == int.class) { + return Integer.class; + } else if (typeClass == long.class) { + return Long.class; + } else if (typeClass == float.class) { + return Float.class; + } else if (typeClass == double.class) { + return Double.class; + } else { + return null; + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/CssMethodsTestBase.java 2015-09-11 21:24:40.609286808 -0400 @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import java.util.Iterator; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import javafx.scene.Node; + +import org.junit.Test; + +import javafx.css.StyleConverter; +import javafx.css.CssMetaData; +import java.util.List; +import javafx.css.Styleable; +import javafx.css.StyleableProperty; + +public abstract class CssMethodsTestBase { + private final Configuration configuration; + + public CssMethodsTestBase(final Configuration configuration) { + this.configuration = configuration; + } + + + @Test // This _must_ be the first test! + public void testCssDefaultSameAsPropertyDefault() { + configuration.cssDefaultsTest(); + } + + @Test + public void testCSSPropertyAndCSSPropertyReferenceEachOther() { + configuration.cssPropertyReferenceIntegrityTest(); + } + + @Test + public void testCssSettable() throws Exception { + configuration.cssSettableTest(); + } + + @Test + public void testCssSet() { + configuration.cssSetTest(); + } + + public static Object[] config( + final Node node, + final String propertyName, + final Object initialValue, + final String cssPropertyKey, + final Object cssPropertyValue) { + return config(new Configuration(node, + propertyName, + initialValue, + cssPropertyKey, + cssPropertyValue)); + } + + public static Object[] config( + final Node node, + final String propertyName, + final Object initialValue, + final String cssPropertyKey, + final Object cssPropertyValue, + final Object expectedFinalValue) { + return config(new Configuration(node, + propertyName, + initialValue, + cssPropertyKey, + cssPropertyValue, + expectedFinalValue)); + } + + public static Object[] config( + final Node node, + final String propertyName, + final Object initialValue, + final String cssPropertyKey, + final Object cssPropertyValue, + final ValueComparator comparator) { + return config(new Configuration(node, + propertyName, + initialValue, + cssPropertyKey, + cssPropertyValue, + comparator)); + } + + public static Object[] config(final Configuration configuration) { + return new Object[] { configuration }; + } + + private static CssMetaData getCssMetaData(Node node, String cssProperty) { + + List> styleables = node.getCssMetaData(); + for(CssMetaData styleable : styleables) { + if (styleable.getProperty().equals(cssProperty)) { + return styleable; + } + } + fail(node.toString() + ": CSSProperty" + cssProperty + " not found"); + return null; + } + + public static class Configuration { + private static final StyleConverter TEST_TYPE = + new StyleConverter(); + + private static final CssMetaData UNDEFINED_KEY = + new CssMetaData("U-N-D-E-F-I-N-E-D", TEST_TYPE, "") { + + @Override + public boolean isSettable(Node n) { + return false; + } + + @Override + public StyleableProperty getStyleableProperty(Node n) { + return null; + } + }; + + private final Node node; + + private final PropertyReference nodePropertyReference; + + private final Object initialValue; + + private final Object defaultValue; + + private final CssMetaData cssPropertyKey; + + private final Object cssPropertyValue; + + private final Object expectedFinalValue; + + private final ValueComparator comparator; + + public Configuration(final Node node, + final String propertyName, + final Object initialValue, + final String cssPropertyKey, + final Object cssPropertyValue) { + this(node, + propertyName, + initialValue, + cssPropertyKey, + cssPropertyValue, + ValueComparator.DEFAULT); + } + + public Configuration(final Node node, + final String propertyName, + final Object initialValue, + final String cssPropertyKey, + final Object cssPropertyValue, + final Object finalExpectedValue) { + this(node, + propertyName, + initialValue, + getCssMetaData(node, cssPropertyKey), + cssPropertyValue, + finalExpectedValue, + ValueComparator.DEFAULT); + } + + public Configuration(final Node node, + final String propertyName, + final Object initialValue, + final String cssPropertyKey, + final Object cssPropertyValue, + final ValueComparator comparator) { + this(node, + propertyName, + initialValue, + getCssMetaData(node, cssPropertyKey), + cssPropertyValue, + cssPropertyValue, + comparator); + } + + public Configuration(final Node node, + final String propertyName, + final Object initialValue, + final CssMetaData cssPropertyKey, + final Object cssPropertyValue, + final Object expectedFinalValue, + final ValueComparator comparator) { + this.node = node; + this.nodePropertyReference = + PropertyReference.createForBean(node.getClass(), + propertyName); + this.initialValue = initialValue; + this.defaultValue = this.nodePropertyReference.getValue(this.node); + this.cssPropertyKey = cssPropertyKey; + this.cssPropertyValue = cssPropertyValue; + this.expectedFinalValue = expectedFinalValue; + this.comparator = comparator; + } + + public void cssSettableTest() throws Exception { + assertFalse(UNDEFINED_KEY.isSettable(node)); + assertTrue(cssPropertyKey.isSettable(node)); + + final Object propertyModel = BindingHelper.getPropertyModel( + node, nodePropertyReference); + assertTrue(cssPropertyKey.isSettable(node)); + + final Class typeClass = nodePropertyReference.getValueType(); + + final Object variable = BindingHelper.createVariable(typeClass); + BindingHelper.setWritableValue(typeClass, variable, initialValue); + + BindingHelper.bind(typeClass, propertyModel, variable); + assertFalse(cssPropertyKey.isSettable(node)); + + BindingHelper.unbind(typeClass, propertyModel); + assertTrue(cssPropertyKey.isSettable(node)); + } + + public void cssSetTest() { + nodePropertyReference.setValue(node, initialValue); + StyleableProperty styleableProperty = cssPropertyKey.getStyleableProperty(node); + styleableProperty.applyStyle(null, cssPropertyValue); + + final Object nodePropertyValue = + nodePropertyReference.getValue(node); + comparator.assertEquals(expectedFinalValue, + nodePropertyValue); + } + + public void cssDefaultsTest() { + + // is the cssInitialValue the same as the node property's default? + final Object cssInitialValue = + cssPropertyKey.getInitialValue(node); + + ValueComparator.DEFAULT.assertEquals(defaultValue, cssInitialValue); + } + + public void cssPropertyReferenceIntegrityTest() { + + StyleableProperty prop = cssPropertyKey.getStyleableProperty(node); + + CssMetaData styleable = prop.getCssMetaData(); + + ValueComparator.DEFAULT.assertEquals(cssPropertyKey, styleable); + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/DoubleComparator.java 2015-09-11 21:24:41.337286800 -0400 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +public class DoubleComparator extends ValueComparator { + + private double delta; + + public DoubleComparator(double delta) { + this.delta = delta; + } + + @Override + public boolean equals(Object expected, Object actual) { + if (expected == actual) { + return true; + } + + if (!(expected instanceof Number)) { + return false; + } + if (!(actual instanceof Number)) { + return false; + } + + double bExpectend = ((Number) expected).doubleValue(); + double bActual = ((Number) actual).doubleValue(); + + if (Math.abs(bExpectend - bActual) > delta) { + return false; + } + + return true; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/MouseEventGenerator.java 2015-09-11 21:24:42.081286791 -0400 @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import javafx.event.EventType; +import javafx.scene.input.MouseButton; +import javafx.scene.input.MouseEvent; + +public final class MouseEventGenerator { + + public static MouseEvent generateMouseEvent(EventType type, + double x, double y) { + + MouseButton button = MouseButton.NONE; + if (type == MouseEvent.MOUSE_PRESSED || + type == MouseEvent.MOUSE_RELEASED || + type == MouseEvent.MOUSE_DRAGGED) { + button = MouseButton.PRIMARY; + } + + boolean primaryButtonDown = false; + + if (type == MouseEvent.MOUSE_PRESSED || + type == MouseEvent.MOUSE_DRAGGED) { + primaryButtonDown = true; + } + + if (type == MouseEvent.MOUSE_RELEASED) { + primaryButtonDown = false; + } + + MouseEvent event = new MouseEvent(type, x, y, x, y, button, + 1, false, false, false, false, primaryButtonDown, + false, false, false, false, false, null); + + return event; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/NodeOrientationTestBase.java 2015-09-11 21:24:42.801286783 -0400 @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import java.util.List; +import javafx.geometry.NodeOrientation; +import javafx.scene.Group; +import javafx.scene.Node; +import javafx.scene.Parent; +import javafx.scene.ParentShim; +import javafx.scene.Scene; +import javafx.scene.SubScene; + +public abstract class NodeOrientationTestBase { + protected NodeOrientationTestBase() { + } + + public interface StateEncoder { + char map(Scene scene); + char map(Node node); + } + + protected static Scene ltrScene(final Parent rootNode) { + final Scene scene = new Scene(rootNode); + scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); + return scene; + } + + protected static Group ltrAutGroup(final Node... childNodes) { + return autGroup(NodeOrientation.LEFT_TO_RIGHT, childNodes); + } + + protected static Group rtlAutGroup(final Node... childNodes) { + return autGroup(NodeOrientation.RIGHT_TO_LEFT, childNodes); + } + + protected static Group inhAutGroup(final Node... childNodes) { + return autGroup(NodeOrientation.INHERIT, childNodes); + } + + protected static SubScene inhSubScene(final Parent rootNode) { + final SubScene subScene = new SubScene(rootNode, 400, 300); + subScene.setNodeOrientation(NodeOrientation.INHERIT); + return subScene; + } + + protected static Group ltrManGroup(final Node... childNodes) { + return manGroup(NodeOrientation.LEFT_TO_RIGHT, childNodes); + } + + protected static Group rtlManGroup(final Node... childNodes) { + return manGroup(NodeOrientation.RIGHT_TO_LEFT, childNodes); + } + + protected static Group inhManGroup(final Node... childNodes) { + return manGroup(NodeOrientation.INHERIT, childNodes); + } + + protected static void updateOrientation(final Scene scene, + final String updateString) { + final NodeOrientation update = + decode(updateString.charAt(0)); + if (update != null) { + scene.setNodeOrientation(update); + } + + final Node rootNode = scene.getRoot(); + if (rootNode != null) { + updateOrientation(rootNode, updateString, 1); + } + } + + protected static String collectState(final Scene scene, + final StateEncoder encoder) { + final StringBuilder dest = new StringBuilder(); + collectState(dest, scene, encoder); + return dest.toString(); + } + + protected static String collectState(final Node node, + final StateEncoder encoder) { + final StringBuilder dest = new StringBuilder(); + collectState(dest, node, encoder); + return dest.toString(); + } + + private static Group autGroup(final NodeOrientation nodeOrientation, + final Node... childNodes) { + final Group group = new Group(); + group.setNodeOrientation(nodeOrientation); + ParentShim.getChildren(group).setAll(childNodes); + + return group; + } + + private static Group manGroup(final NodeOrientation nodeOrientation, + final Node... childNodes) { + final Group group = new Group() { + @Override + public boolean usesMirroring() { + return false; + } + }; + group.setNodeOrientation(nodeOrientation); + ParentShim.getChildren(group).setAll(childNodes); + + return group; + } + + private static int updateOrientation(final Node node, + final String updateString, + final int index) { + final NodeOrientation update = + decode(updateString.charAt(index)); + if (update != null) { + node.setNodeOrientation(update); + } + + int nextIndex = index + 1; + if (node instanceof Parent) { + final List childNodes = + ((Parent) node).getChildrenUnmodifiable(); + for (final Node childNode: childNodes) { + nextIndex = updateOrientation(childNode, updateString, + nextIndex); + } + } else if (node instanceof SubScene) { + final Node nextRoot = ((SubScene) node).getRoot(); + nextIndex = updateOrientation(nextRoot, updateString, + nextIndex); + } + + return nextIndex; + } + + private static NodeOrientation decode(final char updateChar) { + switch (updateChar) { + case '.': + return null; + case 'L': + return NodeOrientation.LEFT_TO_RIGHT; + case 'R': + return NodeOrientation.RIGHT_TO_LEFT; + case 'I': + return NodeOrientation.INHERIT; + default: + throw new IllegalArgumentException("Invalid update character"); + } + } + + private static void collectState(final StringBuilder dest, + final Scene scene, + final StateEncoder encoder) { + dest.append(encoder.map(scene)); + final Node rootNode = scene.getRoot(); + if (rootNode != null) { + collectState(dest, rootNode, encoder); + } + } + + private static void collectState(final StringBuilder dest, + final Node node, + final StateEncoder encoder) { + dest.append(encoder.map(node)); + if (node instanceof Parent) { + final List childNodes = + ((Parent) node).getChildrenUnmodifiable(); + for (final Node childNode: childNodes) { + collectState(dest, childNode, encoder); + } + } else if (node instanceof SubScene) { + final Node nextRoot = ((SubScene) node).getRoot(); + collectState(dest, nextRoot, encoder); + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/ObjectMethodsTestBase.java 2015-09-11 21:24:43.525286775 -0400 @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.fail; + +import org.junit.Test; + +public abstract class ObjectMethodsTestBase { + private final Configuration configuration; + + public ObjectMethodsTestBase(final Configuration configuration) { + this.configuration = configuration; + } + + @Test + public void testEquals() { + configuration.equalsTest(); + } + + @Test + public void testHashCode() { + configuration.hashCodeTest(); + } + + @Test + public void testToString() { + configuration.toStringTest(); + } + + public static Object[] equalObjects(final Object... objects) { + return config(new Configuration(EQUAL_OBJECTS_EQUALS_TEST, + EQUAL_OBJECTS_HASHCODE_TEST, + EQUAL_OBJECTS_TOSTRING_TEST, + objects)); + } + + public static Object[] differentObjects( + final Object... objects) { + return config(new Configuration(DIFFERENT_OBJECTS_EQUALS_TEST, + DIFFERENT_OBJECTS_HARD_HASHCODE_TEST, + DIFFERENT_OBJECTS_TOSTRING_TEST, + objects)); + } + + public static Object[] differentObjectsEasyHashcode( + final Object... objects) { + return config(new Configuration(DIFFERENT_OBJECTS_EQUALS_TEST, + DIFFERENT_OBJECTS_EASY_HASHCODE_TEST, + DIFFERENT_OBJECTS_TOSTRING_TEST, + objects)); + } + + public static Object[] differentObjectsMediumHashcode( + final Object... objects) { + return config(new Configuration(DIFFERENT_OBJECTS_EQUALS_TEST, + DIFFERENT_OBJECTS_MEDIUM_HASHCODE_TEST, + DIFFERENT_OBJECTS_TOSTRING_TEST, + objects)); + } + + public static Object[] config(final Configuration configuration) { + return new Object[] { configuration }; + } + + public static final class Configuration { + private final Object[] objects; + + private final TestInstance equalsTest; + + private final TestInstance hashCodeTest; + + private final TestInstance toStringTest; + + public Configuration(final TestInstance equalsTest, + final TestInstance hashCodeTest, + final TestInstance toStringTest, + final Object... objects) { + this.equalsTest = equalsTest; + this.hashCodeTest = hashCodeTest; + this.toStringTest = toStringTest; + this.objects = objects; + } + + public void equalsTest() { + if (equalsTest != null) { + equalsTest.test(objects); + } + } + + public void hashCodeTest() { + if (hashCodeTest != null) { + hashCodeTest.test(objects); + } + } + + public void toStringTest() { + if (toStringTest != null) { + toStringTest.test(objects); + } + } + } + + public interface TestInstance { + void test(Object[] objects); + } + + public static final TestInstance EQUAL_OBJECTS_EQUALS_TEST = + objects -> { + for (int i = 0; i < objects.length; ++i) { + for (int j = 0; j < objects.length; ++j) { + assertEquals(objects[i], objects[j]); + } + assertFalse(objects[i].equals(null)); + } + }; + + public static final TestInstance EQUAL_OBJECTS_HASHCODE_TEST = + objects -> { + for (int i = 0; i < objects.length; ++i) { + for (int j = 0; j < objects.length; ++j) { + assertEquals(objects[i].hashCode(), + objects[j].hashCode()); + } + } + }; + + public static final TestInstance EQUAL_OBJECTS_TOSTRING_TEST = + objects -> { + for (int i = 0; i < objects.length; ++i) { + for (int j = 0; j < objects.length; ++j) { + assertEquals(objects[i].toString(), + objects[j].toString()); + } + } + }; + + public static final TestInstance DIFFERENT_OBJECTS_EQUALS_TEST = + objects -> { + for (int i = 0; i < objects.length; ++i) { + for (int j = 0; j < objects.length; ++j) { + if (i != j) { + assertFalse(objects[i].equals(objects[j])); + } + } + assertFalse(objects[i].equals(null)); + } + }; + + public static final TestInstance DIFFERENT_OBJECTS_EASY_HASHCODE_TEST = + objects -> { + // if objects are different, their hashcodes can return the + // same or different values + }; + + public static final TestInstance DIFFERENT_OBJECTS_MEDIUM_HASHCODE_TEST = + objects -> { + // we require that at least one tested object returns a + // different hash code value + final int firstHashCodeValue = objects[0].hashCode(); + for (int i = 1; i < objects.length; ++i) { + if (objects[i].hashCode() != firstHashCodeValue) { + return; + } + } + + // all the hash codes are same, this violates our criteria + fail(); + }; + + public static final TestInstance DIFFERENT_OBJECTS_HARD_HASHCODE_TEST = + objects -> { + // we require that at all tested objects returns a different + // hash code value + for (int i = 0; i < objects.length; ++i) { + for (int j = 0; j < objects.length; ++j) { + if (i != j) { + assertNotSame(objects[i].hashCode(), + objects[j].hashCode()); + } + } + } + }; + + public static final TestInstance DIFFERENT_OBJECTS_TOSTRING_TEST = + objects -> { + for (int i = 0; i < objects.length; ++i) { + for (int j = 0; j < objects.length; ++j) { + if (i != j) { + assertFalse(objects[i].toString().equals( + objects[j].toString())); + } + } + } + }; +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/OnInvalidateMethodsTestBase.java 2015-09-11 21:24:44.109286768 -0400 @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Method; +import java.util.List; + +import javafx.scene.Node; +import test.javafx.scene.NodeTest; +import javafx.scene.shape.MoveTo; +import javafx.scene.shape.Path; +import javafx.scene.shape.PathElement; +import javafx.scene.shape.Rectangle; +import javafx.scene.transform.Transform; + +import org.junit.Test; + +import javafx.css.CssMetaData; +import com.sun.javafx.scene.DirtyBits; + +public abstract class OnInvalidateMethodsTestBase { + + private final Configuration configuration; + + public OnInvalidateMethodsTestBase(final Configuration configuration) { + this.configuration = configuration; + } + + @Test + public void testFireOnInvalidate() throws Exception { + configuration.testFireOnInvalidate(); + } + + public static class Configuration { + Class clazz; + String propertyName; + Object inValue; + Object[] expectedDirtyBits; + + public Configuration(Class clazz, String parameterName, + Object inValue, Object[] expectedDirtyBits) { + this.clazz = clazz; + this.propertyName = parameterName; + this.inValue = inValue; + this.expectedDirtyBits = expectedDirtyBits; + } + + static final String GET_PREFIX = "get"; + static final String IS_PREFIX = "is"; + static final String SET_PREFIX = "set"; + + public void testFireOnInvalidate() throws Exception { + StringBuilder sb = new StringBuilder(this.propertyName); + sb.setCharAt(0, Character.toUpperCase(propertyName.charAt(0))); + + if (clazz.getSuperclass().equals(PathElement.class)) { + PathElement e = (PathElement)clazz.newInstance(); + Path path = new Path(); + path.getElements().addAll(new MoveTo(0,0), e); + NodeTest.syncNode(path); + getSetter(clazz, sb.toString()).invoke(e, this.inValue); + assertTrue(NodeTest.isDirty(path, (DirtyBits[])this.expectedDirtyBits)); + } else if (clazz.getSuperclass().equals(Transform.class)) { + Transform tr = (Transform)clazz.newInstance(); + Rectangle rect = new Rectangle(); + rect.getTransforms().add(tr); + NodeTest.syncNode(rect); + getSetter(clazz, sb.toString()).invoke(tr, this.inValue); + assertTrue(NodeTest.isDirty(rect, (DirtyBits[])this.expectedDirtyBits)); + } else { + Node node = (Node)clazz.newInstance(); + NodeTest.syncNode(node); + getSetter(clazz, sb.toString()).invoke(node, this.inValue); + if (this.expectedDirtyBits instanceof DirtyBits[]) { + assertTrue(NodeTest.isDirty(node, (DirtyBits[])this.expectedDirtyBits)); + } else if (this.expectedDirtyBits instanceof CssMetaData[]) { + for(CssMetaData key:(CssMetaData[])this.expectedDirtyBits) { + assertTrue(key.isSettable(node)); + } + } + } + + } + + private Path getPathNode(Class pathElementClazz) throws Exception { + Path p = new Path(); + p.getElements().addAll(new MoveTo(0,0), pathElementClazz.newInstance()); + return p; + } + + private Method getSetter(Class cls, String name) throws Exception { + Method getter = (inValue instanceof Boolean) ? + cls.getMethod(IS_PREFIX + name, new Class[]{}) : + cls.getMethod(GET_PREFIX + name, new Class[]{}); + return cls.getMethod(SET_PREFIX + name, getter.getReturnType()); + } + } + +// protected static CssMetaData findCssKey(Class clazz, String propertyName) { +// final List STYLEABLES = CssMetaData.getStyleables(clazz); +// for(CssMetaData styleable : STYLEABLES) { +// if (styleable.getProperty().equals(propertyName)) return styleable; +// } +// return null; +// } + + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/PropertiesTestBase.java 2015-09-11 21:24:44.777286761 -0400 @@ -0,0 +1,453 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import javafx.beans.property.ReadOnlyProperty; +import javafx.beans.InvalidationListener; +import javafx.beans.Observable; +import javafx.beans.value.ObservableValue; + +import org.junit.Assert; +import org.junit.Test; + +public abstract class PropertiesTestBase { + + private final Configuration configuration; + + public PropertiesTestBase(final Configuration configuration) { + this.configuration = configuration; + } + + @Test + public void testGetBean() { + configuration.getBeanTest(); + } + + @Test + public void testGetName() { + configuration.getNameTest(); + } + + @Test + public void testBasicAccess() { + configuration.basicAccessTest(); + } + + @Test + public void testBinding() { + configuration.bindingTest(); + } + + /** + * Single bean, single property configuration. + */ + public static Object[] config(final Object bean, + final String propertyName, + final Object propertyValue1, + final Object propertyValue2) { + return config(new Configuration(bean, + propertyName, + propertyValue1, + propertyValue2)); + } + + /** + * Single bean, single property configuration with custom value comparator. + */ + public static Object[] config(final Object bean, + final String propertyName, + final Object propertyValue1, + final Object propertyValue2, + final ValueComparator comparator) { + return config(new Configuration(bean, + propertyName, + propertyValue1, + propertyValue2, + comparator)); + } + + /** + * Single bean, propertyA (source) and propertyB (dependent) property + * configuration. + */ + public static Object[] config(final Object beanA, + final String propertyAName, + final Object propertyAValue1, + final Object propertyAValue2, + final String propertyBName, + final Object propertyBValue1, + final Object propertyBValue2) { + return config(new Configuration(beanA, + propertyAName, + propertyAValue1, + propertyAValue2, + propertyBName, + propertyBValue1, + propertyBValue2)); + } + + /** + * BeanA with propertyA (source) and BeanB with propertyB (dependent) + * configuration. + */ + public static Object[] config(final Object beanA, + final String propertyAName, + final Object propertyAValue1, + final Object propertyAValue2, + final Object beanB, + final String propertyBName, + final Object propertyBValue1, + final Object propertyBValue2) { + return config(new Configuration(beanA, + propertyAName, + propertyAValue1, + propertyAValue2, + beanB, + propertyBName, + propertyBValue1, + propertyBValue2)); + } + + /** + * BeanA with propertyA (source) and BeanB with propertyB (dependent) + * with custom value comparator configuration. + */ + public static Object[] config(final Object beanA, + final String propertyAName, + final Object propertyAValue1, + final Object propertyAValue2, + final Object beanB, + final String propertyBName, + final Object propertyBValue1, + final Object propertyBValue2, + final ValueComparator propertyBComparator) { + return config(new Configuration(beanA, + propertyAName, + propertyAValue1, + propertyAValue2, + beanB, + propertyBName, + propertyBValue1, + propertyBValue2, + propertyBComparator)); + } + + public static Object[] config(final Configuration configuration) { + return new Object[] { configuration }; + } + + public static class Configuration { + private final Object beanA; + + private final PropertyReference propertyAReference; + + private final Object propertyAValue1; + + private final Object propertyAValue2; + + private final Object beanB; + + private final PropertyReference propertyBReference; + + private final Object propertyBValue1; + + private final Object propertyBValue2; + + private final ValueComparator propertyBComparator; + + private boolean allowMultipleNotifications; + + public Configuration(final Object bean, + final String propertyName, + final Object propertyValue1, + final Object propertyValue2) { + this(bean, propertyName, propertyValue1, propertyValue2, + bean, propertyName, propertyValue1, propertyValue2, + ValueComparator.DEFAULT); + } + + public Configuration(final Object bean, + final String propertyName, + final Object propertyValue1, + final Object propertyValue2, + final ValueComparator valueComparator) { + this(bean, propertyName, propertyValue1, propertyValue2, + bean, propertyName, propertyValue1, propertyValue2, + valueComparator); + } + + public Configuration(final Object bean, + final String propertyAName, + final Object propertyAValue1, + final Object propertyAValue2, + final String propertyBName, + final Object propertyBValue1, + final Object propertyBValue2) { + this(bean, propertyAName, propertyAValue1, propertyAValue2, + bean, propertyBName, propertyBValue1, propertyBValue2, + ValueComparator.DEFAULT); + } + + public Configuration(final Object beanA, + final String propertyAName, + final Object propertyAValue1, + final Object propertyAValue2, + final Object beanB, + final String propertyBName, + final Object propertyBValue1, + final Object propertyBValue2) { + this(beanA, propertyAName, propertyAValue1, propertyAValue2, + beanB, propertyBName, propertyBValue1, propertyBValue2, + ValueComparator.DEFAULT); + } + + public Configuration(final Object beanA, + final String propertyAName, + final Object propertyAValue1, + final Object propertyAValue2, + final Object beanB, + final String propertyBName, + final Object propertyBValue1, + final Object propertyBValue2, + final ValueComparator propertyBComparator) { + this.beanA = beanA; + this.propertyAReference = PropertyReference.createForBean( + beanA.getClass(), + propertyAName); + this.propertyAValue1 = propertyAValue1; + this.propertyAValue2 = propertyAValue2; + this.beanB = beanB; + this.propertyBReference = PropertyReference.createForBean( + beanB.getClass(), + propertyBName); + this.propertyBValue1 = propertyBValue1; + this.propertyBValue2 = propertyBValue2; + this.propertyBComparator = propertyBComparator; + } + + public void setAllowMultipleNotifications( + final boolean allowMultipleNotifications) { + this.allowMultipleNotifications = allowMultipleNotifications; + } + + public void getBeanTest() { + final ReadOnlyProperty propertyA = + (ReadOnlyProperty) BindingHelper.getPropertyModel( + beanA, propertyAReference); + final ReadOnlyProperty propertyB = + (ReadOnlyProperty) BindingHelper.getPropertyModel( + beanB, propertyBReference); + + Assert.assertSame(beanA, propertyA.getBean()); + Assert.assertSame(beanB, propertyB.getBean()); + } + + public void getNameTest() { + final ReadOnlyProperty propertyA = + (ReadOnlyProperty) BindingHelper.getPropertyModel( + beanA, propertyAReference); + final ReadOnlyProperty propertyB = + (ReadOnlyProperty) BindingHelper.getPropertyModel( + beanB, propertyBReference); + + Assert.assertEquals(propertyAReference.getPropertyName(), + propertyA.getName()); + Assert.assertEquals(propertyBReference.getPropertyName(), + propertyB.getName()); + } + + public void basicAccessTest() { + // set to first value and verify dependet value + propertyAReference.setValue(beanA, propertyAValue1); + propertyBComparator.assertEquals( + propertyBValue1, + propertyBReference.getValue(beanB)); + + final ValueInvalidationListener valueInvalidationListener = + new ValueInvalidationListener(allowMultipleNotifications); + final ObservableValue observableValueB = + (ObservableValue) BindingHelper.getPropertyModel( + beanB, propertyBReference); + + // register listener + observableValueB.addListener(valueInvalidationListener); + + // set to second value + propertyAReference.setValue(beanA, propertyAValue2); + + // verify that the listener has been called + valueInvalidationListener.assertCalled(); + valueInvalidationListener.reset(); + + // test whether the second dependent value is set + propertyBComparator.assertEquals( + propertyBValue2, + propertyBReference.getValue(beanB)); + + // set to the second value again + propertyAReference.setValue(beanA, propertyAValue2); + + // verify that the listener has not been called + valueInvalidationListener.assertNotCalled(); + + // unregister listener + observableValueB.removeListener(valueInvalidationListener); + + // set to the first value again and test + propertyAReference.setValue(beanA, propertyAValue1); + propertyBComparator.assertEquals( + propertyBValue1, + propertyBReference.getValue(beanB)); + + // verify that the listener has not been called + valueInvalidationListener.assertNotCalled(); + } + + public void bindingTest() { + // set to the first value + propertyAReference.setValue(beanA, propertyAValue1); + + // bind to a variable set to second value + final Object firstVariable = + BindingHelper.createVariable(propertyAValue2); + BindingHelper.bind(beanA, propertyAReference, firstVariable); + + // test what we get + propertyBComparator.assertEquals( + propertyBValue2, + propertyBReference.getValue(beanB)); + + final ValueInvalidationListener valueInvalidationListener = + new ValueInvalidationListener(allowMultipleNotifications); + final ObservableValue observableValue = + (ObservableValue) BindingHelper.getPropertyModel( + beanB, propertyBReference); + + // register listener + observableValue.addListener(valueInvalidationListener); + + // change the value of the bound variable + BindingHelper.setWritableValue(propertyAReference.getValueType(), + firstVariable, propertyAValue1); + + // verify that the listener has been called + valueInvalidationListener.assertCalled(); + valueInvalidationListener.reset(); + + // check the value + propertyBComparator.assertEquals( + propertyBValue1, + propertyBReference.getValue(beanB)); + + // change binding + final Object secondVariable = + BindingHelper.createVariable(propertyAValue2); + BindingHelper.bind(beanA, propertyAReference, secondVariable); + + // verify that the listener has been called + valueInvalidationListener.assertCalled(); + valueInvalidationListener.reset(); + + // check the value + propertyBComparator.assertEquals( + propertyBValue2, + propertyBReference.getValue(beanB)); + + // unbind + BindingHelper.unbind(beanA, propertyAReference); + + // verify that the listener has not been called + valueInvalidationListener.assertNotCalled(); + + // change the value of the last bound variable + BindingHelper.setWritableValue(propertyAReference.getValueType(), + secondVariable, propertyAValue1); + + // verify that the listener has not been called + valueInvalidationListener.assertNotCalled(); + + // check that the current property value equals to the last + // value set by binding + propertyBComparator.assertEquals( + propertyBValue2, + propertyBReference.getValue(beanB)); + + // set to the first value again + propertyAReference.setValue(beanA, propertyAValue1); + + // verify that the listener has been called + valueInvalidationListener.assertCalled(); + valueInvalidationListener.reset(); + + // check the value + propertyBComparator.assertEquals( + propertyBValue1, + propertyBReference.getValue(beanB)); + + // unregister listener + observableValue.removeListener(valueInvalidationListener); + } + } + + private static final class ValueInvalidationListener + implements InvalidationListener { + private final boolean allowMultipleNotifications; + + private int counter; + + public ValueInvalidationListener( + final boolean allowMultipleNotifications) { + this.allowMultipleNotifications = allowMultipleNotifications; + } + + public void reset() { + counter = 0; + } + + public void assertCalled() { + if (counter == 0) { + Assert.fail("Listener has not been called!"); + return; + } + + if (!allowMultipleNotifications && (counter > 1)) { + Assert.fail("Listener called multiple times!"); + } + } + + public void assertNotCalled() { + if (counter != 0) { + Assert.fail("Listener has been called!"); + return; + } + } + + @Override + public void invalidated(final Observable valueModel) { + ++counter; + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/PropertyInvalidationCounter.java 2015-09-11 21:24:45.369286754 -0400 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import javafx.beans.InvalidationListener; +import javafx.beans.Observable; +import javafx.beans.value.ObservableValue; + +public final class PropertyInvalidationCounter + implements InvalidationListener { + private int counter; + + @Override + public void invalidated(final Observable observable) { + final ObservableValue observableValue = + (ObservableValue) observable; + + observableValue.getValue(); + ++counter; + } + + public int getCounter() { + return counter; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/PropertyReference.java 2015-09-11 21:24:46.069286746 -0400 @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import java.lang.reflect.Method; + +import test.com.sun.javafx.test.binding.ReflectionHelper; + +public final class PropertyReference { + private final String propertyName; + private final Class valueType; + private final Method getterMethod; + private final Method setterMethod; + + public PropertyReference(final String propertyName, + final Class valueType, + final Method getterMethod, + final Method setterMethod) { + this.propertyName = propertyName; + this.valueType = valueType; + this.getterMethod = getterMethod; + this.setterMethod = setterMethod; + } + + public String getPropertyName() { + return propertyName; + } + + public Class getValueType() { + return valueType; + } + + public Object getValue(final Object object) { + if (getterMethod == null) { + throw new RuntimeException("No getter associated with " + + propertyName + "!"); + } + + return ReflectionHelper.invokeMethod(object, getterMethod); + } + + public void setValue(final Object object, final Object value) { + if (setterMethod == null) { + throw new RuntimeException("No setter associated with " + + propertyName + "!"); + } + + ReflectionHelper.invokeMethod(object, setterMethod, value); + } + + public static PropertyReference createForBean(final Class beanClass, + final String propertyName) { + final String capitalizedPropertyName = capitalizeName(propertyName); + + Method propertyGetterMethod; + try { + propertyGetterMethod = ReflectionHelper.getMethod( + beanClass, + "get" + capitalizedPropertyName); + } catch (final RuntimeException eget) { + // second try with is + try { + propertyGetterMethod = ReflectionHelper.getMethod( + beanClass, + "is" + capitalizedPropertyName); + } catch (final RuntimeException eis) { + throw new RuntimeException("Failed to obtain getter for " + + propertyName + "!"); + } + } + + final Class propertyValueType = propertyGetterMethod.getReturnType(); + + Method propertySetterMethod; + try { + propertySetterMethod = ReflectionHelper.getMethod( + beanClass, + "set" + capitalizedPropertyName, + propertyValueType); + } catch (final RuntimeException e) { + // no setter + propertySetterMethod = null; + } + + return new PropertyReference( + propertyName, + propertyValueType, + propertyGetterMethod, + propertySetterMethod); + } + + private static String capitalizeName(final String input) { + return !input.isEmpty() + ? Character.toUpperCase(input.charAt(0)) + input.substring(1) + : input; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/TestHelper.java 2015-09-11 21:24:46.813286738 -0400 @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.List; + +import javafx.geometry.BoundingBox; +import javafx.geometry.Bounds; +import javafx.scene.Group; +import javafx.scene.Node; + +public class TestHelper { + + // tests that they are within 1px error of being the same. This is to + // account + // for stroke width + public static void assertSimilar(Bounds expected, Bounds actual) { + assertEquals("minX", expected.getMinX(), actual.getMinX(), 1); + assertEquals("minY", expected.getMinY(), actual.getMinY(), 1); + assertEquals("maxX", expected.getMaxX(), actual.getMaxX(), 1); + assertEquals("maxY", expected.getMaxY(), actual.getMaxY(), 1); + } + + public static final float EPSILON = 1.0e-4f; + + public static void assertAlmostEquals(float a, float b) { + assertEquals(a, b, EPSILON); + } + + public static void assertBoundsEqual(Bounds expected, Bounds actual) { + if (expected.isEmpty() && actual.isEmpty()) { + return; + } else { + assertEquals(expected, actual); + } + } + + public static void assertGroupBounds(Group g) { + // first figure out what the 'expected' bounds are + float x1 = 0; + float y1 = 0; + float x2 = -1; + float y2 = -1; + boolean first = true; + for (Node n : g.getChildren()) { + if (n.isVisible() && !n.getBoundsInLocal().isEmpty()) { + if (first) { + x1 = (float) n.getBoundsInParent().getMinX(); + y1 = (float) n.getBoundsInParent().getMinY(); + x2 = (float) n.getBoundsInParent().getMaxX(); + y2 = (float) n.getBoundsInParent().getMaxY(); + first = false; + } else { + x1 = Math.min(x1, (float) n.getBoundsInParent().getMinX()); + y1 = Math.min(y1, (float) n.getBoundsInParent().getMinY()); + x2 = Math.max(x2, (float) n.getBoundsInParent().getMaxX()); + y2 = Math.max(y2, (float) n.getBoundsInParent().getMaxY()); + } + } + } + Bounds expected = box2(x1, y1, x2, y2); + assertBoundsEqual(expected, g.getBoundsInLocal()); + } + + public static String formatBounds(Bounds b) { + return "(" + b.getMinX() + ", " + b.getMinY() + ", " + b.getWidth() + + ", " + b.getHeight() + ")"; + } + + public static BoundingBox box(int minX, int minY, int width, int height) { + return box((float) minX, (float) minY, (float) width, (float) height); + } + + public static BoundingBox box(double minX, double minY, double width, double height) { + return box((float) minX, (float) minY, (float) width, (float) height); + } + + public static BoundingBox box(float minX, float minY, float width, + float height) { + return new BoundingBox(minX, minY, width, height); + } + + public static BoundingBox box(float minX, float minY, float minZ, float width, + float height, float depth) { + return new BoundingBox(minX, minY, minZ, width, height, depth); + } + + public static BoundingBox box2(int minX, int minY, int maxX, int maxY) { + return box2((float) minX, (float) minY, (float) maxX, (float) maxY); + } + + public static BoundingBox box2(float minX, float minY, float maxX, + float maxY) { + return box(minX, minY, maxX - minX, maxY - minY); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static void assertImmutableList(List list) { + try { + list.add(new Object()); + fail("Exception expected while modifying the list."); + } catch (Exception e) { + // expected + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/TransformHelper.java 2015-09-11 21:24:47.609286729 -0400 @@ -0,0 +1,766 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import javafx.scene.transform.Transform; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import com.sun.javafx.geom.transform.Affine3D; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.javafx.geom.transform.GeneralTransform3D; +import com.sun.javafx.scene.transform.TransformUtils; +import javafx.geometry.Point3D; +import javafx.scene.transform.Affine; +import javafx.scene.transform.NonInvertibleTransformException; +import javafx.scene.transform.Rotate; +import javafx.scene.transform.Scale; +import javafx.scene.transform.Shear; +import javafx.scene.transform.Translate; + +/** + * Helper class for transform tests. + */ +public final class TransformHelper { + + /** + * Asserts the {@code matrix} equals to the specified expected values + */ + public static void assertMatrix(Transform matrix, + double mxx, double mxy, double mxz, double tx, + double myx, double myy, double myz, double ty, + double mzx, double mzy, double mzz, double tz) { + assertEquals(mxx, matrix.getMxx(), 0.00001); + assertEquals(mxy, matrix.getMxy(), 0.00001); + assertEquals(mxz, matrix.getMxz(), 0.00001); + assertEquals(tx, matrix.getTx(), 0.00001); + assertEquals(myx, matrix.getMyx(), 0.00001); + assertEquals(myy, matrix.getMyy(), 0.00001); + assertEquals(myz, matrix.getMyz(), 0.00001); + assertEquals(ty, matrix.getTy(), 0.00001); + assertEquals(mzx, matrix.getMzx(), 0.00001); + assertEquals(mzy, matrix.getMzy(), 0.00001); + assertEquals(mzz, matrix.getMzz(), 0.00001); + assertEquals(tz, matrix.getTz(), 0.00001); + } + + /** + * Asserts the {@code matrix} equals to the specified expected values + */ + public static void assertMatrix(BaseTransform matrix, + double mxx, double mxy, double mxz, double tx, + double myx, double myy, double myz, double ty, + double mzx, double mzy, double mzz, double tz) { + assertEquals(mxx, matrix.getMxx(), 0.00001); + assertEquals(mxy, matrix.getMxy(), 0.00001); + assertEquals(mxz, matrix.getMxz(), 0.00001); + assertEquals(tx, matrix.getMxt(), 0.00001); + assertEquals(myx, matrix.getMyx(), 0.00001); + assertEquals(myy, matrix.getMyy(), 0.00001); + assertEquals(myz, matrix.getMyz(), 0.00001); + assertEquals(ty, matrix.getMyt(), 0.00001); + assertEquals(mzx, matrix.getMzx(), 0.00001); + assertEquals(mzy, matrix.getMzy(), 0.00001); + assertEquals(mzz, matrix.getMzz(), 0.00001); + assertEquals(tz, matrix.getMzt(), 0.00001); + } + + /** + * Asserts the {@code matrix} elements equal to the expected values + * specified by {@code reference} + */ + public static void assertMatrix(Transform matrix, + Transform reference) { + assertEquals(reference.getMxx(), matrix.getMxx(), 0.00001); + assertEquals(reference.getMxy(), matrix.getMxy(), 0.00001); + assertEquals(reference.getMxz(), matrix.getMxz(), 0.00001); + assertEquals(reference.getTx(), matrix.getTx(), 0.00001); + assertEquals(reference.getMyx(), matrix.getMyx(), 0.00001); + assertEquals(reference.getMyy(), matrix.getMyy(), 0.00001); + assertEquals(reference.getMyz(), matrix.getMyz(), 0.00001); + assertEquals(reference.getTy(), matrix.getTy(), 0.00001); + assertEquals(reference.getMzx(), matrix.getMzx(), 0.00001); + assertEquals(reference.getMzy(), matrix.getMzy(), 0.00001); + assertEquals(reference.getMzz(), matrix.getMzz(), 0.00001); + assertEquals(reference.getTz(), matrix.getTz(), 0.00001); + } + + /** + * Asserts the {@code matrix} elements equal to the expected values + * specified by {@code reference} + */ + public static void assertMatrix(Affine3D matrix, + BaseTransform reference) { + assertEquals(reference.getMxx(), matrix.getMxx(), 0.00001); + assertEquals(reference.getMxy(), matrix.getMxy(), 0.00001); + assertEquals(reference.getMxz(), matrix.getMxz(), 0.00001); + assertEquals(reference.getMxt(), matrix.getMxt(), 0.00001); + assertEquals(reference.getMyx(), matrix.getMyx(), 0.00001); + assertEquals(reference.getMyy(), matrix.getMyy(), 0.00001); + assertEquals(reference.getMyz(), matrix.getMyz(), 0.00001); + assertEquals(reference.getMyt(), matrix.getMyt(), 0.00001); + assertEquals(reference.getMzx(), matrix.getMzx(), 0.00001); + assertEquals(reference.getMzy(), matrix.getMzy(), 0.00001); + assertEquals(reference.getMzz(), matrix.getMzz(), 0.00001); + assertEquals(reference.getMzt(), matrix.getMzt(), 0.00001); + } + + /** + * Asserts the {@code matrix} elements equal to the expected values + * specified by {@code reference} + */ + public static void assertMatrix(String message, Transform matrix, + Transform reference) { + assertEquals(message, reference.getMxx(), matrix.getMxx(), 0.00001); + assertEquals(message, reference.getMxy(), matrix.getMxy(), 0.00001); + assertEquals(message, reference.getMxz(), matrix.getMxz(), 0.00001); + assertEquals(message, reference.getTx(), matrix.getTx(), 0.00001); + assertEquals(message, reference.getMyx(), matrix.getMyx(), 0.00001); + assertEquals(message, reference.getMyy(), matrix.getMyy(), 0.00001); + assertEquals(message, reference.getMyz(), matrix.getMyz(), 0.00001); + assertEquals(message, reference.getTy(), matrix.getTy(), 0.00001); + assertEquals(message, reference.getMzx(), matrix.getMzx(), 0.00001); + assertEquals(message, reference.getMzy(), matrix.getMzy(), 0.00001); + assertEquals(message, reference.getMzz(), matrix.getMzz(), 0.00001); + assertEquals(message, reference.getTz(), matrix.getTz(), 0.00001); + } + + /** + * Asserts the {@code matrix} elements equal to the expected values + * specified by {@code reference} + */ + public static void assertMatrix(GeneralTransform3D matrix, + GeneralTransform3D reference) { + for (int i = 0; i < 16; i++) { + assertEquals(reference.get(i), matrix.get(i), 0.00001); + } + } + + /** + * Asserts the {@code matrix} is NOT equal to the specified values + */ + public static void assertMatrixDiffers(Transform matrix, + double mxx, double mxy, double mxz, double tx, + double myx, double myy, double myz, double ty, + double mzx, double mzy, double mzz, double tz) { + assertTrue( + mxx != matrix.getMxx() || + mxy != matrix.getMxy() || + mxz != matrix.getMxz() || + tx != matrix.getTx() || + myx != matrix.getMyx() || + myy != matrix.getMyy() || + myz != matrix.getMyz() || + ty != matrix.getTy() || + mzx != matrix.getMzx() || + mzy != matrix.getMzy() || + mzz != matrix.getMzz() || + tz != matrix.getTz()); + } + + /** + * Inverts the given transform. + * @throws NonInvertibleTransformException + */ + public static Transform invert(Transform t) + throws NonInvertibleTransformException { + + final double det = determinant(t); + if (det == 0 || Math.abs(det) <= Double.MIN_VALUE) { + throw new NonInvertibleTransformException("Det is 0"); + } + + final double cxx = minor(t, 0, 0); + final double cyx = - minor(t, 0, 1); + final double czx = minor(t, 0, 2); + final double cxy = - minor(t, 1, 0); + final double cyy = minor(t, 1, 1); + final double czy = - minor(t, 1, 2); + final double cxz = minor(t, 2, 0); + final double cyz = - minor(t, 2, 1); + final double czz = minor(t, 2, 2); + final double cxt = - minor(t, 3, 0); + final double cyt = minor(t, 3, 1); + final double czt = - minor(t, 3, 2); + + return TransformUtils.immutableTransform( + cxx / det, cxy / det, cxz / det, cxt / det, + cyx / det, cyy / det, cyz / det, cyt / det, + czx / det, czy / det, czz / det, czt / det); + } + + /** + * Concatenates the two transforms. + */ + public static Transform concatenate(Transform t1, Transform t2) { + + final double txx = t2.getMxx(); + final double txy = t2.getMxy(); + final double txz = t2.getMxz(); + final double ttx = t2.getTx(); + final double tyx = t2.getMyx(); + final double tyy = t2.getMyy(); + final double tyz = t2.getMyz(); + final double tty = t2.getTy(); + final double tzx = t2.getMzx(); + final double tzy = t2.getMzy(); + final double tzz = t2.getMzz(); + final double ttz = t2.getTz(); + final double rxx = (t1.getMxx() * txx + t1.getMxy() * tyx + t1.getMxz() * tzx /* + getMxt * 0.0 */); + final double rxy = (t1.getMxx() * txy + t1.getMxy() * tyy + t1.getMxz() * tzy /* + getMxt * 0.0 */); + final double rxz = (t1.getMxx() * txz + t1.getMxy() * tyz + t1.getMxz() * tzz /* + getMxt * 0.0 */); + final double rxt = (t1.getMxx() * ttx + t1.getMxy() * tty + t1.getMxz() * ttz + t1.getTx() /* * 1.0 */); + final double ryx = (t1.getMyx() * txx + t1.getMyy() * tyx + t1.getMyz() * tzx /* + getMyt * 0.0 */); + final double ryy = (t1.getMyx() * txy + t1.getMyy() * tyy + t1.getMyz() * tzy /* + getMyt * 0.0 */); + final double ryz = (t1.getMyx() * txz + t1.getMyy() * tyz + t1.getMyz() * tzz /* + getMyt * 0.0 */); + final double ryt = (t1.getMyx() * ttx + t1.getMyy() * tty + t1.getMyz() * ttz + t1.getTy() /* * 1.0 */); + final double rzx = (t1.getMzx() * txx + t1.getMzy() * tyx + t1.getMzz() * tzx /* + getMzt * 0.0 */); + final double rzy = (t1.getMzx() * txy + t1.getMzy() * tyy + t1.getMzz() * tzy /* + getMzt * 0.0 */); + final double rzz = (t1.getMzx() * txz + t1.getMzy() * tyz + t1.getMzz() * tzz /* + getMzt * 0.0 */); + final double rzt = (t1.getMzx() * ttx + t1.getMzy() * tty + t1.getMzz() * ttz + t1.getTz() /* * 1.0 */); + + return TransformUtils.immutableTransform( + rxx, rxy, rxz, rxt, + ryx, ryy, ryz, ryt, + rzx, rzy, rzz, rzt); + } + + /** + * Concatenates the two transforms. + */ + public static Transform concatenate(BaseTransform t1, Transform t2) { + + final double txx = t2.getMxx(); + final double txy = t2.getMxy(); + final double txz = t2.getMxz(); + final double ttx = t2.getTx(); + final double tyx = t2.getMyx(); + final double tyy = t2.getMyy(); + final double tyz = t2.getMyz(); + final double tty = t2.getTy(); + final double tzx = t2.getMzx(); + final double tzy = t2.getMzy(); + final double tzz = t2.getMzz(); + final double ttz = t2.getTz(); + final double rxx = (t1.getMxx() * txx + t1.getMxy() * tyx + t1.getMxz() * tzx /* + getMxt * 0.0 */); + final double rxy = (t1.getMxx() * txy + t1.getMxy() * tyy + t1.getMxz() * tzy /* + getMxt * 0.0 */); + final double rxz = (t1.getMxx() * txz + t1.getMxy() * tyz + t1.getMxz() * tzz /* + getMxt * 0.0 */); + final double rxt = (t1.getMxx() * ttx + t1.getMxy() * tty + t1.getMxz() * ttz + t1.getMxt() /* * 1.0 */); + final double ryx = (t1.getMyx() * txx + t1.getMyy() * tyx + t1.getMyz() * tzx /* + getMyt * 0.0 */); + final double ryy = (t1.getMyx() * txy + t1.getMyy() * tyy + t1.getMyz() * tzy /* + getMyt * 0.0 */); + final double ryz = (t1.getMyx() * txz + t1.getMyy() * tyz + t1.getMyz() * tzz /* + getMyt * 0.0 */); + final double ryt = (t1.getMyx() * ttx + t1.getMyy() * tty + t1.getMyz() * ttz + t1.getMyt() /* * 1.0 */); + final double rzx = (t1.getMzx() * txx + t1.getMzy() * tyx + t1.getMzz() * tzx /* + getMzt * 0.0 */); + final double rzy = (t1.getMzx() * txy + t1.getMzy() * tyy + t1.getMzz() * tzy /* + getMzt * 0.0 */); + final double rzz = (t1.getMzx() * txz + t1.getMzy() * tyz + t1.getMzz() * tzz /* + getMzt * 0.0 */); + final double rzt = (t1.getMzx() * ttx + t1.getMzy() * tty + t1.getMzz() * ttz + t1.getMzt() /* * 1.0 */); + + return TransformUtils.immutableTransform( + rxx, rxy, rxz, rxt, + ryx, ryy, ryz, ryt, + rzx, rzy, rzz, rzt); + } + + /** + * Computes determinant of the specified transform. + */ + public static double determinant(Transform t) { + return + t.getMxx() * (t.getMyy() * t.getMzz() - t.getMzy() * t.getMyz()) + + t.getMxy() * (t.getMyz() * t.getMzx() - t.getMzz() * t.getMyx()) + + t.getMxz() * (t.getMyx() * t.getMzy() - t.getMzx() * t.getMyy()); + } + + /** + * Needed for inversion. + */ + private static double minor(Transform t, int row, int col) { + double m00 = t.getMxx(), m01 = t.getMxy(), m02 = t.getMxz(); + double m10 = t.getMyx(), m11 = t.getMyy(), m12 = t.getMyz(); + double m20 = t.getMzx(), m21 = t.getMzy(), m22 = t.getMzz(); + switch (col) { + case 0: + m00 = m01; + m10 = m11; + m20 = m21; + case 1: + m01 = m02; + m11 = m12; + m21 = m22; + case 2: + m02 = t.getTx(); + m12 = t.getTy(); + m22 = t.getTz(); + } + switch (row) { + case 0: + m00 = m10; + m01 = m11; + // m02 = m12; + case 1: + m10 = m20; + m11 = m21; + // m12 = m22; + case 2: + // m20 = 0.0; + // m21 = 0.0; + // m22 = 1.0; + break; + case 3: + // This is the only row that requires a full 3x3 determinant + return (m00 * (m11 * m22 - m21 * m12) + + m01 * (m12 * m20 - m22 * m10) + + m02 * (m10 * m21 - m20 * m11)); + } + // return (m00 * (m11 * 1.0 - 0.0 * m12) + + // m01 * (m12 * 0.0 - 1.0 * m10) + + // m02 * (m10 * 0.0 - 0.0 * m11)); + return (m00 * m11 - m01 * m10); + } + + /** + * Modifies the given transform, if possible. + * @param t Transform to modify + * @param value Value to set to one of transform's properties + * @return true if the transform was modified + */ + public static boolean modify(Transform t, double value) { + if (t instanceof Translate) { + ((Translate) t).setY(value); + } else if (t instanceof Scale) { + ((Scale) t).setY(value); + } else if (t instanceof Shear) { + ((Shear) t).setY(value); + } else if (t instanceof Rotate) { + Rotate r = (Rotate) t; + if (r.getAxis().equals(new Point3D(0, 0, 0))) { + r.setAxis(Rotate.Z_AXIS); + } + if ((r.getAxis().getX() != 0 || r.getAxis().getY() != 0) && r.getAngle() == 0) { + r.setAxis(Rotate.Z_AXIS); + } + r.setAngle(value); + } else if (t instanceof Affine) { + ((Affine) t).setMyx(value); + } else { + return false; + } + + return true; + } + + /** + * Makes a small modification to the transform, if possible. + * @param t Transform to modify + * @return true if the transform was modified + */ + public static boolean tinyModify(Transform t) { + if (t instanceof Translate) { + Translate tr = (Translate) t; + tr.setY(tr.getY() + 1); + if (tr.getZ() != 0) { + tr.setZ(tr.getZ() + 3); + } + } else if (t instanceof Scale) { + Scale sc = (Scale) t; + sc.setY(sc.getY() + 0.01); + if (sc.getZ() != 1) { + sc.setZ(sc.getZ() + 0.01); + } + } else if (t instanceof Shear) { + ((Shear) t).setY(((Shear) t).getY() + 0.01); + } else if (t instanceof Rotate) { + Rotate r = (Rotate) t; + if (r.getAxis().getX() == 0 && + r.getAxis().getY() == 0 && + r.getAxis().getZ() == 0) { + return false; + } + if ((r.getAxis().getX() != 0 || r.getAxis().getY() != 0) && r.getAngle() == 0) { + return false; + } + r.setAngle(r.getAngle() + 0.2); + } else if (t instanceof Affine) { + Affine a = (Affine) t; + a.setTy(a.getTy() + 1); + if (!a.isType2D()) { + a.setMzz(a.getMzz() + 2); + } + } else { + return false; + } + + return true; + } + + /** + * Makes a small modification to one of the 3D (Z-axis-effective) properties + * of the transform, if possible. + * @param t Transform to modify + * @return true if the transform was modified + */ + public static boolean tinyModify3D(Transform t) { + if (t instanceof Translate) { + ((Translate) t).setZ(((Translate) t).getZ() + 1); + } else if (t instanceof Scale) { + ((Scale) t).setZ(((Scale) t).getZ() + 0.01); + } else if (t instanceof Shear) { + return false; + } else if (t instanceof Rotate) { + Rotate r = (Rotate) t; + if (r.getAxis().getX() == 0 && + r.getAxis().getY() == 0 && + r.getAxis().getZ() == 0) { + return false; + } + r.setAngle(r.getAngle() + 0.2); + } else if (t instanceof Affine) { + ((Affine) t).setTy(((Affine) t).getTy() + 1); + } else { + return false; + } + + return true; + } + + /** + * Makes the transform 3D, if possible. + * @param t Transform to modify + * @return true if the transform was modified to a 3D state + */ + public static boolean make3D(Transform t) { + if (t instanceof Translate) { + ((Translate) t).setZ(42); + } else if (t instanceof Scale) { + ((Scale) t).setZ(42); + } else if (t instanceof Shear) { + return false; + } else if (t instanceof Rotate) { + Rotate r = (Rotate) t; + if (r.getAxis().getX() == 0 && r.getAxis().getY() == 0) { + r.setAxis(Rotate.Y_AXIS); + } + if (r.getAngle() == 0) { + r.setAngle(23); + } + } else if (t instanceof Affine) { + ((Affine) t).setMyz(42); + } else { + return false; + } + + return true; + } + + /** + * Makes the transform 2D, if possible. + * @param t Transform to modify + * @return true if the transform was modified to a 2D state + */ + public static boolean make2D(Transform t) { + if (t instanceof Translate) { + ((Translate) t).setZ(0); + } else if (t instanceof Scale) { + ((Scale) t).setZ(1); + } else if (t instanceof Shear) { + return true; + } else if (t instanceof Rotate) { + ((Rotate) t).setAxis(Rotate.Z_AXIS); + } else if (t instanceof Affine) { + ((Affine) t).setToIdentity(); + } else { + return false; + } + + return true; + } + + /** + * Makes the transform identity, if possible. + * @param t Transform to modify + * @return true if the transform was modified to an identity state + */ + public static boolean makeIdentity(Transform t) { + if (t instanceof Translate) { + ((Translate) t).setX(0); + ((Translate) t).setY(0); + ((Translate) t).setZ(0); + } else if (t instanceof Scale) { + ((Scale) t).setX(1); + ((Scale) t).setY(1); + ((Scale) t).setZ(1); + } else if (t instanceof Shear) { + ((Shear) t).setX(0); + ((Shear) t).setY(0); + } else if (t instanceof Rotate) { + ((Rotate) t).setAngle(0); + } else if (t instanceof Affine) { + ((Affine) t).setToIdentity(); + } else { + return false; + } + + return true; + } + + private static enum State2D { + IDENTITY(0), + TRANSLATE(1), + SCALE(2), + SC_TR(3), + SHEAR(4), + SH_TR(5), + SH_SC(6), + SH_SC_TR(7); + + private int value; + + private State2D(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + + private static enum State3D { + NON_3D(0), + TRANSLATE(1), + SCALE(2), + SC_TR(3), + COMPLEX(4); + + private int value; + + private State3D(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + } + + private static State2D getExpectedState2D(Transform t) { + if (t.getMxy() == 0.0 && t.getMyx() == 0.0) { + if (t.getMxx() == 1.0 && t.getMyy() == 1.0) { + if (t.getTx() == 0.0 && t.getTy() == 0.0) { + return State2D.IDENTITY; + } else { + return State2D.TRANSLATE; + } + } else { + if (t.getTx() == 0.0 && t.getTy() == 0.0) { + return State2D.SCALE; + } else { + return State2D.SC_TR; + } + } + } else { + if (t.getMxx() == 0.0 && t.getMyy() == 0.0) { + if (t.getTx() == 0.0 && t.getTy() == 0.0) { + return State2D.SHEAR; + } else { + return State2D.SH_TR; + } + } else { + if (t.getTx() == 0.0 && t.getTy() == 0.0) { + return State2D.SH_SC; + } else { + return State2D.SH_SC_TR; + } + } + } + } + + private static State3D getExpectedState3D(Transform t) { + if (t.getMxz() == 0.0 && t.getMyz() == 0.0 && + t.getMzx() == 0.0 && t.getMzy() == 0.0 && + t.getMzz() == 1.0 && t.getTz() == 0.0) { + return State3D.NON_3D; + } + + if (t.getMxy() != 0.0 || t.getMxz() != 0.0 || + t.getMyx() != 0.0 || t.getMyz() != 0.0 || + t.getMzx() != 0.0 || t.getMzy() != 0.0) { + return State3D.COMPLEX; + } + + if ((t.getMxx() != 1.0 || t.getMyy() != 1.0 || t.getMzz() != 1.0) && + (t.getTx() != 0.0 || t.getTy() != 0.0 || t.getTz() != 0.0)) { + return State3D.SC_TR; + } + + if (t.getMxx() != 1.0 || t.getMyy() != 1.0 || t.getMzz() != 1.0) { + return State3D.SCALE; + } + if (t.getTx() != 0.0 || t.getTy() != 0.0 || t.getTz() != 0.0) { + return State3D.TRANSLATE; + } + return null; + } + + public static void assertStateOk(Transform t, int state3d, int state2d) { + TransformHelper.State3D expectedState3D = TransformHelper.getExpectedState3D(t); + assertEquals(expectedState3D.getValue(), state3d); + if (expectedState3D == TransformHelper.State3D.NON_3D) { + assertEquals(TransformHelper.getExpectedState2D(t).getValue(), state2d); + } + } + + public static void assertStateOk(String message, Transform t, int state3d, int state2d) { + TransformHelper.State3D expectedState3D = TransformHelper.getExpectedState3D(t); + assertEquals(message, expectedState3D.getValue(), state3d); + if (expectedState3D == TransformHelper.State3D.NON_3D) { + assertEquals(message, TransformHelper.getExpectedState2D(t).getValue(), state2d); + } + } + + /** + * Convenient factory for 2D immutable transforms. + */ + public static Transform immutableTransform( + double mxx, double mxy, double tx, + double myx, double myy, double ty) { + return TransformUtils.immutableTransform( + mxx, mxy, 0.0, tx, + myx, myy, 0.0, ty, + 0.0, 0.0, 1.0, 0.0); + } + + /** + * Creates a raw transformation to test the Transform class. + */ + public static Transform rawTransform( + double mxx, double mxy, double mxz, double tx, + double myx, double myy, double myz, double ty, + double mzx, double mzy, double mzz, double tz) { + return new RawTransform( + mxx, mxy, mxz, tx, + myx, myy, myz, ty, + mzx, mzy, mzz, tz); + } + + private static class RawTransform extends Transform { + private final double mxx, mxy, mxz, tx; + private final double myx, myy, myz, ty; + private final double mzx, mzy, mzz, tz; + + public RawTransform( + double mxx, double mxy, double mxz, double tx, + double myx, double myy, double myz, double ty, + double mzx, double mzy, double mzz, double tz) { + this.mxx = mxx; + this.mxy = mxy; + this.mxz = mxz; + this.tx = tx; + this.myx = myx; + this.myy = myy; + this.myz = myz; + this.ty = ty; + this.mzx = mzx; + this.mzy = mzy; + this.mzz = mzz; + this.tz = tz; + } + + @Override + public double getMxx() { + return mxx; + } + + @Override + public double getMxy() { + return mxy; + } + + @Override + public double getMxz() { + return mxz; + } + + @Override + public double getTx() { + return tx; + } + + @Override + public double getMyx() { + return myx; + } + + @Override + public double getMyy() { + return myy; + } + + @Override + public double getMyz() { + return myz; + } + + @Override + public double getTy() { + return ty; + } + + @Override + public double getMzx() { + return mzx; + } + + @Override + public double getMzy() { + return mzy; + } + + @Override + public double getMzz() { + return mzz; + } + + @Override + public double getTz() { + return tz; + } + + @Override + public void impl_apply(Affine3D t) { + t.concatenate( + getMxx(), getMxy(), getMxz(), getTx(), + getMyx(), getMyy(), getMyz(), getTy(), + getMzx(), getMzy(), getMzz(), getTz()); + } + + @Override + public BaseTransform impl_derive(BaseTransform t) { + return t.deriveWithConcatenation( + getMxx(), getMxy(), getMxz(), getTx(), + getMyx(), getMyy(), getMyz(), getTy(), + getMzx(), getMzy(), getMzz(), getTz()); + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/ValueComparator.java 2015-09-11 21:24:48.433286720 -0400 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test; + +import static org.junit.Assert.assertTrue; + +public abstract class ValueComparator { + public static final ValueComparator DEFAULT = + new ValueComparator() { + @Override + public boolean equals(final Object expected, + final Object actual) { + return (expected == actual) + || (expected != null) && expected.equals(actual); + } + }; + + public abstract boolean equals(Object expected, Object actual); + + public final void assertEquals(final Object expected, + final Object actual) { + assertTrue("expected=" + expected + " actual=" + actual, + equals(expected, actual)); + + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/BindingProxy.java 2015-09-11 21:24:49.217286711 -0400 @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +public class BindingProxy { + private final Class typeClass; + private final ObservableValueProxy observableValueProxy; + private final WritableValueProxy writableValueProxy; + private final VariableFactory variableFactory; + private final PropertyModelProxy propertyModelProxy; + + public BindingProxy(final Class typeClass, + final ObservableValueProxy observableValueProxy, + final WritableValueProxy writableValueProxy, + final VariableFactory variableFactory, + final PropertyModelProxy propertyModelProxy) { + this.typeClass = typeClass; + this.observableValueProxy = observableValueProxy; + this.writableValueProxy = writableValueProxy; + this.variableFactory = variableFactory; + this.propertyModelProxy = propertyModelProxy; + } + + public final Class getTypeClass() { + return typeClass; + } + + public final ObservableValueProxy getObservableValueProxy() { + return observableValueProxy; + } + + public final WritableValueProxy getWritableValueProxy() { + return writableValueProxy; + } + + public final VariableFactory getVariableFactory() { + return variableFactory; + } + + public final PropertyModelProxy getPropertyModelProxy() { + return propertyModelProxy; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/BindingProxyRefImpl.java 2015-09-11 21:24:49.885286703 -0400 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +public final class BindingProxyRefImpl extends BindingProxy { + + public BindingProxyRefImpl(final Class typeClass, + final Class observableValueClass, + final Class writableValueClass, + final Class variableClass, + final Class propertyModelClass) { + super(typeClass, + new ObservableValueProxyRefImpl(observableValueClass), + new WritableValueProxyRefImpl(writableValueClass), + new VariableFactoryRefImpl(variableClass), + new PropertyModelProxyRefImpl(propertyModelClass)); + } + + public static BindingProxyRefImpl autoLookup(final String typeName) { + return new BindingProxyRefImpl( + ReflectionHelper.classForName("java.lang." + typeName), + ReflectionHelper.classForName("javafx.beans.value.Observable" + + typeName + "Value"), + ReflectionHelper.classForName("javafx.beans.value.Writable" + + typeName + "Value"), + ReflectionHelper.classForName("javafx.beans.property.Simple" + + typeName + "Property"), + ReflectionHelper.classForName("javafx.beans.property." + + typeName + + "Property")); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/ObservableValueProxy.java 2015-09-11 21:24:50.477286697 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +public interface ObservableValueProxy { + Object getValue(Object observableValue); +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/ObservableValueProxyRefImpl.java 2015-09-11 21:24:51.061286690 -0400 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +import java.lang.reflect.Method; + +public final class ObservableValueProxyRefImpl implements ObservableValueProxy { + private final Method getValueMethod; + + public ObservableValueProxyRefImpl(final Class observableValueClass) { + this.getValueMethod = ReflectionHelper.getMethod( + observableValueClass, + "getValue"); + } + + @Override + public Object getValue(final Object observableValue) { + return ReflectionHelper.invokeMethod(observableValue, getValueMethod); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/PropertyModelProxy.java 2015-09-11 21:24:51.721286683 -0400 @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +public interface PropertyModelProxy { + void bind(Object propertyModel, Object observableValue); + + void unbind(Object propertyModel); +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/PropertyModelProxyRefImpl.java 2015-09-11 21:24:52.497286674 -0400 @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +import java.lang.reflect.Method; + +import javafx.beans.value.ObservableValue; + +public final class PropertyModelProxyRefImpl implements PropertyModelProxy { + private final Method bindMethod; + private final Method unbindMethod; + + public PropertyModelProxyRefImpl(final Class propertyModelClass) { + this.bindMethod = ReflectionHelper.getMethod(propertyModelClass, + "bind", + ObservableValue.class); + this.unbindMethod = ReflectionHelper.getMethod(propertyModelClass, + "unbind"); + } + + @Override + public void bind(final Object propertyModel, final Object observableValue) { + ReflectionHelper.invokeMethod(propertyModel, + bindMethod, + observableValue); + } + + @Override + public void unbind(final Object propertyModel) { + ReflectionHelper.invokeMethod(propertyModel, + unbindMethod); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/ReflectionHelper.java 2015-09-11 21:24:53.165286667 -0400 @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public final class ReflectionHelper { + private ReflectionHelper() { + } + + public static Class classForName(final String className) { + try { + return Class.forName(className); + } catch (final ClassNotFoundException e) { + throw convertToRuntimeException(e); + } + } + + public static Object newInstance(final Class cls) { + try { + return cls.newInstance(); + } catch (final InstantiationException e) { + throw convertToRuntimeException(e); + } catch (final IllegalAccessException e) { + throw convertToRuntimeException(e); + } + } + + public static Method getMethod(final Class cls, + final String methodName, + final Class... parameterTypes) { + try { + return cls.getMethod(methodName, parameterTypes); + } catch (final NoSuchMethodException e) { + throw convertToRuntimeException(e); + } catch (final SecurityException e) { + throw convertToRuntimeException(e); + } + } + + public static Object invokeMethod(final Object object, + final Method method, + final Object... args) { + try { + return method.invoke(object, args); + } catch (final IllegalAccessException e) { + throw convertToRuntimeException(e); + } catch (final IllegalArgumentException e) { + throw convertToRuntimeException(e); + } catch (final InvocationTargetException e) { + throw convertToRuntimeException(e); + } + } + + private static RuntimeException convertToRuntimeException( + final Exception e) { + return new RuntimeException(e); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/VariableFactory.java 2015-09-11 21:24:53.953286658 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +public interface VariableFactory { + Object createVariable(); +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/VariableFactoryRefImpl.java 2015-09-11 21:24:54.693286649 -0400 @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +public final class VariableFactoryRefImpl implements VariableFactory { + private final Class variableClass; + + public VariableFactoryRefImpl(final Class variableClass) { + this.variableClass = variableClass; + } + + @Override + public Object createVariable() { + return ReflectionHelper.newInstance(variableClass); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/WritableValueProxy.java 2015-09-11 21:24:55.477286641 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +public interface WritableValueProxy { + void setValue(Object writableValue, Object value); +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/binding/WritableValueProxyRefImpl.java 2015-09-11 21:24:56.261286632 -0400 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.binding; + +import java.lang.reflect.Method; + +public final class WritableValueProxyRefImpl implements WritableValueProxy { + private final Method setValueMethod; + + public WritableValueProxyRefImpl(final Class writableValueClass) { + final Method getValueMethod = ReflectionHelper.getMethod( + writableValueClass, + "getValue"); + this.setValueMethod = ReflectionHelper.getMethod( + writableValueClass, + "setValue", + getValueMethod.getReturnType()); + } + + @Override + public void setValue(final Object writableValue, + final Object value) { + ReflectionHelper.invokeMethod(writableValue, setValueMethod, value); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/objects/TestGroup.java 2015-09-11 21:24:56.921286624 -0400 @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.objects; + +import javafx.beans.property.ObjectProperty; +import javafx.beans.property.SimpleObjectProperty; +import javafx.scene.Group; +import javafx.scene.Scene; + +public class TestGroup extends Group { + private final String name; + + private final ObjectProperty _sceneProperty = + new SimpleObjectProperty() { + private Scene old_scene; + + @Override + protected void invalidated() { + final Scene new_scene = get(); + + if (old_scene != new_scene) { + if (getScene() != new_scene) { + if (old_scene != null) { + old_scene.setRoot(null); + } + if (new_scene != null) { + new_scene.setRoot(TestGroup.this); + } + } + + old_scene = new_scene; + } + } + }; + + public TestGroup() { + this("GROUP"); + } + + public TestGroup(final String name) { + this.name = name; + } + + public void set_scene(final Scene scene) { + _sceneProperty.set(scene); + } + + public Scene get_scene() { + return _sceneProperty.get(); + } + + public ObjectProperty _sceneProperty() { + return _sceneProperty; + } + + @Override + public String toString() { + return name; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/objects/TestNode.java 2015-09-11 21:24:57.745286615 -0400 @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.objects; + +import javafx.beans.property.ObjectProperty; +import javafx.beans.property.SimpleObjectProperty; +import javafx.scene.Group; +import javafx.scene.shape.Rectangle; + +public final class TestNode extends Rectangle { + private final String name; + + private final ObjectProperty _parentProperty = + new SimpleObjectProperty() { + private Group old_parent; + + @Override + protected void invalidated() { + final Group new_parent = get(); + + if (old_parent != new_parent) { + if (getParent() != new_parent) { + if (new_parent != null) { + new_parent.getChildren().add(TestNode.this); + } else { + old_parent.getChildren().remove(TestNode.this); + } + } + + old_parent = new_parent; + } + } + }; + + public TestNode() { + this("NODE"); + } + + public TestNode(final String name) { + this.name = name; + } + + public void set_parent(final Group parent) { + _parentProperty.set(parent); + } + + public Group get_parent() { + return _parentProperty.get(); + } + + public ObjectProperty _parentProperty() { + return _parentProperty; + } + + @Override + public String toString() { + return name; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/objects/TestScene.java 2015-09-11 21:24:58.337286608 -0400 @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.objects; + +import javafx.beans.property.ObjectProperty; +import javafx.beans.property.ObjectPropertyBase; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Stage; +import javafx.stage.Window; + +/** + * Test scene with name and possibility to set scene's window directly through + * "_window" property. The later is used in property tests. + */ +public class TestScene extends Scene { + private final String name; + + private final ObjectProperty _windowProperty = + new ObjectPropertyBase() { + private Window old_window; + + @Override + protected void invalidated() { + final Window new_window = get(); + + if (old_window != new_window) { + if (getWindow() != new_window) { + if (new_window instanceof Stage) { + ((Stage)new_window).setScene(TestScene.this); + } else if (old_window instanceof Stage) { + ((Stage)old_window).setScene(null); + } + } + + old_window = new_window; + } + } + + @Override + public Object getBean() { + return TestScene.this; + } + + @Override + public String getName() { + return "_window"; + } + }; + + public TestScene(final Parent root) { + this("SCENE", root); + } + + public TestScene(final String name, final Parent root) { + super(root); + this.name = name; + // init size for camera to work + impl_preferredSize(); + } + + public void set_window(final Window window) { + _windowProperty.set(window); + } + + public Window get_window() { + return _windowProperty.get(); + } + + public ObjectProperty _windowProperty() { + return _windowProperty; + } + + @Override + public String toString() { + return name; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/test/objects/TestStage.java 2015-09-11 21:24:59.069286600 -0400 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.test.objects; + +import javafx.stage.Stage; + +public class TestStage extends Stage { + private final String name; + + public TestStage(final String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/text/TextLayoutTest.java 2015-09-11 21:24:59.869286591 -0400 @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.text; + +import javafx.scene.text.Font; + +import com.sun.javafx.font.PGFont; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.scene.text.GlyphList; +import com.sun.javafx.scene.text.TextSpan; +import com.sun.javafx.scene.text.TextLine; +import com.sun.javafx.text.PrismTextLayout; +import com.sun.javafx.text.PrismTextLayout; + +import org.junit.Ignore; +import org.junit.Test; + +import sun.font.CharToGlyphMapper; +import static org.junit.Assert.*; + +public class TextLayoutTest { + private String J = "\u3041"; //Japanese not complex + private String D = "\u0907"; //Devanagari complex + private String T = "\u0E34"; //Devanagari complex + + class TestSpan implements TextSpan { + String text; + Object font; + TestSpan(Object text, Object font) { + this.text = (String)text; + this.font = font; + } + @Override public String getText() { + return text; + } + @Override public Object getFont() { + return font; + } + @Override public RectBounds getBounds() { + return null; + } + } + + public TextLayoutTest() { + } + + private void setContent(PrismTextLayout layout, Object... content) { + int count = content.length / 2; + TextSpan[] spans = new TextSpan[count]; + int i = 0; + while (i < content.length) { + spans[i>>1] = new TestSpan(content[i++], content[i++]); + } + layout.setContent(spans); + } + + private void verifyLayout(PrismTextLayout layout, int lineCount, int runCount, int... glyphCount) { + TextLine[] lines = layout.getLines(); + assertEquals("lineCount", lineCount, lines.length); + GlyphList[] runs = layout.getRuns(); + assertEquals("runCount", runCount, runs.length); + assertEquals("runCount", runCount, glyphCount.length); + for (int i = 0; i < runs.length; i++) { + assertEquals("run " +i, glyphCount[i], runs[i].getGlyphCount()); + } + } + + private void verifyComplex(PrismTextLayout layout, boolean... complex) { + GlyphList[] runs = layout.getRuns(); + for (int i = 0; i < runs.length; i++) { + assertEquals("run " +i, complex[i], runs[i].isComplex()); + } + } + + @SuppressWarnings("deprecation") + @Ignore("RT-31357") + @Test public void buildRuns() { + + PrismTextLayout layout = new PrismTextLayout(); + PGFont font = (PGFont)Font.font("Monaco", 12).impl_getNativeFont(); + PGFont font2 = (PGFont)Font.font("Tahoma", 12).impl_getNativeFont(); + + /* simple case */ + layout.setContent("hello", font); + verifyLayout(layout, 1, 1, 5); + + /* simple case, two workd*/ + layout.setContent("hello world", font); + verifyLayout(layout, 1, 1, 11); + + /* empty string */ + layout.setContent("", font); + verifyLayout(layout, 1, 1, 0); + + /* line break */ + layout.setContent("\n", font); //first line has the line break (glyphCount=0), + verifyLayout(layout, 2, 2, 0,0); + layout.setContent("\r", font); + verifyLayout(layout, 2, 2, 0,0); + layout.setContent("\r\n", font); + verifyLayout(layout, 2, 2, 0,0); + layout.setContent("a\nb", font); + verifyLayout(layout, 2, 3, 1, 0, 1); + layout.setContent("\n\n\r\r\n", font); + verifyLayout(layout, 5, 5, 0,0,0,0,0); + + /* tabs */ + layout.setContent("\t", font); + verifyLayout(layout, 1, 1, 0); + layout.setContent("\t\t", font); + verifyLayout(layout, 1, 2, 0,0); + layout.setContent("a\tb", font); + verifyLayout(layout, 1, 3, 1,0,1); + + /* complex */ + layout.setContent("aa"+J+J, font); + verifyLayout(layout, 1, 1, 4);// no complex (english to japanese) + verifyComplex(layout, false); + + + layout.setContent(D, font); + verifyLayout(layout, 1, 1, 1);// complex (english to devanagari) + verifyComplex(layout, true); + + layout.setContent("aa"+D+D, font); + verifyLayout(layout, 1, 2, 2,2);// complex (english to devanagari) + verifyComplex(layout, false, true); + + layout.setContent(D+D+"aa", font); + verifyLayout(layout, 1, 2, 2,2);// complex (devanagari to english) + verifyComplex(layout, true, false); + + layout.setContent("aa"+D+D+J+J, font); + verifyLayout(layout, 1, 3, 2,2,2);// complex (english to devanagari to japanese) + verifyComplex(layout, false, true, false); + + /*Tahoma has Thai but no Hindi, font slot break expected*/ + layout.setContent(D+D+T+T, font2); + verifyLayout(layout, 1, 2, 2,2);// complex (devanagari to thai) + verifyComplex(layout, true, true); + + layout.setContent(T+T+D+D+T+T, font2); + verifyLayout(layout, 1, 3, 2,2,2); + verifyComplex(layout, true, true, true); + + layout.setContent(T+T+D+D+"aa", font2); + verifyLayout(layout, 1, 3, 2,2,2); + verifyComplex(layout, true, true, false); + + layout.setContent(T+T+"aa"+T+T, font2); + verifyLayout(layout, 1, 3, 2,2,2); + verifyComplex(layout, true, false, true); + + layout.setContent("aa"+D+D+T+T, font2); + verifyLayout(layout, 1, 3, 2,2,2); + verifyComplex(layout, false, true, true); + + /* Rich Text test */ + + setContent(layout, "hello ", font, "world", font); + verifyLayout(layout, 1, 2, 6,5); + verifyComplex(layout, false, false); + + setContent(layout, "aaa", font, J+J+J, font); + verifyLayout(layout, 1, 2, 3,3); + verifyComplex(layout, false, false); + + setContent(layout, "aaa", font, D+D+D, font); + verifyLayout(layout, 1, 2, 3,3); + verifyComplex(layout, false, true); + + /* can't merge \r\n in different spans*/ + setContent(layout, "aa\r", font, "\nbb", font); + verifyLayout(layout, 3, 4, 2,0,0,2); + verifyComplex(layout, false, false, false, false); + + setContent(layout, "aa\r\n", font, "bb", font); + verifyLayout(layout, 2, 3, 2,0,2); + verifyComplex(layout, false, false, false); + + /* can't merge surrogate pairs in different spans*/ + setContent(layout, "\uD840\uDC0B", font, "\uD840\uDC89\uD840\uDCA2", font); + verifyLayout(layout, 1, 2, 2, 4); + GlyphList[] runs = layout.getRuns(); + assertTrue(runs[0].getGlyphCode(0) != CharToGlyphMapper.INVISIBLE_GLYPH_ID); + assertTrue(runs[0].getGlyphCode(1) == CharToGlyphMapper.INVISIBLE_GLYPH_ID); + assertTrue(runs[1].getGlyphCode(0) != CharToGlyphMapper.INVISIBLE_GLYPH_ID); + assertTrue(runs[1].getGlyphCode(1) == CharToGlyphMapper.INVISIBLE_GLYPH_ID); + assertTrue(runs[1].getGlyphCode(2) != CharToGlyphMapper.INVISIBLE_GLYPH_ID); + assertTrue(runs[1].getGlyphCode(3) == CharToGlyphMapper.INVISIBLE_GLYPH_ID); + + /* Split surrogate pair*/ + setContent(layout, "\uD840\uDC0B\uD840", font, "\uDC89\uD840\uDCA2", font); + verifyLayout(layout, 1, 2, 3, 3); + runs = layout.getRuns(); + assertTrue(runs[0].getGlyphCode(0) != CharToGlyphMapper.INVISIBLE_GLYPH_ID); + assertTrue(runs[0].getGlyphCode(1) == CharToGlyphMapper.INVISIBLE_GLYPH_ID); + assertTrue(runs[0].getGlyphCode(2) != CharToGlyphMapper.INVISIBLE_GLYPH_ID);//broken pair, results in missing glyph + assertTrue(runs[1].getGlyphCode(0) != CharToGlyphMapper.INVISIBLE_GLYPH_ID);//broken pair, results in missing glyph + assertTrue(runs[1].getGlyphCode(1) != CharToGlyphMapper.INVISIBLE_GLYPH_ID); + assertTrue(runs[1].getGlyphCode(2) == CharToGlyphMapper.INVISIBLE_GLYPH_ID); + + } + +} --- old/modules/graphics/src/test/java/com/sun/javafx/tk/quantum/WindowStageTest.java 2015-09-11 21:25:00.813286581 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.tk.quantum; - -import com.sun.prism.Image; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Test; - -public class WindowStageTest { - - private void addImage(List images, int size) { - byte[] pixels = new byte[size * size * 3]; - Image image = Image.fromByteRgbData(pixels, size, size); - images.add(image); - } - - @Test - public void bestIconSizeTest() { - List images = new ArrayList(); - addImage(images, 16); - addImage(images, 32); - addImage(images, 48); - - // sanity check - Image image = WindowStage.findBestImage(images, 16, 16); - Assert.assertEquals(16, image.getWidth()); - image = WindowStage.findBestImage(images, 48, 48); - Assert.assertEquals(48, image.getWidth()); - - //RT-39045 - image = WindowStage.findBestImage(images, 32, 32); - Assert.assertEquals(32, image.getWidth()); - - // scaling up 32 pixels by 4 is better than 48 by 2+2/3 - image = WindowStage.findBestImage(images, 128, 128); - Assert.assertEquals(32, image.getWidth()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/tk/quantum/WindowStageTest.java 2015-09-11 21:25:00.677286582 -0400 @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.tk.quantum; + +import com.sun.javafx.tk.quantum.WindowStageShim; +import com.sun.prism.Image; +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +public class WindowStageTest { + + private void addImage(List images, int size) { + byte[] pixels = new byte[size * size * 3]; + Image image = Image.fromByteRgbData(pixels, size, size); + images.add(image); + } + + @Test + public void bestIconSizeTest() { + List images = new ArrayList(); + addImage(images, 16); + addImage(images, 32); + addImage(images, 48); + + // sanity check + Image image = WindowStageShim.findBestImage(images, 16, 16); + Assert.assertEquals(16, image.getWidth()); + image = WindowStageShim.findBestImage(images, 48, 48); + Assert.assertEquals(48, image.getWidth()); + + //RT-39045 + image = WindowStageShim.findBestImage(images, 32, 32); + Assert.assertEquals(32, image.getWidth()); + + // scaling up 32 pixels by 4 is better than 48 by 2+2/3 + image = WindowStageShim.findBestImage(images, 128, 128); + Assert.assertEquals(32, image.getWidth()); + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/util/UtilsTest.java 2015-09-11 21:25:01.617286572 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,182 +0,0 @@ -/* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.util; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; - -import javafx.geometry.HPos; -import javafx.geometry.Point2D; -import javafx.geometry.VPos; -import javafx.scene.Group; -import javafx.scene.Scene; -import javafx.scene.SubScene; -import javafx.scene.layout.VBox; -import javafx.scene.shape.Rectangle; -import javafx.stage.Stage; -import org.junit.Test; - -public class UtilsTest { - @Test - public void testSplit() { - // normal use case - String s = "VK_ENTER"; - String[] split = Utils.split(s, "_"); - assertEquals("Array content: " + Arrays.toString(split),2, split.length); - assertEquals("VK", split[0]); - assertEquals("ENTER", split[1]); - - // normal use case - s = "VK_LEFT_ARROW"; - split = Utils.split(s, "_"); - assertEquals("Array content: " + Arrays.toString(split),3, split.length); - assertEquals("VK", split[0]); - assertEquals("LEFT", split[1]); - assertEquals("ARROW", split[2]); - - // split with same string as separator - expect empty array - s = "VK_LEFT_ARROW"; - split = Utils.split(s, "VK_LEFT_ARROW"); - assertEquals("Array content: " + Arrays.toString(split),0, split.length); - - // split with longer string as separator - expect empty array - s = "VK_LEFT_ARROW"; - split = Utils.split(s, "VK_LEFT_ARROW_EXT"); - assertEquals("Array content: " + Arrays.toString(split),0, split.length); - } - - @Test - public void testConvertUnicode() { - String s = ""; - String r = Utils.convertUnicode(s); - assertEquals("", r); - - /*String*/ s = "test"; - /*String*/ r = Utils.convertUnicode(s); - assertEquals("test", r); - - /*String*/ s = "hi\\u1234"; - /*String*/ r = Utils.convertUnicode(s); - assertEquals("hi\u1234", r); - - /*String*/ s = "\\u5678"; - /*String*/ r = Utils.convertUnicode(s); - assertEquals("\u5678", r); - - /*String*/ s = "hi\\u1234there\\u432112"; - /*String*/ r = Utils.convertUnicode(s); - assertEquals("hi\u1234there\u432112", r); - - /*String*/ s = "Hello\u5678There"; - /*String*/ r = Utils.convertUnicode(s); - assertEquals("Hello\u5678There", r); - - /*String*/ s = "\\this\\is\\a\\windows\\path"; - /*String*/ r = Utils.convertUnicode(s); - assertEquals("\\this\\is\\a\\windows\\path", r); - - /*String*/ s = "\\this\\is\\a\\12\\windows\\path"; - /*String*/ r = Utils.convertUnicode(s); - assertEquals("\\this\\is\\a\\12\\windows\\path", r); - - /*String*/ s = "u12u12"; - /*String*/ r = Utils.convertUnicode(s); - assertEquals("u12u12", r); - - /*String*/ s = "hello\nu1234\n"; - /*String*/ r = Utils.convertUnicode(s); - assertEquals("hello\nu1234\n", r); - } - - @Test - public void testConvertUnicodeFail2_2() { - - //Error case - null - //String s = null; - //String r = Utils.convertUnicode(s); - //assertEquals("", r); - - //String s = "\\"; - //String r = Utils.convertUnicode(s); - //assertEquals("\\", r); - - //Error case - no length - ///*String*/ s = "hi\\u"; - ///*String*/ r = Utils.convertUnicode(s); - //assertEquals("hi\\u", r); - } - - @Test - public void testConvertUnicodeWrong2_2() { - - //Error case - short length - String s = "hi\\u12"; - String r = Utils.convertUnicode(s); - //assertEquals("hi\\u12", r); - - /*String*/ s = "\\this\\is\\a\\umm\\windows\\path"; - /*String*/ r = Utils.convertUnicode(s); - //assertEquals("\\this\\is\\a\\umm\\windows\\path", r); - } - - @Test - public void testPointRelativeTo() { - VBox root = new VBox(); - final Rectangle rectangle = new Rectangle(50, 50, 100, 100); - root.getChildren().add(rectangle); - Scene scene = new Scene(root,800,600); - Stage stage = new Stage(); - stage.setX(0); - stage.setY(0); - stage.setScene(scene); - final Point2D res = Utils.pointRelativeTo(rectangle, 0, 0, HPos.CENTER, VPos.CENTER, 0, 0, false); - assertEquals(50, res.getX(), 1e-1); - assertEquals(50, res.getY(), 1e-1); - - } - - @Test - public void testPointRelativeTo_InSubScene() { - Group root = new Group(); - Scene scene = new Scene(root,800,600); - VBox subRoot = new VBox(); - SubScene subScene = new SubScene(subRoot, 100, 100); - subScene.setLayoutX(20); - subScene.setLayoutY(20); - root.getChildren().addAll(subScene); - final Rectangle rectangle = new Rectangle(50, 50, 100, 100); - subRoot.getChildren().add(rectangle); - Stage stage = new Stage(); - stage.setX(0); - stage.setY(0); - stage.setScene(scene); - final Point2D res = Utils.pointRelativeTo(rectangle, 0, 0, HPos.CENTER, VPos.CENTER, 0, 0, false); - assertEquals(70, res.getX(), 1e-1); - assertEquals(70, res.getY(), 1e-1); - - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/util/UtilsTest.java 2015-09-11 21:25:01.425286574 -0400 @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.util; + +import com.sun.javafx.util.Utils; +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; + +import javafx.geometry.HPos; +import javafx.geometry.Point2D; +import javafx.geometry.VPos; +import javafx.scene.Group; +import javafx.scene.Scene; +import javafx.scene.SubScene; +import javafx.scene.layout.VBox; +import javafx.scene.shape.Rectangle; +import javafx.stage.Stage; +import org.junit.Test; + +public class UtilsTest { + @Test + public void testSplit() { + // normal use case + String s = "VK_ENTER"; + String[] split = Utils.split(s, "_"); + assertEquals("Array content: " + Arrays.toString(split),2, split.length); + assertEquals("VK", split[0]); + assertEquals("ENTER", split[1]); + + // normal use case + s = "VK_LEFT_ARROW"; + split = Utils.split(s, "_"); + assertEquals("Array content: " + Arrays.toString(split),3, split.length); + assertEquals("VK", split[0]); + assertEquals("LEFT", split[1]); + assertEquals("ARROW", split[2]); + + // split with same string as separator - expect empty array + s = "VK_LEFT_ARROW"; + split = Utils.split(s, "VK_LEFT_ARROW"); + assertEquals("Array content: " + Arrays.toString(split),0, split.length); + + // split with longer string as separator - expect empty array + s = "VK_LEFT_ARROW"; + split = Utils.split(s, "VK_LEFT_ARROW_EXT"); + assertEquals("Array content: " + Arrays.toString(split),0, split.length); + } + + @Test + public void testConvertUnicode() { + String s = ""; + String r = Utils.convertUnicode(s); + assertEquals("", r); + + /*String*/ s = "test"; + /*String*/ r = Utils.convertUnicode(s); + assertEquals("test", r); + + /*String*/ s = "hi\\u1234"; + /*String*/ r = Utils.convertUnicode(s); + assertEquals("hi\u1234", r); + + /*String*/ s = "\\u5678"; + /*String*/ r = Utils.convertUnicode(s); + assertEquals("\u5678", r); + + /*String*/ s = "hi\\u1234there\\u432112"; + /*String*/ r = Utils.convertUnicode(s); + assertEquals("hi\u1234there\u432112", r); + + /*String*/ s = "Hello\u5678There"; + /*String*/ r = Utils.convertUnicode(s); + assertEquals("Hello\u5678There", r); + + /*String*/ s = "\\this\\is\\a\\windows\\path"; + /*String*/ r = Utils.convertUnicode(s); + assertEquals("\\this\\is\\a\\windows\\path", r); + + /*String*/ s = "\\this\\is\\a\\12\\windows\\path"; + /*String*/ r = Utils.convertUnicode(s); + assertEquals("\\this\\is\\a\\12\\windows\\path", r); + + /*String*/ s = "u12u12"; + /*String*/ r = Utils.convertUnicode(s); + assertEquals("u12u12", r); + + /*String*/ s = "hello\nu1234\n"; + /*String*/ r = Utils.convertUnicode(s); + assertEquals("hello\nu1234\n", r); + } + + @Test + public void testConvertUnicodeFail2_2() { + + //Error case - null + //String s = null; + //String r = Utils.convertUnicode(s); + //assertEquals("", r); + + //String s = "\\"; + //String r = Utils.convertUnicode(s); + //assertEquals("\\", r); + + //Error case - no length + ///*String*/ s = "hi\\u"; + ///*String*/ r = Utils.convertUnicode(s); + //assertEquals("hi\\u", r); + } + + @Test + public void testConvertUnicodeWrong2_2() { + + //Error case - short length + String s = "hi\\u12"; + String r = Utils.convertUnicode(s); + //assertEquals("hi\\u12", r); + + /*String*/ s = "\\this\\is\\a\\umm\\windows\\path"; + /*String*/ r = Utils.convertUnicode(s); + //assertEquals("\\this\\is\\a\\umm\\windows\\path", r); + } + + @Test + public void testPointRelativeTo() { + VBox root = new VBox(); + final Rectangle rectangle = new Rectangle(50, 50, 100, 100); + root.getChildren().add(rectangle); + Scene scene = new Scene(root,800,600); + Stage stage = new Stage(); + stage.setX(0); + stage.setY(0); + stage.setScene(scene); + final Point2D res = Utils.pointRelativeTo(rectangle, 0, 0, HPos.CENTER, VPos.CENTER, 0, 0, false); + assertEquals(50, res.getX(), 1e-1); + assertEquals(50, res.getY(), 1e-1); + + } + + @Test + public void testPointRelativeTo_InSubScene() { + Group root = new Group(); + Scene scene = new Scene(root,800,600); + VBox subRoot = new VBox(); + SubScene subScene = new SubScene(subRoot, 100, 100); + subScene.setLayoutX(20); + subScene.setLayoutY(20); + root.getChildren().addAll(subScene); + final Rectangle rectangle = new Rectangle(50, 50, 100, 100); + subRoot.getChildren().add(rectangle); + Stage stage = new Stage(); + stage.setX(0); + stage.setY(0); + stage.setScene(scene); + final Point2D res = Utils.pointRelativeTo(rectangle, 0, 0, HPos.CENTER, VPos.CENTER, 0, 0, false); + assertEquals(70, res.getX(), 1e-1); + assertEquals(70, res.getY(), 1e-1); + + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/util/Utils_getScreenForPoint_Test.java 2015-09-11 21:25:02.337286564 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.util; - -import com.sun.javafx.pgstub.StubToolkit; -import com.sun.javafx.pgstub.StubToolkit.ScreenConfiguration; -import com.sun.javafx.tk.Toolkit; -import java.util.Arrays; -import java.util.Collection; -import javafx.stage.Screen; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public final class Utils_getScreenForPoint_Test { - private final double x; - private final double y; - private final int expectedScreenIndex; - - @Parameters - public static Collection data() { - return Arrays.asList( - new Object[] { - config(100, 100, 0), - config(2000, 200, 1), - config(1920, 0, 0), - config(1920, 200, 1), - config(1920, 1100, 0), - config(2020, 50, 0), - config(2020, 70, 1), - config(1970, -50, 0), - config(2170, -50, 1), - config(2020, 1150, 1), - config(2020, 1170, 0), - config(1970, 1250, 0), - config(2170, 1250, 1) - }); - } - - public Utils_getScreenForPoint_Test( - final double x, final double y, final int expectedScreenIndex) { - this.x = x; - this.y = y; - this.expectedScreenIndex = expectedScreenIndex; - } - - @Before - public void setUp() { - ((StubToolkit) Toolkit.getToolkit()).setScreens( - new ScreenConfiguration(0, 0, 1920, 1200, 0, 0, 1920, 1172, 96), - new ScreenConfiguration(1920, 160, 1440, 900, - 1920, 160, 1440, 900, 96)); - } - - @After - public void tearDown() { - ((StubToolkit) Toolkit.getToolkit()).resetScreens(); - } - - @Test - public void test() { - final Screen selectedScreen = Utils.getScreenForPoint(x, y); - Assert.assertEquals(expectedScreenIndex, - Screen.getScreens().indexOf(selectedScreen)); - } - - private static Object[] config(final double x, final double y, - final int expectedScreenIndex) { - return new Object[] { x, y, expectedScreenIndex }; - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/util/Utils_getScreenForPoint_Test.java 2015-09-11 21:25:02.125286566 -0400 @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.util; + +import test.com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit.ScreenConfiguration; +import com.sun.javafx.tk.Toolkit; +import com.sun.javafx.util.Utils; +import java.util.Arrays; +import java.util.Collection; +import javafx.stage.Screen; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +@RunWith(Parameterized.class) +public final class Utils_getScreenForPoint_Test { + private final double x; + private final double y; + private final int expectedScreenIndex; + + @Parameters + public static Collection data() { + return Arrays.asList( + new Object[] { + config(100, 100, 0), + config(2000, 200, 1), + config(1920, 0, 0), + config(1920, 200, 1), + config(1920, 1100, 0), + config(2020, 50, 0), + config(2020, 70, 1), + config(1970, -50, 0), + config(2170, -50, 1), + config(2020, 1150, 1), + config(2020, 1170, 0), + config(1970, 1250, 0), + config(2170, 1250, 1) + }); + } + + public Utils_getScreenForPoint_Test( + final double x, final double y, final int expectedScreenIndex) { + this.x = x; + this.y = y; + this.expectedScreenIndex = expectedScreenIndex; + } + + @Before + public void setUp() { + ((StubToolkit) Toolkit.getToolkit()).setScreens( + new ScreenConfiguration(0, 0, 1920, 1200, 0, 0, 1920, 1172, 96), + new ScreenConfiguration(1920, 160, 1440, 900, + 1920, 160, 1440, 900, 96)); + } + + @After + public void tearDown() { + ((StubToolkit) Toolkit.getToolkit()).resetScreens(); + } + + @Test + public void test() { + final Screen selectedScreen = Utils.getScreenForPoint(x, y); + Assert.assertEquals(expectedScreenIndex, + Screen.getScreens().indexOf(selectedScreen)); + } + + private static Object[] config(final double x, final double y, + final int expectedScreenIndex) { + return new Object[] { x, y, expectedScreenIndex }; + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/util/Utils_getScreenForRectangle_Test.java 2015-09-11 21:25:03.025286556 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.util; - -import com.sun.javafx.pgstub.StubToolkit; -import com.sun.javafx.pgstub.StubToolkit.ScreenConfiguration; -import com.sun.javafx.tk.Toolkit; -import java.util.Arrays; -import java.util.Collection; -import javafx.geometry.Rectangle2D; -import javafx.stage.Screen; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public final class Utils_getScreenForRectangle_Test { - private final Rectangle2D rectangle; - private final int expectedScreenIndex; - - @Parameters - public static Collection data() { - return Arrays.asList( - new Object[] { - config(100, 100, 100, 100, 0), - config(2020, 200, 100, 100, 1), - config(1920 - 75, 200, 100, 100, 0), - config(1920 - 25, 200, 100, 100, 1), - config(0, 0, 3360, 1200, 0), - config(2020, 50, 100, 100, 1), - config(2020, 70, 100, 100, 1), - config(1970, -50, 100, 100, 0), - config(2170, -50, 100, 100, 1), - config(2020, 1150, 100, 100, 1), - config(2020, 1170, 100, 100, 0), - config(1970, 1250, 100, 100, 0), - config(2170, 1250, 100, 100, 1) - }); - } - - public Utils_getScreenForRectangle_Test( - final Rectangle2D rectangle, final int expectedScreenIndex) { - this.rectangle = rectangle; - this.expectedScreenIndex = expectedScreenIndex; - } - - @Before - public void setUp() { - ((StubToolkit) Toolkit.getToolkit()).setScreens( - new ScreenConfiguration(0, 0, 1920, 1200, 0, 0, 1920, 1172, 96), - new ScreenConfiguration(1920, 160, 1440, 900, - 1920, 160, 1440, 900, 96)); - } - - @After - public void tearDown() { - ((StubToolkit) Toolkit.getToolkit()).resetScreens(); - } - - @Test - public void test() { - final Screen selectedScreen = Utils.getScreenForRectangle(rectangle); - Assert.assertEquals(expectedScreenIndex, - Screen.getScreens().indexOf(selectedScreen)); - } - - private static Object[] config(final double x, final double y, - final double width, final double height, - final int expectedScreenIndex) { - return new Object[] { - new Rectangle2D(x, y, width, height), - expectedScreenIndex - }; - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/util/Utils_getScreenForRectangle_Test.java 2015-09-11 21:25:02.885286557 -0400 @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.util; + +import test.com.sun.javafx.pgstub.StubToolkit; +import test.com.sun.javafx.pgstub.StubToolkit.ScreenConfiguration; +import com.sun.javafx.tk.Toolkit; +import com.sun.javafx.util.Utils; +import java.util.Arrays; +import java.util.Collection; +import javafx.geometry.Rectangle2D; +import javafx.stage.Screen; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +@RunWith(Parameterized.class) +public final class Utils_getScreenForRectangle_Test { + private final Rectangle2D rectangle; + private final int expectedScreenIndex; + + @Parameters + public static Collection data() { + return Arrays.asList( + new Object[] { + config(100, 100, 100, 100, 0), + config(2020, 200, 100, 100, 1), + config(1920 - 75, 200, 100, 100, 0), + config(1920 - 25, 200, 100, 100, 1), + config(0, 0, 3360, 1200, 0), + config(2020, 50, 100, 100, 1), + config(2020, 70, 100, 100, 1), + config(1970, -50, 100, 100, 0), + config(2170, -50, 100, 100, 1), + config(2020, 1150, 100, 100, 1), + config(2020, 1170, 100, 100, 0), + config(1970, 1250, 100, 100, 0), + config(2170, 1250, 100, 100, 1) + }); + } + + public Utils_getScreenForRectangle_Test( + final Rectangle2D rectangle, final int expectedScreenIndex) { + this.rectangle = rectangle; + this.expectedScreenIndex = expectedScreenIndex; + } + + @Before + public void setUp() { + ((StubToolkit) Toolkit.getToolkit()).setScreens( + new ScreenConfiguration(0, 0, 1920, 1200, 0, 0, 1920, 1172, 96), + new ScreenConfiguration(1920, 160, 1440, 900, + 1920, 160, 1440, 900, 96)); + } + + @After + public void tearDown() { + ((StubToolkit) Toolkit.getToolkit()).resetScreens(); + } + + @Test + public void test() { + final Screen selectedScreen = Utils.getScreenForRectangle(rectangle); + Assert.assertEquals(expectedScreenIndex, + Screen.getScreens().indexOf(selectedScreen)); + } + + private static Object[] config(final double x, final double y, + final double width, final double height, + final int expectedScreenIndex) { + return new Object[] { + new Rectangle2D(x, y, width, height), + expectedScreenIndex + }; + } +} --- old/modules/graphics/src/test/java/com/sun/javafx/util/WeakReferenceQueueTest.java 2015-09-11 21:25:03.797286547 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,208 +0,0 @@ -/* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.javafx.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Iterator; - -import org.junit.Test; - -public class WeakReferenceQueueTest { - @Test - public void testAdd() { - WeakReferenceQueue q = new WeakReferenceQueue(); - String s = new String("Wow!"); - q.add(s); - assertEquals(1, q.size); - } - - @Test - public void testRemove() { - WeakReferenceQueue q = new WeakReferenceQueue(); - String a = new String("a"); - q.add(a); - String b = new String("b"); - q.add(b); - String c = new String("c"); - q.add(c); - - assertEquals(3, q.size); - q.remove(a); - q.remove(c); - assertEquals(1, q.size); - } - - @Test - public void testCleanup() { - WeakReferenceQueue q = new WeakReferenceQueue(); - String a = new String("a"); - q.add(a); - String b = new String("b"); - q.add(b); - String c = new String("c"); - q.add(c); - - assertEquals(3, q.size); - a = null; - c = null; - tryGCReallyHard(); - q.cleanup(); - assertEquals(1, q.size); - } - - @Test - public void testIterator() { - WeakReferenceQueue q = new WeakReferenceQueue(); - String a = new String("a"); - q.add(a); - String b = new String("b"); - q.add(b); - String c = new String("c"); - q.add(c); - - // This part of the test requires knowledge that iteration - // is from last to first - Iterator itr = q.iterator(); - assertTrue(itr.hasNext()); - assertEquals(c, itr.next()); - assertTrue(itr.hasNext()); - assertEquals(b, itr.next()); - assertTrue(itr.hasNext()); - assertEquals(a, itr.next()); - assertFalse(itr.hasNext()); - - // and for good measure do it again without calling hasNext just - // to make sure calling hasNext isn't a requirement - itr = q.iterator(); - assertEquals(c, itr.next()); - assertEquals(b, itr.next()); - assertEquals(a, itr.next()); - } - - @Test - public void testEmptyIterator() { - WeakReferenceQueue q = new WeakReferenceQueue(); - Iterator itr = q.iterator(); - assertFalse(itr.hasNext()); - } - - @Test - public void testIteratorRemove() { - WeakReferenceQueue q = new WeakReferenceQueue(); - String a = new String("a"); - q.add(a); - String b = new String("b"); - q.add(b); - String c = new String("c"); - q.add(c); - - Iterator itr = q.iterator(); - itr.next(); // gives me "c" - itr.remove(); - assertEquals(2, q.size); - itr.next(); // gives me "b" - itr.remove(); - assertEquals(1, q.size); - itr.next(); // gives me "a" - itr.remove(); - assertEquals(0, q.size); - - q.add(a); - q.add(b); - q.add(c); - itr = q.iterator(); - itr.next(); - itr.next(); // gives me "b" - itr.remove(); - - itr = q.iterator(); - assertEquals(c, itr.next()); - assertEquals(a, itr.next()); - } - - @Test - public void testIteratingOverSparseQueue() { - WeakReferenceQueue q = new WeakReferenceQueue(); - String a = new String("a"); - q.add(a); - String b = new String("b"); - q.add(b); - String c = new String("c"); - q.add(c); - - assertEquals(3, q.size); - a = null; - c = null; - tryGCReallyHard(); - q.cleanup(); - - Iterator itr = q.iterator(); - assertEquals(b, itr.next()); - assertFalse(itr.hasNext()); - } - - @Test - public void testIteratingOverSparseQueueWithoutCleanup() { - WeakReferenceQueue q = new WeakReferenceQueue(); - String a = new String("a"); - q.add(a); - String b = new String("b"); - q.add(b); - String c = new String("c"); - q.add(c); - - assertEquals(3, q.size); - a = null; - c = null; - tryGCReallyHard(); - - Iterator itr = q.iterator(); - assertEquals(b, itr.next()); - assertFalse(itr.hasNext()); - } - - private void tryGCReallyHard() { - // produce some garbage to increase the need of performing gc - for (int i = 0; i < 100000; i++) { - String s = new String("GARBAGE"); - } - - // now, yell at the VM to run gc - for (int i = 0; i < 10; i++) { - System.gc(); - System.gc(); - System.gc(); - } - - // finally, give the VM some idle time to perform gc - try { Thread.sleep(100); } catch (InterruptedException e) {} - - // hope that worked! - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/javafx/util/WeakReferenceQueueTest.java 2015-09-11 21:25:03.613286549 -0400 @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.javafx.util; + +import com.sun.javafx.util.WeakReferenceQueue; +import com.sun.javafx.util.WeakReferenceQueueShim; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Iterator; + +import org.junit.Test; + +public class WeakReferenceQueueTest { + @Test + public void testAdd() { + WeakReferenceQueue q = new WeakReferenceQueue(); + String s = new String("Wow!"); + q.add(s); + assertEquals(1, WeakReferenceQueueShim.size(q)); + } + + @Test + public void testRemove() { + WeakReferenceQueue q = new WeakReferenceQueue(); + String a = new String("a"); + q.add(a); + String b = new String("b"); + q.add(b); + String c = new String("c"); + q.add(c); + + assertEquals(3, WeakReferenceQueueShim.size(q)); + q.remove(a); + q.remove(c); + assertEquals(1, WeakReferenceQueueShim.size(q)); + } + + @Test + public void testCleanup() { + WeakReferenceQueue q = new WeakReferenceQueue(); + String a = new String("a"); + q.add(a); + String b = new String("b"); + q.add(b); + String c = new String("c"); + q.add(c); + + assertEquals(3, WeakReferenceQueueShim.size(q)); + a = null; + c = null; + tryGCReallyHard(); + q.cleanup(); + assertEquals(1, WeakReferenceQueueShim.size(q)); + } + + @Test + public void testIterator() { + WeakReferenceQueue q = new WeakReferenceQueue(); + String a = new String("a"); + q.add(a); + String b = new String("b"); + q.add(b); + String c = new String("c"); + q.add(c); + + // This part of the test requires knowledge that iteration + // is from last to first + Iterator itr = q.iterator(); + assertTrue(itr.hasNext()); + assertEquals(c, itr.next()); + assertTrue(itr.hasNext()); + assertEquals(b, itr.next()); + assertTrue(itr.hasNext()); + assertEquals(a, itr.next()); + assertFalse(itr.hasNext()); + + // and for good measure do it again without calling hasNext just + // to make sure calling hasNext isn't a requirement + itr = q.iterator(); + assertEquals(c, itr.next()); + assertEquals(b, itr.next()); + assertEquals(a, itr.next()); + } + + @Test + public void testEmptyIterator() { + WeakReferenceQueue q = new WeakReferenceQueue(); + Iterator itr = q.iterator(); + assertFalse(itr.hasNext()); + } + + @Test + public void testIteratorRemove() { + WeakReferenceQueue q = new WeakReferenceQueue(); + String a = new String("a"); + q.add(a); + String b = new String("b"); + q.add(b); + String c = new String("c"); + q.add(c); + + Iterator itr = q.iterator(); + itr.next(); // gives me "c" + itr.remove(); + assertEquals(2, WeakReferenceQueueShim.size(q)); + itr.next(); // gives me "b" + itr.remove(); + assertEquals(1, WeakReferenceQueueShim.size(q)); + itr.next(); // gives me "a" + itr.remove(); + assertEquals(0, WeakReferenceQueueShim.size(q)); + + q.add(a); + q.add(b); + q.add(c); + itr = q.iterator(); + itr.next(); + itr.next(); // gives me "b" + itr.remove(); + + itr = q.iterator(); + assertEquals(c, itr.next()); + assertEquals(a, itr.next()); + } + + @Test + public void testIteratingOverSparseQueue() { + WeakReferenceQueue q = new WeakReferenceQueue(); + String a = new String("a"); + q.add(a); + String b = new String("b"); + q.add(b); + String c = new String("c"); + q.add(c); + + assertEquals(3, WeakReferenceQueueShim.size(q)); + a = null; + c = null; + tryGCReallyHard(); + q.cleanup(); + + Iterator itr = q.iterator(); + assertEquals(b, itr.next()); + assertFalse(itr.hasNext()); + } + + @Test + public void testIteratingOverSparseQueueWithoutCleanup() { + WeakReferenceQueue q = new WeakReferenceQueue(); + String a = new String("a"); + q.add(a); + String b = new String("b"); + q.add(b); + String c = new String("c"); + q.add(c); + + assertEquals(3, WeakReferenceQueueShim.size(q)); + a = null; + c = null; + tryGCReallyHard(); + + Iterator itr = q.iterator(); + assertEquals(b, itr.next()); + assertFalse(itr.hasNext()); + } + + private void tryGCReallyHard() { + // produce some garbage to increase the need of performing gc + for (int i = 0; i < 100000; i++) { + String s = new String("GARBAGE"); + } + + // now, yell at the VM to run gc + for (int i = 0; i < 10; i++) { + System.gc(); + System.gc(); + System.gc(); + } + + // finally, give the VM some idle time to perform gc + try { Thread.sleep(100); } catch (InterruptedException e) {} + + // hope that worked! + } +} --- old/modules/graphics/src/test/java/com/sun/prism/StrokedShapeTest.java 2015-09-11 21:25:04.485286539 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.prism; - -import com.sun.javafx.geom.Path2D; -import com.sun.javafx.geom.transform.BaseTransform; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - -public class StrokedShapeTest { - - BasicStroke stroke; - Path2D path; - - @Before - public void setUp() { - stroke = new BasicStroke(); - stroke.width = 10; - path = new Path2D(); - path.moveTo(0, 0); - } - - @Test - public void lineTo() { - path.lineTo(10, 0); - assertBounds(-5, -5, 15, 5); - } - - @Test - public void lineTo_cap() { - path.lineTo(3, 4); - stroke.cap = BasicStroke.CAP_SQUARE; - assertBounds(-7, -7, 10, 11); - stroke.cap = BasicStroke.CAP_BUTT; - assertBounds(-4, -3, 7, 7); - stroke.cap = BasicStroke.CAP_ROUND; - assertBounds(-5, -5, 8, 9); - } - - @Test - public void quadTo() { - path.quadTo(3, 4, 6, 0); - assertBounds(-7, -7, 13, 7); - } - - @Test - public void quadTo_cap() { - path.quadTo(3, 4, 6, 0); - stroke.cap = BasicStroke.CAP_SQUARE; - assertBounds(-7, -7, 13, 7); - stroke.cap = BasicStroke.CAP_BUTT; - assertBounds(-4, -3, 10, 7); - stroke.cap = BasicStroke.CAP_ROUND; - assertBounds(-5, -5, 11, 7); - } - - @Test - public void curveTo() { - path.curveTo(10, 0, 0, 10, 20, 10); - assertBounds(-5, -5, 25, 15); - - } - - @Test - public void curveTo_cap() { - path.curveTo(3, 4, 6, 0, 9, 4); - stroke.cap = BasicStroke.CAP_SQUARE; - assertBounds(-7, -7, 16, 11); - stroke.cap = BasicStroke.CAP_BUTT; - assertBounds(-4, -3, 13, 7); - stroke.cap = BasicStroke.CAP_ROUND; - assertBounds(-5, -5, 14, 9); - } - - @Test - public void lineLine_join() { - stroke.cap = BasicStroke.CAP_ROUND; // for easy computation - path.lineTo(3, 4); - path.lineTo(6, 0); - stroke.join = BasicStroke.JOIN_MITER; - assertBounds(-5, -5, 11, 12.33f); - stroke.join = BasicStroke.JOIN_BEVEL; - assertBounds(-5, -5, 11, 7); - stroke.join = BasicStroke.JOIN_ROUND; - assertBounds(-5, -5, 11, 9); - } - - @Test - public void lineQuad_join() { - stroke.cap = BasicStroke.CAP_ROUND; // for easy computation - path.lineTo(3, 4); - path.quadTo(6, 0, 10, 4); - stroke.join = BasicStroke.JOIN_MITER; - assertBounds(-5, -5, 15, 12.33f); - stroke.join = BasicStroke.JOIN_BEVEL; - assertBounds(-5, -5, 15, 9); //a better test here? (width accumulates more than join) - stroke.join = BasicStroke.JOIN_ROUND; - assertBounds(-5, -5, 15, 9); - } - - - @Test - public void lineCurve_join() { - stroke.cap = BasicStroke.CAP_ROUND; // for easy computation - path.lineTo(3, 4); - path.curveTo(6, 0, 0, 0, 10, 4); - stroke.join = BasicStroke.JOIN_MITER; - assertBounds(-5, -5, 15, 12.33f); - stroke.join = BasicStroke.JOIN_BEVEL; - assertBounds(-5, -5, 15, 9); //a better test here? (width accumulates more than join) - stroke.join = BasicStroke.JOIN_ROUND; - assertBounds(-5, -5, 15, 9); - } - - private void assertBounds(float x0, float y0, float x1, float y1) { - float[] bbox = new float[]{0, 0, 0, 0}; - stroke.accumulateShapeBounds(bbox, path, BaseTransform.IDENTITY_TRANSFORM); - assertArrayEquals(new float[]{x0, y0, x1, y1}, bbox, 0.01f); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/prism/StrokedShapeTest.java 2015-09-11 21:25:04.349286541 -0400 @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.prism; + +import com.sun.javafx.geom.Path2D; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.prism.BasicStroke; +import com.sun.prism.BasicStrokeShim; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + +public class StrokedShapeTest { + + BasicStroke stroke; + Path2D path; + + @Before + public void setUp() { + stroke = new BasicStroke(); + BasicStrokeShim.set_width(stroke, 10); + path = new Path2D(); + path.moveTo(0, 0); + } + + @Test + public void lineTo() { + path.lineTo(10, 0); + assertBounds(-5, -5, 15, 5); + } + + @Test + public void lineTo_cap() { + path.lineTo(3, 4); + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_SQUARE); + assertBounds(-7, -7, 10, 11); + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_BUTT); + assertBounds(-4, -3, 7, 7); + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_ROUND); + assertBounds(-5, -5, 8, 9); + } + + @Test + public void quadTo() { + path.quadTo(3, 4, 6, 0); + assertBounds(-7, -7, 13, 7); + } + + @Test + public void quadTo_cap() { + path.quadTo(3, 4, 6, 0); + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_SQUARE); + assertBounds(-7, -7, 13, 7); + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_BUTT); + assertBounds(-4, -3, 10, 7); + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_ROUND); + assertBounds(-5, -5, 11, 7); + } + + @Test + public void curveTo() { + path.curveTo(10, 0, 0, 10, 20, 10); + assertBounds(-5, -5, 25, 15); + + } + + @Test + public void curveTo_cap() { + path.curveTo(3, 4, 6, 0, 9, 4); + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_SQUARE); + assertBounds(-7, -7, 16, 11); + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_BUTT); + assertBounds(-4, -3, 13, 7); + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_ROUND); + assertBounds(-5, -5, 14, 9); + } + + @Test + public void lineLine_join() { + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_ROUND); // for easy computation + path.lineTo(3, 4); + path.lineTo(6, 0); + BasicStrokeShim.set_join(stroke, BasicStroke.JOIN_MITER); + assertBounds(-5, -5, 11, 12.33f); + BasicStrokeShim.set_join(stroke, BasicStroke.JOIN_BEVEL); + assertBounds(-5, -5, 11, 7); + BasicStrokeShim.set_join(stroke, BasicStroke.JOIN_ROUND); + assertBounds(-5, -5, 11, 9); + } + + @Test + public void lineQuad_join() { + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_ROUND); // for easy computation + path.lineTo(3, 4); + path.quadTo(6, 0, 10, 4); + BasicStrokeShim.set_join(stroke, BasicStroke.JOIN_MITER); + assertBounds(-5, -5, 15, 12.33f); + BasicStrokeShim.set_join(stroke, BasicStroke.JOIN_BEVEL); + assertBounds(-5, -5, 15, 9); //a better test here? (width accumulates more than join) + BasicStrokeShim.set_join(stroke, BasicStroke.JOIN_ROUND); + assertBounds(-5, -5, 15, 9); + } + + + @Test + public void lineCurve_join() { + BasicStrokeShim.set_cap(stroke, BasicStroke.CAP_ROUND); // for easy computation + path.lineTo(3, 4); + path.curveTo(6, 0, 0, 0, 10, 4); + BasicStrokeShim.set_join(stroke, BasicStroke.JOIN_MITER); + assertBounds(-5, -5, 15, 12.33f); + BasicStrokeShim.set_join(stroke, BasicStroke.JOIN_BEVEL); + assertBounds(-5, -5, 15, 9); //a better test here? (width accumulates more than join) + BasicStrokeShim.set_join(stroke, BasicStroke.JOIN_ROUND); + assertBounds(-5, -5, 15, 9); + } + + private void assertBounds(float x0, float y0, float x1, float y1) { + float[] bbox = new float[]{0, 0, 0, 0}; + stroke.accumulateShapeBounds(bbox, path, BaseTransform.IDENTITY_TRANSFORM); + assertArrayEquals(new float[]{x0, y0, x1, y1}, bbox, 0.01f); + } +} --- old/modules/graphics/src/test/java/com/sun/prism/impl/shape/NativePiscesRasterizerTest.java 2015-09-11 21:25:05.185286532 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,261 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.prism.impl.shape; - -import com.sun.javafx.geom.PathIterator; -import com.sun.prism.BasicStroke; -import org.junit.Test; - -public class NativePiscesRasterizerTest { - static final int JOIN_BEVEL = BasicStroke.JOIN_BEVEL; - static final int JOIN_MITER = BasicStroke.JOIN_MITER; - static final int JOIN_ROUND = BasicStroke.JOIN_ROUND; - - static final int CAP_SQUARE = BasicStroke.CAP_SQUARE; - static final int CAP_ROUND = BasicStroke.CAP_ROUND; - static final int CAP_BUTT = BasicStroke.CAP_BUTT; - - static final byte SEG_MOVETO = PathIterator.SEG_MOVETO; - static final byte SEG_LINETO = PathIterator.SEG_LINETO; - static final byte SEG_QUADTO = PathIterator.SEG_QUADTO; - static final byte SEG_CUBICTO = PathIterator.SEG_CUBICTO; - static final byte SEG_CLOSE = PathIterator.SEG_CLOSE; - - static final float coords6[] = new float[6]; - static final float coords1[] = new float[1]; - static final float coords3[] = new float[3]; - static final float coords5[] = new float[5]; - static final float coords7[] = new float[7]; - static final byte move_arr[] = { SEG_MOVETO }; - static final byte moveline_arr[] = { SEG_MOVETO, SEG_LINETO }; - static final byte movequad_arr[] = { SEG_MOVETO, SEG_QUADTO }; - static final byte movecubic_arr[] = { SEG_MOVETO, SEG_CUBICTO }; - static final int bounds10[] = { 0, 0, 10, 10 }; - static final byte mask1k[] = new byte[1024]; - - @Test(expected=java.lang.NullPointerException.class) - public void FillNullCoords() { - NativePiscesRasterizer.produceFillAlphas(null, move_arr, 1, true, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.NullPointerException.class) - public void FillNullCommands() { - NativePiscesRasterizer.produceFillAlphas(coords6, null, 1, true, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.NullPointerException.class) - public void FillNullBounds() { - NativePiscesRasterizer.produceFillAlphas(coords6, move_arr, 1, true, - 1, 0, 0, 0, 1, 0, - null, mask1k); - } - - @Test(expected=java.lang.NullPointerException.class) - public void FillNullMask() { - NativePiscesRasterizer.produceFillAlphas(coords6, move_arr, 1, true, - 1, 0, 0, 0, 1, 0, - bounds10, null); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void FillShortBounds() { - NativePiscesRasterizer.produceFillAlphas(coords6, move_arr, 1, true, - 1, 0, 0, 0, 1, 0, - new int[3], mask1k); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void FillShortCommands() { - NativePiscesRasterizer.produceFillAlphas(coords6, move_arr, 2, true, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test - public void FillBadCommands() { - byte badcmd_arr[] = new byte[2]; - badcmd_arr[0] = SEG_MOVETO; - for (int i = 0; i < 256; i++) { - switch (i) { - case SEG_MOVETO: - case SEG_LINETO: - case SEG_QUADTO: - case SEG_CUBICTO: - case SEG_CLOSE: - continue; - default: - badcmd_arr[1] = (byte) i; - try { - NativePiscesRasterizer.produceFillAlphas(coords6, badcmd_arr, 2, true, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - throw new RuntimeException("allowed bad command: "+i); - } catch (InternalError e) { - } - break; - } - } - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void FillShortMoveCoords() { - NativePiscesRasterizer.produceFillAlphas(coords1, move_arr, 1, true, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void FillShortLineCoords() { - NativePiscesRasterizer.produceFillAlphas(coords3, moveline_arr, 2, true, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void FillShortQuadCoords() { - NativePiscesRasterizer.produceFillAlphas(coords5, movequad_arr, 2, true, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void FillShortCubicCoords() { - NativePiscesRasterizer.produceFillAlphas(coords7, movecubic_arr, 2, true, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.NullPointerException.class) - public void StrokeNullCoords() { - NativePiscesRasterizer.produceStrokeAlphas(null, move_arr, 1, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.NullPointerException.class) - public void StrokeNullCommands() { - NativePiscesRasterizer.produceStrokeAlphas(coords6, null, 1, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.NullPointerException.class) - public void StrokeNullBounds() { - NativePiscesRasterizer.produceStrokeAlphas(coords6, move_arr, 1, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - null, mask1k); - } - - @Test(expected=java.lang.NullPointerException.class) - public void StrokeNullMask() { - NativePiscesRasterizer.produceStrokeAlphas(coords6, move_arr, 1, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - bounds10, null); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void StrokeShortBounds() { - NativePiscesRasterizer.produceStrokeAlphas(coords6, move_arr, 1, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - new int[3], mask1k); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void StrokeShortCommands() { - NativePiscesRasterizer.produceStrokeAlphas(coords6, move_arr, 2, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test - public void StrokeBadCommands() { - byte badcmd_arr[] = new byte[2]; - badcmd_arr[0] = SEG_MOVETO; - for (int i = 0; i < 256; i++) { - switch (i) { - case SEG_MOVETO: - case SEG_LINETO: - case SEG_QUADTO: - case SEG_CUBICTO: - case SEG_CLOSE: - continue; - default: - badcmd_arr[1] = (byte) i; - try { - NativePiscesRasterizer.produceStrokeAlphas(coords6, badcmd_arr, 2, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - throw new RuntimeException("allowed bad command: "+i); - } catch (InternalError e) { - } - break; - } - } - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void StrokeShortMoveCoords() { - NativePiscesRasterizer.produceStrokeAlphas(coords1, move_arr, 1, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void StrokeShortLineCoords() { - NativePiscesRasterizer.produceStrokeAlphas(coords3, moveline_arr, 2, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void StrokeShortQuadCoords() { - NativePiscesRasterizer.produceStrokeAlphas(coords5, movequad_arr, 2, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } - - @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) - public void StrokeShortCubicCoords() { - NativePiscesRasterizer.produceStrokeAlphas(coords7, movecubic_arr, 2, - 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, - 1, 0, 0, 0, 1, 0, - bounds10, mask1k); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/prism/impl/shape/NativePiscesRasterizerTest.java 2015-09-11 21:25:04.985286534 -0400 @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.prism.impl.shape; + +import com.sun.javafx.geom.PathIterator; +import com.sun.prism.BasicStroke; +import com.sun.prism.impl.shape.NativePiscesRasterizerShim; +import org.junit.Test; + +public class NativePiscesRasterizerTest { + static final int JOIN_BEVEL = BasicStroke.JOIN_BEVEL; + static final int JOIN_MITER = BasicStroke.JOIN_MITER; + static final int JOIN_ROUND = BasicStroke.JOIN_ROUND; + + static final int CAP_SQUARE = BasicStroke.CAP_SQUARE; + static final int CAP_ROUND = BasicStroke.CAP_ROUND; + static final int CAP_BUTT = BasicStroke.CAP_BUTT; + + static final byte SEG_MOVETO = PathIterator.SEG_MOVETO; + static final byte SEG_LINETO = PathIterator.SEG_LINETO; + static final byte SEG_QUADTO = PathIterator.SEG_QUADTO; + static final byte SEG_CUBICTO = PathIterator.SEG_CUBICTO; + static final byte SEG_CLOSE = PathIterator.SEG_CLOSE; + + static final float coords6[] = new float[6]; + static final float coords1[] = new float[1]; + static final float coords3[] = new float[3]; + static final float coords5[] = new float[5]; + static final float coords7[] = new float[7]; + static final byte move_arr[] = { SEG_MOVETO }; + static final byte moveline_arr[] = { SEG_MOVETO, SEG_LINETO }; + static final byte movequad_arr[] = { SEG_MOVETO, SEG_QUADTO }; + static final byte movecubic_arr[] = { SEG_MOVETO, SEG_CUBICTO }; + static final int bounds10[] = { 0, 0, 10, 10 }; + static final byte mask1k[] = new byte[1024]; + + @Test(expected=java.lang.NullPointerException.class) + public void FillNullCoords() { + NativePiscesRasterizerShim.produceFillAlphas(null, move_arr, 1, true, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.NullPointerException.class) + public void FillNullCommands() { + NativePiscesRasterizerShim.produceFillAlphas(coords6, null, 1, true, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.NullPointerException.class) + public void FillNullBounds() { + NativePiscesRasterizerShim.produceFillAlphas(coords6, move_arr, 1, true, + 1, 0, 0, 0, 1, 0, + null, mask1k); + } + + @Test(expected=java.lang.NullPointerException.class) + public void FillNullMask() { + NativePiscesRasterizerShim.produceFillAlphas(coords6, move_arr, 1, true, + 1, 0, 0, 0, 1, 0, + bounds10, null); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void FillShortBounds() { + NativePiscesRasterizerShim.produceFillAlphas(coords6, move_arr, 1, true, + 1, 0, 0, 0, 1, 0, + new int[3], mask1k); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void FillShortCommands() { + NativePiscesRasterizerShim.produceFillAlphas(coords6, move_arr, 2, true, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test + public void FillBadCommands() { + byte badcmd_arr[] = new byte[2]; + badcmd_arr[0] = SEG_MOVETO; + for (int i = 0; i < 256; i++) { + switch (i) { + case SEG_MOVETO: + case SEG_LINETO: + case SEG_QUADTO: + case SEG_CUBICTO: + case SEG_CLOSE: + continue; + default: + badcmd_arr[1] = (byte) i; + try { + NativePiscesRasterizerShim.produceFillAlphas(coords6, badcmd_arr, 2, true, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + throw new RuntimeException("allowed bad command: "+i); + } catch (InternalError e) { + } + break; + } + } + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void FillShortMoveCoords() { + NativePiscesRasterizerShim.produceFillAlphas(coords1, move_arr, 1, true, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void FillShortLineCoords() { + NativePiscesRasterizerShim.produceFillAlphas(coords3, moveline_arr, 2, true, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void FillShortQuadCoords() { + NativePiscesRasterizerShim.produceFillAlphas(coords5, movequad_arr, 2, true, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void FillShortCubicCoords() { + NativePiscesRasterizerShim.produceFillAlphas(coords7, movecubic_arr, 2, true, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.NullPointerException.class) + public void StrokeNullCoords() { + NativePiscesRasterizerShim.produceStrokeAlphas(null, move_arr, 1, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.NullPointerException.class) + public void StrokeNullCommands() { + NativePiscesRasterizerShim.produceStrokeAlphas(coords6, null, 1, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.NullPointerException.class) + public void StrokeNullBounds() { + NativePiscesRasterizerShim.produceStrokeAlphas(coords6, move_arr, 1, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + null, mask1k); + } + + @Test(expected=java.lang.NullPointerException.class) + public void StrokeNullMask() { + NativePiscesRasterizerShim.produceStrokeAlphas(coords6, move_arr, 1, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + bounds10, null); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void StrokeShortBounds() { + NativePiscesRasterizerShim.produceStrokeAlphas(coords6, move_arr, 1, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + new int[3], mask1k); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void StrokeShortCommands() { + NativePiscesRasterizerShim.produceStrokeAlphas(coords6, move_arr, 2, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test + public void StrokeBadCommands() { + byte badcmd_arr[] = new byte[2]; + badcmd_arr[0] = SEG_MOVETO; + for (int i = 0; i < 256; i++) { + switch (i) { + case SEG_MOVETO: + case SEG_LINETO: + case SEG_QUADTO: + case SEG_CUBICTO: + case SEG_CLOSE: + continue; + default: + badcmd_arr[1] = (byte) i; + try { + NativePiscesRasterizerShim.produceStrokeAlphas(coords6, badcmd_arr, 2, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + throw new RuntimeException("allowed bad command: "+i); + } catch (InternalError e) { + } + break; + } + } + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void StrokeShortMoveCoords() { + NativePiscesRasterizerShim.produceStrokeAlphas(coords1, move_arr, 1, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void StrokeShortLineCoords() { + NativePiscesRasterizerShim.produceStrokeAlphas(coords3, moveline_arr, 2, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void StrokeShortQuadCoords() { + NativePiscesRasterizerShim.produceStrokeAlphas(coords5, movequad_arr, 2, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } + + @Test(expected=java.lang.ArrayIndexOutOfBoundsException.class) + public void StrokeShortCubicCoords() { + NativePiscesRasterizerShim.produceStrokeAlphas(coords7, movecubic_arr, 2, + 10, CAP_ROUND, JOIN_ROUND, 10, null, 0, + 1, 0, 0, 0, 1, 0, + bounds10, mask1k); + } +} --- old/modules/graphics/src/test/java/com/sun/scenario/SettingsTest.java 2015-09-11 21:25:05.781286525 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import javafx.util.Callback; - -import org.junit.Test; - -public class SettingsTest { - - - @Test - public void testStringValue() { - Settings.set("foo", "foobar"); - assertEquals("foobar", Settings.get("foo")); - } - - @Test - public void testBooleanValue() { - Settings.set("foo", "false"); - assertFalse(Settings.getBoolean("foo")); - assertFalse(Settings.getBoolean("foo", false)); - assertFalse(Settings.getBoolean("bar", false)); - Settings.set("bar", "true"); - assertTrue(Settings.getBoolean("bar", false)); - } - - @Test - public void testIntValue() { - Settings.set("foo", "128"); - assertEquals(128, Settings.getInt("foo", 32)); - assertEquals(32, Settings.getInt("bar", 32)); - } - - private String tmp; - - @Test - public void testListener() { - final Callback listener = key -> { - tmp = Settings.get(key); - return null; - }; - Settings.addPropertyChangeListener(listener); - Settings.set("foo", "bar"); - assertEquals(tmp, "bar"); - Settings.removePropertyChangeListener(listener); - } - - @Test - public void testSystemProperties() { - System.setProperty("foo", "bar"); - Settings.set("foo", null); - assertEquals(Settings.get("foo"), "bar"); - - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/SettingsTest.java 2015-09-11 21:25:05.645286526 -0400 @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario; + +import com.sun.scenario.Settings; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import javafx.util.Callback; + +import org.junit.Test; + +public class SettingsTest { + + + @Test + public void testStringValue() { + Settings.set("foo", "foobar"); + assertEquals("foobar", Settings.get("foo")); + } + + @Test + public void testBooleanValue() { + Settings.set("foo", "false"); + assertFalse(Settings.getBoolean("foo")); + assertFalse(Settings.getBoolean("foo", false)); + assertFalse(Settings.getBoolean("bar", false)); + Settings.set("bar", "true"); + assertTrue(Settings.getBoolean("bar", false)); + } + + @Test + public void testIntValue() { + Settings.set("foo", "128"); + assertEquals(128, Settings.getInt("foo", 32)); + assertEquals(32, Settings.getInt("bar", 32)); + } + + private String tmp; + + @Test + public void testListener() { + final Callback listener = key -> { + tmp = Settings.get(key); + return null; + }; + Settings.addPropertyChangeListener(listener); + Settings.set("foo", "bar"); + assertEquals(tmp, "bar"); + Settings.removePropertyChangeListener(listener); + } + + @Test + public void testSystemProperties() { + System.setProperty("foo", "bar"); + Settings.set("foo", null); + assertEquals(Settings.get("foo"), "bar"); + + } +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/AbstractMasterTimerTest.java 2015-09-11 21:25:06.493286517 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,185 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario.animation; - -import javafx.animation.AnimationTimer; -import com.sun.scenario.DelayedRunnable; -import com.sun.scenario.animation.shared.PulseReceiver; -import com.sun.scenario.animation.shared.TimerReceiver; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class AbstractMasterTimerTest { - - private AbstractMasterTimerStub timer; - - - @Before - public void setUp() { - timer = new AbstractMasterTimerStub(); - } - - @Test - public void testPauseResume() { - // pause timer - timer.setNanos(2L); - assertEquals(2L, timer.nanos()); - timer.pause(); - assertEquals(2L, timer.nanos()); - - // test nanos during pause - timer.setNanos(5L); - assertEquals(2L, timer.nanos()); - - // pause again - timer.setNanos(10L); - timer.pause(); - assertEquals(2L, timer.nanos()); - - // resume - timer.setNanos(17L); - timer.resume(); - assertEquals(2L, timer.nanos()); - timer.setNanos(28L); - assertEquals(13L, timer.nanos()); - - // resume again - timer.setNanos(41L); - timer.resume(); - assertEquals(26L, timer.nanos()); - - // pause again - timer.setNanos(58L); - assertEquals(43L, timer.nanos()); - timer.pause(); - assertEquals(43L, timer.nanos()); - - // test nanos during pause - timer.setNanos(77L); - assertEquals(43L, timer.nanos()); - - // resume - timer.setNanos(100L); - timer.resume(); - assertEquals(43L, timer.nanos()); - timer.setNanos(129L); - assertEquals(72L, timer.nanos()); - } - - @Test - public void testPulseReceiver() { - final Flag flag = new Flag(); - - final PulseReceiver pulseReceiver = now -> flag.flag(); - - // add PulseReceiver - timer.addPulseReceiver(pulseReceiver); - timer.simulatePulse(); - assertTrue(flag.isFlagged()); - - // remove PulseReceiver - flag.unflag(); - timer.removePulseReceiver(pulseReceiver); - timer.simulatePulse(); - assertFalse(flag.isFlagged()); - } - - @Test - public void testAnimationTimers() { - final Flag flag = new Flag(); - - final AnimationTimer animationTimer = new AnimationTimer() { - @Override - public void handle(long now) { - flag.flag(); - } - }; - - final TimerReceiver timerReceiver = l -> animationTimer.handle(l); - - // add AnimationTimer - timer.addAnimationTimer(timerReceiver); - timer.simulatePulse(); - assertTrue(flag.isFlagged()); - - // remove AnimationTimer - flag.unflag(); - timer.removeAnimationTimer(timerReceiver); - timer.simulatePulse(); - assertFalse(flag.isFlagged()); - } - - private static class Flag { - - private boolean flagged; - - public void flag() { - flagged = true; - } - - public void unflag() { - flagged = false; - } - - public boolean isFlagged() { - return flagged; - } - } - - private static class AbstractMasterTimerStub extends AbstractMasterTimer { - - private long nanos; - private DelayedRunnable animationRunnable; - - public void setNanos(long nanos) { - this.nanos = nanos; - } - - public void simulatePulse() { - if (animationRunnable != null) { - animationRunnable.run(); - } - } - - @Override public long nanos() { - return isPaused() ? getStartPauseTime() : nanos - getTotalPausedTime(); - } - - @Override - protected void postUpdateAnimationRunnable( - DelayedRunnable animationRunnable) { - this.animationRunnable = animationRunnable; - } - - @Override - protected int getPulseDuration(int precision) { - return precision / 60; - } - - }; -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/AbstractMasterTimerTest.java 2015-09-11 21:25:06.353286518 -0400 @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.animation; + +import javafx.animation.AnimationTimer; +import com.sun.scenario.DelayedRunnable; +import com.sun.scenario.animation.AbstractMasterTimer; +import com.sun.scenario.animation.AbstractMasterTimerShim; +import com.sun.scenario.animation.shared.PulseReceiver; +import com.sun.scenario.animation.shared.TimerReceiver; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class AbstractMasterTimerTest { + + private AbstractMasterTimerStub timer; + + + @Before + public void setUp() { + timer = new AbstractMasterTimerStub(); + } + + @Test + public void testPauseResume() { + // pause timer + timer.setNanos(2L); + assertEquals(2L, timer.nanos()); + timer.pause(); + assertEquals(2L, timer.nanos()); + + // test nanos during pause + timer.setNanos(5L); + assertEquals(2L, timer.nanos()); + + // pause again + timer.setNanos(10L); + timer.pause(); + assertEquals(2L, timer.nanos()); + + // resume + timer.setNanos(17L); + timer.resume(); + assertEquals(2L, timer.nanos()); + timer.setNanos(28L); + assertEquals(13L, timer.nanos()); + + // resume again + timer.setNanos(41L); + timer.resume(); + assertEquals(26L, timer.nanos()); + + // pause again + timer.setNanos(58L); + assertEquals(43L, timer.nanos()); + timer.pause(); + assertEquals(43L, timer.nanos()); + + // test nanos during pause + timer.setNanos(77L); + assertEquals(43L, timer.nanos()); + + // resume + timer.setNanos(100L); + timer.resume(); + assertEquals(43L, timer.nanos()); + timer.setNanos(129L); + assertEquals(72L, timer.nanos()); + } + + @Test + public void testPulseReceiver() { + final Flag flag = new Flag(); + + final PulseReceiver pulseReceiver = now -> flag.flag(); + + // add PulseReceiver + timer.addPulseReceiver(pulseReceiver); + timer.simulatePulse(); + assertTrue(flag.isFlagged()); + + // remove PulseReceiver + flag.unflag(); + timer.removePulseReceiver(pulseReceiver); + timer.simulatePulse(); + assertFalse(flag.isFlagged()); + } + + @Test + public void testAnimationTimers() { + final Flag flag = new Flag(); + + final AnimationTimer animationTimer = new AnimationTimer() { + @Override + public void handle(long now) { + flag.flag(); + } + }; + + final TimerReceiver timerReceiver = l -> animationTimer.handle(l); + + // add AnimationTimer + timer.addAnimationTimer(timerReceiver); + timer.simulatePulse(); + assertTrue(flag.isFlagged()); + + // remove AnimationTimer + flag.unflag(); + timer.removeAnimationTimer(timerReceiver); + timer.simulatePulse(); + assertFalse(flag.isFlagged()); + } + + private static class Flag { + + private boolean flagged; + + public void flag() { + flagged = true; + } + + public void unflag() { + flagged = false; + } + + public boolean isFlagged() { + return flagged; + } + } + + private static class AbstractMasterTimerStub extends AbstractMasterTimer { + + private long nanos; + private DelayedRunnable animationRunnable; + + public void setNanos(long nanos) { + this.nanos = nanos; + } + + public void simulatePulse() { + if (animationRunnable != null) { + animationRunnable.run(); + } + } + + @Override public long nanos() { + return AbstractMasterTimerShim.isPaused(this) ? + AbstractMasterTimerShim.getStartPauseTime(this) : + nanos - AbstractMasterTimerShim.getTotalPausedTime(this); + } + + @Override + protected void postUpdateAnimationRunnable( + DelayedRunnable animationRunnable) { + this.animationRunnable = animationRunnable; + } + + @Override + protected int getPulseDuration(int precision) { + return precision / 60; + } + + }; +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/NumberTangentInterpolatorTest.java 2015-09-11 21:25:07.109286510 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario.animation; - - -import javafx.animation.Interpolator; -import static org.junit.Assert.*; -import static javafx.util.Duration.*; - -import org.junit.Before; -import org.junit.Test; - -public class NumberTangentInterpolatorTest { - - private static final double EPSILON_DOUBLE = 1e-12; - private static final double EPSILON_FLOAT = 1e-6; - - private NumberTangentInterpolator interpolator; - - @Before - public void setUp() throws Exception { - interpolator = new NumberTangentInterpolator(ZERO, 0); - } - - @Test - public void testCreate() { - final NumberTangentInterpolator interpolator1 = new NumberTangentInterpolator(millis(2000), Math.PI); - assertEquals(Math.PI, interpolator1.getInValue(), EPSILON_DOUBLE); - assertEquals(12000.0, interpolator1.getInTicks(), EPSILON_DOUBLE); - assertEquals(Math.PI, interpolator1.getOutValue(), EPSILON_DOUBLE); - assertEquals(12000.0, interpolator1.getOutTicks(), EPSILON_DOUBLE); - - final NumberTangentInterpolator interpolator2 = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), -Math.PI); - assertEquals(Math.E, interpolator2.getInValue(), EPSILON_DOUBLE); - assertEquals(3000.0, interpolator2.getInTicks(), EPSILON_DOUBLE); - assertEquals(-Math.PI, interpolator2.getOutValue(), EPSILON_DOUBLE); - assertEquals(6000.0, interpolator2.getOutTicks(), EPSILON_DOUBLE); - } - - @Test - public void testInterpolate_boolean() { - assertEquals(false, interpolator.interpolate(false, true, 0.0)); - assertEquals(false, interpolator.interpolate(false, true, 0.5)); - assertEquals(true, interpolator.interpolate(false, true, 1.0)); - } - - @Test - public void testInterpolate_double() { - assertEquals( 0.0, interpolator.interpolate(0.0, 10.0, 0.0), EPSILON_DOUBLE); - assertEquals( 5.0, interpolator.interpolate(0.0, 10.0, 0.5), EPSILON_DOUBLE); - assertEquals(10.0, interpolator.interpolate(0.0, 10.0, 1.0), EPSILON_DOUBLE); - } - - @Test - public void testInterpolate_int() { - assertEquals( 0, interpolator.interpolate(0, 10, 0.0)); - assertEquals( 5, interpolator.interpolate(0, 10, 0.5)); - assertEquals(10, interpolator.interpolate(0, 10, 1.0)); - } - - @Test - public void testInterpolate_long() { - assertEquals( 0L, interpolator.interpolate(0L, 10L, 0.0)); - assertEquals( 5L, interpolator.interpolate(0L, 10L, 0.5)); - assertEquals(10L, interpolator.interpolate(0L, 10L, 1.0)); - } - - @Test - public void testInterpolate_float() { - assertEquals( 0.0f, interpolator.interpolate(0.0f, 10.0f, 0.0), EPSILON_FLOAT); - assertEquals( 5.0f, interpolator.interpolate(0.0f, 10.0f, 0.5), EPSILON_FLOAT); - assertEquals(10.0f, interpolator.interpolate(0.0f, 10.0f, 1.0), EPSILON_FLOAT); - } - - @Test - public void testInterpolate_Object() { - assertEquals("Hello World", interpolator.interpolate("Hello World", "Goodbye World", 0.0)); - assertEquals("Hello World", interpolator.interpolate("Hello World", "Goodbye World", 0.5)); - assertEquals("Goodbye World", interpolator.interpolate("Hello World", "Goodbye World", 1.0)); - } - - @Test - public void testInterpolate_Number() { - assertEquals(Integer.valueOf( 0), interpolator.interpolate(Integer.valueOf(0), Integer.valueOf(10), 0.0)); - assertEquals(Integer.valueOf( 5), interpolator.interpolate(Integer.valueOf(0), Integer.valueOf(10), 0.5)); - assertEquals(Integer.valueOf(10), interpolator.interpolate(Integer.valueOf(0), Integer.valueOf(10), 1.0)); - } - - private static void testEqualsAndHashCode(Interpolator one, Interpolator another) { - assertTrue(one.equals(another)); - assertTrue(another.equals(one)); - assertEquals(one.hashCode(), another.hashCode()); - } - - private static void testNotEqualsAndHashCode(Interpolator one, Interpolator another) { - assertFalse(one.equals(another)); - assertFalse(another.equals(one)); - assertFalse(one.hashCode() == another.hashCode()); - } - - @Test public void testEqualsAndHashCodeShort() { - testEqualsAndHashCode(interpolator, new NumberTangentInterpolator(ZERO, 0)); - } - - @Test public void testNotEqualsAndHashCodeShort() { - testNotEqualsAndHashCode(interpolator, new NumberTangentInterpolator(millis(500), 0)); - testNotEqualsAndHashCode(interpolator, new NumberTangentInterpolator(ZERO, 1)); - } - - @Test public void testEqualsAndHashCode() { - Interpolator one = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), -Math.PI); - Interpolator another = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), -Math.PI); - testEqualsAndHashCode(one, another); - } - - @Test public void testNotEqualsAndHashCode() { - Interpolator one = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), -Math.PI); - Interpolator another = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), Math.PI); - testNotEqualsAndHashCode(one, another); - - another = new NumberTangentInterpolator(millis(500), Math.E, millis(800), -Math.PI); - testNotEqualsAndHashCode(one, another); - - another = new NumberTangentInterpolator(millis(500), Math.PI, millis(1000), -Math.PI); - testNotEqualsAndHashCode(one, another); - - another = new NumberTangentInterpolator(millis(100), Math.E, millis(1000), -Math.PI); - testNotEqualsAndHashCode(one, another); - } - - @Test public void testEqualsAndHashCodeFullToShort() { - NumberTangentInterpolator sh = new NumberTangentInterpolator(millis(200), 105); - NumberTangentInterpolator full = new NumberTangentInterpolator(millis(200), 105, millis(200), 105); - testEqualsAndHashCode(sh, full); - } - - @Test public void testNotEqualsAndHashCodeFullToShort() { - NumberTangentInterpolator sh = new NumberTangentInterpolator(millis(200), 105); - Interpolator full = new NumberTangentInterpolator(millis(500), 105, millis(500), 105); - testNotEqualsAndHashCode(sh, full); - - full = new NumberTangentInterpolator(millis(200), 115, millis(200), 115); - testNotEqualsAndHashCode(sh, full); - - full = new NumberTangentInterpolator(millis(200), 105, millis(200), 100); - testNotEqualsAndHashCode(sh, full); - - full = new NumberTangentInterpolator(millis(200), 105, millis(205), 105); - testNotEqualsAndHashCode(sh, full); - - full = new NumberTangentInterpolator(millis(200), 106, millis(200), 105); - testNotEqualsAndHashCode(sh, full); - - full = new NumberTangentInterpolator(millis(210), 105, millis(200), 105); - testNotEqualsAndHashCode(sh, full); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/NumberTangentInterpolatorTest.java 2015-09-11 21:25:06.973286511 -0400 @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.animation; + + +import com.sun.scenario.animation.NumberTangentInterpolator; +import javafx.animation.Interpolator; +import static org.junit.Assert.*; +import static javafx.util.Duration.*; + +import org.junit.Before; +import org.junit.Test; + +public class NumberTangentInterpolatorTest { + + private static final double EPSILON_DOUBLE = 1e-12; + private static final double EPSILON_FLOAT = 1e-6; + + private NumberTangentInterpolator interpolator; + + @Before + public void setUp() throws Exception { + interpolator = new NumberTangentInterpolator(ZERO, 0); + } + + @Test + public void testCreate() { + final NumberTangentInterpolator interpolator1 = new NumberTangentInterpolator(millis(2000), Math.PI); + assertEquals(Math.PI, interpolator1.getInValue(), EPSILON_DOUBLE); + assertEquals(12000.0, interpolator1.getInTicks(), EPSILON_DOUBLE); + assertEquals(Math.PI, interpolator1.getOutValue(), EPSILON_DOUBLE); + assertEquals(12000.0, interpolator1.getOutTicks(), EPSILON_DOUBLE); + + final NumberTangentInterpolator interpolator2 = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), -Math.PI); + assertEquals(Math.E, interpolator2.getInValue(), EPSILON_DOUBLE); + assertEquals(3000.0, interpolator2.getInTicks(), EPSILON_DOUBLE); + assertEquals(-Math.PI, interpolator2.getOutValue(), EPSILON_DOUBLE); + assertEquals(6000.0, interpolator2.getOutTicks(), EPSILON_DOUBLE); + } + + @Test + public void testInterpolate_boolean() { + assertEquals(false, interpolator.interpolate(false, true, 0.0)); + assertEquals(false, interpolator.interpolate(false, true, 0.5)); + assertEquals(true, interpolator.interpolate(false, true, 1.0)); + } + + @Test + public void testInterpolate_double() { + assertEquals( 0.0, interpolator.interpolate(0.0, 10.0, 0.0), EPSILON_DOUBLE); + assertEquals( 5.0, interpolator.interpolate(0.0, 10.0, 0.5), EPSILON_DOUBLE); + assertEquals(10.0, interpolator.interpolate(0.0, 10.0, 1.0), EPSILON_DOUBLE); + } + + @Test + public void testInterpolate_int() { + assertEquals( 0, interpolator.interpolate(0, 10, 0.0)); + assertEquals( 5, interpolator.interpolate(0, 10, 0.5)); + assertEquals(10, interpolator.interpolate(0, 10, 1.0)); + } + + @Test + public void testInterpolate_long() { + assertEquals( 0L, interpolator.interpolate(0L, 10L, 0.0)); + assertEquals( 5L, interpolator.interpolate(0L, 10L, 0.5)); + assertEquals(10L, interpolator.interpolate(0L, 10L, 1.0)); + } + + @Test + public void testInterpolate_float() { + assertEquals( 0.0f, interpolator.interpolate(0.0f, 10.0f, 0.0), EPSILON_FLOAT); + assertEquals( 5.0f, interpolator.interpolate(0.0f, 10.0f, 0.5), EPSILON_FLOAT); + assertEquals(10.0f, interpolator.interpolate(0.0f, 10.0f, 1.0), EPSILON_FLOAT); + } + + @Test + public void testInterpolate_Object() { + assertEquals("Hello World", interpolator.interpolate("Hello World", "Goodbye World", 0.0)); + assertEquals("Hello World", interpolator.interpolate("Hello World", "Goodbye World", 0.5)); + assertEquals("Goodbye World", interpolator.interpolate("Hello World", "Goodbye World", 1.0)); + } + + @Test + public void testInterpolate_Number() { + assertEquals(Integer.valueOf( 0), interpolator.interpolate(Integer.valueOf(0), Integer.valueOf(10), 0.0)); + assertEquals(Integer.valueOf( 5), interpolator.interpolate(Integer.valueOf(0), Integer.valueOf(10), 0.5)); + assertEquals(Integer.valueOf(10), interpolator.interpolate(Integer.valueOf(0), Integer.valueOf(10), 1.0)); + } + + private static void testEqualsAndHashCode(Interpolator one, Interpolator another) { + assertTrue(one.equals(another)); + assertTrue(another.equals(one)); + assertEquals(one.hashCode(), another.hashCode()); + } + + private static void testNotEqualsAndHashCode(Interpolator one, Interpolator another) { + assertFalse(one.equals(another)); + assertFalse(another.equals(one)); + assertFalse(one.hashCode() == another.hashCode()); + } + + @Test public void testEqualsAndHashCodeShort() { + testEqualsAndHashCode(interpolator, new NumberTangentInterpolator(ZERO, 0)); + } + + @Test public void testNotEqualsAndHashCodeShort() { + testNotEqualsAndHashCode(interpolator, new NumberTangentInterpolator(millis(500), 0)); + testNotEqualsAndHashCode(interpolator, new NumberTangentInterpolator(ZERO, 1)); + } + + @Test public void testEqualsAndHashCode() { + Interpolator one = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), -Math.PI); + Interpolator another = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), -Math.PI); + testEqualsAndHashCode(one, another); + } + + @Test public void testNotEqualsAndHashCode() { + Interpolator one = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), -Math.PI); + Interpolator another = new NumberTangentInterpolator(millis(500), Math.E, millis(1000), Math.PI); + testNotEqualsAndHashCode(one, another); + + another = new NumberTangentInterpolator(millis(500), Math.E, millis(800), -Math.PI); + testNotEqualsAndHashCode(one, another); + + another = new NumberTangentInterpolator(millis(500), Math.PI, millis(1000), -Math.PI); + testNotEqualsAndHashCode(one, another); + + another = new NumberTangentInterpolator(millis(100), Math.E, millis(1000), -Math.PI); + testNotEqualsAndHashCode(one, another); + } + + @Test public void testEqualsAndHashCodeFullToShort() { + NumberTangentInterpolator sh = new NumberTangentInterpolator(millis(200), 105); + NumberTangentInterpolator full = new NumberTangentInterpolator(millis(200), 105, millis(200), 105); + testEqualsAndHashCode(sh, full); + } + + @Test public void testNotEqualsAndHashCodeFullToShort() { + NumberTangentInterpolator sh = new NumberTangentInterpolator(millis(200), 105); + Interpolator full = new NumberTangentInterpolator(millis(500), 105, millis(500), 105); + testNotEqualsAndHashCode(sh, full); + + full = new NumberTangentInterpolator(millis(200), 115, millis(200), 115); + testNotEqualsAndHashCode(sh, full); + + full = new NumberTangentInterpolator(millis(200), 105, millis(200), 100); + testNotEqualsAndHashCode(sh, full); + + full = new NumberTangentInterpolator(millis(200), 105, millis(205), 105); + testNotEqualsAndHashCode(sh, full); + + full = new NumberTangentInterpolator(millis(200), 106, millis(200), 105); + testNotEqualsAndHashCode(sh, full); + + full = new NumberTangentInterpolator(millis(210), 105, millis(200), 105); + testNotEqualsAndHashCode(sh, full); + } +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/SplineInterpolatorTest.java 2015-09-11 21:25:07.841286502 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.sun.scenario.animation; - -import javafx.animation.Interpolator; -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -public class SplineInterpolatorTest { - - private SplineInterpolator interpolator; - - @Before - public void setUp() throws Exception { - interpolator = new SplineInterpolator(0.2, 0.1, 0.3, 0.4); - } - - private static void testEqualsAndHashCode(Interpolator one, Interpolator another) { - assertTrue(one.equals(another)); - assertTrue(another.equals(one)); - assertEquals(one.hashCode(), another.hashCode()); - } - - private static void testNotEqualsAndHashCode(Interpolator one, Interpolator another) { - assertFalse(one.equals(another)); - assertFalse(another.equals(one)); - assertFalse(one.hashCode() == another.hashCode()); - } - - @Test - public void testEqualsAndHashCode() { - Interpolator another = new SplineInterpolator(0.2, 0.1, 0.3, 0.4); - testEqualsAndHashCode(interpolator, another); - } - - @Test - public void testNotEqualsAndHashCode() { - Interpolator another = new SplineInterpolator(0.2, 0.1, 0.3, 0.5); - testNotEqualsAndHashCode(interpolator, another); - - another = new SplineInterpolator(0.3, 0.5, 0.2, 0.1); - testNotEqualsAndHashCode(interpolator, another); - - another = new SplineInterpolator(0.2, 0.1, 0.6, 0.4); - testNotEqualsAndHashCode(interpolator, another); - - another = new SplineInterpolator(0.2, 0.14, 0.3, 0.4); - testNotEqualsAndHashCode(interpolator, another); - - another = new SplineInterpolator(0.25, 0.1, 0.3, 0.4); - testNotEqualsAndHashCode(interpolator, another); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/SplineInterpolatorTest.java 2015-09-11 21:25:07.641286504 -0400 @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package test.com.sun.scenario.animation; + +import com.sun.scenario.animation.SplineInterpolator; +import javafx.animation.Interpolator; +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +public class SplineInterpolatorTest { + + private SplineInterpolator interpolator; + + @Before + public void setUp() throws Exception { + interpolator = new SplineInterpolator(0.2, 0.1, 0.3, 0.4); + } + + private static void testEqualsAndHashCode(Interpolator one, Interpolator another) { + assertTrue(one.equals(another)); + assertTrue(another.equals(one)); + assertEquals(one.hashCode(), another.hashCode()); + } + + private static void testNotEqualsAndHashCode(Interpolator one, Interpolator another) { + assertFalse(one.equals(another)); + assertFalse(another.equals(one)); + assertFalse(one.hashCode() == another.hashCode()); + } + + @Test + public void testEqualsAndHashCode() { + Interpolator another = new SplineInterpolator(0.2, 0.1, 0.3, 0.4); + testEqualsAndHashCode(interpolator, another); + } + + @Test + public void testNotEqualsAndHashCode() { + Interpolator another = new SplineInterpolator(0.2, 0.1, 0.3, 0.5); + testNotEqualsAndHashCode(interpolator, another); + + another = new SplineInterpolator(0.3, 0.5, 0.2, 0.1); + testNotEqualsAndHashCode(interpolator, another); + + another = new SplineInterpolator(0.2, 0.1, 0.6, 0.4); + testNotEqualsAndHashCode(interpolator, another); + + another = new SplineInterpolator(0.2, 0.14, 0.3, 0.4); + testNotEqualsAndHashCode(interpolator, another); + + another = new SplineInterpolator(0.25, 0.1, 0.3, 0.4); + testNotEqualsAndHashCode(interpolator, another); + } +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/shared/ClipEnvelopeMock.java 2015-09-11 21:25:08.453286495 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario.animation.shared; - -import javafx.animation.Animation; -import javafx.util.Duration; - -public class ClipEnvelopeMock extends ClipEnvelope { - - public long getTimelineTicks() { - return cycleTicks; - } - - public double getRate() { - return rate; - } - private boolean autoReverse; - - public boolean getAutoReverse() { - return autoReverse; - } - - @Override - public void setAutoReverse(boolean autoReverse) { - this.autoReverse = autoReverse; - } - private int cycleCount; - - public int getCycleCount() { - return cycleCount; - } - private long lastJumpTo; - - public long getLastJumpTo() { - final long v = lastJumpTo; - lastJumpTo = 0L; - return v; - } - private long lastTimePulse; - - public long getLastTimePulse() { - final long v = lastTimePulse; - lastTimePulse = 0L; - return v; - } - - public ClipEnvelopeMock() { - super(null); - } - - public void setAnimation(Animation animation) { - this.animation = animation; - setCycleDuration(animation.getCycleDuration()); - } - - @Override - public boolean wasSynched() { - return true; - } - - @Override - public ClipEnvelope setCycleCount(int cycleCount) { - this.cycleCount = cycleCount; - return this; - } - - @Override - public void timePulse(long currentTick) { - lastTimePulse = currentTick; - } - - @Override - public void jumpTo(long ticks) { - lastJumpTo = ticks; - // Emulate what ClipEnvelope is supposed to do - while (ticks > cycleTicks) { - ticks -= cycleTicks; - } - AnimationAccessor.getDefault().jumpTo(animation, ticks, cycleTicks, false); - } - - @Override - public ClipEnvelope setCycleDuration(Duration cycleDuration) { - updateCycleTicks(cycleDuration); - return this; - } - - @Override - public void setRate(double rate) { - this.rate = rate; - } - - @Override - protected double calculateCurrentRate() { - return rate; - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/shared/ClipEnvelopeMock.java 2015-09-11 21:25:08.313286496 -0400 @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.animation.shared; + +import com.sun.scenario.animation.shared.AnimationAccessor; +import com.sun.scenario.animation.shared.ClipEnvelope; +import javafx.animation.Animation; +import javafx.util.Duration; + +public class ClipEnvelopeMock extends ClipEnvelope { + + public long getTimelineTicks() { + return cycleTicks; + } + + public double getRate() { + return rate; + } + private boolean autoReverse; + + public boolean getAutoReverse() { + return autoReverse; + } + + @Override + public void setAutoReverse(boolean autoReverse) { + this.autoReverse = autoReverse; + } + private int cycleCount; + + public int getCycleCount() { + return cycleCount; + } + private long lastJumpTo; + + public long getLastJumpTo() { + final long v = lastJumpTo; + lastJumpTo = 0L; + return v; + } + private long lastTimePulse; + + public long getLastTimePulse() { + final long v = lastTimePulse; + lastTimePulse = 0L; + return v; + } + + public ClipEnvelopeMock() { + super(null); + } + + public void setAnimation(Animation animation) { + this.animation = animation; + setCycleDuration(animation.getCycleDuration()); + } + + @Override + public boolean wasSynched() { + return true; + } + + @Override + public ClipEnvelope setCycleCount(int cycleCount) { + this.cycleCount = cycleCount; + return this; + } + + @Override + public void timePulse(long currentTick) { + lastTimePulse = currentTick; + } + + @Override + public void jumpTo(long ticks) { + lastJumpTo = ticks; + // Emulate what ClipEnvelope is supposed to do + while (ticks > cycleTicks) { + ticks -= cycleTicks; + } + AnimationAccessor.getDefault().jumpTo(animation, ticks, cycleTicks, false); + } + + @Override + public ClipEnvelope setCycleDuration(Duration cycleDuration) { + updateCycleTicks(cycleDuration); + return this; + } + + @Override + public void setRate(double rate) { + this.rate = rate; + } + + @Override + protected double calculateCurrentRate() { + return rate; + } +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/shared/FiniteClipEnvelopeTest.java 2015-09-11 21:25:09.165286487 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,723 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario.animation.shared; - - -import com.sun.javafx.tk.Toolkit; -import javafx.animation.Animation; -import javafx.animation.Animation.Status; -import javafx.animation.AnimationMock; -import javafx.animation.AnimationMock.Command; -import javafx.util.Duration; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class FiniteClipEnvelopeTest { - - private final long CYCLE_TICKS = Math.round(6.0 * AnimationMock.DEFAULT_DURATION.toMillis()); - - private ClipEnvelope clip; - private AnimationMock animation; - - @Before - public void setUp() { - animation = new AnimationMock(Toolkit.getToolkit().getMasterTimer(), AnimationMock.DEFAULT_DURATION, AnimationMock.DEFAULT_RATE, 9, AnimationMock.DEFAULT_AUTOREVERSE); - clip = new FiniteClipEnvelope(animation); - } - - @Test - public void testSetValues() { - ClipEnvelope c; - - // Setting cycleCount to 1 - animation.setCycleCount(1); - animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); - c = clip.setCycleCount(1); - assertNotSame(clip, c); - assertTrue(c instanceof SingleLoopClipEnvelope); - - // Setting cycleCount to INDEFINITE - animation.setCycleCount(Animation.INDEFINITE); - animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); - c = clip.setCycleCount(Animation.INDEFINITE); - assertNotSame(clip, c); - assertTrue(c instanceof InfiniteClipEnvelope); - - // Setting cycleDuration to INDEFINITE - animation.setCycleCount(9); - animation.mockCycleDuration(Duration.INDEFINITE); - c = clip.setCycleDuration(Duration.INDEFINITE); - assertNotSame(clip, c); - assertTrue(c instanceof SingleLoopClipEnvelope); - - } - - @Test - public void testJump() { - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - clip.jumpTo(0); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - clip.jumpTo(6 * 1000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - - clip.jumpTo(-1); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - clip.jumpTo(6 * 1000 + 1); - animation.check(Command.JUMP, 1, CYCLE_TICKS); - - clip.jumpTo(6 * 9000 + 1); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - } - - @Test - public void testTimePulseForward() { - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.timePulse(1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 500); - animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 700); - animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 + 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 4300); - animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse close to the end - clip.timePulse(6 * 9000 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse at the end - clip.timePulse(6 * 9000); - animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testTimePulseBackward() { - clip.setRate(-1.0); - clip.jumpTo(6 * 9000); - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.timePulse(1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 500); - animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 700); - animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 + 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 4300); - animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse close to the end - clip.timePulse(6 * 9000 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse at the end - clip.timePulse(6 * 9000); - animation.check(Command.PLAY, 0, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testTimePulseForwardAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.setAutoReverse(true); - clip.start(); - - clip.timePulse(1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 + 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse one cycle ahead - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse two cycles ahead - clip.timePulse(6 * 4300); - animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // another pulse one cycle ahead - clip.timePulse(6 * 5400); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // another pulse two cycles ahead - clip.timePulse(6 * 7100); - animation.check(Command.PLAY, 6 * 900, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse close to the end - clip.timePulse(6 * 9000 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse at the end - clip.timePulse(6 * 9000); - animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testTimePulseBackwardAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.jumpTo(6 * 9000); - clip.start(); - clip.setAutoReverse(true); - clip.setRate(-1); - - clip.timePulse(1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 200); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 + 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse one cycle ahead - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse two cycles ahead - clip.timePulse(6 * 4300); - animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // another pulse one cycle ahead - clip.timePulse(6 * 5400); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // another pulse two cycles ahead - clip.timePulse(6 * 7100); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse close to the end - clip.timePulse(6 * 9000 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse at the end - clip.timePulse(6 * 9000); - animation.check(Command.PLAY, 0, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseForward() { - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - clip.timePulse(6 * 800); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 50); - animation.check(Command.JUMP, 6 * 50, CYCLE_TICKS); - - clip.timePulse(6 * 1850); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(0); - animation.check(Command.JUMP, 6 * 0, CYCLE_TICKS); - - clip.timePulse(6 * 2000); - animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 1000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 3400); - animation.check(Command.JUMP, 6 * 400, CYCLE_TICKS); - - clip.timePulse(6 * 2400); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 1100); - animation.check(Command.JUMP, 6 * 100, CYCLE_TICKS); - - clip.timePulse(6 * 2500); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse close to the end - clip.timePulse(6 * 10300 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse at the end - clip.timePulse(6 * 10300); - animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseBackward() { - animation.mockStatus(Status.RUNNING); - clip.jumpTo(6 * 9000); - clip.setRate(-1); - clip.start(); - - // jump forward - clip.jumpTo(6 * 8300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse in next cycle - clip.timePulse(6 * 700); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump backward - clip.jumpTo(6 * 7900); - animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse one cycle ahead - clip.timePulse(6 * 1750); - animation.check(Command.PLAY, 6 * 850, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to same position at end - clip.jumpTo(6 * 7000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // normal pulse - clip.timePulse(6 * 2000); - animation.check(Command.PLAY, 6 * 750, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to start - clip.jumpTo(6 * 6000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // normal pulse - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 3400); - animation.check(Command.JUMP, 6 * 400, CYCLE_TICKS); - - clip.timePulse(6 * 2400); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 5100); - animation.check(Command.JUMP, 6 * 100, CYCLE_TICKS); - - clip.timePulse(6 * 2700); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse close to the end - clip.timePulse(6 * 7500 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse at the end - clip.timePulse(6 * 7500); - animation.check(Command.PLAY, 0, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseForwardAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.setAutoReverse(true); - clip.start(); - - // jump forward - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - // pulse in next cycle - clip.timePulse(6 * 900); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump backward - clip.jumpTo(6 * 900); - animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); - - // pulse one cycle ahead - clip.timePulse(6 * 1850); - animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to start - clip.jumpTo(6 * 0); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - // normal pulse - clip.timePulse(6 * 2000); - animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to end - clip.jumpTo(6 * 1000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - - // normal pulse - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 3400); - animation.check(Command.JUMP, 6 * 600, CYCLE_TICKS); - - clip.timePulse(6 * 2400); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 1100); - animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); - - clip.timePulse(6 * 2500); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse close to the end - clip.timePulse(6 * 10300 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse at the end - clip.timePulse(6 * 10300); - animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseBackwardAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.setAutoReverse(true); - clip.setRate(-1); - clip.start(); - - // jump forward - clip.jumpTo(6 * 8300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse in next cycle - clip.timePulse(6 * 700); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump backward - clip.jumpTo(6 * 7900); - animation.check(Command.JUMP, 6 * 100, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse one cycle ahead - clip.timePulse(6 * 1750); - animation.check(Command.PLAY, 6 * 850, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to same position at end - clip.jumpTo(6 * 7000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // normal pulse - clip.timePulse(6 * 2000); - animation.check(Command.PLAY, 6 * 750, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to start - clip.jumpTo(6 * 6000); - animation.check(Command.JUMP, 6 * 0, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // normal pulse - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 3400); - animation.check(Command.JUMP, 6 * 600, CYCLE_TICKS); - - clip.timePulse(6 * 2400); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 5100); - animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); - - clip.timePulse(6 * 2700); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse close to the end - clip.timePulse(6 * 7500 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse at the end - clip.timePulse(6 * 7500); - animation.check(Command.PLAY, 0, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testPositiveFastForwardRate() { - animation.mockStatus(Status.RUNNING); - clip.setRate(2.5); - clip.start(); - - clip.timePulse(6 * 300); - animation.check(Command.PLAY, 6 * 750, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 3600 - 2); // 9000 / 2.5 - animation.check(Command.PLAY, 6 * 1000 - 5, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 3600); // 9000 / 2.5 - animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testPositiveSlowDownRate() { - animation.mockStatus(Status.RUNNING); - clip.setRate(0.2); - clip.start(); - - clip.timePulse(6 * 300); - animation.check(Command.PLAY, 6 * 60, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 45000 - 5); // 9000 / 0.2 - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 45000); // 9000 / 0.2 - animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testNegativeFastForwardRate() { - clip.jumpTo(6 * 9000); - clip.setRate(-2.5); - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.timePulse(6 * 300); - animation.check(Command.PLAY, 6 * 250, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 3600 - 2); // 9000 / 2.5 - animation.check(Command.PLAY, 5, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 3600); // 9000 / 2.5 - animation.check(Command.PLAY, 0, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testNegativeSlowDownRate() { - clip.jumpTo(6 * 9000); - clip.setRate(-0.2); - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.timePulse(6 * 300); - animation.check(Command.PLAY, 6 * 940, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 45000 - 5); // 9000 / 0.2 - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 45000); // 9000 / 0.2 - animation.check(Command.PLAY, 0, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testChangeRateWhilePlaying() { - animation.mockStatus(Status.RUNNING); - clip.setRate(0.5); - clip.start(); - - clip.timePulse(6 * 200); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - - clip.setRate(3.0); - clip.timePulse(6 * 300); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - - clip.setRate(2.0); - clip.timePulse(6 * 500); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - - clip.setRate(-0.5); - clip.timePulse(6 * 1100); - animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); - - clip.setRate(-3.0); - clip.timePulse(6 * 1200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - - clip.setRate(0.5); - clip.timePulse(6 * 2100); - animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); - - clip.setRate(1.5); - clip.timePulse(6 * 2600); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - - clip.setRate(-2.0); - clip.timePulse(6 * 3000); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - } - - @Test - public void testRateAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.setAutoReverse(true); - clip.setRate(0.5); - clip.start(); - - clip.timePulse(6 * 200); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - - clip.setRate(3.0); - clip.timePulse(6 * 300); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - - clip.setRate(2.0); - clip.timePulse(6 * 500); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - - clip.setRate(-0.5); - clip.timePulse(6 * 1100); - animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); - - clip.setRate(-3.0); - clip.timePulse(6 * 1200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - - clip.setRate(0.5); - clip.timePulse(6 * 2100); - animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); - - clip.setRate(1.5); - clip.timePulse(6 * 2600); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - - clip.setRate(-2.0); - clip.timePulse(6 * 3000); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/shared/FiniteClipEnvelopeTest.java 2015-09-11 21:25:08.953286489 -0400 @@ -0,0 +1,727 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.animation.shared; + + +import com.sun.javafx.tk.Toolkit; +import com.sun.scenario.animation.shared.ClipEnvelope; +import com.sun.scenario.animation.shared.FiniteClipEnvelopeShim; +import com.sun.scenario.animation.shared.InfiniteClipEnvelope; +import com.sun.scenario.animation.shared.SingleLoopClipEnvelope; +import javafx.animation.Animation; +import javafx.animation.Animation.Status; +import test.javafx.animation.AnimationMock; +import test.javafx.animation.AnimationMock.Command; +import javafx.util.Duration; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class FiniteClipEnvelopeTest { + + private final long CYCLE_TICKS = Math.round(6.0 * AnimationMock.DEFAULT_DURATION.toMillis()); + + private ClipEnvelope clip; + private AnimationMock animation; + + @Before + public void setUp() { + animation = new AnimationMock(Toolkit.getToolkit().getMasterTimer(), AnimationMock.DEFAULT_DURATION, AnimationMock.DEFAULT_RATE, 9, AnimationMock.DEFAULT_AUTOREVERSE); + clip = new FiniteClipEnvelopeShim(animation); + } + + @Test + public void testSetValues() { + ClipEnvelope c; + + // Setting cycleCount to 1 + animation.setCycleCount(1); + animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); + c = clip.setCycleCount(1); + assertNotSame(clip, c); + assertTrue(c instanceof SingleLoopClipEnvelope); + + // Setting cycleCount to INDEFINITE + animation.setCycleCount(Animation.INDEFINITE); + animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); + c = clip.setCycleCount(Animation.INDEFINITE); + assertNotSame(clip, c); + assertTrue(c instanceof InfiniteClipEnvelope); + + // Setting cycleDuration to INDEFINITE + animation.setCycleCount(9); + animation.mockCycleDuration(Duration.INDEFINITE); + c = clip.setCycleDuration(Duration.INDEFINITE); + assertNotSame(clip, c); + assertTrue(c instanceof SingleLoopClipEnvelope); + + } + + @Test + public void testJump() { + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + clip.jumpTo(0); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + clip.jumpTo(6 * 1000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + + clip.jumpTo(-1); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + clip.jumpTo(6 * 1000 + 1); + animation.check(Command.JUMP, 1, CYCLE_TICKS); + + clip.jumpTo(6 * 9000 + 1); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + } + + @Test + public void testTimePulseForward() { + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.timePulse(1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 500); + animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 700); + animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 + 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 4300); + animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse close to the end + clip.timePulse(6 * 9000 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse at the end + clip.timePulse(6 * 9000); + animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testTimePulseBackward() { + clip.setRate(-1.0); + clip.jumpTo(6 * 9000); + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.timePulse(1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 500); + animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 700); + animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 + 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 4300); + animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse close to the end + clip.timePulse(6 * 9000 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse at the end + clip.timePulse(6 * 9000); + animation.check(Command.PLAY, 0, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testTimePulseForwardAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.setAutoReverse(true); + clip.start(); + + clip.timePulse(1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 + 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse one cycle ahead + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse two cycles ahead + clip.timePulse(6 * 4300); + animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // another pulse one cycle ahead + clip.timePulse(6 * 5400); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // another pulse two cycles ahead + clip.timePulse(6 * 7100); + animation.check(Command.PLAY, 6 * 900, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse close to the end + clip.timePulse(6 * 9000 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse at the end + clip.timePulse(6 * 9000); + animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testTimePulseBackwardAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.jumpTo(6 * 9000); + clip.start(); + clip.setAutoReverse(true); + clip.setRate(-1); + + clip.timePulse(1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 200); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 + 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse one cycle ahead + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse two cycles ahead + clip.timePulse(6 * 4300); + animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // another pulse one cycle ahead + clip.timePulse(6 * 5400); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // another pulse two cycles ahead + clip.timePulse(6 * 7100); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse close to the end + clip.timePulse(6 * 9000 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse at the end + clip.timePulse(6 * 9000); + animation.check(Command.PLAY, 0, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseForward() { + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + clip.timePulse(6 * 800); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 50); + animation.check(Command.JUMP, 6 * 50, CYCLE_TICKS); + + clip.timePulse(6 * 1850); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(0); + animation.check(Command.JUMP, 6 * 0, CYCLE_TICKS); + + clip.timePulse(6 * 2000); + animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 1000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 3400); + animation.check(Command.JUMP, 6 * 400, CYCLE_TICKS); + + clip.timePulse(6 * 2400); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 1100); + animation.check(Command.JUMP, 6 * 100, CYCLE_TICKS); + + clip.timePulse(6 * 2500); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse close to the end + clip.timePulse(6 * 10300 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse at the end + clip.timePulse(6 * 10300); + animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseBackward() { + animation.mockStatus(Status.RUNNING); + clip.jumpTo(6 * 9000); + clip.setRate(-1); + clip.start(); + + // jump forward + clip.jumpTo(6 * 8300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse in next cycle + clip.timePulse(6 * 700); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump backward + clip.jumpTo(6 * 7900); + animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse one cycle ahead + clip.timePulse(6 * 1750); + animation.check(Command.PLAY, 6 * 850, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to same position at end + clip.jumpTo(6 * 7000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // normal pulse + clip.timePulse(6 * 2000); + animation.check(Command.PLAY, 6 * 750, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to start + clip.jumpTo(6 * 6000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // normal pulse + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 3400); + animation.check(Command.JUMP, 6 * 400, CYCLE_TICKS); + + clip.timePulse(6 * 2400); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 5100); + animation.check(Command.JUMP, 6 * 100, CYCLE_TICKS); + + clip.timePulse(6 * 2700); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse close to the end + clip.timePulse(6 * 7500 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse at the end + clip.timePulse(6 * 7500); + animation.check(Command.PLAY, 0, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseForwardAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.setAutoReverse(true); + clip.start(); + + // jump forward + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + // pulse in next cycle + clip.timePulse(6 * 900); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump backward + clip.jumpTo(6 * 900); + animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); + + // pulse one cycle ahead + clip.timePulse(6 * 1850); + animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to start + clip.jumpTo(6 * 0); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + // normal pulse + clip.timePulse(6 * 2000); + animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to end + clip.jumpTo(6 * 1000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + + // normal pulse + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 3400); + animation.check(Command.JUMP, 6 * 600, CYCLE_TICKS); + + clip.timePulse(6 * 2400); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 1100); + animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); + + clip.timePulse(6 * 2500); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse close to the end + clip.timePulse(6 * 10300 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse at the end + clip.timePulse(6 * 10300); + animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseBackwardAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.setAutoReverse(true); + clip.setRate(-1); + clip.start(); + + // jump forward + clip.jumpTo(6 * 8300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse in next cycle + clip.timePulse(6 * 700); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump backward + clip.jumpTo(6 * 7900); + animation.check(Command.JUMP, 6 * 100, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse one cycle ahead + clip.timePulse(6 * 1750); + animation.check(Command.PLAY, 6 * 850, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to same position at end + clip.jumpTo(6 * 7000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // normal pulse + clip.timePulse(6 * 2000); + animation.check(Command.PLAY, 6 * 750, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to start + clip.jumpTo(6 * 6000); + animation.check(Command.JUMP, 6 * 0, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // normal pulse + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 3400); + animation.check(Command.JUMP, 6 * 600, CYCLE_TICKS); + + clip.timePulse(6 * 2400); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 5100); + animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); + + clip.timePulse(6 * 2700); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse close to the end + clip.timePulse(6 * 7500 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse at the end + clip.timePulse(6 * 7500); + animation.check(Command.PLAY, 0, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testPositiveFastForwardRate() { + animation.mockStatus(Status.RUNNING); + clip.setRate(2.5); + clip.start(); + + clip.timePulse(6 * 300); + animation.check(Command.PLAY, 6 * 750, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 3600 - 2); // 9000 / 2.5 + animation.check(Command.PLAY, 6 * 1000 - 5, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 3600); // 9000 / 2.5 + animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testPositiveSlowDownRate() { + animation.mockStatus(Status.RUNNING); + clip.setRate(0.2); + clip.start(); + + clip.timePulse(6 * 300); + animation.check(Command.PLAY, 6 * 60, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 45000 - 5); // 9000 / 0.2 + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 45000); // 9000 / 0.2 + animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testNegativeFastForwardRate() { + clip.jumpTo(6 * 9000); + clip.setRate(-2.5); + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.timePulse(6 * 300); + animation.check(Command.PLAY, 6 * 250, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 3600 - 2); // 9000 / 2.5 + animation.check(Command.PLAY, 5, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 3600); // 9000 / 2.5 + animation.check(Command.PLAY, 0, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testNegativeSlowDownRate() { + clip.jumpTo(6 * 9000); + clip.setRate(-0.2); + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.timePulse(6 * 300); + animation.check(Command.PLAY, 6 * 940, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 45000 - 5); // 9000 / 0.2 + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 45000); // 9000 / 0.2 + animation.check(Command.PLAY, 0, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testChangeRateWhilePlaying() { + animation.mockStatus(Status.RUNNING); + clip.setRate(0.5); + clip.start(); + + clip.timePulse(6 * 200); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + + clip.setRate(3.0); + clip.timePulse(6 * 300); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + + clip.setRate(2.0); + clip.timePulse(6 * 500); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + + clip.setRate(-0.5); + clip.timePulse(6 * 1100); + animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); + + clip.setRate(-3.0); + clip.timePulse(6 * 1200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + + clip.setRate(0.5); + clip.timePulse(6 * 2100); + animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); + + clip.setRate(1.5); + clip.timePulse(6 * 2600); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + + clip.setRate(-2.0); + clip.timePulse(6 * 3000); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + } + + @Test + public void testRateAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.setAutoReverse(true); + clip.setRate(0.5); + clip.start(); + + clip.timePulse(6 * 200); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + + clip.setRate(3.0); + clip.timePulse(6 * 300); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + + clip.setRate(2.0); + clip.timePulse(6 * 500); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + + clip.setRate(-0.5); + clip.timePulse(6 * 1100); + animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); + + clip.setRate(-3.0); + clip.timePulse(6 * 1200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + + clip.setRate(0.5); + clip.timePulse(6 * 2100); + animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); + + clip.setRate(1.5); + clip.timePulse(6 * 2600); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + + clip.setRate(-2.0); + clip.timePulse(6 * 3000); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + } + +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/shared/GeneralClipInterpolatorTest.java 2015-09-11 21:25:09.873286479 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,735 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario.animation.shared; - -import com.sun.javafx.animation.TickCalculation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import javafx.animation.KeyFrame; -import javafx.animation.KeyValue; -import javafx.beans.property.IntegerProperty; -import javafx.beans.property.SimpleIntegerProperty; -import javafx.util.Duration; - -import org.junit.Test; - -public class GeneralClipInterpolatorTest { - - @Test - public void testSetKeyFrame() { - final KeyFrame kf1 = new KeyFrame(Duration.ZERO); - final KeyFrame kf2 = new KeyFrame(Duration.millis(1000)); - final KeyFrame kf3 = new KeyFrame(Duration.millis(2000)); - final GeneralClipInterpolator gci = new GeneralClipInterpolator(new KeyFrame[] {kf1, kf2, kf3}, new long[] {0, 6000, 6000}); - - assertSame (gci, gci.setKeyFrames(new KeyFrame[]{kf1, kf2, kf3}, new long[] {0, 6000, 6000})); - assertNotSame(gci, gci.setKeyFrames(new KeyFrame[]{kf1, kf2 }, new long[] {0, 6000 })); - assertNotSame(gci, gci.setKeyFrames(new KeyFrame[]{kf1, kf3}, new long[] {0, 6000})); - assertSame (gci, gci.setKeyFrames(new KeyFrame[]{kf1 }, new long[] {0 })); - assertSame (gci, gci.setKeyFrames(new KeyFrame[]{ kf2, kf3}, new long[] { 6000, 6000})); - assertNotSame(gci, gci.setKeyFrames(new KeyFrame[]{ kf2 }, new long[] { 6000 })); - assertNotSame(gci, gci.setKeyFrames(new KeyFrame[]{ kf3}, new long[] { 6000})); - assertSame (gci, gci.setKeyFrames(new KeyFrame[]{ }, new long[] { })); - } - - @Test - public void test_OneKeyFrameOnly() { - // main purpose of this test is to ensure we do not throw exceptions - final KeyFrame kf1 = new KeyFrame(Duration.ZERO); - final KeyFrame kf2 = new KeyFrame(Duration.ZERO); - - // one key frame - final GeneralClipInterpolator gci1 = new GeneralClipInterpolator (new KeyFrame[] {kf1}, new long[] {0}); - gci1.validate(true); - gci1.validate(true); - gci1.setKeyFrames(new KeyFrame[]{kf2}, new long[] {6000}); - gci1.validate(true); - gci1.setKeyFrames(new KeyFrame[]{}, new long[] {}); - gci1.validate(true); - - // no key frames - final GeneralClipInterpolator gci2 = new GeneralClipInterpolator (new KeyFrame[] {}, new long[] {}); - gci2.validate(true); - gci2.validate(true); - gci2.setKeyFrames(new KeyFrame[]{kf1}, new long[] {0}); - gci2.validate(true); - } - - @Test - public void test_NoKeyValues() { - final KeyFrame start1 = new KeyFrame(Duration.ZERO); - final KeyFrame start2 = new KeyFrame(Duration.ZERO); - final KeyFrame end1 = new KeyFrame(Duration.millis(1000)); - final KeyFrame end2a = new KeyFrame(Duration.millis(2000)); - final KeyFrame end2b = new KeyFrame(Duration.millis(3000)); - - // four key frames - final GeneralClipInterpolator gci1 = new GeneralClipInterpolator (new KeyFrame[] {start1, start2, end1, end2a}, new long[] {0, 0, 6000, 12000}); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(300)); - gci1.interpolate(TickCalculation.fromMillis(1300)); - - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(800)); - gci1.interpolate(TickCalculation.fromMillis(1800)); - - gci1.setKeyFrames(new KeyFrame[]{start1, start2, end1, end2b}, new long[] {0, 0, 6000, 18000}); - gci1.interpolate(TickCalculation.fromMillis(400)); - gci1.interpolate(TickCalculation.fromMillis(1400)); - - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(600)); - gci1.interpolate(TickCalculation.fromMillis(1600)); - - // two key frames - final GeneralClipInterpolator gci2 = new GeneralClipInterpolator (new KeyFrame[] {end1, end2a}, new long[] {6000, 12000}); - gci2.validate(true); - gci2.interpolate(TickCalculation.fromMillis(300)); - gci2.interpolate(TickCalculation.fromMillis(1300)); - - gci2.validate(true); - gci2.interpolate(TickCalculation.fromMillis(800)); - gci2.interpolate(TickCalculation.fromMillis(1800)); - - gci2.setKeyFrames(new KeyFrame[]{end1, end2b}, new long[] {6000, 18000}); - gci2.interpolate(TickCalculation.fromMillis(400)); - gci2.interpolate(TickCalculation.fromMillis(1400)); - - gci2.validate(true); - gci2.interpolate(TickCalculation.fromMillis(600)); - gci2.interpolate(TickCalculation.fromMillis(1600)); - } - - @Test - public void test_ThreeKeyFrames_OneKeyValue() { - final IntegerProperty v = new SimpleIntegerProperty(); - final KeyFrame start1 = new KeyFrame(Duration.ZERO); - final KeyFrame start2 = new KeyFrame(Duration.ZERO, new KeyValue(v, 30)); - final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v, 40)); - final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v, 60)); - final KeyFrame end2 = new KeyFrame(Duration.millis(4000), new KeyValue(v, 70)); - - final GeneralClipInterpolator gci1 = new GeneralClipInterpolator (new KeyFrame[] {start1, start2, mid1, end1}, new long[] {0, 0, 6000, 12000}); - v.set(0); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v.get()); - gci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals(33, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1600)); - assertEquals(52, v.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v.get()); - - // re-validate - v.set(20); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v.get()); - gci1.interpolate(TickCalculation.fromMillis(800)); - assertEquals(38, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1200)); - assertEquals(44, v.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v.get()); - - // set new key frames - gci1.setKeyFrames(new KeyFrame[]{start1, start2, mid1, end2}, new long[] {0, 0, 6000, 24000}); - v.set(0); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v.get()); - gci1.interpolate(TickCalculation.fromMillis(600)); - assertEquals(36, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1300)); - assertEquals(46, v.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v.get()); - - // validate new key frames - v.set(0); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v.get()); - gci1.interpolate(TickCalculation.fromMillis(700)); - assertEquals(37, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1300)); - assertEquals(43, v.get()); - gci1.interpolate(TickCalculation.fromMillis(4000)); - assertEquals(70, v.get()); - } - - @Test - public void test_TwoKeyFrames_OneKeyValue() { - final IntegerProperty v = new SimpleIntegerProperty(); - final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v, 40)); - final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v, 60)); - final KeyFrame end2 = new KeyFrame(Duration.millis(4000), new KeyValue(v, 70)); - - final GeneralClipInterpolator gci1 = new GeneralClipInterpolator (new KeyFrame[] {mid1, end1}, new long[] {6000, 12000}); - v.set(0); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 0, v.get()); - gci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals(12, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1600)); - assertEquals(52, v.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v.get()); - - // re-validate - v.set(20); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(20, v.get()); - gci1.interpolate(TickCalculation.fromMillis(800)); - assertEquals(36, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1200)); - assertEquals(44, v.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v.get()); - - // set new key frames - gci1.setKeyFrames(new KeyFrame[]{mid1, end2}, new long[] {6000, 24000}); - v.set(0); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(20, v.get()); - gci1.interpolate(TickCalculation.fromMillis(600)); - assertEquals(32, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1300)); - assertEquals(46, v.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v.get()); - - // validate new key frames - v.set(0); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 0, v.get()); - gci1.interpolate(TickCalculation.fromMillis(700)); - assertEquals(28, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - gci1.interpolate(TickCalculation.fromMillis(1300)); - assertEquals(43, v.get()); - gci1.interpolate(TickCalculation.fromMillis(4000)); - assertEquals(70, v.get()); - } - - @Test - public void test_ThreeKeyFrames_ThreeKeyValues() { - final IntegerProperty v1 = new SimpleIntegerProperty(); - final IntegerProperty v2 = new SimpleIntegerProperty(); - final IntegerProperty v3 = new SimpleIntegerProperty(); - final IntegerProperty v4 = new SimpleIntegerProperty(); - final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v3, 230), new KeyValue(v4, 330)); - final KeyFrame start2 = new KeyFrame(Duration.ZERO, new KeyValue(v2, 130)); - final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 140), new KeyValue(v3, 240)); - final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 160)); - final KeyFrame end2 = new KeyFrame(Duration.millis(4000), new KeyValue(v1, 70), new KeyValue(v2, 170)); - - final GeneralClipInterpolator gci1 = new GeneralClipInterpolator (new KeyFrame[] {start1, start2, mid1, end1}, new long[] {0, 0, 6000, 12000}); - v1.set( 0); - v2.set(100); - v3.set(200); - v4.set(300); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 0, v1.get()); - assertEquals(130, v2.get()); - assertEquals(230, v3.get()); - assertEquals(300, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals( 12, v1.get()); - assertEquals(133, v2.get()); - assertEquals(233, v3.get()); - assertEquals(300, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - assertEquals(300, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(1600)); - assertEquals( 52, v1.get()); - assertEquals(152, v2.get()); - assertEquals(240, v3.get()); - assertEquals(300, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals( 60, v1.get()); - assertEquals(160, v2.get()); - assertEquals(240, v3.get()); - assertEquals(300, v4.get()); - - // re-validate - v1.set( 20); - v2.set(120); - v3.set(220); - v4.set(320); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(130, v2.get()); - assertEquals(230, v3.get()); - assertEquals(320, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(800)); - assertEquals( 36, v1.get()); - assertEquals(138, v2.get()); - assertEquals(238, v3.get()); - assertEquals(320, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - assertEquals(320, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(1200)); - assertEquals( 44, v1.get()); - assertEquals(144, v2.get()); - assertEquals(240, v3.get()); - assertEquals(320, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals( 60, v1.get()); - assertEquals(160, v2.get()); - assertEquals(240, v3.get()); - assertEquals(320, v4.get()); - - // change key frames - gci1.setKeyFrames(new KeyFrame[]{start1, start2, mid1, end2}, new long[] {0, 0, 6000, 24000}); - v1.set( 0); - v2.set(100); - v3.set(200); - v4.set(300); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(130, v2.get()); - assertEquals(230, v3.get()); - assertEquals(300, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals( 26, v1.get()); - assertEquals(133, v2.get()); - assertEquals(233, v3.get()); - assertEquals(300, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - assertEquals(300, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(1300)); - assertEquals( 46, v1.get()); - assertEquals(146, v2.get()); - assertEquals(240, v3.get()); - assertEquals(300, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals( 60, v1.get()); - assertEquals(160, v2.get()); - assertEquals(240, v3.get()); - assertEquals(300, v4.get()); - - // validate new key frames - v1.set( 20); - v2.set(120); - v3.set(220); - v4.set(320); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(130, v2.get()); - assertEquals(230, v3.get()); - assertEquals(320, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(600)); - assertEquals( 32, v1.get()); - assertEquals(136, v2.get()); - assertEquals(236, v3.get()); - assertEquals(320, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - assertEquals(320, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(1300)); - assertEquals( 43, v1.get()); - assertEquals(143, v2.get()); - assertEquals(240, v3.get()); - assertEquals(320, v4.get()); - gci1.interpolate(TickCalculation.fromMillis(4000)); - assertEquals( 70, v1.get()); - assertEquals(170, v2.get()); - assertEquals(240, v3.get()); - assertEquals(320, v4.get()); - } - - @Test - public void test_TwoKeyFrames_ThreeKeyValues() { - final IntegerProperty v1 = new SimpleIntegerProperty(); - final IntegerProperty v2 = new SimpleIntegerProperty(); - final IntegerProperty v3 = new SimpleIntegerProperty(); - final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 140), new KeyValue(v3, 240)); - final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 160), new KeyValue(v3, 260)); - final KeyFrame end2 = new KeyFrame(Duration.millis(4000), new KeyValue(v1, 70), new KeyValue(v2, 170), new KeyValue(v3, 270)); - - final GeneralClipInterpolator gci1 = new GeneralClipInterpolator (new KeyFrame[] {mid1, end1}, new long[] {6000, 12000}); - v1.set( 0); - v2.set(100); - v3.set(200); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 0, v1.get()); - assertEquals(100, v2.get()); - assertEquals(200, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals( 12, v1.get()); - assertEquals(112, v2.get()); - assertEquals(212, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(1600)); - assertEquals( 52, v1.get()); - assertEquals(152, v2.get()); - assertEquals(252, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals( 60, v1.get()); - assertEquals(160, v2.get()); - assertEquals(260, v3.get()); - - // re-validate - v1.set( 20); - v2.set(120); - v3.set(220); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(120, v2.get()); - assertEquals(220, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(800)); - assertEquals( 36, v1.get()); - assertEquals(136, v2.get()); - assertEquals(236, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(1200)); - assertEquals( 44, v1.get()); - assertEquals(144, v2.get()); - assertEquals(244, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals( 60, v1.get()); - assertEquals(160, v2.get()); - assertEquals(260, v3.get()); - - // change key frames - gci1.setKeyFrames(new KeyFrame[]{mid1, end2}, new long[] {6000, 24000}); - v1.set( 0); - v2.set(100); - v3.set(200); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(120, v2.get()); - assertEquals(220, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals( 26, v1.get()); - assertEquals(126, v2.get()); - assertEquals(226, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(1300)); - assertEquals( 46, v1.get()); - assertEquals(146, v2.get()); - assertEquals(246, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals( 60, v1.get()); - assertEquals(160, v2.get()); - assertEquals(260, v3.get()); - - // validate new key frames - v1.set( 20); - v2.set(120); - v3.set(220); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(120, v2.get()); - assertEquals(220, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(600)); - assertEquals( 32, v1.get()); - assertEquals(132, v2.get()); - assertEquals(232, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(1300)); - assertEquals( 43, v1.get()); - assertEquals(143, v2.get()); - assertEquals(243, v3.get()); - gci1.interpolate(TickCalculation.fromMillis(4000)); - assertEquals( 70, v1.get()); - assertEquals(170, v2.get()); - assertEquals(270, v3.get()); - } - - - @Test - public void test_DuplicateKeyValue() { - final IntegerProperty v1 = new SimpleIntegerProperty(); - final IntegerProperty v2 = new SimpleIntegerProperty(); - final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v1, 30), new KeyValue(v2, 0)); - final KeyFrame start2 = new KeyFrame(Duration.ZERO, new KeyValue(v1, 30), new KeyValue(v1, -30), new KeyValue(v2, 0)); - final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 100)); - final KeyFrame mid2 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v1, -40), new KeyValue(v2, 100)); - final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 0)); - final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v1, -60), new KeyValue(v2, 0)); - - // single value in start, single value in mid, duplicate value in end - final GeneralClipInterpolator gci1 = new GeneralClipInterpolator (new KeyFrame[] {start1, mid1, end2}, new long[] {0, 6000, 12000}); - v1.set(0); - v2.set(0); - gci1.validate(true); - gci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v1.get()); - assertEquals(0, v2.get()); - gci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals(33, v1.get()); - assertEquals(30, v2.get()); - gci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v1.get()); - assertEquals(100, v2.get()); - gci1.interpolate(TickCalculation.fromMillis(1600)); - assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get())); - assertEquals(40, v2.get()); - gci1.interpolate(TickCalculation.fromMillis(2000)); - assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); - assertEquals(0, v2.get()); - - // single value in start, duplicate value in mid, single value in end - final GeneralClipInterpolator gci2 = new GeneralClipInterpolator (new KeyFrame[] {start1, mid2, end1}, new long[] {0, 6000, 12000}); - v1.set(0); - v2.set(0); - gci2.validate(true); - gci2.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v1.get()); - assertEquals(0, v2.get()); - gci2.interpolate(TickCalculation.fromMillis(300)); - assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get())); - assertEquals(30, v2.get()); - gci2.interpolate(TickCalculation.fromMillis(1000)); - assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); - assertEquals(100, v2.get()); - gci2.interpolate(TickCalculation.fromMillis(1600)); - assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (20 == v1.get())); - assertEquals(40, v2.get()); - gci2.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v1.get()); - assertEquals(0, v2.get()); - - // duplicate value in start, single value in mid, single value in end - final GeneralClipInterpolator gci3 = new GeneralClipInterpolator (new KeyFrame[] {start2, mid1, end1}, new long[] {0, 6000, 12000}); - v1.set(0); - v2.set(0); - gci3.validate(true); - gci3.interpolate(TickCalculation.fromMillis(0)); - assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); - assertEquals(0, v2.get()); - gci3.interpolate(TickCalculation.fromMillis(300)); - assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (-9 == v1.get())); - assertEquals(30, v2.get()); - gci3.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v1.get()); - assertEquals(100, v2.get()); - gci3.interpolate(TickCalculation.fromMillis(1600)); - assertEquals(52, v1.get()); - assertEquals(40, v2.get()); - gci3.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v1.get()); - assertEquals(0, v2.get()); - - // duplicate value in start, duplicate value in mid, single value in end - final GeneralClipInterpolator gci4 = new GeneralClipInterpolator (new KeyFrame[] {start2, mid2, end1}, new long[] {0, 6000, 12000}); - v1.set(0); - v2.set(0); - gci4.validate(true); - gci4.interpolate(TickCalculation.fromMillis(0)); - assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); - assertEquals(0, v2.get()); - gci4.interpolate(TickCalculation.fromMillis(300)); - assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get()) || (-9 == v1.get()) || (-33 == v1.get())); - assertEquals(30, v2.get()); - gci4.interpolate(TickCalculation.fromMillis(1000)); - assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); - assertEquals(100, v2.get()); - gci4.interpolate(TickCalculation.fromMillis(1600)); - assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (20 == v1.get())); - assertEquals(40, v2.get()); - gci4.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v1.get()); - assertEquals(0, v2.get()); - - // duplicate value in start, single value in mid, duplicate value in end - final GeneralClipInterpolator gci5 = new GeneralClipInterpolator (new KeyFrame[] {start2, mid1, end2}, new long[] {0, 6000, 12000}); - v1.set(0); - v2.set(0); - gci5.validate(true); - gci5.interpolate(TickCalculation.fromMillis(0)); - assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); - assertEquals(0, v2.get()); - gci5.interpolate(TickCalculation.fromMillis(300)); - assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (-9 == v1.get())); - assertEquals(30, v2.get()); - gci5.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v1.get()); - assertEquals(100, v2.get()); - gci5.interpolate(TickCalculation.fromMillis(1600)); - assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get())); - assertEquals(40, v2.get()); - gci5.interpolate(TickCalculation.fromMillis(2000)); - assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); - assertEquals(0, v2.get()); - - // single value in start, duplicate value in mid, duplicate value in end - final GeneralClipInterpolator gci6 = new GeneralClipInterpolator (new KeyFrame[] {start1, mid2, end2}, new long[] {0, 6000, 12000}); - v1.set(0); - v2.set(0); - gci6.validate(true); - gci6.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v1.get()); - assertEquals(0, v2.get()); - gci6.interpolate(TickCalculation.fromMillis(300)); - assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get())); - assertEquals(30, v2.get()); - gci6.interpolate(TickCalculation.fromMillis(1000)); - assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); - assertEquals(100, v2.get()); - gci6.interpolate(TickCalculation.fromMillis(1600)); - assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get()) || (20 == v1.get()) || (-52 == v1.get())); - assertEquals(40, v2.get()); - gci6.interpolate(TickCalculation.fromMillis(2000)); - assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); - assertEquals(0, v2.get()); - - // duplicate value in start, duplicate value in mid, duplicate value in end - final GeneralClipInterpolator gci7 = new GeneralClipInterpolator (new KeyFrame[] {start2, mid2, end2}, new long[] {0, 6000, 12000}); - v1.set(0); - v2.set(0); - gci7.validate(true); - gci7.interpolate(TickCalculation.fromMillis(0)); - assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); - assertEquals(0, v2.get()); - gci7.interpolate(TickCalculation.fromMillis(300)); - assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get()) || (-9 == v1.get()) || (-33 == v1.get())); - assertEquals(30, v2.get()); - gci7.interpolate(TickCalculation.fromMillis(1000)); - assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); - assertEquals(100, v2.get()); - gci7.interpolate(TickCalculation.fromMillis(1600)); - assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get()) || (20 == v1.get()) || (-52 == v1.get())); - assertEquals(40, v2.get()); - gci7.interpolate(TickCalculation.fromMillis(2000)); - assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); - assertEquals(0, v2.get()); - - // no value in start, single value in mid, duplicate value in end - final GeneralClipInterpolator gci8 = new GeneralClipInterpolator (new KeyFrame[] {mid1, end2}, new long[] {6000, 12000}); - v1.set(0); - v2.set(0); - gci8.validate(true); - gci8.interpolate(TickCalculation.fromMillis(0)); - assertEquals(0, v1.get()); - assertEquals(0, v2.get()); - gci8.interpolate(TickCalculation.fromMillis(400)); - assertEquals(16, v1.get()); - assertEquals(40, v2.get()); - gci8.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v1.get()); - assertEquals(100, v2.get()); - gci8.interpolate(TickCalculation.fromMillis(1600)); - assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get())); - assertEquals(40, v2.get()); - gci8.interpolate(TickCalculation.fromMillis(2000)); - assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); - assertEquals(0, v2.get()); - - // no value in start, duplicate value in mid, single value in end - final GeneralClipInterpolator gci9 = new GeneralClipInterpolator (new KeyFrame[] {mid2, end1}, new long[] {6000, 12000}); - v1.set(0); - v2.set(0); - gci9.validate(true); - gci9.interpolate(TickCalculation.fromMillis(0)); - assertEquals(0, v1.get()); - assertEquals(0, v2.get()); - gci9.interpolate(TickCalculation.fromMillis(400)); - assertTrue("v1.get(): " + v1.get(), (16 == v1.get()) || (-16 == v1.get())); - assertEquals(40, v2.get()); - gci9.interpolate(TickCalculation.fromMillis(1000)); - assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); - assertEquals(100, v2.get()); - gci9.interpolate(TickCalculation.fromMillis(1600)); - assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (20 == v1.get())); - assertEquals(40, v2.get()); - gci9.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v1.get()); - assertEquals(0, v2.get()); - - // no value in start, duplicate value in mid, duplicate value in end - final GeneralClipInterpolator gci10 = new GeneralClipInterpolator (new KeyFrame[] {mid2, end2}, new long[] {6000, 12000}); - v1.set(0); - v2.set(0); - gci10.validate(true); - gci10.interpolate(TickCalculation.fromMillis(0)); - assertEquals(0, v1.get()); - assertEquals(0, v2.get()); - gci10.interpolate(TickCalculation.fromMillis(400)); - assertTrue("v1.get(): " + v1.get(), (16 == v1.get()) || (-16 == v1.get())); - assertEquals(40, v2.get()); - gci10.interpolate(TickCalculation.fromMillis(1000)); - assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); - assertEquals(100, v2.get()); - gci10.interpolate(TickCalculation.fromMillis(1600)); - assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get()) || (20 == v1.get()) || (-52 == v1.get())); - assertEquals(40, v2.get()); - gci10.interpolate(TickCalculation.fromMillis(2000)); - assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); - assertEquals(0, v2.get()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/shared/GeneralClipInterpolatorTest.java 2015-09-11 21:25:09.661286481 -0400 @@ -0,0 +1,736 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.animation.shared; + +import com.sun.javafx.animation.TickCalculation; +import com.sun.scenario.animation.shared.GeneralClipInterpolatorShim; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import javafx.animation.KeyFrame; +import javafx.animation.KeyValue; +import javafx.beans.property.IntegerProperty; +import javafx.beans.property.SimpleIntegerProperty; +import javafx.util.Duration; + +import org.junit.Test; + +public class GeneralClipInterpolatorTest { + + @Test + public void testSetKeyFrame() { + final KeyFrame kf1 = new KeyFrame(Duration.ZERO); + final KeyFrame kf2 = new KeyFrame(Duration.millis(1000)); + final KeyFrame kf3 = new KeyFrame(Duration.millis(2000)); + final GeneralClipInterpolatorShim gci = new GeneralClipInterpolatorShim(new KeyFrame[] {kf1, kf2, kf3}, new long[] {0, 6000, 6000}); + + assertSame (gci, gci.setKeyFrames(new KeyFrame[]{kf1, kf2, kf3}, new long[] {0, 6000, 6000})); + assertNotSame(gci, gci.setKeyFrames(new KeyFrame[]{kf1, kf2 }, new long[] {0, 6000 })); + assertNotSame(gci, gci.setKeyFrames(new KeyFrame[]{kf1, kf3}, new long[] {0, 6000})); + assertSame (gci, gci.setKeyFrames(new KeyFrame[]{kf1 }, new long[] {0 })); + assertSame (gci, gci.setKeyFrames(new KeyFrame[]{ kf2, kf3}, new long[] { 6000, 6000})); + assertNotSame(gci, gci.setKeyFrames(new KeyFrame[]{ kf2 }, new long[] { 6000 })); + assertNotSame(gci, gci.setKeyFrames(new KeyFrame[]{ kf3}, new long[] { 6000})); + assertSame (gci, gci.setKeyFrames(new KeyFrame[]{ }, new long[] { })); + } + + @Test + public void test_OneKeyFrameOnly() { + // main purpose of this test is to ensure we do not throw exceptions + final KeyFrame kf1 = new KeyFrame(Duration.ZERO); + final KeyFrame kf2 = new KeyFrame(Duration.ZERO); + + // one key frame + final GeneralClipInterpolatorShim gci1 = new GeneralClipInterpolatorShim (new KeyFrame[] {kf1}, new long[] {0}); + gci1.validate(true); + gci1.validate(true); + gci1.setKeyFrames(new KeyFrame[]{kf2}, new long[] {6000}); + gci1.validate(true); + gci1.setKeyFrames(new KeyFrame[]{}, new long[] {}); + gci1.validate(true); + + // no key frames + final GeneralClipInterpolatorShim gci2 = new GeneralClipInterpolatorShim (new KeyFrame[] {}, new long[] {}); + gci2.validate(true); + gci2.validate(true); + gci2.setKeyFrames(new KeyFrame[]{kf1}, new long[] {0}); + gci2.validate(true); + } + + @Test + public void test_NoKeyValues() { + final KeyFrame start1 = new KeyFrame(Duration.ZERO); + final KeyFrame start2 = new KeyFrame(Duration.ZERO); + final KeyFrame end1 = new KeyFrame(Duration.millis(1000)); + final KeyFrame end2a = new KeyFrame(Duration.millis(2000)); + final KeyFrame end2b = new KeyFrame(Duration.millis(3000)); + + // four key frames + final GeneralClipInterpolatorShim gci1 = new GeneralClipInterpolatorShim (new KeyFrame[] {start1, start2, end1, end2a}, new long[] {0, 0, 6000, 12000}); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(300)); + gci1.interpolate(TickCalculation.fromMillis(1300)); + + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(800)); + gci1.interpolate(TickCalculation.fromMillis(1800)); + + gci1.setKeyFrames(new KeyFrame[]{start1, start2, end1, end2b}, new long[] {0, 0, 6000, 18000}); + gci1.interpolate(TickCalculation.fromMillis(400)); + gci1.interpolate(TickCalculation.fromMillis(1400)); + + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(600)); + gci1.interpolate(TickCalculation.fromMillis(1600)); + + // two key frames + final GeneralClipInterpolatorShim gci2 = new GeneralClipInterpolatorShim (new KeyFrame[] {end1, end2a}, new long[] {6000, 12000}); + gci2.validate(true); + gci2.interpolate(TickCalculation.fromMillis(300)); + gci2.interpolate(TickCalculation.fromMillis(1300)); + + gci2.validate(true); + gci2.interpolate(TickCalculation.fromMillis(800)); + gci2.interpolate(TickCalculation.fromMillis(1800)); + + gci2.setKeyFrames(new KeyFrame[]{end1, end2b}, new long[] {6000, 18000}); + gci2.interpolate(TickCalculation.fromMillis(400)); + gci2.interpolate(TickCalculation.fromMillis(1400)); + + gci2.validate(true); + gci2.interpolate(TickCalculation.fromMillis(600)); + gci2.interpolate(TickCalculation.fromMillis(1600)); + } + + @Test + public void test_ThreeKeyFrames_OneKeyValue() { + final IntegerProperty v = new SimpleIntegerProperty(); + final KeyFrame start1 = new KeyFrame(Duration.ZERO); + final KeyFrame start2 = new KeyFrame(Duration.ZERO, new KeyValue(v, 30)); + final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v, 40)); + final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v, 60)); + final KeyFrame end2 = new KeyFrame(Duration.millis(4000), new KeyValue(v, 70)); + + final GeneralClipInterpolatorShim gci1 = new GeneralClipInterpolatorShim (new KeyFrame[] {start1, start2, mid1, end1}, new long[] {0, 0, 6000, 12000}); + v.set(0); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v.get()); + gci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals(33, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1600)); + assertEquals(52, v.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v.get()); + + // re-validate + v.set(20); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v.get()); + gci1.interpolate(TickCalculation.fromMillis(800)); + assertEquals(38, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1200)); + assertEquals(44, v.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v.get()); + + // set new key frames + gci1.setKeyFrames(new KeyFrame[]{start1, start2, mid1, end2}, new long[] {0, 0, 6000, 24000}); + v.set(0); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v.get()); + gci1.interpolate(TickCalculation.fromMillis(600)); + assertEquals(36, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1300)); + assertEquals(46, v.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v.get()); + + // validate new key frames + v.set(0); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v.get()); + gci1.interpolate(TickCalculation.fromMillis(700)); + assertEquals(37, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1300)); + assertEquals(43, v.get()); + gci1.interpolate(TickCalculation.fromMillis(4000)); + assertEquals(70, v.get()); + } + + @Test + public void test_TwoKeyFrames_OneKeyValue() { + final IntegerProperty v = new SimpleIntegerProperty(); + final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v, 40)); + final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v, 60)); + final KeyFrame end2 = new KeyFrame(Duration.millis(4000), new KeyValue(v, 70)); + + final GeneralClipInterpolatorShim gci1 = new GeneralClipInterpolatorShim (new KeyFrame[] {mid1, end1}, new long[] {6000, 12000}); + v.set(0); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 0, v.get()); + gci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals(12, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1600)); + assertEquals(52, v.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v.get()); + + // re-validate + v.set(20); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(20, v.get()); + gci1.interpolate(TickCalculation.fromMillis(800)); + assertEquals(36, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1200)); + assertEquals(44, v.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v.get()); + + // set new key frames + gci1.setKeyFrames(new KeyFrame[]{mid1, end2}, new long[] {6000, 24000}); + v.set(0); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(20, v.get()); + gci1.interpolate(TickCalculation.fromMillis(600)); + assertEquals(32, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1300)); + assertEquals(46, v.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v.get()); + + // validate new key frames + v.set(0); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 0, v.get()); + gci1.interpolate(TickCalculation.fromMillis(700)); + assertEquals(28, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + gci1.interpolate(TickCalculation.fromMillis(1300)); + assertEquals(43, v.get()); + gci1.interpolate(TickCalculation.fromMillis(4000)); + assertEquals(70, v.get()); + } + + @Test + public void test_ThreeKeyFrames_ThreeKeyValues() { + final IntegerProperty v1 = new SimpleIntegerProperty(); + final IntegerProperty v2 = new SimpleIntegerProperty(); + final IntegerProperty v3 = new SimpleIntegerProperty(); + final IntegerProperty v4 = new SimpleIntegerProperty(); + final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v3, 230), new KeyValue(v4, 330)); + final KeyFrame start2 = new KeyFrame(Duration.ZERO, new KeyValue(v2, 130)); + final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 140), new KeyValue(v3, 240)); + final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 160)); + final KeyFrame end2 = new KeyFrame(Duration.millis(4000), new KeyValue(v1, 70), new KeyValue(v2, 170)); + + final GeneralClipInterpolatorShim gci1 = new GeneralClipInterpolatorShim (new KeyFrame[] {start1, start2, mid1, end1}, new long[] {0, 0, 6000, 12000}); + v1.set( 0); + v2.set(100); + v3.set(200); + v4.set(300); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 0, v1.get()); + assertEquals(130, v2.get()); + assertEquals(230, v3.get()); + assertEquals(300, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals( 12, v1.get()); + assertEquals(133, v2.get()); + assertEquals(233, v3.get()); + assertEquals(300, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + assertEquals(300, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(1600)); + assertEquals( 52, v1.get()); + assertEquals(152, v2.get()); + assertEquals(240, v3.get()); + assertEquals(300, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals( 60, v1.get()); + assertEquals(160, v2.get()); + assertEquals(240, v3.get()); + assertEquals(300, v4.get()); + + // re-validate + v1.set( 20); + v2.set(120); + v3.set(220); + v4.set(320); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(130, v2.get()); + assertEquals(230, v3.get()); + assertEquals(320, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(800)); + assertEquals( 36, v1.get()); + assertEquals(138, v2.get()); + assertEquals(238, v3.get()); + assertEquals(320, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + assertEquals(320, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(1200)); + assertEquals( 44, v1.get()); + assertEquals(144, v2.get()); + assertEquals(240, v3.get()); + assertEquals(320, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals( 60, v1.get()); + assertEquals(160, v2.get()); + assertEquals(240, v3.get()); + assertEquals(320, v4.get()); + + // change key frames + gci1.setKeyFrames(new KeyFrame[]{start1, start2, mid1, end2}, new long[] {0, 0, 6000, 24000}); + v1.set( 0); + v2.set(100); + v3.set(200); + v4.set(300); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(130, v2.get()); + assertEquals(230, v3.get()); + assertEquals(300, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals( 26, v1.get()); + assertEquals(133, v2.get()); + assertEquals(233, v3.get()); + assertEquals(300, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + assertEquals(300, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(1300)); + assertEquals( 46, v1.get()); + assertEquals(146, v2.get()); + assertEquals(240, v3.get()); + assertEquals(300, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals( 60, v1.get()); + assertEquals(160, v2.get()); + assertEquals(240, v3.get()); + assertEquals(300, v4.get()); + + // validate new key frames + v1.set( 20); + v2.set(120); + v3.set(220); + v4.set(320); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(130, v2.get()); + assertEquals(230, v3.get()); + assertEquals(320, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(600)); + assertEquals( 32, v1.get()); + assertEquals(136, v2.get()); + assertEquals(236, v3.get()); + assertEquals(320, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + assertEquals(320, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(1300)); + assertEquals( 43, v1.get()); + assertEquals(143, v2.get()); + assertEquals(240, v3.get()); + assertEquals(320, v4.get()); + gci1.interpolate(TickCalculation.fromMillis(4000)); + assertEquals( 70, v1.get()); + assertEquals(170, v2.get()); + assertEquals(240, v3.get()); + assertEquals(320, v4.get()); + } + + @Test + public void test_TwoKeyFrames_ThreeKeyValues() { + final IntegerProperty v1 = new SimpleIntegerProperty(); + final IntegerProperty v2 = new SimpleIntegerProperty(); + final IntegerProperty v3 = new SimpleIntegerProperty(); + final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 140), new KeyValue(v3, 240)); + final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 160), new KeyValue(v3, 260)); + final KeyFrame end2 = new KeyFrame(Duration.millis(4000), new KeyValue(v1, 70), new KeyValue(v2, 170), new KeyValue(v3, 270)); + + final GeneralClipInterpolatorShim gci1 = new GeneralClipInterpolatorShim (new KeyFrame[] {mid1, end1}, new long[] {6000, 12000}); + v1.set( 0); + v2.set(100); + v3.set(200); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 0, v1.get()); + assertEquals(100, v2.get()); + assertEquals(200, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals( 12, v1.get()); + assertEquals(112, v2.get()); + assertEquals(212, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(1600)); + assertEquals( 52, v1.get()); + assertEquals(152, v2.get()); + assertEquals(252, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals( 60, v1.get()); + assertEquals(160, v2.get()); + assertEquals(260, v3.get()); + + // re-validate + v1.set( 20); + v2.set(120); + v3.set(220); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(120, v2.get()); + assertEquals(220, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(800)); + assertEquals( 36, v1.get()); + assertEquals(136, v2.get()); + assertEquals(236, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(1200)); + assertEquals( 44, v1.get()); + assertEquals(144, v2.get()); + assertEquals(244, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals( 60, v1.get()); + assertEquals(160, v2.get()); + assertEquals(260, v3.get()); + + // change key frames + gci1.setKeyFrames(new KeyFrame[]{mid1, end2}, new long[] {6000, 24000}); + v1.set( 0); + v2.set(100); + v3.set(200); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(120, v2.get()); + assertEquals(220, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals( 26, v1.get()); + assertEquals(126, v2.get()); + assertEquals(226, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(1300)); + assertEquals( 46, v1.get()); + assertEquals(146, v2.get()); + assertEquals(246, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals( 60, v1.get()); + assertEquals(160, v2.get()); + assertEquals(260, v3.get()); + + // validate new key frames + v1.set( 20); + v2.set(120); + v3.set(220); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(120, v2.get()); + assertEquals(220, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(600)); + assertEquals( 32, v1.get()); + assertEquals(132, v2.get()); + assertEquals(232, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(1300)); + assertEquals( 43, v1.get()); + assertEquals(143, v2.get()); + assertEquals(243, v3.get()); + gci1.interpolate(TickCalculation.fromMillis(4000)); + assertEquals( 70, v1.get()); + assertEquals(170, v2.get()); + assertEquals(270, v3.get()); + } + + + @Test + public void test_DuplicateKeyValue() { + final IntegerProperty v1 = new SimpleIntegerProperty(); + final IntegerProperty v2 = new SimpleIntegerProperty(); + final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v1, 30), new KeyValue(v2, 0)); + final KeyFrame start2 = new KeyFrame(Duration.ZERO, new KeyValue(v1, 30), new KeyValue(v1, -30), new KeyValue(v2, 0)); + final KeyFrame mid1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 100)); + final KeyFrame mid2 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v1, -40), new KeyValue(v2, 100)); + final KeyFrame end1 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 0)); + final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v1, -60), new KeyValue(v2, 0)); + + // single value in start, single value in mid, duplicate value in end + final GeneralClipInterpolatorShim gci1 = new GeneralClipInterpolatorShim (new KeyFrame[] {start1, mid1, end2}, new long[] {0, 6000, 12000}); + v1.set(0); + v2.set(0); + gci1.validate(true); + gci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v1.get()); + assertEquals(0, v2.get()); + gci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals(33, v1.get()); + assertEquals(30, v2.get()); + gci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v1.get()); + assertEquals(100, v2.get()); + gci1.interpolate(TickCalculation.fromMillis(1600)); + assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get())); + assertEquals(40, v2.get()); + gci1.interpolate(TickCalculation.fromMillis(2000)); + assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); + assertEquals(0, v2.get()); + + // single value in start, duplicate value in mid, single value in end + final GeneralClipInterpolatorShim gci2 = new GeneralClipInterpolatorShim (new KeyFrame[] {start1, mid2, end1}, new long[] {0, 6000, 12000}); + v1.set(0); + v2.set(0); + gci2.validate(true); + gci2.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v1.get()); + assertEquals(0, v2.get()); + gci2.interpolate(TickCalculation.fromMillis(300)); + assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get())); + assertEquals(30, v2.get()); + gci2.interpolate(TickCalculation.fromMillis(1000)); + assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); + assertEquals(100, v2.get()); + gci2.interpolate(TickCalculation.fromMillis(1600)); + assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (20 == v1.get())); + assertEquals(40, v2.get()); + gci2.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v1.get()); + assertEquals(0, v2.get()); + + // duplicate value in start, single value in mid, single value in end + final GeneralClipInterpolatorShim gci3 = new GeneralClipInterpolatorShim (new KeyFrame[] {start2, mid1, end1}, new long[] {0, 6000, 12000}); + v1.set(0); + v2.set(0); + gci3.validate(true); + gci3.interpolate(TickCalculation.fromMillis(0)); + assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); + assertEquals(0, v2.get()); + gci3.interpolate(TickCalculation.fromMillis(300)); + assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (-9 == v1.get())); + assertEquals(30, v2.get()); + gci3.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v1.get()); + assertEquals(100, v2.get()); + gci3.interpolate(TickCalculation.fromMillis(1600)); + assertEquals(52, v1.get()); + assertEquals(40, v2.get()); + gci3.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v1.get()); + assertEquals(0, v2.get()); + + // duplicate value in start, duplicate value in mid, single value in end + final GeneralClipInterpolatorShim gci4 = new GeneralClipInterpolatorShim (new KeyFrame[] {start2, mid2, end1}, new long[] {0, 6000, 12000}); + v1.set(0); + v2.set(0); + gci4.validate(true); + gci4.interpolate(TickCalculation.fromMillis(0)); + assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); + assertEquals(0, v2.get()); + gci4.interpolate(TickCalculation.fromMillis(300)); + assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get()) || (-9 == v1.get()) || (-33 == v1.get())); + assertEquals(30, v2.get()); + gci4.interpolate(TickCalculation.fromMillis(1000)); + assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); + assertEquals(100, v2.get()); + gci4.interpolate(TickCalculation.fromMillis(1600)); + assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (20 == v1.get())); + assertEquals(40, v2.get()); + gci4.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v1.get()); + assertEquals(0, v2.get()); + + // duplicate value in start, single value in mid, duplicate value in end + final GeneralClipInterpolatorShim gci5 = new GeneralClipInterpolatorShim (new KeyFrame[] {start2, mid1, end2}, new long[] {0, 6000, 12000}); + v1.set(0); + v2.set(0); + gci5.validate(true); + gci5.interpolate(TickCalculation.fromMillis(0)); + assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); + assertEquals(0, v2.get()); + gci5.interpolate(TickCalculation.fromMillis(300)); + assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (-9 == v1.get())); + assertEquals(30, v2.get()); + gci5.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v1.get()); + assertEquals(100, v2.get()); + gci5.interpolate(TickCalculation.fromMillis(1600)); + assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get())); + assertEquals(40, v2.get()); + gci5.interpolate(TickCalculation.fromMillis(2000)); + assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); + assertEquals(0, v2.get()); + + // single value in start, duplicate value in mid, duplicate value in end + final GeneralClipInterpolatorShim gci6 = new GeneralClipInterpolatorShim (new KeyFrame[] {start1, mid2, end2}, new long[] {0, 6000, 12000}); + v1.set(0); + v2.set(0); + gci6.validate(true); + gci6.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v1.get()); + assertEquals(0, v2.get()); + gci6.interpolate(TickCalculation.fromMillis(300)); + assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get())); + assertEquals(30, v2.get()); + gci6.interpolate(TickCalculation.fromMillis(1000)); + assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); + assertEquals(100, v2.get()); + gci6.interpolate(TickCalculation.fromMillis(1600)); + assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get()) || (20 == v1.get()) || (-52 == v1.get())); + assertEquals(40, v2.get()); + gci6.interpolate(TickCalculation.fromMillis(2000)); + assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); + assertEquals(0, v2.get()); + + // duplicate value in start, duplicate value in mid, duplicate value in end + final GeneralClipInterpolatorShim gci7 = new GeneralClipInterpolatorShim (new KeyFrame[] {start2, mid2, end2}, new long[] {0, 6000, 12000}); + v1.set(0); + v2.set(0); + gci7.validate(true); + gci7.interpolate(TickCalculation.fromMillis(0)); + assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); + assertEquals(0, v2.get()); + gci7.interpolate(TickCalculation.fromMillis(300)); + assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get()) || (-9 == v1.get()) || (-33 == v1.get())); + assertEquals(30, v2.get()); + gci7.interpolate(TickCalculation.fromMillis(1000)); + assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); + assertEquals(100, v2.get()); + gci7.interpolate(TickCalculation.fromMillis(1600)); + assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get()) || (20 == v1.get()) || (-52 == v1.get())); + assertEquals(40, v2.get()); + gci7.interpolate(TickCalculation.fromMillis(2000)); + assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); + assertEquals(0, v2.get()); + + // no value in start, single value in mid, duplicate value in end + final GeneralClipInterpolatorShim gci8 = new GeneralClipInterpolatorShim (new KeyFrame[] {mid1, end2}, new long[] {6000, 12000}); + v1.set(0); + v2.set(0); + gci8.validate(true); + gci8.interpolate(TickCalculation.fromMillis(0)); + assertEquals(0, v1.get()); + assertEquals(0, v2.get()); + gci8.interpolate(TickCalculation.fromMillis(400)); + assertEquals(16, v1.get()); + assertEquals(40, v2.get()); + gci8.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v1.get()); + assertEquals(100, v2.get()); + gci8.interpolate(TickCalculation.fromMillis(1600)); + assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get())); + assertEquals(40, v2.get()); + gci8.interpolate(TickCalculation.fromMillis(2000)); + assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); + assertEquals(0, v2.get()); + + // no value in start, duplicate value in mid, single value in end + final GeneralClipInterpolatorShim gci9 = new GeneralClipInterpolatorShim (new KeyFrame[] {mid2, end1}, new long[] {6000, 12000}); + v1.set(0); + v2.set(0); + gci9.validate(true); + gci9.interpolate(TickCalculation.fromMillis(0)); + assertEquals(0, v1.get()); + assertEquals(0, v2.get()); + gci9.interpolate(TickCalculation.fromMillis(400)); + assertTrue("v1.get(): " + v1.get(), (16 == v1.get()) || (-16 == v1.get())); + assertEquals(40, v2.get()); + gci9.interpolate(TickCalculation.fromMillis(1000)); + assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); + assertEquals(100, v2.get()); + gci9.interpolate(TickCalculation.fromMillis(1600)); + assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (20 == v1.get())); + assertEquals(40, v2.get()); + gci9.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v1.get()); + assertEquals(0, v2.get()); + + // no value in start, duplicate value in mid, duplicate value in end + final GeneralClipInterpolatorShim gci10 = new GeneralClipInterpolatorShim (new KeyFrame[] {mid2, end2}, new long[] {6000, 12000}); + v1.set(0); + v2.set(0); + gci10.validate(true); + gci10.interpolate(TickCalculation.fromMillis(0)); + assertEquals(0, v1.get()); + assertEquals(0, v2.get()); + gci10.interpolate(TickCalculation.fromMillis(400)); + assertTrue("v1.get(): " + v1.get(), (16 == v1.get()) || (-16 == v1.get())); + assertEquals(40, v2.get()); + gci10.interpolate(TickCalculation.fromMillis(1000)); + assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); + assertEquals(100, v2.get()); + gci10.interpolate(TickCalculation.fromMillis(1600)); + assertTrue("v1.get(): " + v1.get(), (52 == v1.get()) || (-20 == v1.get()) || (20 == v1.get()) || (-52 == v1.get())); + assertEquals(40, v2.get()); + gci10.interpolate(TickCalculation.fromMillis(2000)); + assertTrue("v1.get(): " + v1.get(), (60 == v1.get()) || (-60 == v1.get())); + assertEquals(0, v2.get()); + } +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/shared/InfiniteClipEnvelopeTest.java 2015-09-11 21:25:10.485286472 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,494 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario.animation.shared; - - -import com.sun.javafx.tk.Toolkit; -import javafx.animation.Animation; -import javafx.animation.Animation.Status; -import javafx.animation.AnimationMock; -import javafx.animation.AnimationMock.Command; -import javafx.util.Duration; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class InfiniteClipEnvelopeTest { - - private final long CYCLE_TICKS = Math.round(6.0 * AnimationMock.DEFAULT_DURATION.toMillis()); - - private ClipEnvelope clip; - private AnimationMock animation; - - @Before - public void setUp() { - animation = new AnimationMock(Toolkit.getToolkit().getMasterTimer(), AnimationMock.DEFAULT_DURATION, AnimationMock.DEFAULT_RATE, Animation.INDEFINITE, AnimationMock.DEFAULT_AUTOREVERSE); - clip = new InfiniteClipEnvelope(animation); - } - - @Test - public void testSetValues() { - ClipEnvelope c; - - // Setting cycleCount to 2 - animation.setCycleCount(2); - animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); - c = clip.setCycleCount(2); - assertNotSame(clip, c); - assertTrue(c instanceof FiniteClipEnvelope); - - // Setting cycleDuration to INDEFINITE - animation.setCycleCount(Animation.INDEFINITE); - animation.mockCycleDuration(Duration.INDEFINITE); - c = clip.setCycleDuration(Duration.INDEFINITE); - assertNotSame(clip, c); - assertTrue(c instanceof SingleLoopClipEnvelope); - - } - - @Test - public void testJump() { - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - clip.jumpTo(0); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - clip.jumpTo(6 * 1000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - - clip.jumpTo(-1); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - clip.jumpTo(6 * 1000 + 1); - animation.check(Command.JUMP, 1, CYCLE_TICKS); - } - - @Test - public void testTimePulseForward() { - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.timePulse(1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 500); - animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 700); - animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 + 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 4300); - animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - } - - @Test - public void testTimePulseBackward() { - clip.setRate(-1.0); - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.timePulse(1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 500); - animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 700); - animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 + 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 4300); - animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - } - - @Test - public void testTimePulseForwardAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.setAutoReverse(true); - clip.start(); - - clip.timePulse(1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 + 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse one cycle ahead - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse two cycles ahead - clip.timePulse(6 * 4300); - animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // another pulse one cycle ahead - clip.timePulse(6 * 5400); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // another pulse two cycles ahead - clip.timePulse(6 * 7100); - animation.check(Command.PLAY, 6 * 900, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - } - - @Test - public void testTimePulseBackwardAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.setAutoReverse(true); - clip.setRate(-1); - clip.start(); - - clip.timePulse(1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 + 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse one cycle ahead - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse two cycles ahead - clip.timePulse(6 * 4300); - animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // another pulse one cycle ahead - clip.timePulse(6 * 5400); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // another pulse two cycles ahead - clip.timePulse(6 * 7100); - animation.check(Command.PLAY, 6 * 900, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseForward() { - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - clip.timePulse(6 * 800); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 50); - animation.check(Command.JUMP, 6 * 50, CYCLE_TICKS); - - clip.timePulse(6 * 1850); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 0); - animation.check(Command.JUMP, 6 * 0, CYCLE_TICKS); - - clip.timePulse(6 * 2000); - animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 1000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseBackward() { - animation.mockStatus(Status.RUNNING); - clip.setRate(-1); - clip.start(); - - // jump forward - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse in next cycle - clip.timePulse(6 * 700); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump backward - clip.jumpTo(6 * 900); - animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // pulse one cycle ahead - clip.timePulse(6 * 1750); - animation.check(Command.PLAY, 6 * 850, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to same position at end - clip.jumpTo(6 * 1000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // normal pulse - clip.timePulse(6 * 2000); - animation.check(Command.PLAY, 6 * 750, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to start - clip.jumpTo(0); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // normal pulse - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseForwardAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.setAutoReverse(true); - clip.start(); - - // jump forward - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - // pulse in next cycle - clip.timePulse(6 * 900); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump backward - clip.jumpTo(6 * 900); - animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); - - // pulse one cycle ahead - clip.timePulse(6 * 1850); - animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to start - clip.jumpTo(6 * 0); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - // normal pulse - clip.timePulse(6 * 2000); - animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to end - clip.jumpTo(6 * 1000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - - // normal pulse - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseBackwardAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.setAutoReverse(true); - clip.setRate(-1); - clip.start(); - - // jump forward - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - // pulse in next cycle - clip.timePulse(6 * 700); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump backward - clip.jumpTo(6 * 100); - animation.check(Command.JUMP, 6 * 100, CYCLE_TICKS); - - // pulse one cycle ahead - clip.timePulse(6 * 1800 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - clip.timePulse(6 * 1800 + 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to end - clip.jumpTo(6 * 1000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - - // normal pulse - clip.timePulse(6 * 2000); - animation.check(Command.PLAY, 6 * 800 + 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - // jump to start - clip.jumpTo(0); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - // normal pulse - clip.timePulse(6 * 2200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - } - - @Test - public void testRate() { - animation.mockStatus(Status.RUNNING); - clip.setRate(0.5); - clip.start(); - - clip.timePulse(6 * 200); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - - clip.setRate(3.0); - clip.timePulse(6 * 300); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - - clip.setRate(2.0); - clip.timePulse(6 * 500); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - - clip.setRate(-0.5); - clip.timePulse(6 * 1100); - animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); - - clip.setRate(-3.0); - clip.timePulse(6 * 1200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - - clip.setRate(0.5); - clip.timePulse(6 * 2100); - animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); - - clip.setRate(1.5); - clip.timePulse(6 * 2600); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - - clip.setRate(-2.0); - clip.timePulse(6 * 3000); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - } - - @Test - public void testRateAutoReverse() { - animation.mockStatus(Status.RUNNING); - clip.setAutoReverse(true); - clip.setRate(0.5); - clip.start(); - - clip.timePulse(6 * 200); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - - clip.setRate(3.0); - clip.timePulse(6 * 300); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - - clip.setRate(2.0); - clip.timePulse(6 * 500); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - - clip.setRate(-0.5); - clip.timePulse(6 * 1100); - animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); - - clip.setRate(-3.0); - clip.timePulse(6 * 1200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - - clip.setRate(0.5); - clip.timePulse(6 * 2100); - animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); - - clip.setRate(1.5); - clip.timePulse(6 * 2600); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - - clip.setRate(-2.0); - clip.timePulse(6 * 3000); - animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/shared/InfiniteClipEnvelopeTest.java 2015-09-11 21:25:10.345286474 -0400 @@ -0,0 +1,498 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.animation.shared; + + +import com.sun.javafx.tk.Toolkit; +import com.sun.scenario.animation.shared.ClipEnvelope; +import com.sun.scenario.animation.shared.FiniteClipEnvelope; +import com.sun.scenario.animation.shared.InfiniteClipEnvelopeShim; +import com.sun.scenario.animation.shared.SingleLoopClipEnvelope; +import javafx.animation.Animation; +import javafx.animation.Animation.Status; +import test.javafx.animation.AnimationMock; +import test.javafx.animation.AnimationMock.Command; +import javafx.util.Duration; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class InfiniteClipEnvelopeTest { + + private final long CYCLE_TICKS = Math.round(6.0 * AnimationMock.DEFAULT_DURATION.toMillis()); + + private ClipEnvelope clip; + private AnimationMock animation; + + @Before + public void setUp() { + animation = new AnimationMock(Toolkit.getToolkit().getMasterTimer(), AnimationMock.DEFAULT_DURATION, AnimationMock.DEFAULT_RATE, Animation.INDEFINITE, AnimationMock.DEFAULT_AUTOREVERSE); + clip = new InfiniteClipEnvelopeShim(animation); + } + + @Test + public void testSetValues() { + ClipEnvelope c; + + // Setting cycleCount to 2 + animation.setCycleCount(2); + animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); + c = clip.setCycleCount(2); + assertNotSame(clip, c); + assertTrue(c instanceof FiniteClipEnvelope); + + // Setting cycleDuration to INDEFINITE + animation.setCycleCount(Animation.INDEFINITE); + animation.mockCycleDuration(Duration.INDEFINITE); + c = clip.setCycleDuration(Duration.INDEFINITE); + assertNotSame(clip, c); + assertTrue(c instanceof SingleLoopClipEnvelope); + + } + + @Test + public void testJump() { + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + clip.jumpTo(0); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + clip.jumpTo(6 * 1000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + + clip.jumpTo(-1); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + clip.jumpTo(6 * 1000 + 1); + animation.check(Command.JUMP, 1, CYCLE_TICKS); + } + + @Test + public void testTimePulseForward() { + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.timePulse(1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 500); + animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 700); + animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 + 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 4300); + animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + } + + @Test + public void testTimePulseBackward() { + clip.setRate(-1.0); + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.timePulse(1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 500); + animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 700); + animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 + 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 4300); + animation.check(Command.PLAY, 6 * 700, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + } + + @Test + public void testTimePulseForwardAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.setAutoReverse(true); + clip.start(); + + clip.timePulse(1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 + 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse one cycle ahead + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse two cycles ahead + clip.timePulse(6 * 4300); + animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // another pulse one cycle ahead + clip.timePulse(6 * 5400); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // another pulse two cycles ahead + clip.timePulse(6 * 7100); + animation.check(Command.PLAY, 6 * 900, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + } + + @Test + public void testTimePulseBackwardAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.setAutoReverse(true); + clip.setRate(-1); + clip.start(); + + clip.timePulse(1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 + 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse one cycle ahead + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse two cycles ahead + clip.timePulse(6 * 4300); + animation.check(Command.PLAY, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // another pulse one cycle ahead + clip.timePulse(6 * 5400); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // another pulse two cycles ahead + clip.timePulse(6 * 7100); + animation.check(Command.PLAY, 6 * 900, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseForward() { + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + clip.timePulse(6 * 800); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 50); + animation.check(Command.JUMP, 6 * 50, CYCLE_TICKS); + + clip.timePulse(6 * 1850); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 0); + animation.check(Command.JUMP, 6 * 0, CYCLE_TICKS); + + clip.timePulse(6 * 2000); + animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 1000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseBackward() { + animation.mockStatus(Status.RUNNING); + clip.setRate(-1); + clip.start(); + + // jump forward + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse in next cycle + clip.timePulse(6 * 700); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump backward + clip.jumpTo(6 * 900); + animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // pulse one cycle ahead + clip.timePulse(6 * 1750); + animation.check(Command.PLAY, 6 * 850, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to same position at end + clip.jumpTo(6 * 1000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // normal pulse + clip.timePulse(6 * 2000); + animation.check(Command.PLAY, 6 * 750, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to start + clip.jumpTo(0); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // normal pulse + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseForwardAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.setAutoReverse(true); + clip.start(); + + // jump forward + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + // pulse in next cycle + clip.timePulse(6 * 900); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump backward + clip.jumpTo(6 * 900); + animation.check(Command.JUMP, 6 * 900, CYCLE_TICKS); + + // pulse one cycle ahead + clip.timePulse(6 * 1850); + animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to start + clip.jumpTo(6 * 0); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + // normal pulse + clip.timePulse(6 * 2000); + animation.check(Command.PLAY, 6 * 150, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to end + clip.jumpTo(6 * 1000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + + // normal pulse + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseBackwardAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.setAutoReverse(true); + clip.setRate(-1); + clip.start(); + + // jump forward + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + // pulse in next cycle + clip.timePulse(6 * 700); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump backward + clip.jumpTo(6 * 100); + animation.check(Command.JUMP, 6 * 100, CYCLE_TICKS); + + // pulse one cycle ahead + clip.timePulse(6 * 1800 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + clip.timePulse(6 * 1800 + 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to end + clip.jumpTo(6 * 1000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + + // normal pulse + clip.timePulse(6 * 2000); + animation.check(Command.PLAY, 6 * 800 + 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + // jump to start + clip.jumpTo(0); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + // normal pulse + clip.timePulse(6 * 2200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + } + + @Test + public void testRate() { + animation.mockStatus(Status.RUNNING); + clip.setRate(0.5); + clip.start(); + + clip.timePulse(6 * 200); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + + clip.setRate(3.0); + clip.timePulse(6 * 300); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + + clip.setRate(2.0); + clip.timePulse(6 * 500); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + + clip.setRate(-0.5); + clip.timePulse(6 * 1100); + animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); + + clip.setRate(-3.0); + clip.timePulse(6 * 1200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + + clip.setRate(0.5); + clip.timePulse(6 * 2100); + animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); + + clip.setRate(1.5); + clip.timePulse(6 * 2600); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + + clip.setRate(-2.0); + clip.timePulse(6 * 3000); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + } + + @Test + public void testRateAutoReverse() { + animation.mockStatus(Status.RUNNING); + clip.setAutoReverse(true); + clip.setRate(0.5); + clip.start(); + + clip.timePulse(6 * 200); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + + clip.setRate(3.0); + clip.timePulse(6 * 300); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + + clip.setRate(2.0); + clip.timePulse(6 * 500); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + + clip.setRate(-0.5); + clip.timePulse(6 * 1100); + animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); + + clip.setRate(-3.0); + clip.timePulse(6 * 1200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + + clip.setRate(0.5); + clip.timePulse(6 * 2100); + animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); + + clip.setRate(1.5); + clip.timePulse(6 * 2600); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + + clip.setRate(-2.0); + clip.timePulse(6 * 3000); + animation.check(Command.PLAY, 6 * 600, CYCLE_TICKS); + } +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/shared/SimpleClipInterpolatorTest.java 2015-09-11 21:25:11.273286463 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,424 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario.animation.shared; - -import com.sun.javafx.animation.TickCalculation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import javafx.animation.KeyFrame; -import javafx.animation.KeyValue; -import javafx.beans.property.IntegerProperty; -import javafx.beans.property.SimpleIntegerProperty; -import javafx.util.Duration; - -import org.junit.Test; - -public class SimpleClipInterpolatorTest { - - @Test - public void testSetKeyFrame() { - final KeyFrame kf1 = new KeyFrame(Duration.ZERO); - final KeyFrame kf2 = new KeyFrame(Duration.millis(1000)); - final KeyFrame kf3 = new KeyFrame(Duration.millis(2000)); - final SimpleClipInterpolator sci = new SimpleClipInterpolator(kf1, kf2, 6000); - - assertNotSame(sci, sci.setKeyFrames(new KeyFrame[]{kf1, kf2, kf3}, new long[] {0, 6000, 12000})); - assertSame (sci, sci.setKeyFrames(new KeyFrame[]{kf1, kf2 }, new long[] {0, 6000, })); - assertSame (sci, sci.setKeyFrames(new KeyFrame[]{kf1, kf3}, new long[] {0, 12000})); - assertNotSame(sci, sci.setKeyFrames(new KeyFrame[]{kf1 }, new long[] {0, })); - assertNotSame(sci, sci.setKeyFrames(new KeyFrame[]{ kf2, kf3}, new long[] { 6000, 12000})); - assertSame (sci, sci.setKeyFrames(new KeyFrame[]{ kf2 }, new long[] { 6000 })); - assertSame (sci, sci.setKeyFrames(new KeyFrame[]{ kf3}, new long[] { 12000})); - assertNotSame(sci, sci.setKeyFrames(new KeyFrame[]{ }, new long[] { })); - } - - @Test - public void test_NoKeyValues() { - final KeyFrame start = new KeyFrame(Duration.ZERO); - final KeyFrame end1 = new KeyFrame(Duration.millis(1000)); - final KeyFrame end2 = new KeyFrame(Duration.millis(2000)); - - // two key frames - final SimpleClipInterpolator sci1 = new SimpleClipInterpolator (start, end1, 6000); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(300)); - - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(800)); - - sci1.setKeyFrames(new KeyFrame[]{start, end2}, new long[] {0, 12000}); - sci1.interpolate(TickCalculation.fromMillis(400)); - - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(600)); - - // one key frame - final SimpleClipInterpolator sci2 = new SimpleClipInterpolator (end1, 6000); - sci2.validate(true); - sci2.interpolate(TickCalculation.fromMillis(300)); - - sci2.validate(true); - sci2.interpolate(TickCalculation.fromMillis(800)); - - sci2.setKeyFrames(new KeyFrame[]{end2}, new long[] {12000}); - sci2.interpolate(TickCalculation.fromMillis(400)); - - sci2.validate(true); - sci2.interpolate(TickCalculation.fromMillis(600)); - } - - @Test - public void test_TwoKeyFrames_OneKeyValue() { - final IntegerProperty v = new SimpleIntegerProperty(); - final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v, 30)); - final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v, 40)); - final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v, 60)); - - final SimpleClipInterpolator sci1 = new SimpleClipInterpolator (start1, end1, 6000); - v.set(0); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v.get()); - sci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals(33, v.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - - // re-validate - v.set(20); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v.get()); - sci1.interpolate(TickCalculation.fromMillis(800)); - assertEquals(38, v.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - - // set new key frames - sci1.setKeyFrames(new KeyFrame[]{start1, end2}, new long[] {0, 12000}); - v.set(0); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v.get()); - sci1.interpolate(TickCalculation.fromMillis(400)); - assertEquals(34, v.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - - // validate new key frames - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v.get()); - sci1.interpolate(TickCalculation.fromMillis(600)); - assertEquals(39, v.get()); - sci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v.get()); - - } - - @Test - public void test_OneKeyFrame_OneKeyValue() { - final IntegerProperty v = new SimpleIntegerProperty(); - final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v, 40)); - final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v, 60)); - - final SimpleClipInterpolator sci3 = new SimpleClipInterpolator (end1, 6000); - v.set(0); - sci3.validate(true); - sci3.interpolate(TickCalculation.fromMillis(0)); - assertEquals(0, v.get()); - sci3.interpolate(TickCalculation.fromMillis(300)); - assertEquals(12, v.get()); - sci3.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - - // re-validate - v.set(20); - sci3.validate(true); - sci3.interpolate(TickCalculation.fromMillis(0)); - assertEquals(20, v.get()); - sci3.interpolate(TickCalculation.fromMillis(800)); - assertEquals(36, v.get()); - sci3.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - - // set new key frames - sci3.setKeyFrames(new KeyFrame[]{end2}, new long[] {12000}); - v.set(0); - sci3.interpolate(TickCalculation.fromMillis(0)); - assertEquals(20, v.get()); - sci3.interpolate(TickCalculation.fromMillis(400)); - assertEquals(28, v.get()); - sci3.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v.get()); - - // validate new key frames - v.set(20); - sci3.validate(true); - sci3.interpolate(TickCalculation.fromMillis(0)); - assertEquals(20, v.get()); - sci3.interpolate(TickCalculation.fromMillis(600)); - assertEquals(32, v.get()); - sci3.interpolate(TickCalculation.fromMillis(2000)); - assertEquals(60, v.get()); - } - - @Test - public void test_TwoKeyFrames_ThreeKeyValues() { - final IntegerProperty v1 = new SimpleIntegerProperty(); - final IntegerProperty v2 = new SimpleIntegerProperty(); - final IntegerProperty v3 = new SimpleIntegerProperty(); - final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v2, 130), new KeyValue(v3, 230)); - final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 140)); - final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 160)); - - final SimpleClipInterpolator sci1 = new SimpleClipInterpolator (start1, end1, 6000); - v1.set( 0); - v2.set(100); - v3.set(200); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 0, v1.get()); - assertEquals(130, v2.get()); - assertEquals(200, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals( 12, v1.get()); - assertEquals(133, v2.get()); - assertEquals(200, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(200, v3.get()); - - // re-validate - v1.set( 20); - v2.set(120); - v3.set(220); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(130, v2.get()); - assertEquals(220, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(800)); - assertEquals( 36, v1.get()); - assertEquals(138, v2.get()); - assertEquals(220, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(220, v3.get()); - - // change key frames - sci1.setKeyFrames(new KeyFrame[]{start1, end2}, new long[] {0, 12000}); - v1.set( 0); - v2.set(100); - v3.set(200); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(130, v2.get()); - assertEquals(200, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals( 26, v1.get()); - assertEquals(133, v2.get()); - assertEquals(200, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(200, v3.get()); - - // validate new key frames - v1.set( 20); - v2.set(120); - v3.set(220); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(130, v2.get()); - assertEquals(220, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(600)); - assertEquals( 32, v1.get()); - assertEquals(139, v2.get()); - assertEquals(220, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals( 60, v1.get()); - assertEquals(160, v2.get()); - assertEquals(220, v3.get()); - - } - - @Test - public void test_OneKeyFrames_ThreeKeyValues() { - final IntegerProperty v1 = new SimpleIntegerProperty(); - final IntegerProperty v2 = new SimpleIntegerProperty(); - final IntegerProperty v3 = new SimpleIntegerProperty(); - final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 140), new KeyValue(v3, 240)); - final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 160), new KeyValue(v3, 260)); - - final SimpleClipInterpolator sci1 = new SimpleClipInterpolator (end1, 6000); - v1.set( 0); - v2.set(100); - v3.set(200); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 0, v1.get()); - assertEquals(100, v2.get()); - assertEquals(200, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals( 12, v1.get()); - assertEquals(112, v2.get()); - assertEquals(212, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - - // re-validate - v1.set( 20); - v2.set(120); - v3.set(220); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(120, v2.get()); - assertEquals(220, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(800)); - assertEquals( 36, v1.get()); - assertEquals(136, v2.get()); - assertEquals(236, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - - // change key frames - sci1.setKeyFrames(new KeyFrame[]{end2}, new long[] {12000}); - v1.set( 0); - v2.set(100); - v3.set(200); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(120, v2.get()); - assertEquals(220, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(300)); - assertEquals( 26, v1.get()); - assertEquals(126, v2.get()); - assertEquals(226, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertEquals( 40, v1.get()); - assertEquals(140, v2.get()); - assertEquals(240, v3.get()); - - // validate new key frames - v1.set( 20); - v2.set(120); - v3.set(220); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals( 20, v1.get()); - assertEquals(120, v2.get()); - assertEquals(220, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(600)); - assertEquals( 32, v1.get()); - assertEquals(132, v2.get()); - assertEquals(232, v3.get()); - sci1.interpolate(TickCalculation.fromMillis(2000)); - assertEquals( 60, v1.get()); - assertEquals(160, v2.get()); - assertEquals(260, v3.get()); - } - - @Test - public void test_DuplicateKeyValue() { - final IntegerProperty v1 = new SimpleIntegerProperty(); - final IntegerProperty v2 = new SimpleIntegerProperty(); - final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v1, 30), new KeyValue(v2, 0)); - final KeyFrame start2 = new KeyFrame(Duration.ZERO, new KeyValue(v1, 30), new KeyValue(v1, -30), new KeyValue(v2, 0)); - final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 100)); - final KeyFrame end2 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v1, -40), new KeyValue(v2, 100)); - - // single value in start, duplicate value in end - final SimpleClipInterpolator sci1 = new SimpleClipInterpolator (start1, end2, 6000); - v1.set(0); - v2.set(0); - sci1.validate(true); - sci1.interpolate(TickCalculation.fromMillis(0)); - assertEquals(30, v1.get()); - assertEquals(0, v2.get()); - sci1.interpolate(TickCalculation.fromMillis(300)); - assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get())); - assertEquals(30, v2.get()); - sci1.interpolate(TickCalculation.fromMillis(1000)); - assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); - assertEquals(100, v2.get()); - - // duplicate value in start, single value in end - final SimpleClipInterpolator sci2 = new SimpleClipInterpolator (start2, end1, 6000); - v1.set(0); - v2.set(0); - sci2.validate(true); - sci2.interpolate(TickCalculation.fromMillis(0)); - assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); - assertEquals(0, v2.get()); - sci2.interpolate(TickCalculation.fromMillis(300)); - assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (-9 == v1.get())); - assertEquals(30, v2.get()); - sci2.interpolate(TickCalculation.fromMillis(1000)); - assertEquals(40, v1.get()); - assertEquals(100, v2.get()); - - // duplicate value in start, duplicate value in end - final SimpleClipInterpolator sci3 = new SimpleClipInterpolator (start2, end2, 6000); - v1.set(0); - v2.set(0); - sci3.validate(true); - sci3.interpolate(TickCalculation.fromMillis(0)); - assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); - assertEquals(0, v2.get()); - sci3.interpolate(TickCalculation.fromMillis(300)); - assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get()) || (-9 == v1.get()) || (-33 == v1.get())); - assertEquals(30, v2.get()); - sci3.interpolate(TickCalculation.fromMillis(1000)); - assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); - assertEquals(100, v2.get()); - - // no value in start, duplicate value in end - final SimpleClipInterpolator sci4 = new SimpleClipInterpolator (end2, 6000); - v1.set(0); - v2.set(0); - sci4.validate(true); - sci4.interpolate(TickCalculation.fromMillis(0)); - assertEquals(0, v1.get()); - assertEquals(0, v2.get()); - sci4.interpolate(TickCalculation.fromMillis(400)); - assertTrue("v1.get(): " + v1.get(), (16 == v1.get()) || (-16 == v1.get())); - assertEquals(40, v2.get()); - sci4.interpolate(TickCalculation.fromMillis(1000)); - assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); - assertEquals(100, v2.get()); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/shared/SimpleClipInterpolatorTest.java 2015-09-11 21:25:11.061286465 -0400 @@ -0,0 +1,425 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.animation.shared; + +import com.sun.javafx.animation.TickCalculation; +import com.sun.scenario.animation.shared.SimpleClipInterpolatorShim; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import javafx.animation.KeyFrame; +import javafx.animation.KeyValue; +import javafx.beans.property.IntegerProperty; +import javafx.beans.property.SimpleIntegerProperty; +import javafx.util.Duration; + +import org.junit.Test; + +public class SimpleClipInterpolatorTest { + + @Test + public void testSetKeyFrame() { + final KeyFrame kf1 = new KeyFrame(Duration.ZERO); + final KeyFrame kf2 = new KeyFrame(Duration.millis(1000)); + final KeyFrame kf3 = new KeyFrame(Duration.millis(2000)); + final SimpleClipInterpolatorShim sci = new SimpleClipInterpolatorShim(kf1, kf2, 6000); + + assertNotSame(sci, sci.setKeyFrames(new KeyFrame[]{kf1, kf2, kf3}, new long[] {0, 6000, 12000})); + assertSame (sci, sci.setKeyFrames(new KeyFrame[]{kf1, kf2 }, new long[] {0, 6000, })); + assertSame (sci, sci.setKeyFrames(new KeyFrame[]{kf1, kf3}, new long[] {0, 12000})); + assertNotSame(sci, sci.setKeyFrames(new KeyFrame[]{kf1 }, new long[] {0, })); + assertNotSame(sci, sci.setKeyFrames(new KeyFrame[]{ kf2, kf3}, new long[] { 6000, 12000})); + assertSame (sci, sci.setKeyFrames(new KeyFrame[]{ kf2 }, new long[] { 6000 })); + assertSame (sci, sci.setKeyFrames(new KeyFrame[]{ kf3}, new long[] { 12000})); + assertNotSame(sci, sci.setKeyFrames(new KeyFrame[]{ }, new long[] { })); + } + + @Test + public void test_NoKeyValues() { + final KeyFrame start = new KeyFrame(Duration.ZERO); + final KeyFrame end1 = new KeyFrame(Duration.millis(1000)); + final KeyFrame end2 = new KeyFrame(Duration.millis(2000)); + + // two key frames + final SimpleClipInterpolatorShim sci1 = new SimpleClipInterpolatorShim(start, end1, 6000); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(300)); + + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(800)); + + sci1.setKeyFrames(new KeyFrame[]{start, end2}, new long[] {0, 12000}); + sci1.interpolate(TickCalculation.fromMillis(400)); + + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(600)); + + // one key frame + final SimpleClipInterpolatorShim sci2 = new SimpleClipInterpolatorShim(end1, 6000); + sci2.validate(true); + sci2.interpolate(TickCalculation.fromMillis(300)); + + sci2.validate(true); + sci2.interpolate(TickCalculation.fromMillis(800)); + + sci2.setKeyFrames(new KeyFrame[]{end2}, new long[] {12000}); + sci2.interpolate(TickCalculation.fromMillis(400)); + + sci2.validate(true); + sci2.interpolate(TickCalculation.fromMillis(600)); + } + + @Test + public void test_TwoKeyFrames_OneKeyValue() { + final IntegerProperty v = new SimpleIntegerProperty(); + final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v, 30)); + final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v, 40)); + final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v, 60)); + + final SimpleClipInterpolatorShim sci1 = new SimpleClipInterpolatorShim(start1, end1, 6000); + v.set(0); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v.get()); + sci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals(33, v.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + + // re-validate + v.set(20); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v.get()); + sci1.interpolate(TickCalculation.fromMillis(800)); + assertEquals(38, v.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + + // set new key frames + sci1.setKeyFrames(new KeyFrame[]{start1, end2}, new long[] {0, 12000}); + v.set(0); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v.get()); + sci1.interpolate(TickCalculation.fromMillis(400)); + assertEquals(34, v.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + + // validate new key frames + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v.get()); + sci1.interpolate(TickCalculation.fromMillis(600)); + assertEquals(39, v.get()); + sci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v.get()); + + } + + @Test + public void test_OneKeyFrame_OneKeyValue() { + final IntegerProperty v = new SimpleIntegerProperty(); + final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v, 40)); + final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v, 60)); + + final SimpleClipInterpolatorShim sci3 = new SimpleClipInterpolatorShim(end1, 6000); + v.set(0); + sci3.validate(true); + sci3.interpolate(TickCalculation.fromMillis(0)); + assertEquals(0, v.get()); + sci3.interpolate(TickCalculation.fromMillis(300)); + assertEquals(12, v.get()); + sci3.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + + // re-validate + v.set(20); + sci3.validate(true); + sci3.interpolate(TickCalculation.fromMillis(0)); + assertEquals(20, v.get()); + sci3.interpolate(TickCalculation.fromMillis(800)); + assertEquals(36, v.get()); + sci3.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + + // set new key frames + sci3.setKeyFrames(new KeyFrame[]{end2}, new long[] {12000}); + v.set(0); + sci3.interpolate(TickCalculation.fromMillis(0)); + assertEquals(20, v.get()); + sci3.interpolate(TickCalculation.fromMillis(400)); + assertEquals(28, v.get()); + sci3.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v.get()); + + // validate new key frames + v.set(20); + sci3.validate(true); + sci3.interpolate(TickCalculation.fromMillis(0)); + assertEquals(20, v.get()); + sci3.interpolate(TickCalculation.fromMillis(600)); + assertEquals(32, v.get()); + sci3.interpolate(TickCalculation.fromMillis(2000)); + assertEquals(60, v.get()); + } + + @Test + public void test_TwoKeyFrames_ThreeKeyValues() { + final IntegerProperty v1 = new SimpleIntegerProperty(); + final IntegerProperty v2 = new SimpleIntegerProperty(); + final IntegerProperty v3 = new SimpleIntegerProperty(); + final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v2, 130), new KeyValue(v3, 230)); + final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 140)); + final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 160)); + + final SimpleClipInterpolatorShim sci1 = new SimpleClipInterpolatorShim(start1, end1, 6000); + v1.set( 0); + v2.set(100); + v3.set(200); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 0, v1.get()); + assertEquals(130, v2.get()); + assertEquals(200, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals( 12, v1.get()); + assertEquals(133, v2.get()); + assertEquals(200, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(200, v3.get()); + + // re-validate + v1.set( 20); + v2.set(120); + v3.set(220); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(130, v2.get()); + assertEquals(220, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(800)); + assertEquals( 36, v1.get()); + assertEquals(138, v2.get()); + assertEquals(220, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(220, v3.get()); + + // change key frames + sci1.setKeyFrames(new KeyFrame[]{start1, end2}, new long[] {0, 12000}); + v1.set( 0); + v2.set(100); + v3.set(200); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(130, v2.get()); + assertEquals(200, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals( 26, v1.get()); + assertEquals(133, v2.get()); + assertEquals(200, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(200, v3.get()); + + // validate new key frames + v1.set( 20); + v2.set(120); + v3.set(220); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(130, v2.get()); + assertEquals(220, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(600)); + assertEquals( 32, v1.get()); + assertEquals(139, v2.get()); + assertEquals(220, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals( 60, v1.get()); + assertEquals(160, v2.get()); + assertEquals(220, v3.get()); + + } + + @Test + public void test_OneKeyFrames_ThreeKeyValues() { + final IntegerProperty v1 = new SimpleIntegerProperty(); + final IntegerProperty v2 = new SimpleIntegerProperty(); + final IntegerProperty v3 = new SimpleIntegerProperty(); + final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 140), new KeyValue(v3, 240)); + final KeyFrame end2 = new KeyFrame(Duration.millis(2000), new KeyValue(v1, 60), new KeyValue(v2, 160), new KeyValue(v3, 260)); + + final SimpleClipInterpolatorShim sci1 = new SimpleClipInterpolatorShim(end1, 6000); + v1.set( 0); + v2.set(100); + v3.set(200); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 0, v1.get()); + assertEquals(100, v2.get()); + assertEquals(200, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals( 12, v1.get()); + assertEquals(112, v2.get()); + assertEquals(212, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + + // re-validate + v1.set( 20); + v2.set(120); + v3.set(220); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(120, v2.get()); + assertEquals(220, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(800)); + assertEquals( 36, v1.get()); + assertEquals(136, v2.get()); + assertEquals(236, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + + // change key frames + sci1.setKeyFrames(new KeyFrame[]{end2}, new long[] {12000}); + v1.set( 0); + v2.set(100); + v3.set(200); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(120, v2.get()); + assertEquals(220, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(300)); + assertEquals( 26, v1.get()); + assertEquals(126, v2.get()); + assertEquals(226, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertEquals( 40, v1.get()); + assertEquals(140, v2.get()); + assertEquals(240, v3.get()); + + // validate new key frames + v1.set( 20); + v2.set(120); + v3.set(220); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals( 20, v1.get()); + assertEquals(120, v2.get()); + assertEquals(220, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(600)); + assertEquals( 32, v1.get()); + assertEquals(132, v2.get()); + assertEquals(232, v3.get()); + sci1.interpolate(TickCalculation.fromMillis(2000)); + assertEquals( 60, v1.get()); + assertEquals(160, v2.get()); + assertEquals(260, v3.get()); + } + + @Test + public void test_DuplicateKeyValue() { + final IntegerProperty v1 = new SimpleIntegerProperty(); + final IntegerProperty v2 = new SimpleIntegerProperty(); + final KeyFrame start1 = new KeyFrame(Duration.ZERO, new KeyValue(v1, 30), new KeyValue(v2, 0)); + final KeyFrame start2 = new KeyFrame(Duration.ZERO, new KeyValue(v1, 30), new KeyValue(v1, -30), new KeyValue(v2, 0)); + final KeyFrame end1 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v2, 100)); + final KeyFrame end2 = new KeyFrame(Duration.millis(1000), new KeyValue(v1, 40), new KeyValue(v1, -40), new KeyValue(v2, 100)); + + // single value in start, duplicate value in end + final SimpleClipInterpolatorShim sci1 = new SimpleClipInterpolatorShim(start1, end2, 6000); + v1.set(0); + v2.set(0); + sci1.validate(true); + sci1.interpolate(TickCalculation.fromMillis(0)); + assertEquals(30, v1.get()); + assertEquals(0, v2.get()); + sci1.interpolate(TickCalculation.fromMillis(300)); + assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get())); + assertEquals(30, v2.get()); + sci1.interpolate(TickCalculation.fromMillis(1000)); + assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); + assertEquals(100, v2.get()); + + // duplicate value in start, single value in end + final SimpleClipInterpolatorShim sci2 = new SimpleClipInterpolatorShim(start2, end1, 6000); + v1.set(0); + v2.set(0); + sci2.validate(true); + sci2.interpolate(TickCalculation.fromMillis(0)); + assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); + assertEquals(0, v2.get()); + sci2.interpolate(TickCalculation.fromMillis(300)); + assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (-9 == v1.get())); + assertEquals(30, v2.get()); + sci2.interpolate(TickCalculation.fromMillis(1000)); + assertEquals(40, v1.get()); + assertEquals(100, v2.get()); + + // duplicate value in start, duplicate value in end + final SimpleClipInterpolatorShim sci3 = new SimpleClipInterpolatorShim(start2, end2, 6000); + v1.set(0); + v2.set(0); + sci3.validate(true); + sci3.interpolate(TickCalculation.fromMillis(0)); + assertTrue("v1.get(): " + v1.get(), (30 == v1.get()) || (-30 == v1.get())); + assertEquals(0, v2.get()); + sci3.interpolate(TickCalculation.fromMillis(300)); + assertTrue("v1.get(): " + v1.get(), (33 == v1.get()) || (9 == v1.get()) || (-9 == v1.get()) || (-33 == v1.get())); + assertEquals(30, v2.get()); + sci3.interpolate(TickCalculation.fromMillis(1000)); + assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); + assertEquals(100, v2.get()); + + // no value in start, duplicate value in end + final SimpleClipInterpolatorShim sci4 = new SimpleClipInterpolatorShim(end2, 6000); + v1.set(0); + v2.set(0); + sci4.validate(true); + sci4.interpolate(TickCalculation.fromMillis(0)); + assertEquals(0, v1.get()); + assertEquals(0, v2.get()); + sci4.interpolate(TickCalculation.fromMillis(400)); + assertTrue("v1.get(): " + v1.get(), (16 == v1.get()) || (-16 == v1.get())); + assertEquals(40, v2.get()); + sci4.interpolate(TickCalculation.fromMillis(1000)); + assertTrue("v1.get(): " + v1.get(), (40 == v1.get()) || (-40 == v1.get())); + assertEquals(100, v2.get()); + } + +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/shared/SingleLoopClipEnvelopeTest.java 2015-09-11 21:25:12.033286455 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario.animation.shared; - -import com.sun.javafx.tk.Toolkit; -import javafx.animation.Animation.Status; -import javafx.animation.AnimationMock; -import javafx.animation.AnimationMock.Command; -import javafx.util.Duration; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class SingleLoopClipEnvelopeTest { - - - private final long CYCLE_TICKS = Math.round(6.0 * AnimationMock.DEFAULT_DURATION.toMillis()); - - private ClipEnvelope clip; - private AnimationMock animation; - - @Before - public void setUp() { - animation = new AnimationMock(Toolkit.getToolkit().getMasterTimer(), AnimationMock.DEFAULT_DURATION, AnimationMock.DEFAULT_RATE, 1, AnimationMock.DEFAULT_AUTOREVERSE); - clip = new SingleLoopClipEnvelope(animation); - } - - @Test - public void testSetValues() { - ClipEnvelope c; - - // Setting cycleCount to 2 - animation.setCycleCount(2); - animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); - c = clip.setCycleCount(2); - assertNotSame(clip, c); - assertTrue(c instanceof FiniteClipEnvelope); - - // Setting cycleDuration to INDEFINITE - animation.setCycleCount(1); - animation.mockCycleDuration(Duration.INDEFINITE); - c = clip.setCycleDuration(Duration.INDEFINITE); - assertSame(clip, c); - - // Setting cycleCount to 2 - animation.setCycleCount(2); - animation.mockCycleDuration(Duration.INDEFINITE); - c = clip.setCycleCount(2); - assertSame(clip, c); - - // Setting cycleDuration to < INDEFINITE - animation.setCycleCount(2); - animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); - c = clip.setCycleDuration(AnimationMock.DEFAULT_DURATION); - assertNotSame(clip, c); - assertTrue(c instanceof FiniteClipEnvelope); - - // Setting cycleCount to 1 - animation.setCycleCount(1); - animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); - c = clip.setCycleCount(1); - assertSame(clip, c); - } - - @Test - public void testJump() { - clip.jumpTo(0); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - clip.jumpTo(0); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - clip.jumpTo(6 * 1000); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - - clip.jumpTo(-1); - animation.check(Command.JUMP, 0, CYCLE_TICKS); - - clip.jumpTo(6 * 1000 + 1); - animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); - } - - @Test - public void testTimePulseForward() { - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.timePulse(1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000); - animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testTimePulseBackward() { - clip.jumpTo(6 * 1000); - clip.setRate(-1.0); - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.timePulse(1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 1000); - animation.check(Command.PLAY, 0, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseForward() { - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - clip.timePulse(6 * 700 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 500); - animation.check(Command.JUMP, 6 * 500, CYCLE_TICKS); - - clip.timePulse(6 * 700 - 1 + 6 * 500 - 1); - animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 700 - 1 + 6 * 500 - 1 + 1); - animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testJumpAndPulseBackward() { - clip.jumpTo(6 * 1000); - clip.setRate(-1.0); - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.jumpTo(6 * 300); - animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); - - clip.timePulse(6 * 300 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.jumpTo(6 * 500); - animation.check(Command.JUMP, 6 * 500, CYCLE_TICKS); - - clip.timePulse(6 * 300 - 1 + 6 * 500 - 1); - animation.check(Command.PLAY, 1, CYCLE_TICKS); - assertFalse(animation.finishCalled()); - - clip.timePulse(6 * 300 - 1 + 6 * 500 - 1 + 1); - animation.check(Command.PLAY, 0, CYCLE_TICKS); - assertTrue(animation.finishCalled()); - } - - @Test - public void testRate() { - clip.setRate(0.5); - animation.mockStatus(Status.RUNNING); - clip.start(); - - clip.timePulse(6 * 200); - animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); - - clip.setRate(3.0); - clip.timePulse(6 * 300); - animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); - - clip.setRate(2.0); - clip.timePulse(6 * 500); - animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); - - clip.setRate(-0.5); - clip.timePulse(6 * 1100); - animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); - - clip.setRate(-3.0); - clip.timePulse(6 * 1200); - animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); - - clip.setRate(0.5); - clip.timePulse(6 * 2100); - animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/shared/SingleLoopClipEnvelopeTest.java 2015-09-11 21:25:11.889286456 -0400 @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.animation.shared; + +import com.sun.javafx.tk.Toolkit; +import com.sun.scenario.animation.shared.ClipEnvelope; +import com.sun.scenario.animation.shared.FiniteClipEnvelope; +import com.sun.scenario.animation.shared.SingleLoopClipEnvelopeShim; +import javafx.animation.Animation.Status; +import test.javafx.animation.AnimationMock; +import test.javafx.animation.AnimationMock.Command; +import javafx.util.Duration; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class SingleLoopClipEnvelopeTest { + + + private final long CYCLE_TICKS = Math.round(6.0 * AnimationMock.DEFAULT_DURATION.toMillis()); + + private ClipEnvelope clip; + private AnimationMock animation; + + @Before + public void setUp() { + animation = new AnimationMock(Toolkit.getToolkit().getMasterTimer(), AnimationMock.DEFAULT_DURATION, AnimationMock.DEFAULT_RATE, 1, AnimationMock.DEFAULT_AUTOREVERSE); + clip = new SingleLoopClipEnvelopeShim(animation); + } + + @Test + public void testSetValues() { + ClipEnvelope c; + + // Setting cycleCount to 2 + animation.setCycleCount(2); + animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); + c = clip.setCycleCount(2); + assertNotSame(clip, c); + assertTrue(c instanceof FiniteClipEnvelope); + + // Setting cycleDuration to INDEFINITE + animation.setCycleCount(1); + animation.mockCycleDuration(Duration.INDEFINITE); + c = clip.setCycleDuration(Duration.INDEFINITE); + assertSame(clip, c); + + // Setting cycleCount to 2 + animation.setCycleCount(2); + animation.mockCycleDuration(Duration.INDEFINITE); + c = clip.setCycleCount(2); + assertSame(clip, c); + + // Setting cycleDuration to < INDEFINITE + animation.setCycleCount(2); + animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); + c = clip.setCycleDuration(AnimationMock.DEFAULT_DURATION); + assertNotSame(clip, c); + assertTrue(c instanceof FiniteClipEnvelope); + + // Setting cycleCount to 1 + animation.setCycleCount(1); + animation.mockCycleDuration(AnimationMock.DEFAULT_DURATION); + c = clip.setCycleCount(1); + assertSame(clip, c); + } + + @Test + public void testJump() { + clip.jumpTo(0); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + clip.jumpTo(0); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + clip.jumpTo(6 * 1000); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + + clip.jumpTo(-1); + animation.check(Command.JUMP, 0, CYCLE_TICKS); + + clip.jumpTo(6 * 1000 + 1); + animation.check(Command.JUMP, 6 * 1000, CYCLE_TICKS); + } + + @Test + public void testTimePulseForward() { + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.timePulse(1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000); + animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testTimePulseBackward() { + clip.jumpTo(6 * 1000); + clip.setRate(-1.0); + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.timePulse(1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 1000); + animation.check(Command.PLAY, 0, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseForward() { + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + clip.timePulse(6 * 700 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 500); + animation.check(Command.JUMP, 6 * 500, CYCLE_TICKS); + + clip.timePulse(6 * 700 - 1 + 6 * 500 - 1); + animation.check(Command.PLAY, 6 * 1000 - 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 700 - 1 + 6 * 500 - 1 + 1); + animation.check(Command.PLAY, 6 * 1000, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testJumpAndPulseBackward() { + clip.jumpTo(6 * 1000); + clip.setRate(-1.0); + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.jumpTo(6 * 300); + animation.check(Command.JUMP, 6 * 300, CYCLE_TICKS); + + clip.timePulse(6 * 300 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.jumpTo(6 * 500); + animation.check(Command.JUMP, 6 * 500, CYCLE_TICKS); + + clip.timePulse(6 * 300 - 1 + 6 * 500 - 1); + animation.check(Command.PLAY, 1, CYCLE_TICKS); + assertFalse(animation.finishCalled()); + + clip.timePulse(6 * 300 - 1 + 6 * 500 - 1 + 1); + animation.check(Command.PLAY, 0, CYCLE_TICKS); + assertTrue(animation.finishCalled()); + } + + @Test + public void testRate() { + clip.setRate(0.5); + animation.mockStatus(Status.RUNNING); + clip.start(); + + clip.timePulse(6 * 200); + animation.check(Command.PLAY, 6 * 100, CYCLE_TICKS); + + clip.setRate(3.0); + clip.timePulse(6 * 300); + animation.check(Command.PLAY, 6 * 400, CYCLE_TICKS); + + clip.setRate(2.0); + clip.timePulse(6 * 500); + animation.check(Command.PLAY, 6 * 800, CYCLE_TICKS); + + clip.setRate(-0.5); + clip.timePulse(6 * 1100); + animation.check(Command.PLAY, 6 * 500, CYCLE_TICKS); + + clip.setRate(-3.0); + clip.timePulse(6 * 1200); + animation.check(Command.PLAY, 6 * 200, CYCLE_TICKS); + + clip.setRate(0.5); + clip.timePulse(6 * 2100); + animation.check(Command.PLAY, 6 * 650, CYCLE_TICKS); + } + +} --- old/modules/graphics/src/test/java/com/sun/scenario/animation/shared/TimelineClipCoreTest.java 2015-09-11 21:25:12.669286447 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,221 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.scenario.animation.shared; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import javafx.animation.KeyFrame; -import javafx.animation.KeyValue; -import javafx.animation.Timeline; -import javafx.animation.TimelineHelper; -import javafx.beans.property.IntegerProperty; -import javafx.beans.property.SimpleIntegerProperty; -import javafx.event.ActionEvent; -import javafx.event.EventHandler; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; - -public class TimelineClipCoreTest { - private Timeline timeline; - - private KeyFrame start; - private KeyFrame middle; - private KeyFrame end; - private IntegerProperty target; - - private TimelineClipCore core; - - private boolean tmpBool; - - @Before - public void setUp() { - target = new SimpleIntegerProperty(); - - start = new KeyFrame(Duration.ZERO, new KeyValue(target, 10)); - middle = new KeyFrame(new Duration(500)); - end = new KeyFrame(new Duration(1000), new KeyValue(target, 20)); - - timeline = new Timeline(); - timeline.getKeyFrames().setAll(start, middle, end); - timeline.setRate(1.0); - timeline.setCycleCount(1); - timeline.setAutoReverse(false); - core = TimelineHelper.getClipCore(timeline); - } - - @Test - public void testPlayTo() { - //forward - timeline.play(); - timeline.pause(); - core.playTo(6 * 500); - assertEquals(15, target.get()); - - //to the end - core.playTo(6 * 1000); - assertEquals(20, target.get()); - - //backwards - core.playTo(6 * 200); - assertEquals(12, target.get()); - - //back to start - core.playTo(0); - assertEquals(10, target.get()); - - //catching up - tmpBool = false; - final KeyFrame newMiddle = new KeyFrame( - Duration.millis(500), - event -> { - tmpBool = true; - } - ); - timeline.getKeyFrames().set(1, newMiddle); - - core.playTo(6 * 1000); - assertEquals(20, target.get()); - assertTrue(tmpBool); - -// //visit last -// core.start(); -// tmpBool = false; -// end.setCanSkip(true); -// end.setAction(new Runnable() { -// -// @Override -// public void run() { -// tmpBool = true; -// } -// }); -// -// core.playTo(1000, true, true); -// assertTrue(tmpBool); - } - - @Test - public void testPlayTo_ThrowsException() { - final PrintStream defaultErrorStream = System.err; - final PrintStream nirvana = new PrintStream(new OutputStream() { - @Override - public void write(int i) throws IOException { - } - }); - final OnFinishedExceptionListener eventHandler = new OnFinishedExceptionListener() ; - start = new KeyFrame(Duration.ZERO, eventHandler); - middle = new KeyFrame(new Duration(500), eventHandler); - end = new KeyFrame(new Duration(1000), eventHandler); - timeline.getKeyFrames().setAll(start, middle, end); - - try { - System.setErr(nirvana); - } catch (SecurityException ex) { - // ignore - } - timeline.play(); - timeline.pause(); - core.playTo(6 * 100); - try { - System.setErr(defaultErrorStream); - } catch (SecurityException ex) { - // ignore - } - assertEquals(1, eventHandler.callCount); - - try { - System.setErr(nirvana); - } catch (SecurityException ex) { - // ignore - } - core.playTo(6 * 600); - try { - System.setErr(defaultErrorStream); - } catch (SecurityException ex) { - // ignore - } - assertEquals(2, eventHandler.callCount); - - try { - System.setErr(nirvana); - } catch (SecurityException ex) { - // ignore - } - core.playTo(6 * 1000); - try { - System.setErr(defaultErrorStream); - } catch (SecurityException ex) { - // ignore - } - assertEquals(3, eventHandler.callCount); - } - - @Ignore - @Test - public void testJumpTo() { - // jumpTo on stopped timeline - tmpBool = false; - final KeyFrame newMiddle = new KeyFrame( - Duration.millis(500), - event -> { - tmpBool = true; - } - ); - timeline.getKeyFrames().set(1, newMiddle); - - core.jumpTo(6 * 600, false); - assertEquals(0, target.get()); - assertFalse(tmpBool); - - // jumpTo on paused timeline - tmpBool = false; - timeline.play(); - timeline.pause(); - core.jumpTo(6 * 400, false); - assertEquals(14, target.get()); - assertFalse(tmpBool); - } - - private static class OnFinishedExceptionListener implements EventHandler { - - private int callCount = 0; - - @Override - public void handle(ActionEvent event) { - callCount++; - throw new RuntimeException("Test Exception"); - } - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/animation/shared/TimelineClipCoreTest.java 2015-09-11 21:25:12.533286449 -0400 @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.animation.shared; + +import com.sun.scenario.animation.shared.TimelineClipCore; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import javafx.animation.KeyFrame; +import javafx.animation.KeyValue; +import javafx.animation.Timeline; +import javafx.beans.property.IntegerProperty; +import javafx.beans.property.SimpleIntegerProperty; +import javafx.event.ActionEvent; +import javafx.event.EventHandler; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import javafx.animation.TimelineShim; + +public class TimelineClipCoreTest { + private Timeline timeline; + + private KeyFrame start; + private KeyFrame middle; + private KeyFrame end; + private IntegerProperty target; + + private TimelineClipCore core; + + private boolean tmpBool; + + @Before + public void setUp() { + target = new SimpleIntegerProperty(); + + start = new KeyFrame(Duration.ZERO, new KeyValue(target, 10)); + middle = new KeyFrame(new Duration(500)); + end = new KeyFrame(new Duration(1000), new KeyValue(target, 20)); + + timeline = new Timeline(); + timeline.getKeyFrames().setAll(start, middle, end); + timeline.setRate(1.0); + timeline.setCycleCount(1); + timeline.setAutoReverse(false); + core = TimelineShim.getClipCore(timeline); + } + + @Test + public void testPlayTo() { + //forward + timeline.play(); + timeline.pause(); + core.playTo(6 * 500); + assertEquals(15, target.get()); + + //to the end + core.playTo(6 * 1000); + assertEquals(20, target.get()); + + //backwards + core.playTo(6 * 200); + assertEquals(12, target.get()); + + //back to start + core.playTo(0); + assertEquals(10, target.get()); + + //catching up + tmpBool = false; + final KeyFrame newMiddle = new KeyFrame( + Duration.millis(500), + event -> { + tmpBool = true; + } + ); + timeline.getKeyFrames().set(1, newMiddle); + + core.playTo(6 * 1000); + assertEquals(20, target.get()); + assertTrue(tmpBool); + +// //visit last +// core.start(); +// tmpBool = false; +// end.setCanSkip(true); +// end.setAction(new Runnable() { +// +// @Override +// public void run() { +// tmpBool = true; +// } +// }); +// +// core.playTo(1000, true, true); +// assertTrue(tmpBool); + } + + @Test + public void testPlayTo_ThrowsException() { + final PrintStream defaultErrorStream = System.err; + final PrintStream nirvana = new PrintStream(new OutputStream() { + @Override + public void write(int i) throws IOException { + } + }); + final OnFinishedExceptionListener eventHandler = new OnFinishedExceptionListener() ; + start = new KeyFrame(Duration.ZERO, eventHandler); + middle = new KeyFrame(new Duration(500), eventHandler); + end = new KeyFrame(new Duration(1000), eventHandler); + timeline.getKeyFrames().setAll(start, middle, end); + + try { + System.setErr(nirvana); + } catch (SecurityException ex) { + // ignore + } + timeline.play(); + timeline.pause(); + core.playTo(6 * 100); + try { + System.setErr(defaultErrorStream); + } catch (SecurityException ex) { + // ignore + } + assertEquals(1, eventHandler.callCount); + + try { + System.setErr(nirvana); + } catch (SecurityException ex) { + // ignore + } + core.playTo(6 * 600); + try { + System.setErr(defaultErrorStream); + } catch (SecurityException ex) { + // ignore + } + assertEquals(2, eventHandler.callCount); + + try { + System.setErr(nirvana); + } catch (SecurityException ex) { + // ignore + } + core.playTo(6 * 1000); + try { + System.setErr(defaultErrorStream); + } catch (SecurityException ex) { + // ignore + } + assertEquals(3, eventHandler.callCount); + } + + @Ignore + @Test + public void testJumpTo() { + // jumpTo on stopped timeline + tmpBool = false; + final KeyFrame newMiddle = new KeyFrame( + Duration.millis(500), + event -> { + tmpBool = true; + } + ); + timeline.getKeyFrames().set(1, newMiddle); + + core.jumpTo(6 * 600, false); + assertEquals(0, target.get()); + assertFalse(tmpBool); + + // jumpTo on paused timeline + tmpBool = false; + timeline.play(); + timeline.pause(); + core.jumpTo(6 * 400, false); + assertEquals(14, target.get()); + assertFalse(tmpBool); + } + + private static class OnFinishedExceptionListener implements EventHandler { + + private int callCount = 0; + + @Override + public void handle(ActionEvent event) { + callCount++; + throw new RuntimeException("Test Exception"); + } + + } + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/com/sun/scenario/effect/rt_5239/RT_5239Test.java 2015-09-11 21:25:13.149286442 -0400 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.com.sun.scenario.effect.rt_5239; + +import com.sun.prism.paint.Color; +import com.sun.javafx.geom.BaseBounds; +import com.sun.javafx.geom.RectBounds; +import com.sun.javafx.geom.transform.BaseTransform; +import com.sun.scenario.effect.Effect; +import com.sun.scenario.effect.Flood; +import com.sun.scenario.effect.InnerShadow; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Fix to verify RT-5239 + * InnerShadow pads the bounds despite not padding the image + */ +public class RT_5239Test { + @Test + public void test() { + Effect e = new InnerShadow(); + Flood src = new Flood(Color.RED, new RectBounds(0, 0, 10, 10)); + BaseBounds srcbounds = src.getBounds(BaseTransform.IDENTITY_TRANSFORM, null); + BaseBounds effectbounds = e.getBounds(null, src); + assertEquals(srcbounds, effectbounds); + } +} --- old/modules/graphics/src/test/java/javafx/animation/AbstractMasterTimerMock.java 2015-09-11 21:25:13.993286433 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import java.util.HashSet; -import java.util.Set; -import com.sun.javafx.animation.TickCalculation; -import com.sun.scenario.DelayedRunnable; -import com.sun.scenario.animation.AbstractMasterTimer; -import com.sun.scenario.animation.shared.PulseReceiver; - -public class AbstractMasterTimerMock extends AbstractMasterTimer { - - private final Set targets = new HashSet(); - - private long nanos; - - protected AbstractMasterTimerMock() { - } - - @Override - public long nanos() { - return nanos; - } - - @Override - protected void postUpdateAnimationRunnable(DelayedRunnable animationRunnable) { - } - - @Override - protected int getPulseDuration(int precision) { - return precision / 60; - } - - @Override - public void addPulseReceiver(PulseReceiver target) { - super.addPulseReceiver(target); - targets.add(target); - } - - @Override - public void removePulseReceiver(PulseReceiver target) { - super.addPulseReceiver(target); - targets.remove(target); - } - - public void pulse() { - nanos += TickCalculation.toMillis(100) * 1000000L; - for (PulseReceiver pr : targets) { - pr.timePulse(TickCalculation.fromNano(nanos)); - } - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/AbstractMasterTimerMock.java 2015-09-11 21:25:13.797286435 -0400 @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import java.util.HashSet; +import java.util.Set; +import com.sun.javafx.animation.TickCalculation; +import com.sun.scenario.DelayedRunnable; +import com.sun.scenario.animation.AbstractMasterTimer; +import com.sun.scenario.animation.shared.PulseReceiver; + +public class AbstractMasterTimerMock extends AbstractMasterTimer { + + private final Set targets = new HashSet(); + + private long nanos; + + public void setNanos(long nanos) { + this.nanos = nanos; + } + + @Override + public long nanos() { + return nanos; + } + + @Override + protected void postUpdateAnimationRunnable(DelayedRunnable animationRunnable) { + } + + @Override + protected int getPulseDuration(int precision) { + return precision / 60; + } + + @Override + public void addPulseReceiver(PulseReceiver target) { + super.addPulseReceiver(target); + targets.add(target); + } + + @Override + public void removePulseReceiver(PulseReceiver target) { + super.addPulseReceiver(target); + targets.remove(target); + } + + public boolean containsPulseReceiver(PulseReceiver target) { + return targets.contains(target); + } + + public void pulse() { + nanos += TickCalculation.toMillis(100) * 1000000L; + for (PulseReceiver pr : targets) { + pr.timePulse(TickCalculation.fromNano(nanos)); + } + } + +} --- old/modules/graphics/src/test/java/javafx/animation/AnimationDummy.java 2015-09-11 21:25:14.669286425 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import javafx.util.Duration; - -public class AnimationDummy extends Animation { - - public AnimationDummy(Duration duration) { - setCycleDuration(duration); - } - - @Override - public void impl_playTo(long currentTicks, long cycleTicks) { - // TODO Auto-generated method stub - - } - - @Override - public void impl_jumpTo(long currentTicks, long cycleTicks, boolean forceJump) { - // TODO Auto-generated method stub - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/AnimationDummy.java 2015-09-11 21:25:14.473286427 -0400 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.util.Duration; + +public class AnimationDummy extends AnimationImpl { + + public AnimationDummy(Duration duration) { + super.setCycleDuration(duration); + } + + @Override + public void impl_playTo(long currentTicks, long cycleTicks) { + // TODO Auto-generated method stub + + } + + @Override + public void impl_jumpTo(long currentTicks, long cycleTicks, boolean forceJump) { + // TODO Auto-generated method stub + + } + +} --- old/modules/graphics/src/test/java/javafx/animation/AnimationImpl.java 2015-09-11 21:25:15.333286417 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import com.sun.scenario.animation.AbstractMasterTimer; -import com.sun.scenario.animation.shared.ClipEnvelope; - -public class AnimationImpl extends Animation { - - public AnimationImpl(AbstractMasterTimer timer, ClipEnvelope clipEnvelope, int resolution) { - super(timer, clipEnvelope, resolution); - } - - public AnimationImpl() { - super(); - } - - - @Override - public void impl_playTo(long currentTicks, long cycleTicks) { - } - - @Override - public void impl_jumpTo(long currentTicks, long cycleTicks, boolean forceJump) { - impl_setCurrentTicks(currentTicks); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/AnimationImpl.java 2015-09-11 21:25:15.153286419 -0400 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import com.sun.scenario.animation.AbstractMasterTimer; +import com.sun.scenario.animation.shared.ClipEnvelope; +import javafx.animation.AnimationShim; + +public class AnimationImpl extends AnimationShim { + + public AnimationImpl(AbstractMasterTimer timer, ClipEnvelope clipEnvelope, int resolution) { + super(timer, clipEnvelope, resolution); + } + + public AnimationImpl() { + super(); + } + + public AnimationImpl(AbstractMasterTimer timer) { + super(timer); + } + + @Override + public void impl_playTo(long currentTicks, long cycleTicks) { + } + + @Override + public void impl_jumpTo(long currentTicks, long cycleTicks, boolean forceJump) { + impl_setCurrentTicks(currentTicks); + } + +} --- old/modules/graphics/src/test/java/javafx/animation/AnimationMock.java 2015-09-11 21:25:16.081286409 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import javafx.event.ActionEvent; -import javafx.event.EventHandler; -import javafx.util.Duration; -import com.sun.scenario.animation.AbstractMasterTimer; - -import static org.junit.Assert.*; - -public class AnimationMock extends Animation { - - public static final Duration DEFAULT_DURATION = Duration.seconds(1); - public static final double DEFAULT_RATE = 1.0; - public static final int DEFAULT_CYCLE_COUNT = 1; - public static final boolean DEFAULT_AUTOREVERSE = false; - private long lastTimePulse; - - public enum Command {PLAY, JUMP, NONE}; - - private Command lastCommand = Command.NONE; - private long lastCurrentTicks = -1; - private long lastCycleTicks = -1; - private boolean finishFlag; - - public void mockStatus(Status status) { - this.setStatus(status); - } - - public void mockCycleDuration(Duration duration) { - this.setCycleDuration(duration); - } - - public AnimationMock(AbstractMasterTimer timer, Duration cycleDuration, double rate, int cycleCount, boolean autoReverse) { - super(timer); - setCycleDuration(cycleDuration); - setRate(rate); - setCycleCount(cycleCount); - setAutoReverse(autoReverse); - super.setOnFinished(event -> { - finishFlag = true; - }); - } - - public void check(Command lastCommand, long lastCurrentTicks, long lastCycleTicks) { - assertEquals(lastCommand, this.lastCommand); - if (lastCommand != Command.NONE) { - assertEquals(lastCurrentTicks, this.lastCurrentTicks); - assertEquals(lastCycleTicks, this.lastCycleTicks); - } - this.lastCommand = Command.NONE; - this.lastCurrentTicks = -1; - this.lastCycleTicks = -1; - } - - public boolean finishCalled() { - final boolean result = finishFlag; - finishFlag = false; - return result; - } - - public long getLastTimePulse() { - final long p = lastTimePulse; - lastTimePulse = 0L; - return p; - } - - - @Override - public void impl_playTo(long currentTicks, long cycleTicks) { - lastCommand = Command.PLAY; - lastCurrentTicks = currentTicks; - lastCycleTicks = cycleTicks; - } - - @Override - public void impl_jumpTo(long currentTicks, long cycleTicks, boolean forceJump) { - lastCommand = Command.JUMP; - lastCurrentTicks = currentTicks; - lastCycleTicks = cycleTicks; - } - - @Override - void impl_timePulse(long elapsedTime) { - super.impl_timePulse(elapsedTime); - lastTimePulse = elapsedTime; - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/AnimationMock.java 2015-09-11 21:25:15.877286411 -0400 @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.util.Duration; +import com.sun.scenario.animation.AbstractMasterTimer; + +import static org.junit.Assert.*; + +public class AnimationMock extends AnimationImpl { + + public static final Duration DEFAULT_DURATION = Duration.seconds(1); + public static final double DEFAULT_RATE = 1.0; + public static final int DEFAULT_CYCLE_COUNT = 1; + public static final boolean DEFAULT_AUTOREVERSE = false; + private long lastTimePulse; + + public enum Command {PLAY, JUMP, NONE}; + + private Command lastCommand = Command.NONE; + private long lastCurrentTicks = -1; + private long lastCycleTicks = -1; + private boolean finishFlag; + + public void mockStatus(Status status) { + this.setStatus(status); + } + + public void mockCycleDuration(Duration duration) { + shim_setCycleDuration(duration); + } + + public AnimationMock(AbstractMasterTimer timer, Duration cycleDuration, double rate, int cycleCount, boolean autoReverse) { + super(timer); + shim_setCycleDuration(cycleDuration); + setRate(rate); + setCycleCount(cycleCount); + setAutoReverse(autoReverse); + super.setOnFinished(event -> { + finishFlag = true; + }); + } + + public void check(Command lastCommand, long lastCurrentTicks, long lastCycleTicks) { + assertEquals(lastCommand, this.lastCommand); + if (lastCommand != Command.NONE) { + assertEquals(lastCurrentTicks, this.lastCurrentTicks); + assertEquals(lastCycleTicks, this.lastCycleTicks); + } + this.lastCommand = Command.NONE; + this.lastCurrentTicks = -1; + this.lastCycleTicks = -1; + } + + public boolean finishCalled() { + final boolean result = finishFlag; + finishFlag = false; + return result; + } + + public long getLastTimePulse() { + final long p = lastTimePulse; + lastTimePulse = 0L; + return p; + } + + + @Override + public void impl_playTo(long currentTicks, long cycleTicks) { + lastCommand = Command.PLAY; + lastCurrentTicks = currentTicks; + lastCycleTicks = cycleTicks; + } + + @Override + public void impl_jumpTo(long currentTicks, long cycleTicks, boolean forceJump) { + lastCommand = Command.JUMP; + lastCurrentTicks = currentTicks; + lastCycleTicks = cycleTicks; + } + + @Override + public void impl_timePulse(long elapsedTime) { + super.impl_timePulse(elapsedTime); + lastTimePulse = elapsedTime; + } + +} --- old/modules/graphics/src/test/java/javafx/animation/AnimationPulseReceiverTest.java 2015-09-11 21:25:16.837286401 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.sun.javafx.tk.Toolkit; -import javafx.animation.Animation; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.sun.scenario.animation.AbstractMasterTimerMock; -import javafx.animation.AnimationMock; -import javafx.util.Duration; - -public class AnimationPulseReceiverTest { - - private static final int DEFAULT_RESOLUTION = Toolkit.getToolkit().getMasterTimer().getDefaultResolution(); - private static final double TICKS_2_NANOS = 1.0 / 6e-6; - private AbstractMasterTimerMock timer; - private AnimationMock animation; - - @Before - public void setUp() { - timer = new AbstractMasterTimerMock(); - animation = new AnimationMock(timer, Duration.INDEFINITE, 1.0, 1, false); - } - - @After - public void tearDown() { - animation.impl_stop(); - } - - @Test - public void testPlay_DefaultResolution() { - // start animatiom - timer.setNanos(Math.round(3 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.startReceiver(0); - assertTrue(timer.containsPulseReceiver(animation.pulseReceiver)); - - // send pulse - animation.pulseReceiver.timePulse(7 * DEFAULT_RESOLUTION); - assertEquals(4 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); - - // another pulse - animation.pulseReceiver.timePulse(16 * DEFAULT_RESOLUTION); - assertEquals(13 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); - - // stop animation - animation.impl_stop(); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - - // stop again - animation.impl_stop(); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - - // start again - timer.setNanos(Math.round(30 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.startReceiver(0); - assertTrue(timer.containsPulseReceiver(animation.pulseReceiver)); - - // send pulse - animation.pulseReceiver.timePulse(43 * DEFAULT_RESOLUTION); - assertEquals(13 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); - } - - @Test - public void testPause_DefaultResolution() { - // start animation - timer.setNanos(Math.round(3 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.startReceiver(0); - assertTrue(timer.containsPulseReceiver(animation.pulseReceiver)); - - // pause animation - timer.setNanos(Math.round(18 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.pauseReceiver(); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - - // pause again - timer.setNanos(Math.round(27 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.pauseReceiver(); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - - // resume - timer.setNanos(Math.round(36 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.resumeReceiver(); - assertTrue(timer.containsPulseReceiver(animation.pulseReceiver)); - - // resume again - timer.setNanos(Math.round(42 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.resumeReceiver(); - assertTrue(timer.containsPulseReceiver(animation.pulseReceiver)); - - // send pulse - animation.pulseReceiver.timePulse(51 * DEFAULT_RESOLUTION); - assertEquals(30 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); - } - - @Test - public void testDelay() { - // start animatiom - timer.setNanos(Math.round(3 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.startReceiver(17 * DEFAULT_RESOLUTION); - assertTrue(timer.containsPulseReceiver(animation.pulseReceiver)); - - // send pulse during delay - animation.pulseReceiver.timePulse(5 * DEFAULT_RESOLUTION); - assertEquals(0, animation.getLastTimePulse()); - - // pause & resume - timer.setNanos(Math.round(10 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.pauseReceiver(); - timer.setNanos(Math.round(37 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); - animation.resumeReceiver(); - - // send pulse during delay - animation.pulseReceiver.timePulse(41 * DEFAULT_RESOLUTION); - assertEquals(0, animation.getLastTimePulse()); - - // send pulse after delay - animation.pulseReceiver.timePulse(48 * DEFAULT_RESOLUTION); - assertEquals(1 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/AnimationPulseReceiverTest.java 2015-09-11 21:25:16.625286403 -0400 @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.sun.javafx.tk.Toolkit; +import javafx.animation.Animation; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javafx.util.Duration; + +public class AnimationPulseReceiverTest { + + private static final int DEFAULT_RESOLUTION = Toolkit.getToolkit().getMasterTimer().getDefaultResolution(); + private static final double TICKS_2_NANOS = 1.0 / 6e-6; + private AbstractMasterTimerMock timer; + private AnimationMock animation; + + @Before + public void setUp() { + timer = new AbstractMasterTimerMock(); + animation = new AnimationMock(timer, Duration.INDEFINITE, 1.0, 1, false); + } + + @After + public void tearDown() { + animation.impl_stop(); + } + + @Test + public void testPlay_DefaultResolution() { + // start animatiom + timer.setNanos(Math.round(3 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.startReceiver(0); + assertTrue(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // send pulse + animation.shim_pulseReceiver().timePulse(7 * DEFAULT_RESOLUTION); + assertEquals(4 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); + + // another pulse + animation.shim_pulseReceiver().timePulse(16 * DEFAULT_RESOLUTION); + assertEquals(13 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); + + // stop animation + animation.impl_stop(); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // stop again + animation.impl_stop(); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // start again + timer.setNanos(Math.round(30 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.startReceiver(0); + assertTrue(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // send pulse + animation.shim_pulseReceiver().timePulse(43 * DEFAULT_RESOLUTION); + assertEquals(13 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); + } + + @Test + public void testPause_DefaultResolution() { + // start animation + timer.setNanos(Math.round(3 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.startReceiver(0); + assertTrue(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // pause animation + timer.setNanos(Math.round(18 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.pauseReceiver(); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // pause again + timer.setNanos(Math.round(27 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.pauseReceiver(); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // resume + timer.setNanos(Math.round(36 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.resumeReceiver(); + assertTrue(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // resume again + timer.setNanos(Math.round(42 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.resumeReceiver(); + assertTrue(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // send pulse + animation.shim_pulseReceiver().timePulse(51 * DEFAULT_RESOLUTION); + assertEquals(30 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); + } + + @Test + public void testDelay() { + // start animatiom + timer.setNanos(Math.round(3 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.startReceiver(17 * DEFAULT_RESOLUTION); + assertTrue(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // send pulse during delay + animation.shim_pulseReceiver().timePulse(5 * DEFAULT_RESOLUTION); + assertEquals(0, animation.getLastTimePulse()); + + // pause & resume + timer.setNanos(Math.round(10 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.pauseReceiver(); + timer.setNanos(Math.round(37 * DEFAULT_RESOLUTION * TICKS_2_NANOS)); + animation.resumeReceiver(); + + // send pulse during delay + animation.shim_pulseReceiver().timePulse(41 * DEFAULT_RESOLUTION); + assertEquals(0, animation.getLastTimePulse()); + + // send pulse after delay + animation.shim_pulseReceiver().timePulse(48 * DEFAULT_RESOLUTION); + assertEquals(1 * DEFAULT_RESOLUTION, animation.getLastTimePulse()); + } +} --- old/modules/graphics/src/test/java/javafx/animation/AnimationSetRateTest.java 2015-09-11 21:25:17.429286394 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,375 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - - -import javafx.animation.Animation.Status; -import javafx.util.Duration; -import com.sun.scenario.animation.AbstractMasterTimerMock; -import com.sun.scenario.animation.shared.ClipEnvelopeMock; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class AnimationSetRateTest { - - private static final double EPSILON = 1e-12; - - private AbstractMasterTimerMock timer; - private Animation animation; - private ClipEnvelopeMock clipEnvelope; - - @Before - public void setUp() throws Exception { - timer = new AbstractMasterTimerMock(); - clipEnvelope = new ClipEnvelopeMock(); - animation = new AnimationImpl(timer, clipEnvelope, 1); - animation.setCycleDuration(Duration.millis(1000)); - clipEnvelope.setAnimation(animation); - } - - private void assertAnimation(double rate, double currentRate, Status status, boolean addedToMasterTimer) { - assertEquals(rate, animation.getRate(), EPSILON); - assertEquals(currentRate, animation.getCurrentRate(), EPSILON); - assertEquals(status, animation.getStatus()); - assertEquals(addedToMasterTimer, timer.containsPulseReceiver(animation.pulseReceiver)); - } - - @Test - public void testSetRate() { - // changing the rate of a playing animation - animation.play(); - animation.setRate(3.0); - assertAnimation(3.0, 3.0, Status.RUNNING, true); - - // toggling a playing animation - animation.setRate(-2.0); - assertAnimation(-2.0, -2.0, Status.RUNNING, true); - - // changing the rate - animation.setRate(-2.5); - assertAnimation(-2.5, -2.5, Status.RUNNING, true); - - // toggling back - animation.setRate(1.5); - assertAnimation(1.5, 1.5, Status.RUNNING, true); - - // changing the rate of a animation playing in reverse - animation.impl_setCurrentRate(-1.5); - animation.setRate(2.2); - assertAnimation(2.2, -2.2, Status.RUNNING, true); - - // toggling a animation playing in reverse - animation.setRate(-1.8); - assertAnimation(-1.8, 1.8, Status.RUNNING, true); - - // changing the rate - animation.setRate(-1.3); - assertAnimation(-1.3, 1.3, Status.RUNNING, true); - - // toggling back - animation.setRate(0.5); - assertAnimation(0.5, -0.5, Status.RUNNING, true); - } - - @Test - public void testSetRateOfStoppedAnimation() { - // changing the rate - animation.setRate(2.0); - assertAnimation(2.0, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(2.0, 2.0, Status.RUNNING, true); - - // toggling the rate of a stopped animation - animation.stop(); - animation.setRate(-1.0); - assertAnimation(-1.0, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(-1.0, -1.0, Status.RUNNING, true); - - // toggling back - animation.stop(); - animation.setRate(3.0); - assertAnimation(3.0, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(3.0, 3.0, Status.RUNNING, true); - - // setting rate of stopped animation to zero - animation.stop(); - animation.setRate(0); - assertAnimation(0.0, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - - // setting rate of stopped animation to non-zero - animation.stop(); - animation.setRate(1.5); - assertAnimation(1.5, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(1.5, 1.5, Status.RUNNING, true); - - // setting rate of stopped animation to zero - animation.stop(); - animation.setRate(0); - assertAnimation(0.0, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - - // toggling rate of stopped animation to non-zero - animation.stop(); - animation.setRate(-0.5); - assertAnimation(-0.5, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(-0.5, -0.5, Status.RUNNING, true); - - // setting rate of stopped animation to zero - animation.stop(); - animation.setRate(0); - assertAnimation(0.0, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - - // setting rate of stopped animation to non-zero - animation.stop(); - animation.setRate(-2.3); - assertAnimation(-2.3, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(-2.3, -2.3, Status.RUNNING, true); - - // setting rate of stopped animation to zero - animation.stop(); - animation.setRate(0); - assertAnimation(0.0, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - - // toggling rate of stopped animation to non-zero - animation.stop(); - animation.setRate(1.7); - assertAnimation(1.7, 0.0, Status.STOPPED, false); - animation.play(); - assertAnimation(1.7, 1.7, Status.RUNNING, true); - } - - @Test - public void testSetRateToZeroForRunningAnimation() { - // changing the rate of a playing animation - animation.play(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - animation.setRate(3.0); - assertAnimation(3.0, 3.0, Status.RUNNING, true); - - // toggling a playing animation - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - animation.setRate(-2.0); - assertAnimation(-2.0, -2.0, Status.RUNNING, true); - - // changing the rate - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - animation.setRate(-2.5); - assertAnimation(-2.5, -2.5, Status.RUNNING, true); - - // toggling back - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - animation.setRate(1.5); - assertAnimation(1.5, 1.5, Status.RUNNING, true); - - // changing the rate of a animation playing in reverse - animation.impl_setCurrentRate(-1.5); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - animation.setRate(2.2); - assertAnimation(2.2, -2.2, Status.RUNNING, true); - - // toggling a animation playing in reverse - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - animation.setRate(-1.8); - assertAnimation(-1.8, 1.8, Status.RUNNING, true); - - // changing the rate - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - animation.setRate(-1.3); - assertAnimation(-1.3, 1.3, Status.RUNNING, true); - - // toggling back - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - animation.setRate(0.5); - assertAnimation(0.5, -0.5, Status.RUNNING, true); - } - - @Test - public void testSetRateOfPausedAnimation() { - // changing the rate of a paused animation - animation.play(); - animation.pause(); - animation.setRate(3.0); - assertAnimation(3.0, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(3.0, 3.0, Status.RUNNING, true); - - // toggling a pausing animation - animation.pause(); - animation.setRate(-2.0); - assertAnimation(-2.0, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(-2.0, -2.0, Status.RUNNING, true); - - // changing the rate - animation.pause(); - animation.setRate(-2.5); - assertAnimation(-2.5, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(-2.5, -2.5, Status.RUNNING, true); - - // toggling back - animation.pause(); - animation.setRate(1.5); - assertAnimation(1.5, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(1.5, 1.5, Status.RUNNING, true); - - // changing the rate of a paused animation pointing in reverse - animation.impl_setCurrentRate(-1.5); - animation.pause(); - animation.setRate(2.2); - assertAnimation(2.2, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(2.2, -2.2, Status.RUNNING, true); - - // toggling a paused playing pointing in reverse - animation.pause(); - animation.setRate(-1.8); - assertAnimation(-1.8, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(-1.8, 1.8, Status.RUNNING, true); - - // changing the rate - animation.pause(); - animation.setRate(-1.3); - assertAnimation(-1.3, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(-1.3, 1.3, Status.RUNNING, true); - - // toggling back - animation.pause(); - animation.setRate(0.5); - assertAnimation(0.5, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(0.5, -0.5, Status.RUNNING, true); - } - - @Test - public void testSetRateToZeroForPausedAnimation() { - // starting a paused animation with rate 0 - animation.play(); - animation.pause(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(0.0, 0.0, Status.RUNNING, false); - - // changing the rate of a paused animation - animation.pause(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.PAUSED, false); - animation.setRate(3.0); - assertAnimation(3.0, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(3.0, 3.0, Status.RUNNING, true); - - // toggling a paused animation - animation.pause(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.PAUSED, false); - animation.setRate(-2.0); - assertAnimation(-2.0, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(-2.0, -2.0, Status.RUNNING, true); - - // changing the rate - animation.pause(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.PAUSED, false); - animation.setRate(-2.5); - assertAnimation(-2.5, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(-2.5, -2.5, Status.RUNNING, true); - - // toggling back - animation.pause(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.PAUSED, false); - animation.setRate(1.5); - assertAnimation(1.5, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(1.5, 1.5, Status.RUNNING, true); - - // changing the rate of a paused animation pointing in reverse - animation.impl_setCurrentRate(-1.5); - animation.pause(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.PAUSED, false); - animation.setRate(2.2); - assertAnimation(2.2, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(2.2, -2.2, Status.RUNNING, true); - - // toggling a paused animation pointing in reverse - animation.pause(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.PAUSED, false); - animation.setRate(-1.8); - assertAnimation(-1.8, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(-1.8, 1.8, Status.RUNNING, true); - - // changing the rate - animation.pause(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.PAUSED, false); - animation.setRate(-1.3); - assertAnimation(-1.3, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(-1.3, 1.3, Status.RUNNING, true); - - // toggling back - animation.pause(); - animation.setRate(0.0); - assertAnimation(0.0, 0.0, Status.PAUSED, false); - animation.setRate(0.5); - assertAnimation(0.5, 0.0, Status.PAUSED, false); - animation.play(); - assertAnimation(0.5, -0.5, Status.RUNNING, true); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/AnimationSetRateTest.java 2015-09-11 21:25:17.293286395 -0400 @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + + +import javafx.animation.Animation.Status; +import javafx.util.Duration; +import test.com.sun.scenario.animation.shared.ClipEnvelopeMock; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class AnimationSetRateTest { + + private static final double EPSILON = 1e-12; + + private AbstractMasterTimerMock timer; + private AnimationImpl animation; + private ClipEnvelopeMock clipEnvelope; + + @Before + public void setUp() throws Exception { + timer = new AbstractMasterTimerMock(); + clipEnvelope = new ClipEnvelopeMock(); + animation = new AnimationImpl(timer, clipEnvelope, 1); + animation.shim_setCycleDuration(Duration.millis(1000)); + clipEnvelope.setAnimation(animation); + } + + private void assertAnimation(double rate, double currentRate, Status status, boolean addedToMasterTimer) { + assertEquals(rate, animation.getRate(), EPSILON); + assertEquals(currentRate, animation.getCurrentRate(), EPSILON); + assertEquals(status, animation.getStatus()); + assertEquals(addedToMasterTimer, timer.containsPulseReceiver(animation.shim_pulseReceiver())); + } + + @Test + public void testSetRate() { + // changing the rate of a playing animation + animation.play(); + animation.setRate(3.0); + assertAnimation(3.0, 3.0, Status.RUNNING, true); + + // toggling a playing animation + animation.setRate(-2.0); + assertAnimation(-2.0, -2.0, Status.RUNNING, true); + + // changing the rate + animation.setRate(-2.5); + assertAnimation(-2.5, -2.5, Status.RUNNING, true); + + // toggling back + animation.setRate(1.5); + assertAnimation(1.5, 1.5, Status.RUNNING, true); + + // changing the rate of a animation playing in reverse + animation.impl_setCurrentRate(-1.5); + animation.setRate(2.2); + assertAnimation(2.2, -2.2, Status.RUNNING, true); + + // toggling a animation playing in reverse + animation.setRate(-1.8); + assertAnimation(-1.8, 1.8, Status.RUNNING, true); + + // changing the rate + animation.setRate(-1.3); + assertAnimation(-1.3, 1.3, Status.RUNNING, true); + + // toggling back + animation.setRate(0.5); + assertAnimation(0.5, -0.5, Status.RUNNING, true); + } + + @Test + public void testSetRateOfStoppedAnimation() { + // changing the rate + animation.setRate(2.0); + assertAnimation(2.0, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(2.0, 2.0, Status.RUNNING, true); + + // toggling the rate of a stopped animation + animation.stop(); + animation.setRate(-1.0); + assertAnimation(-1.0, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(-1.0, -1.0, Status.RUNNING, true); + + // toggling back + animation.stop(); + animation.setRate(3.0); + assertAnimation(3.0, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(3.0, 3.0, Status.RUNNING, true); + + // setting rate of stopped animation to zero + animation.stop(); + animation.setRate(0); + assertAnimation(0.0, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + + // setting rate of stopped animation to non-zero + animation.stop(); + animation.setRate(1.5); + assertAnimation(1.5, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(1.5, 1.5, Status.RUNNING, true); + + // setting rate of stopped animation to zero + animation.stop(); + animation.setRate(0); + assertAnimation(0.0, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + + // toggling rate of stopped animation to non-zero + animation.stop(); + animation.setRate(-0.5); + assertAnimation(-0.5, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(-0.5, -0.5, Status.RUNNING, true); + + // setting rate of stopped animation to zero + animation.stop(); + animation.setRate(0); + assertAnimation(0.0, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + + // setting rate of stopped animation to non-zero + animation.stop(); + animation.setRate(-2.3); + assertAnimation(-2.3, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(-2.3, -2.3, Status.RUNNING, true); + + // setting rate of stopped animation to zero + animation.stop(); + animation.setRate(0); + assertAnimation(0.0, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + + // toggling rate of stopped animation to non-zero + animation.stop(); + animation.setRate(1.7); + assertAnimation(1.7, 0.0, Status.STOPPED, false); + animation.play(); + assertAnimation(1.7, 1.7, Status.RUNNING, true); + } + + @Test + public void testSetRateToZeroForRunningAnimation() { + // changing the rate of a playing animation + animation.play(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + animation.setRate(3.0); + assertAnimation(3.0, 3.0, Status.RUNNING, true); + + // toggling a playing animation + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + animation.setRate(-2.0); + assertAnimation(-2.0, -2.0, Status.RUNNING, true); + + // changing the rate + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + animation.setRate(-2.5); + assertAnimation(-2.5, -2.5, Status.RUNNING, true); + + // toggling back + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + animation.setRate(1.5); + assertAnimation(1.5, 1.5, Status.RUNNING, true); + + // changing the rate of a animation playing in reverse + animation.impl_setCurrentRate(-1.5); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + animation.setRate(2.2); + assertAnimation(2.2, -2.2, Status.RUNNING, true); + + // toggling a animation playing in reverse + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + animation.setRate(-1.8); + assertAnimation(-1.8, 1.8, Status.RUNNING, true); + + // changing the rate + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + animation.setRate(-1.3); + assertAnimation(-1.3, 1.3, Status.RUNNING, true); + + // toggling back + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + animation.setRate(0.5); + assertAnimation(0.5, -0.5, Status.RUNNING, true); + } + + @Test + public void testSetRateOfPausedAnimation() { + // changing the rate of a paused animation + animation.play(); + animation.pause(); + animation.setRate(3.0); + assertAnimation(3.0, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(3.0, 3.0, Status.RUNNING, true); + + // toggling a pausing animation + animation.pause(); + animation.setRate(-2.0); + assertAnimation(-2.0, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(-2.0, -2.0, Status.RUNNING, true); + + // changing the rate + animation.pause(); + animation.setRate(-2.5); + assertAnimation(-2.5, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(-2.5, -2.5, Status.RUNNING, true); + + // toggling back + animation.pause(); + animation.setRate(1.5); + assertAnimation(1.5, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(1.5, 1.5, Status.RUNNING, true); + + // changing the rate of a paused animation pointing in reverse + animation.impl_setCurrentRate(-1.5); + animation.pause(); + animation.setRate(2.2); + assertAnimation(2.2, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(2.2, -2.2, Status.RUNNING, true); + + // toggling a paused playing pointing in reverse + animation.pause(); + animation.setRate(-1.8); + assertAnimation(-1.8, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(-1.8, 1.8, Status.RUNNING, true); + + // changing the rate + animation.pause(); + animation.setRate(-1.3); + assertAnimation(-1.3, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(-1.3, 1.3, Status.RUNNING, true); + + // toggling back + animation.pause(); + animation.setRate(0.5); + assertAnimation(0.5, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(0.5, -0.5, Status.RUNNING, true); + } + + @Test + public void testSetRateToZeroForPausedAnimation() { + // starting a paused animation with rate 0 + animation.play(); + animation.pause(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(0.0, 0.0, Status.RUNNING, false); + + // changing the rate of a paused animation + animation.pause(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.PAUSED, false); + animation.setRate(3.0); + assertAnimation(3.0, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(3.0, 3.0, Status.RUNNING, true); + + // toggling a paused animation + animation.pause(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.PAUSED, false); + animation.setRate(-2.0); + assertAnimation(-2.0, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(-2.0, -2.0, Status.RUNNING, true); + + // changing the rate + animation.pause(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.PAUSED, false); + animation.setRate(-2.5); + assertAnimation(-2.5, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(-2.5, -2.5, Status.RUNNING, true); + + // toggling back + animation.pause(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.PAUSED, false); + animation.setRate(1.5); + assertAnimation(1.5, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(1.5, 1.5, Status.RUNNING, true); + + // changing the rate of a paused animation pointing in reverse + animation.impl_setCurrentRate(-1.5); + animation.pause(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.PAUSED, false); + animation.setRate(2.2); + assertAnimation(2.2, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(2.2, -2.2, Status.RUNNING, true); + + // toggling a paused animation pointing in reverse + animation.pause(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.PAUSED, false); + animation.setRate(-1.8); + assertAnimation(-1.8, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(-1.8, 1.8, Status.RUNNING, true); + + // changing the rate + animation.pause(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.PAUSED, false); + animation.setRate(-1.3); + assertAnimation(-1.3, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(-1.3, 1.3, Status.RUNNING, true); + + // toggling back + animation.pause(); + animation.setRate(0.0); + assertAnimation(0.0, 0.0, Status.PAUSED, false); + animation.setRate(0.5); + assertAnimation(0.5, 0.0, Status.PAUSED, false); + animation.play(); + assertAnimation(0.5, -0.5, Status.RUNNING, true); + } +} --- old/modules/graphics/src/test/java/javafx/animation/AnimationTest.java 2015-09-11 21:25:18.097286386 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,617 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; - -import com.sun.javafx.tk.Toolkit; -import javafx.animation.Animation.Status; -import javafx.event.ActionEvent; -import javafx.event.EventHandler; -import javafx.util.Duration; -import com.sun.scenario.animation.AbstractMasterTimerMock; -import com.sun.scenario.animation.shared.ClipEnvelopeMock; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class AnimationTest { - - private static final Duration ONE_SEC = Duration.millis(1000); - private static final Duration TWO_SECS = Duration.millis(2000); - private static final Duration THREE_SECS = Duration.millis(3000); - private static final Duration FOUR_SECS = Duration.millis(4000); - - private static final double DEFAULT_RATE = 1.0; - private static final int DEFAULT_REPEAT_COUNT = 1; - private static final boolean DEFAULT_AUTO_REVERSE = false; - - private static final double EPSILON = 1e-12; - - private AbstractMasterTimerMock timer; - private Animation animation; - private ClipEnvelopeMock clipEnvelope; - - @Before - public void setUp() { - timer = new AbstractMasterTimerMock(); - clipEnvelope = new ClipEnvelopeMock(); - animation = new AnimationImpl(timer, clipEnvelope, 1); - animation.setCycleDuration(ONE_SEC); - clipEnvelope.setAnimation(animation); - } - - @After - public void tearDown() { - animation.stop(); - } - - @Test - public void testConstructors() { - final Animation animation0 = new AnimationImpl(); - assertEquals(DEFAULT_RATE, animation0.getRate(), EPSILON); - assertEquals(0.0, animation0.getCurrentRate(), EPSILON); - assertEquals(Duration.ZERO, animation0.getCycleDuration()); - assertEquals(Duration.ZERO, animation0.getTotalDuration()); - assertEquals(Duration.ZERO, animation0.getCurrentTime()); - assertEquals(DEFAULT_REPEAT_COUNT, animation0.getCycleCount()); - assertEquals(DEFAULT_AUTO_REVERSE, animation0.isAutoReverse()); - assertEquals(Status.STOPPED, animation0.getStatus()); - assertEquals(6000.0 / Toolkit.getToolkit().getMasterTimer().getDefaultResolution(), animation0.getTargetFramerate(), EPSILON); - assertEquals(null, animation0.getOnFinished()); - assertEquals(0, animation0.getCuePoints().size()); - - final Animation animation1 = new AnimationImpl(timer, clipEnvelope, 600); - assertEquals(10.0, animation1.getTargetFramerate(), EPSILON); - } - - @Test - public void testReadOnlyProperties() { - // currentRate - assertEquals("currentRate", animation.currentRateProperty().getName()); - assertEquals(animation, animation.currentRateProperty().getBean()); - - // cycleDuration - assertEquals("cycleDuration", animation.cycleDurationProperty().getName()); - assertEquals(animation, animation.cycleDurationProperty().getBean()); - - // totalDuration - assertEquals("totalDuration", animation.totalDurationProperty().getName()); - assertEquals(animation, animation.totalDurationProperty().getBean()); - - // currentTime - assertEquals("currentTime", animation.currentTimeProperty().getName()); - assertEquals(animation, animation.currentTimeProperty().getBean()); - - // status - assertEquals("status", animation.statusProperty().getName()); - assertEquals(animation, animation.statusProperty().getBean()); - - } - - @Test - public void testCalculationOfTotalDuration() { - // 1000ms - assertEquals(ONE_SEC, animation.getTotalDuration()); - animation.setCycleCount(0); - assertEquals(ONE_SEC, animation.getTotalDuration()); - animation.setCycleCount(7); - assertEquals(ONE_SEC.multiply(7), animation.getTotalDuration()); - animation.setCycleCount(Animation.INDEFINITE); - assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); - animation.setCycleCount(1); - - // Duration.ZERO - animation.setCycleDuration(Duration.ZERO); - assertEquals(Duration.ZERO, animation.getTotalDuration()); - animation.setCycleCount(0); - assertEquals(Duration.ZERO, animation.getTotalDuration()); - animation.setCycleCount(7); - assertEquals(Duration.ZERO, animation.getTotalDuration()); - animation.setCycleCount(Animation.INDEFINITE); - assertEquals(Duration.ZERO, animation.getTotalDuration()); - animation.setCycleCount(1); - - // Duration.INDEFINITE - animation.setCycleDuration(Duration.INDEFINITE); - assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); - animation.setCycleCount(0); - assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); - animation.setCycleCount(7); - assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); - animation.setCycleCount(Animation.INDEFINITE); - assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); - animation.setCycleCount(1); - } - - @Test - public void testDecreaseTotalDuration() { - animation.jumpTo(ONE_SEC); - animation.setCycleDuration(ONE_SEC.divide(2)); - assertEquals(ONE_SEC.divide(2), animation.getCurrentTime()); - animation.setCycleDuration(Duration.ZERO); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - } - - @Test - public void testJumpTo() { - animation.setCycleDuration(TWO_SECS); - - // cycleCount = 1 - animation.jumpTo(ONE_SEC); - assertEquals(ONE_SEC, animation.getCurrentTime()); - assertEquals(6000, clipEnvelope.getLastJumpTo()); - animation.jumpTo(TWO_SECS); - assertEquals(TWO_SECS, animation.getCurrentTime()); - assertEquals(12000, clipEnvelope.getLastJumpTo()); - animation.jumpTo(Duration.ZERO); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertEquals(0, clipEnvelope.getLastJumpTo()); - animation.jumpTo(TWO_SECS.add(Duration.ONE)); - assertEquals(TWO_SECS, animation.getCurrentTime()); - assertEquals(12000, clipEnvelope.getLastJumpTo()); - animation.jumpTo(Duration.ONE.negate()); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertEquals(0, clipEnvelope.getLastJumpTo()); - - // cycleCount = 2 - animation.setCycleCount(2); - animation.jumpTo(ONE_SEC); - assertEquals(ONE_SEC, animation.getCurrentTime()); - assertEquals(6000, clipEnvelope.getLastJumpTo()); - animation.jumpTo(TWO_SECS); - assertEquals(TWO_SECS, animation.getCurrentTime()); - assertEquals(12000, clipEnvelope.getLastJumpTo()); - animation.jumpTo(THREE_SECS); - assertEquals(ONE_SEC, animation.getCurrentTime()); - assertEquals(18000, clipEnvelope.getLastJumpTo()); - animation.jumpTo(FOUR_SECS); - assertEquals(TWO_SECS, animation.getCurrentTime()); - assertEquals(24000, clipEnvelope.getLastJumpTo()); - animation.jumpTo(Duration.ZERO); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertEquals(0, clipEnvelope.getLastJumpTo()); - animation.jumpTo(FOUR_SECS.add(Duration.ONE)); - assertEquals(TWO_SECS, animation.getCurrentTime()); - assertEquals(24000, clipEnvelope.getLastJumpTo()); - animation.jumpTo(Duration.ONE.negate()); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertEquals(0, clipEnvelope.getLastJumpTo()); - } - - @Test - public void testJumpTo_ZeroLengthAnimation() { - animation.setCycleDuration(Duration.ZERO); - - // cycleCount = 1 - animation.jumpTo(Duration.ZERO); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertEquals(0, clipEnvelope.getLastJumpTo()); - animation.jumpTo(ONE_SEC); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertEquals(0, clipEnvelope.getLastJumpTo()); - - // cycleCount = 2 - animation.setCycleCount(2); - animation.jumpTo(Duration.ZERO); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertEquals(0, clipEnvelope.getLastJumpTo()); - animation.jumpTo(ONE_SEC); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertEquals(0, clipEnvelope.getLastJumpTo()); - } - - @Test - public void testDurationRoundingError() { - final Duration duration = Duration.millis(0.01); - animation.setCycleDuration(duration); - assertTrue(animation.getCycleDuration().greaterThan(Duration.ZERO)); - - // should not be startable - assertFalse(animation.impl_startable(true)); - - // jump - animation.jumpTo(Duration.ZERO); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertEquals(0, clipEnvelope.getLastJumpTo()); - } - - @Test(expected=NullPointerException.class) - public void testJumpTo_Null() { - animation.jumpTo((Duration)null); - } - - @Test(expected=IllegalArgumentException.class) - public void testJumpTo_UNKNOWN() { - animation.jumpTo(Duration.UNKNOWN); - } - - @Test - public void testJumpToCuePoint_Default() { - animation.getCuePoints().put("ONE_SEC", ONE_SEC); - animation.getCuePoints().put("THREE_SECS", THREE_SECS); - animation.setCycleDuration(TWO_SECS); - - // normal jumps - animation.jumpTo("end"); - assertEquals(TWO_SECS, animation.getCurrentTime()); - animation.jumpTo("start"); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - animation.jumpTo("ONE_SEC"); - assertEquals(ONE_SEC, animation.getCurrentTime()); - - // jump to non-existing cue-point - animation.jumpTo("undefined"); - assertEquals(ONE_SEC, animation.getCurrentTime()); - - // jump to cue-point behind end of animation - animation.jumpTo("THREE_SECS"); - assertEquals(TWO_SECS, animation.getCurrentTime()); - } - - @Test - public void testJumpToCuePoint_ZeroLengthAnimation() { - animation.getCuePoints().put("ONE_SEC", ONE_SEC); - animation.setCycleDuration(Duration.ZERO); - - animation.jumpTo("start"); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - animation.jumpTo("end"); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - animation.jumpTo("ONE_SEC"); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - } - - @Test(expected=NullPointerException.class) - public void testJumpToCuePoint_Null() { - animation.jumpTo((String)null); - } - - @Test - public void testPlay() { - final OnFinishedListener listener = new OnFinishedListener(); - animation.setOnFinished(listener); - - // stopped timeline - listener.wasCalled = false; - animation.play(); - assertEquals(Status.RUNNING, animation.getStatus()); - assertFalse(listener.wasCalled); - assertTrue(timer.containsPulseReceiver(animation.pulseReceiver)); - - // calling play on playing timeline - animation.play(); - assertEquals(Status.RUNNING, animation.getStatus()); - assertFalse(listener.wasCalled); - assertTrue(timer.containsPulseReceiver(animation.pulseReceiver)); - animation.stop(); - - // stopped timeline, rate = 0 - listener.wasCalled = false; - animation.setRate(0.0); - animation.play(); - assertEquals(Status.RUNNING, animation.getStatus()); - assertFalse(listener.wasCalled); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - animation.stop(); - animation.setRate(1.0); - - // stopped timeline, cycleDuration = 0 - listener.wasCalled = false; - animation.setCycleDuration(Duration.ZERO); - animation.play(); - assertEquals(Status.STOPPED, animation.getStatus()); - assertTrue(listener.wasCalled); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - animation.stop(); - animation.setCycleDuration(ONE_SEC); - - // paused timeline - animation.play(); - animation.pause(); - animation.play(); - assertEquals(Status.RUNNING, animation.getStatus()); - assertTrue(timer.containsPulseReceiver(animation.pulseReceiver)); - animation.stop(); - - // paused timeline, rate = 0 - animation.play(); - animation.pause(); - animation.setRate(0.0); - animation.play(); - assertEquals(Status.RUNNING, animation.getStatus()); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - } - - @Test - public void testStop() { - // stopped timeline - animation.jumpTo(ONE_SEC); - animation.stop(); - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertEquals(ONE_SEC, animation.getCurrentTime()); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - - // playing timeline - animation.jumpTo(ONE_SEC); - animation.play(); - animation.stop(); - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - - // paused timeline - animation.jumpTo(ONE_SEC); - animation.play(); - animation.pause(); - animation.stop(); - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - } - - @Test - public void testPause() { - // stopped timeline - animation.jumpTo(ONE_SEC); - animation.pause(); - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - - // playing timeline - animation.jumpTo(ONE_SEC); - animation.play(); - animation.pause(); - assertEquals(Status.PAUSED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - - // paused timeline - animation.jumpTo(ONE_SEC); - animation.play(); - animation.pause(); - animation.pause(); - assertEquals(Status.PAUSED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertFalse(timer.containsPulseReceiver(animation.pulseReceiver)); - } - - @Test - public void testStart() { - // cycleDuration = 1000ms - assertTrue(animation.impl_startable(true)); - animation.impl_start(true); - assertEquals(Status.RUNNING, animation.getStatus()); - assertEquals(1.0, animation.getCurrentRate(), EPSILON); - assertEquals(6000, clipEnvelope.getTimelineTicks()); - assertEquals(1.0, clipEnvelope.getRate(), EPSILON); - assertEquals(false, clipEnvelope.getAutoReverse()); - assertEquals(1, clipEnvelope.getCycleCount()); - animation.impl_finished(); - - // change all values and try again - animation.setCycleDuration(TWO_SECS); - animation.setRate(-2.0); - animation.setAutoReverse(true); - animation.setCycleCount(Animation.INDEFINITE); - assertTrue(animation.impl_startable(true)); - animation.impl_start(true); - assertEquals(Status.RUNNING, animation.getStatus()); - assertEquals(-2.0, animation.getCurrentRate(), EPSILON); - assertEquals(12000, clipEnvelope.getTimelineTicks()); - assertEquals(-2.0, clipEnvelope.getRate(), EPSILON); - assertEquals(true, clipEnvelope.getAutoReverse()); - assertEquals(Animation.INDEFINITE, clipEnvelope.getCycleCount()); - animation.impl_finished(); - - // cycleDuration = 0 - animation.setCycleDuration(Duration.ZERO); - assertFalse(animation.impl_startable(true)); - } - - @Test - public void testChangeCycleDurationAfterFinish_RT32657() { - animation.setCycleDuration(TWO_SECS); - animation.play(); - assertEquals(Status.RUNNING, animation.getStatus()); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - animation.impl_setCurrentTicks(12000); - assertEquals(TWO_SECS, animation.getCurrentTime()); - animation.impl_finished(); - - animation.setCycleDuration(ONE_SEC); - animation.play(); - assertEquals(Status.RUNNING, animation.getStatus()); - assertEquals(Duration.ZERO, animation.getCurrentTime()); - } - - @Test - public void testFinished() { - final OnFinishedListener listener = new OnFinishedListener(); - animation.setOnFinished(listener); - - // stopped timeline - animation.impl_finished(); - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertTrue(listener.wasCalled); - - // playing timeline - animation.play(); - animation.impl_finished(); - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertTrue(listener.wasCalled); - - // paused timeline - animation.play(); - animation.pause(); - animation.impl_finished(); - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertTrue(listener.wasCalled); - } - - @Test - public void testFinished_ThrowsException() { - final OnFinishedExceptionListener listener = new OnFinishedExceptionListener(); - final PrintStream defaultErrorStream = System.err; - final PrintStream nirvana = new PrintStream(new OutputStream() { - @Override - public void write(int i) throws IOException { - } - }); - animation.setOnFinished(listener); - - // stopped timeline - try { - System.setErr(nirvana); - } catch (SecurityException ex) { - // ignore - } - animation.impl_finished(); - try { - System.setErr(defaultErrorStream); - } catch (SecurityException ex) { - // ignore - } - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertTrue(listener.wasCalled); - - // playing timeline - animation.play(); - try { - System.setErr(nirvana); - } catch (SecurityException ex) { - // ignore - } - animation.impl_finished(); - try { - System.setErr(defaultErrorStream); - } catch (SecurityException ex) { - // ignore - } - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertTrue(listener.wasCalled); - - // paused timeline - animation.play(); - animation.pause(); - try { - System.setErr(nirvana); - } catch (SecurityException ex) { - // ignore - } - animation.impl_finished(); - try { - System.setErr(defaultErrorStream); - } catch (SecurityException ex) { - // ignore - } - assertEquals(Status.STOPPED, animation.getStatus()); - assertEquals(0.0, animation.getCurrentRate(), EPSILON); - assertTrue(listener.wasCalled); - } - - @Test - public void testFullSpeedResolution() { - final int resolution = Toolkit.getToolkit().getMasterTimer().getDefaultResolution(); - - // send pulse - animation.impl_timePulse(4 * resolution); - assertEquals(4 * resolution, clipEnvelope.getLastTimePulse()); - - // send half pulse - animation.impl_timePulse(Math.round(4.5 * resolution)); - assertEquals(Math.round(4.5 * resolution), clipEnvelope.getLastTimePulse()); - - // send full pulse - animation.impl_timePulse(Math.round(5.5 * resolution)); - assertEquals(Math.round(5.5 * resolution), clipEnvelope.getLastTimePulse()); - - // send half pulse - animation.impl_timePulse(6 * resolution); - assertEquals(6 * resolution, clipEnvelope.getLastTimePulse()); - - } - - @Test - public void testCustomResolution() { - final int resolution = 100; - animation = new AnimationImpl(timer, clipEnvelope, resolution); - - // send pulse - animation.impl_timePulse(4 * resolution); - assertEquals(4 * resolution, clipEnvelope.getLastTimePulse()); - - // send half pulse - animation.impl_timePulse(Math.round(4.5 * resolution)); - assertEquals(0, clipEnvelope.getLastTimePulse()); - - // send full pulse - animation.impl_timePulse(Math.round(5.5 * resolution)); - assertEquals(Math.round(5.5 * resolution), clipEnvelope.getLastTimePulse()); - - // send half pulse, this time it should trigger a pulse - animation.impl_timePulse(6 * resolution); - assertEquals(6 * resolution, clipEnvelope.getLastTimePulse()); - - } - - private static class OnFinishedListener implements EventHandler { - - private boolean wasCalled = false; - - @Override - public void handle(ActionEvent event) { - wasCalled = true; - } - - } - - private static class OnFinishedExceptionListener implements EventHandler { - - private boolean wasCalled = false; - - @Override - public void handle(ActionEvent event) { - wasCalled = true; - throw new RuntimeException("Test Exception"); - } - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/AnimationTest.java 2015-09-11 21:25:17.961286388 -0400 @@ -0,0 +1,618 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import com.sun.javafx.tk.Toolkit; +import test.com.sun.scenario.animation.shared.ClipEnvelopeMock; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import javafx.animation.Animation; +import javafx.animation.Animation.Status; +import javafx.event.ActionEvent; +import javafx.event.EventHandler; +import javafx.util.Duration; +import org.junit.After; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; + +public class AnimationTest { + + private static final Duration ONE_SEC = Duration.millis(1000); + private static final Duration TWO_SECS = Duration.millis(2000); + private static final Duration THREE_SECS = Duration.millis(3000); + private static final Duration FOUR_SECS = Duration.millis(4000); + + private static final double DEFAULT_RATE = 1.0; + private static final int DEFAULT_REPEAT_COUNT = 1; + private static final boolean DEFAULT_AUTO_REVERSE = false; + + private static final double EPSILON = 1e-12; + + private AbstractMasterTimerMock timer; + private AnimationImpl animation; + private ClipEnvelopeMock clipEnvelope; + + @Before + public void setUp() { + timer = new AbstractMasterTimerMock(); + clipEnvelope = new ClipEnvelopeMock(); + animation = new AnimationImpl(timer, clipEnvelope, 1); + animation.shim_setCycleDuration(ONE_SEC); + clipEnvelope.setAnimation(animation); + } + + @After + public void tearDown() { + animation.stop(); + } + + @Test + public void testConstructors() { + final Animation animation0 = new AnimationImpl(); + assertEquals(DEFAULT_RATE, animation0.getRate(), EPSILON); + assertEquals(0.0, animation0.getCurrentRate(), EPSILON); + assertEquals(Duration.ZERO, animation0.getCycleDuration()); + assertEquals(Duration.ZERO, animation0.getTotalDuration()); + assertEquals(Duration.ZERO, animation0.getCurrentTime()); + assertEquals(DEFAULT_REPEAT_COUNT, animation0.getCycleCount()); + assertEquals(DEFAULT_AUTO_REVERSE, animation0.isAutoReverse()); + assertEquals(Status.STOPPED, animation0.getStatus()); + assertEquals(6000.0 / Toolkit.getToolkit().getMasterTimer().getDefaultResolution(), animation0.getTargetFramerate(), EPSILON); + assertEquals(null, animation0.getOnFinished()); + assertEquals(0, animation0.getCuePoints().size()); + + final Animation animation1 = new AnimationImpl(timer, clipEnvelope, 600); + assertEquals(10.0, animation1.getTargetFramerate(), EPSILON); + } + + @Test + public void testReadOnlyProperties() { + // currentRate + assertEquals("currentRate", animation.currentRateProperty().getName()); + assertEquals(animation, animation.currentRateProperty().getBean()); + + // cycleDuration + assertEquals("cycleDuration", animation.cycleDurationProperty().getName()); + assertEquals(animation, animation.cycleDurationProperty().getBean()); + + // totalDuration + assertEquals("totalDuration", animation.totalDurationProperty().getName()); + assertEquals(animation, animation.totalDurationProperty().getBean()); + + // currentTime + assertEquals("currentTime", animation.currentTimeProperty().getName()); + assertEquals(animation, animation.currentTimeProperty().getBean()); + + // status + assertEquals("status", animation.statusProperty().getName()); + assertEquals(animation, animation.statusProperty().getBean()); + + } + + @Test + public void testCalculationOfTotalDuration() { + // 1000ms + assertEquals(ONE_SEC, animation.getTotalDuration()); + animation.setCycleCount(0); + assertEquals(ONE_SEC, animation.getTotalDuration()); + animation.setCycleCount(7); + assertEquals(ONE_SEC.multiply(7), animation.getTotalDuration()); + animation.setCycleCount(Animation.INDEFINITE); + assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); + animation.setCycleCount(1); + + // Duration.ZERO + animation.shim_setCycleDuration(Duration.ZERO); + assertEquals(Duration.ZERO, animation.getTotalDuration()); + animation.setCycleCount(0); + assertEquals(Duration.ZERO, animation.getTotalDuration()); + animation.setCycleCount(7); + assertEquals(Duration.ZERO, animation.getTotalDuration()); + animation.setCycleCount(Animation.INDEFINITE); + assertEquals(Duration.ZERO, animation.getTotalDuration()); + animation.setCycleCount(1); + + // Duration.INDEFINITE + animation.shim_setCycleDuration(Duration.INDEFINITE); + assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); + animation.setCycleCount(0); + assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); + animation.setCycleCount(7); + assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); + animation.setCycleCount(Animation.INDEFINITE); + assertEquals(Duration.INDEFINITE, animation.getTotalDuration()); + animation.setCycleCount(1); + } + + @Test + public void testDecreaseTotalDuration() { + animation.jumpTo(ONE_SEC); + animation.shim_setCycleDuration(ONE_SEC.divide(2)); + assertEquals(ONE_SEC.divide(2), animation.getCurrentTime()); + animation.shim_setCycleDuration(Duration.ZERO); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + } + + @Test + public void testJumpTo() { + animation.shim_setCycleDuration(TWO_SECS); + assertEquals(TWO_SECS,animation.getCycleDuration()); + + // cycleCount = 1 + animation.jumpTo(ONE_SEC); + assertEquals(ONE_SEC, animation.getCurrentTime()); + assertEquals(6000, clipEnvelope.getLastJumpTo()); + animation.jumpTo(TWO_SECS); + assertEquals(TWO_SECS, animation.getCurrentTime()); + assertEquals(12000, clipEnvelope.getLastJumpTo()); + animation.jumpTo(Duration.ZERO); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertEquals(0, clipEnvelope.getLastJumpTo()); + animation.jumpTo(TWO_SECS.add(Duration.ONE)); + assertEquals(TWO_SECS, animation.getCurrentTime()); + assertEquals(12000, clipEnvelope.getLastJumpTo()); + animation.jumpTo(Duration.ONE.negate()); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertEquals(0, clipEnvelope.getLastJumpTo()); + + // cycleCount = 2 + animation.setCycleCount(2); + animation.jumpTo(ONE_SEC); + assertEquals(ONE_SEC, animation.getCurrentTime()); + assertEquals(6000, clipEnvelope.getLastJumpTo()); + animation.jumpTo(TWO_SECS); + assertEquals(TWO_SECS, animation.getCurrentTime()); + assertEquals(12000, clipEnvelope.getLastJumpTo()); + animation.jumpTo(THREE_SECS); + assertEquals(ONE_SEC, animation.getCurrentTime()); + assertEquals(18000, clipEnvelope.getLastJumpTo()); + animation.jumpTo(FOUR_SECS); + assertEquals(TWO_SECS, animation.getCurrentTime()); + assertEquals(24000, clipEnvelope.getLastJumpTo()); + animation.jumpTo(Duration.ZERO); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertEquals(0, clipEnvelope.getLastJumpTo()); + animation.jumpTo(FOUR_SECS.add(Duration.ONE)); + assertEquals(TWO_SECS, animation.getCurrentTime()); + assertEquals(24000, clipEnvelope.getLastJumpTo()); + animation.jumpTo(Duration.ONE.negate()); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertEquals(0, clipEnvelope.getLastJumpTo()); + } + + @Test + public void testJumpTo_ZeroLengthAnimation() { + animation.shim_setCycleDuration(Duration.ZERO); + + // cycleCount = 1 + animation.jumpTo(Duration.ZERO); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertEquals(0, clipEnvelope.getLastJumpTo()); + animation.jumpTo(ONE_SEC); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertEquals(0, clipEnvelope.getLastJumpTo()); + + // cycleCount = 2 + animation.setCycleCount(2); + animation.jumpTo(Duration.ZERO); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertEquals(0, clipEnvelope.getLastJumpTo()); + animation.jumpTo(ONE_SEC); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertEquals(0, clipEnvelope.getLastJumpTo()); + } + + @Test + public void testDurationRoundingError() { + final Duration duration = Duration.millis(0.01); + animation.shim_setCycleDuration(duration); + assertTrue(animation.getCycleDuration().greaterThan(Duration.ZERO)); + + // should not be startable + assertFalse(animation.impl_startable(true)); + + // jump + animation.jumpTo(Duration.ZERO); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertEquals(0, clipEnvelope.getLastJumpTo()); + } + + @Test(expected=NullPointerException.class) + public void testJumpTo_Null() { + animation.jumpTo((Duration)null); + } + + @Test(expected=IllegalArgumentException.class) + public void testJumpTo_UNKNOWN() { + animation.jumpTo(Duration.UNKNOWN); + } + + @Test + public void testJumpToCuePoint_Default() { + animation.getCuePoints().put("ONE_SEC", ONE_SEC); + animation.getCuePoints().put("THREE_SECS", THREE_SECS); + animation.shim_setCycleDuration(TWO_SECS); + + // normal jumps + animation.jumpTo("end"); + assertEquals(TWO_SECS, animation.getCurrentTime()); + animation.jumpTo("start"); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + animation.jumpTo("ONE_SEC"); + assertEquals(ONE_SEC, animation.getCurrentTime()); + + // jump to non-existing cue-point + animation.jumpTo("undefined"); + assertEquals(ONE_SEC, animation.getCurrentTime()); + + // jump to cue-point behind end of animation + animation.jumpTo("THREE_SECS"); + assertEquals(TWO_SECS, animation.getCurrentTime()); + } + + @Test + public void testJumpToCuePoint_ZeroLengthAnimation() { + animation.getCuePoints().put("ONE_SEC", ONE_SEC); + animation.shim_setCycleDuration(Duration.ZERO); + + animation.jumpTo("start"); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + animation.jumpTo("end"); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + animation.jumpTo("ONE_SEC"); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + } + + @Test(expected=NullPointerException.class) + public void testJumpToCuePoint_Null() { + animation.jumpTo((String)null); + } + + @Test + public void testPlay() { + final OnFinishedListener listener = new OnFinishedListener(); + animation.setOnFinished(listener); + + // stopped timeline + listener.wasCalled = false; + animation.play(); + assertEquals(Status.RUNNING, animation.getStatus()); + assertFalse(listener.wasCalled); + assertTrue(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // calling play on playing timeline + animation.play(); + assertEquals(Status.RUNNING, animation.getStatus()); + assertFalse(listener.wasCalled); + assertTrue(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + animation.stop(); + + // stopped timeline, rate = 0 + listener.wasCalled = false; + animation.setRate(0.0); + animation.play(); + assertEquals(Status.RUNNING, animation.getStatus()); + assertFalse(listener.wasCalled); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + animation.stop(); + animation.setRate(1.0); + + // stopped timeline, cycleDuration = 0 + listener.wasCalled = false; + animation.shim_setCycleDuration(Duration.ZERO); + animation.play(); + assertEquals(Status.STOPPED, animation.getStatus()); + assertTrue(listener.wasCalled); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + animation.stop(); + animation.shim_setCycleDuration(ONE_SEC); + + // paused timeline + animation.play(); + animation.pause(); + animation.play(); + assertEquals(Status.RUNNING, animation.getStatus()); + assertTrue(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + animation.stop(); + + // paused timeline, rate = 0 + animation.play(); + animation.pause(); + animation.setRate(0.0); + animation.play(); + assertEquals(Status.RUNNING, animation.getStatus()); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + } + + @Test + public void testStop() { + // stopped timeline + animation.jumpTo(ONE_SEC); + animation.stop(); + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertEquals(ONE_SEC, animation.getCurrentTime()); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // playing timeline + animation.jumpTo(ONE_SEC); + animation.play(); + animation.stop(); + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // paused timeline + animation.jumpTo(ONE_SEC); + animation.play(); + animation.pause(); + animation.stop(); + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + } + + @Test + public void testPause() { + // stopped timeline + animation.jumpTo(ONE_SEC); + animation.pause(); + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // playing timeline + animation.jumpTo(ONE_SEC); + animation.play(); + animation.pause(); + assertEquals(Status.PAUSED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + + // paused timeline + animation.jumpTo(ONE_SEC); + animation.play(); + animation.pause(); + animation.pause(); + assertEquals(Status.PAUSED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertFalse(timer.containsPulseReceiver(animation.shim_pulseReceiver())); + } + + @Test + public void testStart() { + // cycleDuration = 1000ms + assertTrue(animation.impl_startable(true)); + animation.impl_start(true); + assertEquals(Status.RUNNING, animation.getStatus()); + assertEquals(1.0, animation.getCurrentRate(), EPSILON); + assertEquals(6000, clipEnvelope.getTimelineTicks()); + assertEquals(1.0, clipEnvelope.getRate(), EPSILON); + assertEquals(false, clipEnvelope.getAutoReverse()); + assertEquals(1, clipEnvelope.getCycleCount()); + animation.shim_impl_finished(); + + // change all values and try again + animation.shim_setCycleDuration(TWO_SECS); + animation.setRate(-2.0); + animation.setAutoReverse(true); + animation.setCycleCount(Animation.INDEFINITE); + assertTrue(animation.impl_startable(true)); + animation.impl_start(true); + assertEquals(Status.RUNNING, animation.getStatus()); + assertEquals(-2.0, animation.getCurrentRate(), EPSILON); + assertEquals(12000, clipEnvelope.getTimelineTicks()); + assertEquals(-2.0, clipEnvelope.getRate(), EPSILON); + assertEquals(true, clipEnvelope.getAutoReverse()); + assertEquals(Animation.INDEFINITE, clipEnvelope.getCycleCount()); + animation.shim_impl_finished(); + + // cycleDuration = 0 + animation.shim_setCycleDuration(Duration.ZERO); + assertFalse(animation.impl_startable(true)); + } + + @Test + public void testChangeCycleDurationAfterFinish_RT32657() { + animation.shim_setCycleDuration(TWO_SECS); + animation.play(); + assertEquals(Status.RUNNING, animation.getStatus()); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + animation.impl_setCurrentTicks(12000); + assertEquals(TWO_SECS, animation.getCurrentTime()); + animation.shim_impl_finished(); + + animation.shim_setCycleDuration(ONE_SEC); + animation.play(); + assertEquals(Status.RUNNING, animation.getStatus()); + assertEquals(Duration.ZERO, animation.getCurrentTime()); + } + + @Test + public void testFinished() { + final OnFinishedListener listener = new OnFinishedListener(); + animation.setOnFinished(listener); + + // stopped timeline + animation.shim_impl_finished(); + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertTrue(listener.wasCalled); + + // playing timeline + animation.play(); + animation.shim_impl_finished(); + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertTrue(listener.wasCalled); + + // paused timeline + animation.play(); + animation.pause(); + animation.shim_impl_finished(); + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertTrue(listener.wasCalled); + } + + @Test + public void testFinished_ThrowsException() { + final OnFinishedExceptionListener listener = new OnFinishedExceptionListener(); + final PrintStream defaultErrorStream = System.err; + final PrintStream nirvana = new PrintStream(new OutputStream() { + @Override + public void write(int i) throws IOException { + } + }); + animation.setOnFinished(listener); + + // stopped timeline + try { + System.setErr(nirvana); + } catch (SecurityException ex) { + // ignore + } + animation.shim_impl_finished(); + try { + System.setErr(defaultErrorStream); + } catch (SecurityException ex) { + // ignore + } + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertTrue(listener.wasCalled); + + // playing timeline + animation.play(); + try { + System.setErr(nirvana); + } catch (SecurityException ex) { + // ignore + } + animation.shim_impl_finished(); + try { + System.setErr(defaultErrorStream); + } catch (SecurityException ex) { + // ignore + } + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertTrue(listener.wasCalled); + + // paused timeline + animation.play(); + animation.pause(); + try { + System.setErr(nirvana); + } catch (SecurityException ex) { + // ignore + } + animation.shim_impl_finished(); + try { + System.setErr(defaultErrorStream); + } catch (SecurityException ex) { + // ignore + } + assertEquals(Status.STOPPED, animation.getStatus()); + assertEquals(0.0, animation.getCurrentRate(), EPSILON); + assertTrue(listener.wasCalled); + } + + @Test + public void testFullSpeedResolution() { + final int resolution = Toolkit.getToolkit().getMasterTimer().getDefaultResolution(); + + // send pulse + animation.impl_timePulse(4 * resolution); + assertEquals(4 * resolution, clipEnvelope.getLastTimePulse()); + + // send half pulse + animation.impl_timePulse(Math.round(4.5 * resolution)); + assertEquals(Math.round(4.5 * resolution), clipEnvelope.getLastTimePulse()); + + // send full pulse + animation.impl_timePulse(Math.round(5.5 * resolution)); + assertEquals(Math.round(5.5 * resolution), clipEnvelope.getLastTimePulse()); + + // send half pulse + animation.impl_timePulse(6 * resolution); + assertEquals(6 * resolution, clipEnvelope.getLastTimePulse()); + + } + + @Test + public void testCustomResolution() { + final int resolution = 100; + animation = new AnimationImpl(timer, clipEnvelope, resolution); + + // send pulse + animation.impl_timePulse(4 * resolution); + assertEquals(4 * resolution, clipEnvelope.getLastTimePulse()); + + // send half pulse + animation.impl_timePulse(Math.round(4.5 * resolution)); + assertEquals(0, clipEnvelope.getLastTimePulse()); + + // send full pulse + animation.impl_timePulse(Math.round(5.5 * resolution)); + assertEquals(Math.round(5.5 * resolution), clipEnvelope.getLastTimePulse()); + + // send half pulse, this time it should trigger a pulse + animation.impl_timePulse(6 * resolution); + assertEquals(6 * resolution, clipEnvelope.getLastTimePulse()); + + } + + private static class OnFinishedListener implements EventHandler { + + private boolean wasCalled = false; + + @Override + public void handle(ActionEvent event) { + wasCalled = true; + } + + } + + private static class OnFinishedExceptionListener implements EventHandler { + + private boolean wasCalled = false; + + @Override + public void handle(ActionEvent event) { + wasCalled = true; + throw new RuntimeException("Test Exception"); + } + + } + +} --- old/modules/graphics/src/test/java/javafx/animation/FadeTransitionTest.java 2015-09-11 21:25:18.781286379 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,434 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import javafx.scene.Node; -import javafx.scene.shape.Rectangle; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - -public class FadeTransitionTest { - - private static Duration DEFAULT_DURATION = Duration.millis(400); - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; - - private static double EPSILON = 1e-12; - private static Duration ONE_SEC = Duration.millis(1000); - private static Duration TWO_SECS = Duration.millis(2000); - - private Node node; - - @Before - public void setUp() { - node = new Rectangle(); - } - - @Test - public void testDefaultValues() { - // empty ctor - final FadeTransition t0 = new FadeTransition(); - assertEquals(DEFAULT_DURATION, t0.getDuration()); - assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); - assertTrue(Double.isNaN(t0.getFromValue())); - assertTrue(Double.isNaN(t0.getToValue())); - assertEquals(0.0, t0.getByValue(), EPSILON); - assertNull(t0.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration only - final FadeTransition t1 = new FadeTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.getDuration()); - assertTrue(Double.isNaN(t1.getFromValue())); - assertTrue(Double.isNaN(t1.getToValue())); - assertEquals(0.0, t1.getByValue(), EPSILON); - assertNull(t1.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); - assertNull(t1.getOnFinished()); - - // duration and node - final FadeTransition t2 = new FadeTransition(TWO_SECS, node); - assertEquals(TWO_SECS, t2.getDuration()); - assertTrue(Double.isNaN(t2.getFromValue())); - assertTrue(Double.isNaN(t2.getToValue())); - assertEquals(0.0, t2.getByValue(), EPSILON); - assertEquals(node, t2.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); - assertNull(t2.getOnFinished()); - } - - @Test - public void testDefaultValuesFromProperties() { - // empty ctor - final FadeTransition t0 = new FadeTransition(); - assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); - assertTrue(Double.isNaN(t0.fromValueProperty().get())); - assertTrue(Double.isNaN(t0.toValueProperty().get())); - assertEquals(0.0, t0.byValueProperty().get(), EPSILON); - assertNull(t0.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t0.interpolatorProperty().get()); - assertNull(t0.onFinishedProperty().get()); - - // duration only - final FadeTransition t1 = new FadeTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.durationProperty().get()); - assertTrue(Double.isNaN(t1.fromValueProperty().get())); - assertTrue(Double.isNaN(t1.toValueProperty().get())); - assertEquals(0.0, t1.byValueProperty().get(), EPSILON); - assertNull(t1.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t1.interpolatorProperty().get()); - assertNull(t1.onFinishedProperty().get()); - - // duration and node - final FadeTransition t2 = new FadeTransition(TWO_SECS, node); - assertEquals(TWO_SECS, t2.durationProperty().get()); - assertTrue(Double.isNaN(t2.fromValueProperty().get())); - assertTrue(Double.isNaN(t2.toValueProperty().get())); - assertEquals(0.0, t2.byValueProperty().get(), EPSILON); - assertEquals(node, t2.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t2.interpolatorProperty().get()); - assertNull(t2.onFinishedProperty().get()); - } - - @Test - public void testInterpolate() { - final FadeTransition t0 = new FadeTransition(ONE_SEC, node); - t0.setFromValue(0.5); - t0.setToValue(1.0); - - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(0.5, node.getOpacity(), EPSILON); - t0.interpolate(0.4); - assertEquals(0.7, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(1.0, node.getOpacity(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testValueCombinations() { - final FadeTransition t0 = new FadeTransition(ONE_SEC, node); - final double originalValue = 0.6; - final double fromValue = 0.4; - final double toValue = 0.9; - final double byValue = -0.2; - - // no value set - node.setOpacity(originalValue); - t0.setFromValue(Double.NaN); - t0.setToValue(Double.NaN); - t0.setByValue(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // only from-value set - node.setOpacity(originalValue); - t0.setFromValue(fromValue); - t0.setToValue(Double.NaN); - t0.setByValue(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // only to-value set - node.setOpacity(originalValue); - t0.setFromValue(Double.NaN); - t0.setToValue(toValue); - t0.setByValue(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // only by-value set - node.setOpacity(originalValue); - t0.setFromValue(Double.NaN); - t0.setToValue(Double.NaN); - t0.setByValue(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue + byValue, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // from- and to-values set - node.setOpacity(originalValue); - t0.setFromValue(fromValue); - t0.setToValue(toValue); - t0.setByValue(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // from- and by-values set - node.setOpacity(originalValue); - t0.setFromValue(fromValue); - t0.setToValue(Double.NaN); - t0.setByValue(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue + byValue, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // to- and by-values set - node.setOpacity(originalValue); - t0.setFromValue(Double.NaN); - t0.setToValue(toValue); - t0.setByValue(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // all values set - node.setOpacity(originalValue); - t0.setFromValue(fromValue); - t0.setToValue(toValue); - t0.setByValue(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getOpacity(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testOutOfBoundValues() { - final FadeTransition t0 = new FadeTransition(ONE_SEC, node); - t0.setInterpolator(Interpolator.LINEAR); - - // start < 0.0 - t0.setFromValue(-0.4); - t0.setToValue(0.6); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(0.0, node.getOpacity(), EPSILON); - t0.interpolate(0.5); - assertEquals(0.3, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(0.6, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // start > 1.0 - t0.setFromValue(1.3); - t0.setToValue(0.3); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(1.0, node.getOpacity(), EPSILON); - t0.interpolate(0.5); - assertEquals(0.65, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(0.3, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // end < 0.0 - t0.setFromValue(0.2); - t0.setToValue(-1.2); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(0.2, node.getOpacity(), EPSILON); - t0.interpolate(0.5); - assertEquals(0.1, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(0.0, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // end > 1.0 - t0.setFromValue(0.9); - t0.setToValue(1.9); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(0.9, node.getOpacity(), EPSILON); - t0.interpolate(0.5); - assertEquals(0.95, node.getOpacity(), EPSILON); - t0.interpolate(1.0); - assertEquals(1.0, node.getOpacity(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testGetTargetNode() { - final FadeTransition ft = new FadeTransition(ONE_SEC, node); - ft.setInterpolator(Interpolator.LINEAR); - ft.setFromValue(0.5); - ft.setToValue(1.0); - final Rectangle node2 = new Rectangle(); - final ParallelTransition pt = new ParallelTransition(); - pt.getChildren().add(ft); - pt.setNode(node2); - - // node set, parent set - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.interpolate(0.5); - assertEquals(0.75, node.getOpacity(), EPSILON); - assertEquals(1.0, node2.getOpacity(), EPSILON); - ft.impl_finished(); - - // node null, parent set - ft.setNode(null); - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.interpolate(0.4); - assertEquals(0.75, node.getOpacity(), EPSILON); - assertEquals(0.7, node2.getOpacity(), EPSILON); - ft.impl_finished(); - - // node null, parent null - pt.setNode(null); - assertFalse(ft.impl_startable(true)); - } - - @Test - public void testCachedValues() { - final FadeTransition ft = new FadeTransition(ONE_SEC, node); - ft.setInterpolator(Interpolator.LINEAR); - ft.setFromValue(0.5); - ft.setToValue(1.0); - - // start - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setFromValue(0.0); - ft.interpolate(0.5); - assertEquals(0.75, node.getOpacity(), EPSILON); - ft.impl_finished(); - ft.setFromValue(0.5); - - // end - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setToValue(0.0); - ft.interpolate(0.2); - assertEquals(0.6, node.getOpacity(), EPSILON); - ft.impl_finished(); - ft.setToValue(1.0); - - // node - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setNode(null); - ft.interpolate(0.7); - assertEquals(0.85, node.getOpacity(), EPSILON); - ft.impl_finished(); - ft.setNode(node); - - // interpolator - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setInterpolator(null); - ft.interpolate(0.1); - assertEquals(0.55, node.getOpacity(), EPSILON); - ft.impl_finished(); - ft.setInterpolator(Interpolator.LINEAR); - } - - @Test - public void testStartable() { - final FadeTransition t0 = new FadeTransition(Duration.ONE, node); - assertTrue(t0.impl_startable(true)); - - // duration is 0 - t0.setDuration(Duration.ZERO); - assertFalse(t0.impl_startable(true)); - t0.setDuration(Duration.ONE); - assertTrue(t0.impl_startable(true)); - - // node is null - t0.setNode(null); - assertFalse(t0.impl_startable(true)); - t0.setNode(node); - assertTrue(t0.impl_startable(true)); - - // interpolator is null - t0.setInterpolator(null); - assertFalse(t0.impl_startable(true)); - t0.setInterpolator(Interpolator.LINEAR); - assertTrue(t0.impl_startable(true)); - } - - @Test - public void testEvaluateStartValue() { - final FadeTransition t0 = new FadeTransition(Duration.INDEFINITE, node); - - // first run - node.setOpacity(0.6); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - node.setOpacity(0.8); - t0.interpolate(0.0); - assertEquals(0.6, node.getOpacity(), EPSILON); - t0.impl_finished(); - - // second run - node.setOpacity(0.2); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - node.setOpacity(0.8); - t0.interpolate(0.0); - assertEquals(0.2, node.getOpacity(), EPSILON); - t0.impl_finished(); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/FadeTransitionTest.java 2015-09-11 21:25:18.645286380 -0400 @@ -0,0 +1,439 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.animation.AnimationShim; +import javafx.animation.FadeTransition; +import javafx.animation.Interpolator; +import javafx.animation.ParallelTransition; +import javafx.animation.TransitionShim; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import javafx.scene.Node; +import javafx.scene.shape.Rectangle; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + +public class FadeTransitionTest { + + private static Duration DEFAULT_DURATION = Duration.millis(400); + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; + + private static double EPSILON = 1e-12; + private static Duration ONE_SEC = Duration.millis(1000); + private static Duration TWO_SECS = Duration.millis(2000); + + private Node node; + + @Before + public void setUp() { + node = new Rectangle(); + } + + @Test + public void testDefaultValues() { + // empty ctor + final FadeTransition t0 = new FadeTransition(); + assertEquals(DEFAULT_DURATION, t0.getDuration()); + assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); + assertTrue(Double.isNaN(t0.getFromValue())); + assertTrue(Double.isNaN(t0.getToValue())); + assertEquals(0.0, t0.getByValue(), EPSILON); + assertNull(t0.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration only + final FadeTransition t1 = new FadeTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.getDuration()); + assertTrue(Double.isNaN(t1.getFromValue())); + assertTrue(Double.isNaN(t1.getToValue())); + assertEquals(0.0, t1.getByValue(), EPSILON); + assertNull(t1.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); + assertNull(t1.getOnFinished()); + + // duration and node + final FadeTransition t2 = new FadeTransition(TWO_SECS, node); + assertEquals(TWO_SECS, t2.getDuration()); + assertTrue(Double.isNaN(t2.getFromValue())); + assertTrue(Double.isNaN(t2.getToValue())); + assertEquals(0.0, t2.getByValue(), EPSILON); + assertEquals(node, t2.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); + assertNull(t2.getOnFinished()); + } + + @Test + public void testDefaultValuesFromProperties() { + // empty ctor + final FadeTransition t0 = new FadeTransition(); + assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); + assertTrue(Double.isNaN(t0.fromValueProperty().get())); + assertTrue(Double.isNaN(t0.toValueProperty().get())); + assertEquals(0.0, t0.byValueProperty().get(), EPSILON); + assertNull(t0.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t0.interpolatorProperty().get()); + assertNull(t0.onFinishedProperty().get()); + + // duration only + final FadeTransition t1 = new FadeTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.durationProperty().get()); + assertTrue(Double.isNaN(t1.fromValueProperty().get())); + assertTrue(Double.isNaN(t1.toValueProperty().get())); + assertEquals(0.0, t1.byValueProperty().get(), EPSILON); + assertNull(t1.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t1.interpolatorProperty().get()); + assertNull(t1.onFinishedProperty().get()); + + // duration and node + final FadeTransition t2 = new FadeTransition(TWO_SECS, node); + assertEquals(TWO_SECS, t2.durationProperty().get()); + assertTrue(Double.isNaN(t2.fromValueProperty().get())); + assertTrue(Double.isNaN(t2.toValueProperty().get())); + assertEquals(0.0, t2.byValueProperty().get(), EPSILON); + assertEquals(node, t2.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t2.interpolatorProperty().get()); + assertNull(t2.onFinishedProperty().get()); + } + + @Test + public void testInterpolate() { + final FadeTransition t0 = new FadeTransition(ONE_SEC, node); + t0.setFromValue(0.5); + t0.setToValue(1.0); + + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.5, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,0.4); + assertEquals(0.7, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(1.0, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testValueCombinations() { + final FadeTransition t0 = new FadeTransition(ONE_SEC, node); + final double originalValue = 0.6; + final double fromValue = 0.4; + final double toValue = 0.9; + final double byValue = -0.2; + + // no value set + node.setOpacity(originalValue); + t0.setFromValue(Double.NaN); + t0.setToValue(Double.NaN); + t0.setByValue(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // only from-value set + node.setOpacity(originalValue); + t0.setFromValue(fromValue); + t0.setToValue(Double.NaN); + t0.setByValue(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // only to-value set + node.setOpacity(originalValue); + t0.setFromValue(Double.NaN); + t0.setToValue(toValue); + t0.setByValue(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // only by-value set + node.setOpacity(originalValue); + t0.setFromValue(Double.NaN); + t0.setToValue(Double.NaN); + t0.setByValue(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue + byValue, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and to-values set + node.setOpacity(originalValue); + t0.setFromValue(fromValue); + t0.setToValue(toValue); + t0.setByValue(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and by-values set + node.setOpacity(originalValue); + t0.setFromValue(fromValue); + t0.setToValue(Double.NaN); + t0.setByValue(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue + byValue, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // to- and by-values set + node.setOpacity(originalValue); + t0.setFromValue(Double.NaN); + t0.setToValue(toValue); + t0.setByValue(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // all values set + node.setOpacity(originalValue); + t0.setFromValue(fromValue); + t0.setToValue(toValue); + t0.setByValue(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testOutOfBoundValues() { + final FadeTransition t0 = new FadeTransition(ONE_SEC, node); + t0.setInterpolator(Interpolator.LINEAR); + + // start < 0.0 + t0.setFromValue(-0.4); + t0.setToValue(0.6); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.0, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,0.5); + assertEquals(0.3, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(0.6, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // start > 1.0 + t0.setFromValue(1.3); + t0.setToValue(0.3); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(1.0, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,0.5); + assertEquals(0.65, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(0.3, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // end < 0.0 + t0.setFromValue(0.2); + t0.setToValue(-1.2); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.2, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,0.5); + assertEquals(0.1, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(0.0, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // end > 1.0 + t0.setFromValue(0.9); + t0.setToValue(1.9); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.9, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,0.5); + assertEquals(0.95, node.getOpacity(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(1.0, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testGetTargetNode() { + final FadeTransition ft = new FadeTransition(ONE_SEC, node); + ft.setInterpolator(Interpolator.LINEAR); + ft.setFromValue(0.5); + ft.setToValue(1.0); + final Rectangle node2 = new Rectangle(); + final ParallelTransition pt = new ParallelTransition(); + pt.getChildren().add(ft); + pt.setNode(node2); + + // node set, parent set + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + TransitionShim.interpolate(ft,0.5); + assertEquals(0.75, node.getOpacity(), EPSILON); + assertEquals(1.0, node2.getOpacity(), EPSILON); + AnimationShim.impl_finished(ft); + + // node null, parent set + ft.setNode(null); + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + TransitionShim.interpolate(ft,0.4); + assertEquals(0.75, node.getOpacity(), EPSILON); + assertEquals(0.7, node2.getOpacity(), EPSILON); + AnimationShim.impl_finished(ft); + + // node null, parent null + pt.setNode(null); + assertFalse(AnimationShim.impl_startable(ft,true)); + } + + @Test + public void testCachedValues() { + final FadeTransition ft = new FadeTransition(ONE_SEC, node); + ft.setInterpolator(Interpolator.LINEAR); + ft.setFromValue(0.5); + ft.setToValue(1.0); + + // start + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setFromValue(0.0); + TransitionShim.interpolate(ft,0.5); + assertEquals(0.75, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(ft); + ft.setFromValue(0.5); + + // end + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setToValue(0.0); + TransitionShim.interpolate(ft,0.2); + assertEquals(0.6, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(ft); + ft.setToValue(1.0); + + // node + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setNode(null); + TransitionShim.interpolate(ft,0.7); + assertEquals(0.85, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(ft); + ft.setNode(node); + + // interpolator + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setInterpolator(null); + TransitionShim.interpolate(ft,0.1); + assertEquals(0.55, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(ft); + ft.setInterpolator(Interpolator.LINEAR); + } + + @Test + public void testStartable() { + final FadeTransition t0 = new FadeTransition(Duration.ONE, node); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // duration is 0 + t0.setDuration(Duration.ZERO); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setDuration(Duration.ONE); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // node is null + t0.setNode(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setNode(node); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // interpolator is null + t0.setInterpolator(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setInterpolator(Interpolator.LINEAR); + assertTrue(AnimationShim.impl_startable(t0,true)); + } + + @Test + public void testEvaluateStartValue() { + final FadeTransition t0 = new FadeTransition(Duration.INDEFINITE, node); + + // first run + node.setOpacity(0.6); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + node.setOpacity(0.8); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.6, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + + // second run + node.setOpacity(0.2); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + node.setOpacity(0.8); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.2, node.getOpacity(), EPSILON); + AnimationShim.impl_finished(t0); + } + +} --- old/modules/graphics/src/test/java/javafx/animation/FillTransitionTest.java 2015-09-11 21:25:19.545286370 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,356 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import javafx.scene.Group; -import javafx.scene.paint.Color; -import javafx.scene.paint.LinearGradient; -import javafx.scene.paint.Paint; -import javafx.scene.paint.Stop; -import javafx.scene.shape.Rectangle; -import javafx.scene.shape.Shape; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - -public class FillTransitionTest { - - private static Duration DEFAULT_DURATION = Duration.millis(400); - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; - - private static float EPSILON = 1e-6f; - private static Duration ONE_SEC = Duration.millis(1000); - private static Duration TWO_SECS = Duration.millis(2000); - - private Shape shape; - - @Before - public void setUp() { - shape = new Rectangle(); - } - - private void assertColorEquals(Color expected, Paint actualPaint) { - assertTrue(actualPaint instanceof Color); - final Color actual = (Color)actualPaint; - assertEquals(expected.getRed(), actual.getRed(), EPSILON); - assertEquals(expected.getGreen(), actual.getGreen(), EPSILON); - assertEquals(expected.getBlue(), actual.getBlue(), EPSILON); - assertEquals(expected.getOpacity(), actual.getOpacity(), EPSILON); - } - - @Test - public void testDefaultValues() { - // empty ctor - FillTransition t0 = new FillTransition(); - assertEquals(DEFAULT_DURATION, t0.getDuration()); - assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); - assertNull(t0.getFromValue()); - assertNull(t0.getToValue()); - assertNull(t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration only - t0 = new FillTransition(ONE_SEC); - assertEquals(ONE_SEC, t0.getDuration()); - assertNull(t0.getFromValue()); - assertNull(t0.getToValue()); - assertNull(t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration and shape - t0 = new FillTransition(TWO_SECS, shape); - assertEquals(TWO_SECS, t0.getDuration()); - assertNull(t0.getFromValue()); - assertNull(t0.getToValue()); - assertEquals(shape, t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration and values - t0 = new FillTransition(TWO_SECS, Color.BLACK, Color.WHITE); - assertEquals(TWO_SECS, t0.getDuration()); - assertColorEquals(Color.BLACK, t0.getFromValue()); - assertColorEquals(Color.WHITE, t0.getToValue()); - assertNull(t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration, shape, and values - t0 = new FillTransition(TWO_SECS, shape, Color.BLACK, Color.WHITE); - assertEquals(TWO_SECS, t0.getDuration()); - assertColorEquals(Color.BLACK, t0.getFromValue()); - assertColorEquals(Color.WHITE, t0.getToValue()); - assertEquals(shape, t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - } - - @Test - public void testInterpolate() { - final Color fromValue = Color.color(0.2, 0.3, 0.7, 0.1); - final Color toValue = Color.color(0.8, 0.4, 0.2, 0.9); - final FillTransition t0 = new FillTransition(ONE_SEC, shape, fromValue, toValue); - - assertTrue(t0.impl_startable(false)); - t0.impl_start(false); - t0.interpolate(0.0); - assertColorEquals(Color.color(0.2, 0.3, 0.7, 0.1), shape.getFill()); - t0.interpolate(0.4); - assertColorEquals(Color.color(0.44, 0.34, 0.5, 0.42), shape.getFill()); - t0.interpolate(1.0); - assertColorEquals(Color.color(0.8, 0.4, 0.2, 0.9), shape.getFill()); - t0.impl_finished(); - } - - @Test - public void testValueCombinations() { - final FillTransition t0 = new FillTransition(ONE_SEC, shape, null, Color.WHITE); - final double original = 0.6; - final double from = 0.4; - final Color originalValue = Color.color(original, original, original); - final Color fromValue = Color.color(from, from, from); - - // no from value set - shape.setFill(originalValue); - t0.setFromValue(null); - assertTrue(t0.impl_startable(false)); - t0.impl_start(false); - t0.interpolate(0.0); - assertColorEquals(originalValue, shape.getFill()); - t0.impl_finished(); - - // from-value set - shape.setFill(originalValue); - t0.setFromValue(fromValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertColorEquals(fromValue, shape.getFill()); - t0.impl_finished(); - } - - @Test - public void testGetTargetNode() { - final Color fromValue = Color.color(0.0, 0.4, 0.8, 1.0); - final Color toValue = Color.color(1.0, 0.8, 0.6, 0.4); - final FillTransition ft = new FillTransition(ONE_SEC, shape, fromValue, toValue); - ft.setInterpolator(Interpolator.LINEAR); - final Shape shape2 = new Rectangle(); - final ParallelTransition pt = new ParallelTransition(); - pt.getChildren().add(ft); - pt.setNode(shape2); - shape.setFill(Color.WHITE); - shape2.setFill(Color.WHITE); - - // node set, parent set - assertTrue(ft.impl_startable(false)); - ft.impl_start(false); - ft.interpolate(0.5); - assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.7), shape.getFill()); - assertColorEquals(Color.WHITE, shape2.getFill()); - ft.impl_finished(); - - // node null, parent set - ft.setShape(null); - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.interpolate(0.4); - assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.7), shape.getFill()); - assertColorEquals(Color.color(0.4, 0.56, 0.72, 0.76), shape2.getFill()); - ft.impl_finished(); - - // node null, parent not shape set - pt.setNode(new Group()); - assertFalse(ft.impl_startable(true)); - - // node null, parent null - pt.setNode(null); - assertFalse(ft.impl_startable(true)); - } - - @Test - public void testCachedValues() { - final Color fromValue = Color.color(0.0, 0.4, 0.8, 0.2); - final Color toValue = Color.color(1.0, 0.8, 0.6, 0.4); - final FillTransition ft = new FillTransition(ONE_SEC, shape, fromValue, toValue); - ft.setInterpolator(Interpolator.LINEAR); - - // start - assertTrue(ft.impl_startable(false)); - ft.impl_start(false); - ft.setFromValue(Color.WHITE); - ft.interpolate(0.5); - assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.3), shape.getFill()); - ft.impl_finished(); - ft.setFromValue(fromValue); - - // end - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setToValue(Color.BLACK); - ft.interpolate(0.2); - assertColorEquals(Color.color(0.2, 0.48, 0.76, 0.24), shape.getFill()); - ft.impl_finished(); - ft.setToValue(toValue); - - // shape - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setShape(null); - ft.interpolate(0.7); - assertColorEquals(Color.color(0.7, 0.68, 0.66, 0.34), shape.getFill()); - ft.impl_finished(); - ft.setShape(shape); - - // interpolator - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setInterpolator(null); - ft.interpolate(0.1); - assertColorEquals(Color.color(0.1, 0.44, 0.78, 0.22), shape.getFill()); - ft.impl_finished(); - ft.setInterpolator(Interpolator.LINEAR); - } - - @Test - public void testStartable_unsynchronized() { - final FillTransition t0 = new FillTransition(Duration.ONE, shape, Color.WHITE, Color.BLACK); - final Paint paint2 = new LinearGradient(0, 0, 1, 1, false, null, - new Stop[] { new Stop(0, Color.RED) }); - assertTrue(t0.impl_startable(true)); - - // duration is 0 - t0.setDuration(Duration.ZERO); - assertFalse(t0.impl_startable(true)); - t0.setDuration(Duration.ONE); - assertTrue(t0.impl_startable(true)); - - // interpolator is null - t0.setInterpolator(null); - assertFalse(t0.impl_startable(true)); - t0.setInterpolator(Interpolator.LINEAR); - assertTrue(t0.impl_startable(true)); - - // shape is null - t0.setShape(null); - assertFalse(t0.impl_startable(false)); - assertFalse(t0.impl_startable(true)); - t0.setShape(shape); - assertTrue(t0.impl_startable(false)); - assertTrue(t0.impl_startable(true)); - - // fromValue - t0.setFromValue(null); - shape.setFill(paint2); - assertFalse(t0.impl_startable(false)); - assertFalse(t0.impl_startable(true)); - shape.setFill(Color.BLACK); - assertTrue(t0.impl_startable(false)); - assertTrue(t0.impl_startable(true)); - t0.setFromValue(Color.WHITE); - shape.setFill(paint2); - assertTrue(t0.impl_startable(false)); - assertTrue(t0.impl_startable(true)); - - // toValue - t0.setToValue(null); - assertFalse(t0.impl_startable(false)); - assertFalse(t0.impl_startable(true)); - t0.setToValue(Color.BLACK); - assertTrue(t0.impl_startable(false)); - assertTrue(t0.impl_startable(true)); - } - - @Test - public void testStartable_synchronized() { - final FillTransition t0 = new FillTransition(Duration.ONE, shape, Color.WHITE, Color.BLACK); - final Paint paint2 = new LinearGradient(0, 0, 1, 1, false, null, - new Stop[] { new Stop(0, Color.RED) }); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.impl_finished(); - - // shape is null - t0.setShape(null); - assertTrue(t0.impl_startable(false)); - assertFalse(t0.impl_startable(true)); - t0.setShape(shape); - assertTrue(t0.impl_startable(false)); - assertTrue(t0.impl_startable(true)); - - // fromValue - t0.setFromValue(null); - shape.setFill(paint2); - assertTrue(t0.impl_startable(false)); - assertFalse(t0.impl_startable(true)); - shape.setFill(Color.BLACK); - assertTrue(t0.impl_startable(false)); - assertTrue(t0.impl_startable(true)); - t0.setFromValue(Color.WHITE); - shape.setFill(paint2); - assertTrue(t0.impl_startable(false)); - assertTrue(t0.impl_startable(true)); - - // toValue - t0.setToValue(null); - assertTrue(t0.impl_startable(false)); - assertFalse(t0.impl_startable(true)); - t0.setToValue(Color.BLACK); - assertTrue(t0.impl_startable(false)); - assertTrue(t0.impl_startable(true)); - } - - @Test - public void testEvaluateStartValue() { - final FillTransition t0 = new FillTransition(Duration.INDEFINITE, shape, null, Color.WHITE); - - // first run - shape.setFill(Color.GREY); - assertTrue(t0.impl_startable(false)); - t0.impl_start(false); - shape.setFill(Color.TRANSPARENT); - t0.interpolate(0.0); - assertColorEquals(Color.GREY, shape.getFill()); - t0.impl_finished(); - - // second run - shape.setFill(Color.BLACK); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - shape.setFill(Color.WHITE); - t0.interpolate(0.0); - assertColorEquals(Color.BLACK, shape.getFill()); - t0.impl_finished(); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/FillTransitionTest.java 2015-09-11 21:25:19.333286372 -0400 @@ -0,0 +1,361 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.animation.AnimationShim; +import javafx.animation.FillTransition; +import javafx.animation.Interpolator; +import javafx.animation.ParallelTransition; +import javafx.animation.TransitionShim; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import javafx.scene.Group; +import javafx.scene.paint.Color; +import javafx.scene.paint.LinearGradient; +import javafx.scene.paint.Paint; +import javafx.scene.paint.Stop; +import javafx.scene.shape.Rectangle; +import javafx.scene.shape.Shape; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + +public class FillTransitionTest { + + private static Duration DEFAULT_DURATION = Duration.millis(400); + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; + + private static float EPSILON = 1e-6f; + private static Duration ONE_SEC = Duration.millis(1000); + private static Duration TWO_SECS = Duration.millis(2000); + + private Shape shape; + + @Before + public void setUp() { + shape = new Rectangle(); + } + + private void assertColorEquals(Color expected, Paint actualPaint) { + assertTrue(actualPaint instanceof Color); + final Color actual = (Color)actualPaint; + assertEquals(expected.getRed(), actual.getRed(), EPSILON); + assertEquals(expected.getGreen(), actual.getGreen(), EPSILON); + assertEquals(expected.getBlue(), actual.getBlue(), EPSILON); + assertEquals(expected.getOpacity(), actual.getOpacity(), EPSILON); + } + + @Test + public void testDefaultValues() { + // empty ctor + FillTransition t0 = new FillTransition(); + assertEquals(DEFAULT_DURATION, t0.getDuration()); + assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); + assertNull(t0.getFromValue()); + assertNull(t0.getToValue()); + assertNull(t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration only + t0 = new FillTransition(ONE_SEC); + assertEquals(ONE_SEC, t0.getDuration()); + assertNull(t0.getFromValue()); + assertNull(t0.getToValue()); + assertNull(t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration and shape + t0 = new FillTransition(TWO_SECS, shape); + assertEquals(TWO_SECS, t0.getDuration()); + assertNull(t0.getFromValue()); + assertNull(t0.getToValue()); + assertEquals(shape, t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration and values + t0 = new FillTransition(TWO_SECS, Color.BLACK, Color.WHITE); + assertEquals(TWO_SECS, t0.getDuration()); + assertColorEquals(Color.BLACK, t0.getFromValue()); + assertColorEquals(Color.WHITE, t0.getToValue()); + assertNull(t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration, shape, and values + t0 = new FillTransition(TWO_SECS, shape, Color.BLACK, Color.WHITE); + assertEquals(TWO_SECS, t0.getDuration()); + assertColorEquals(Color.BLACK, t0.getFromValue()); + assertColorEquals(Color.WHITE, t0.getToValue()); + assertEquals(shape, t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + } + + @Test + public void testInterpolate() { + final Color fromValue = Color.color(0.2, 0.3, 0.7, 0.1); + final Color toValue = Color.color(0.8, 0.4, 0.2, 0.9); + final FillTransition t0 = new FillTransition(ONE_SEC, shape, fromValue, toValue); + + assertTrue(AnimationShim.impl_startable(t0,false)); + AnimationShim.impl_start(t0,false); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(Color.color(0.2, 0.3, 0.7, 0.1), shape.getFill()); + TransitionShim.interpolate(t0,0.4); + assertColorEquals(Color.color(0.44, 0.34, 0.5, 0.42), shape.getFill()); + TransitionShim.interpolate(t0,1.0); + assertColorEquals(Color.color(0.8, 0.4, 0.2, 0.9), shape.getFill()); + AnimationShim.impl_finished(t0); + } + + @Test + public void testValueCombinations() { + final FillTransition t0 = new FillTransition(ONE_SEC, shape, null, Color.WHITE); + final double original = 0.6; + final double from = 0.4; + final Color originalValue = Color.color(original, original, original); + final Color fromValue = Color.color(from, from, from); + + // no from value set + shape.setFill(originalValue); + t0.setFromValue(null); + assertTrue(AnimationShim.impl_startable(t0,false)); + AnimationShim.impl_start(t0,false); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(originalValue, shape.getFill()); + AnimationShim.impl_finished(t0); + + // from-value set + shape.setFill(originalValue); + t0.setFromValue(fromValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(fromValue, shape.getFill()); + AnimationShim.impl_finished(t0); + } + + @Test + public void testGetTargetNode() { + final Color fromValue = Color.color(0.0, 0.4, 0.8, 1.0); + final Color toValue = Color.color(1.0, 0.8, 0.6, 0.4); + final FillTransition ft = new FillTransition(ONE_SEC, shape, fromValue, toValue); + ft.setInterpolator(Interpolator.LINEAR); + final Shape shape2 = new Rectangle(); + final ParallelTransition pt = new ParallelTransition(); + pt.getChildren().add(ft); + pt.setNode(shape2); + shape.setFill(Color.WHITE); + shape2.setFill(Color.WHITE); + + // node set, parent set + assertTrue(AnimationShim.impl_startable(ft,false)); + AnimationShim.impl_start(ft,false); + TransitionShim.interpolate(ft,0.5); + assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.7), shape.getFill()); + assertColorEquals(Color.WHITE, shape2.getFill()); + AnimationShim.impl_finished(ft); + + // node null, parent set + ft.setShape(null); + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + TransitionShim.interpolate(ft,0.4); + assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.7), shape.getFill()); + assertColorEquals(Color.color(0.4, 0.56, 0.72, 0.76), shape2.getFill()); + AnimationShim.impl_finished(ft); + + // node null, parent not shape set + pt.setNode(new Group()); + assertFalse(AnimationShim.impl_startable(ft,true)); + + // node null, parent null + pt.setNode(null); + assertFalse(AnimationShim.impl_startable(ft,true)); + } + + @Test + public void testCachedValues() { + final Color fromValue = Color.color(0.0, 0.4, 0.8, 0.2); + final Color toValue = Color.color(1.0, 0.8, 0.6, 0.4); + final FillTransition ft = new FillTransition(ONE_SEC, shape, fromValue, toValue); + ft.setInterpolator(Interpolator.LINEAR); + + // start + assertTrue(AnimationShim.impl_startable(ft,false)); + AnimationShim.impl_start(ft,false); + ft.setFromValue(Color.WHITE); + TransitionShim.interpolate(ft,0.5); + assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.3), shape.getFill()); + AnimationShim.impl_finished(ft); + ft.setFromValue(fromValue); + + // end + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setToValue(Color.BLACK); + TransitionShim.interpolate(ft,0.2); + assertColorEquals(Color.color(0.2, 0.48, 0.76, 0.24), shape.getFill()); + AnimationShim.impl_finished(ft); + ft.setToValue(toValue); + + // shape + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setShape(null); + TransitionShim.interpolate(ft,0.7); + assertColorEquals(Color.color(0.7, 0.68, 0.66, 0.34), shape.getFill()); + AnimationShim.impl_finished(ft); + ft.setShape(shape); + + // interpolator + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setInterpolator(null); + TransitionShim.interpolate(ft,0.1); + assertColorEquals(Color.color(0.1, 0.44, 0.78, 0.22), shape.getFill()); + AnimationShim.impl_finished(ft); + ft.setInterpolator(Interpolator.LINEAR); + } + + @Test + public void testStartable_unsynchronized() { + final FillTransition t0 = new FillTransition(Duration.ONE, shape, Color.WHITE, Color.BLACK); + final Paint paint2 = new LinearGradient(0, 0, 1, 1, false, null, + new Stop[] { new Stop(0, Color.RED) }); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // duration is 0 + t0.setDuration(Duration.ZERO); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setDuration(Duration.ONE); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // interpolator is null + t0.setInterpolator(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setInterpolator(Interpolator.LINEAR); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // shape is null + t0.setShape(null); + assertFalse(AnimationShim.impl_startable(t0,false)); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setShape(shape); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // fromValue + t0.setFromValue(null); + shape.setFill(paint2); + assertFalse(AnimationShim.impl_startable(t0,false)); + assertFalse(AnimationShim.impl_startable(t0,true)); + shape.setFill(Color.BLACK); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertTrue(AnimationShim.impl_startable(t0,true)); + t0.setFromValue(Color.WHITE); + shape.setFill(paint2); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // toValue + t0.setToValue(null); + assertFalse(AnimationShim.impl_startable(t0,false)); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setToValue(Color.BLACK); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertTrue(AnimationShim.impl_startable(t0,true)); + } + + @Test + public void testStartable_synchronized() { + final FillTransition t0 = new FillTransition(Duration.ONE, shape, Color.WHITE, Color.BLACK); + final Paint paint2 = new LinearGradient(0, 0, 1, 1, false, null, + new Stop[] { new Stop(0, Color.RED) }); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + AnimationShim.impl_finished(t0); + + // shape is null + t0.setShape(null); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setShape(shape); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // fromValue + t0.setFromValue(null); + shape.setFill(paint2); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertFalse(AnimationShim.impl_startable(t0,true)); + shape.setFill(Color.BLACK); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertTrue(AnimationShim.impl_startable(t0,true)); + t0.setFromValue(Color.WHITE); + shape.setFill(paint2); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // toValue + t0.setToValue(null); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setToValue(Color.BLACK); + assertTrue(AnimationShim.impl_startable(t0,false)); + assertTrue(AnimationShim.impl_startable(t0,true)); + } + + @Test + public void testEvaluateStartValue() { + final FillTransition t0 = new FillTransition(Duration.INDEFINITE, shape, null, Color.WHITE); + + // first run + shape.setFill(Color.GREY); + assertTrue(AnimationShim.impl_startable(t0,false)); + AnimationShim.impl_start(t0,false); + shape.setFill(Color.TRANSPARENT); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(Color.GREY, shape.getFill()); + AnimationShim.impl_finished(t0); + + // second run + shape.setFill(Color.BLACK); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + shape.setFill(Color.WHITE); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(Color.BLACK, shape.getFill()); + AnimationShim.impl_finished(t0); + } + +} --- old/modules/graphics/src/test/java/javafx/animation/InterpolatorTest.java 2015-09-11 21:25:20.285286362 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,305 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import com.sun.javafx.animation.TickCalculation; -import com.sun.scenario.animation.shared.InterpolationInterval; -import javafx.beans.property.Property; -import javafx.beans.property.SimpleLongProperty; -import javafx.util.Duration; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class InterpolatorTest { - - private static final double EPSILON = 1e-12; - private static final float EPSILON_FLOAT = 1e-6f; - private static final DummyInterpolatable START = new DummyInterpolatable(0); - private static final DummyInterpolatable END = new DummyInterpolatable(10); - - @Test - public void testInterpolateWithObjects() { - final DummyInterpolatable i1 = new DummyInterpolatable(1); - final DummyInterpolatable i2 = new DummyInterpolatable(4); - final Object o = new Object(); - - assertEquals(Double.valueOf(2.5), (Double)Interpolator.LINEAR.interpolate(Double.valueOf(1), Integer.valueOf(4), 0.5), EPSILON); - assertEquals(Double.valueOf(2.5), (Double)Interpolator.LINEAR.interpolate(Integer.valueOf(4), Double.valueOf(1), 0.5), EPSILON); - assertEquals(Float.valueOf(2.5f), (Float)Interpolator.LINEAR.interpolate(Float.valueOf(1), Integer.valueOf(4), 0.5), EPSILON_FLOAT); - assertEquals(Float.valueOf(2.5f), (Float)Interpolator.LINEAR.interpolate(Integer.valueOf(4), Float.valueOf(1), 0.5), EPSILON_FLOAT); - assertEquals(Long.valueOf(3L), Interpolator.LINEAR.interpolate(Long.valueOf(1), Integer.valueOf(4), 0.5)); - assertEquals(Long.valueOf(3L), Interpolator.LINEAR.interpolate(Integer.valueOf(4), Long.valueOf(1), 0.5)); - assertEquals(Integer.valueOf(3), Interpolator.LINEAR.interpolate(Integer.valueOf(1), Integer.valueOf(4), 0.5)); - assertEquals(2.5, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(i1, i2, 0.5)).value, EPSILON); - - assertEquals(o, Interpolator.LINEAR.interpolate(o, Integer.MIN_VALUE, 1.0-2*EPSILON)); - assertEquals(Integer.MIN_VALUE, Interpolator.LINEAR.interpolate(o, Integer.MIN_VALUE, 1.0)); - - assertEquals(Integer.MIN_VALUE, Interpolator.LINEAR.interpolate(Integer.MIN_VALUE, o, 1.0-2*EPSILON)); - assertEquals(o, Interpolator.LINEAR.interpolate(Integer.MIN_VALUE, o, 1.0)); - - assertEquals(i1, Interpolator.LINEAR.interpolate(i1, o, 1.0-2*EPSILON)); - assertEquals(o, Interpolator.LINEAR.interpolate(i1, o, 1.0)); - } - - @Test - public void testDISCRETE() { - assertEquals(false, Interpolator.DISCRETE.interpolate(false, true, 1.0-2*EPSILON)); - assertEquals(true, Interpolator.DISCRETE.interpolate(false, true, 1.0)); - - assertEquals(1.0, Interpolator.DISCRETE.interpolate(1.0, 2.0, 1.0-2*EPSILON), EPSILON); - assertEquals(2.0, Interpolator.DISCRETE.interpolate(1.0, 2.0, 1.0), EPSILON); - - assertEquals(-3, Interpolator.DISCRETE.interpolate(-3, 7, 1.0-2*EPSILON)); - assertEquals( 7, Interpolator.DISCRETE.interpolate(-3, 7, 1.0)); - - assertEquals( 12L, Interpolator.DISCRETE.interpolate(12L, -201L, 1.0-2*EPSILON)); - assertEquals(-201L, Interpolator.DISCRETE.interpolate(12L, -201L, 1.0)); - - assertEquals( 0, ((DummyInterpolatable)Interpolator.DISCRETE.interpolate(START, END, 1.0-2*EPSILON)).value, EPSILON); - assertEquals(10, ((DummyInterpolatable)Interpolator.DISCRETE.interpolate(START, END, 1.0)).value, EPSILON); - } - - @Test - public void testLINEAR() { - assertEquals(false, Interpolator.LINEAR.interpolate(false, true, 0.0)); - assertEquals(false, Interpolator.LINEAR.interpolate(false, true, 0.1)); - assertEquals(false, Interpolator.LINEAR.interpolate(false, true, 0.5)); - assertEquals(false, Interpolator.LINEAR.interpolate(false, true, 0.9)); - assertEquals(true, Interpolator.LINEAR.interpolate(false, true, 1.0)); - - assertEquals(1.0, Interpolator.LINEAR.interpolate(1.0, 2.0, 0.0), EPSILON); - assertEquals(1.1, Interpolator.LINEAR.interpolate(1.0, 2.0, 0.1), EPSILON); - assertEquals(1.5, Interpolator.LINEAR.interpolate(1.0, 2.0, 0.5), EPSILON); - assertEquals(1.9, Interpolator.LINEAR.interpolate(1.0, 2.0, 0.9), EPSILON); - assertEquals(2.0, Interpolator.LINEAR.interpolate(1.0, 2.0, 1.0), EPSILON); - - assertEquals(-3, Interpolator.LINEAR.interpolate(-3, 7, 0.0)); - assertEquals(-2, Interpolator.LINEAR.interpolate(-3, 7, 0.1)); - assertEquals( 2, Interpolator.LINEAR.interpolate(-3, 7, 0.5)); - assertEquals( 6, Interpolator.LINEAR.interpolate(-3, 7, 0.9)); - assertEquals( 7, Interpolator.LINEAR.interpolate(-3, 7, 1.0)); - - assertEquals(-3L, Interpolator.LINEAR.interpolate(-3L, 7L, 0.0)); - assertEquals(-2L, Interpolator.LINEAR.interpolate(-3L, 7L, 0.1)); - assertEquals( 2L, Interpolator.LINEAR.interpolate(-3L, 7L, 0.5)); - assertEquals( 6L, Interpolator.LINEAR.interpolate(-3L, 7L, 0.9)); - assertEquals( 7L, Interpolator.LINEAR.interpolate(-3L, 7L, 1.0)); - - assertEquals( 0, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 0.0)).value, EPSILON); - assertEquals( 1, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 0.1)).value, EPSILON); - assertEquals( 5, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 0.5)).value, EPSILON); - assertEquals( 9, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 0.9)).value, EPSILON); - assertEquals(10, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 1.0)).value, EPSILON); - } - - @Test - public void testEASE_BOTH() { - // Expected results calculated with JavaFX SDK 1.3 - - assertEquals(false, Interpolator.EASE_BOTH.interpolate(false, true, 0.0)); - assertEquals(false, Interpolator.EASE_BOTH.interpolate(false, true, 0.1)); - assertEquals(false, Interpolator.EASE_BOTH.interpolate(false, true, 0.5)); - assertEquals(false, Interpolator.EASE_BOTH.interpolate(false, true, 0.9)); - assertEquals(true, Interpolator.EASE_BOTH.interpolate(false, true, 1.0)); - - assertEquals(1.0, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 0.0), EPSILON); - assertEquals(1.125, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 0.2), EPSILON); - assertEquals(1.5, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 0.5), EPSILON); - assertEquals(1.875, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 0.8), EPSILON); - assertEquals(2.0, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 1.0), EPSILON); - - assertEquals(-3, Interpolator.EASE_BOTH.interpolate(-3, 7, 0.0)); - assertEquals(-2, Interpolator.EASE_BOTH.interpolate(-3, 7, 0.2)); - assertEquals( 2, Interpolator.EASE_BOTH.interpolate(-3, 7, 0.5)); - assertEquals( 6, Interpolator.EASE_BOTH.interpolate(-3, 7, 0.8)); - assertEquals( 7, Interpolator.EASE_BOTH.interpolate(-3, 7, 1.0)); - - assertEquals(-3L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 0.0)); - assertEquals(-2L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 0.2)); - assertEquals( 2L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 0.5)); - assertEquals( 6L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 0.8)); - assertEquals( 7L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 1.0)); - - assertEquals( 0, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 0.0)).value, EPSILON); - assertEquals( 1.25, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 0.2)).value, EPSILON); - assertEquals( 5, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 0.5)).value, EPSILON); - assertEquals( 8.75, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 0.8)).value, EPSILON); - assertEquals(10, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 1.0)).value, EPSILON); - } - - @Test - public void testEASE_IN() { - // Expected results calculated with JavaFX SDK 1.3 - - assertEquals(false, Interpolator.EASE_IN.interpolate(false, true, 0.0)); - assertEquals(false, Interpolator.EASE_IN.interpolate(false, true, 0.1)); - assertEquals(false, Interpolator.EASE_IN.interpolate(false, true, 0.5)); - assertEquals(false, Interpolator.EASE_IN.interpolate(false, true, 0.9)); - assertEquals(true, Interpolator.EASE_IN.interpolate(false, true, 1.0)); - - assertEquals(1.0, Interpolator.EASE_IN.interpolate(1.0, 2.0, 0.0), EPSILON); - assertEquals(1.1111111111111112, Interpolator.EASE_IN.interpolate(1.0, 2.0, 0.2), EPSILON); - assertEquals(1.4444444444444444, Interpolator.EASE_IN.interpolate(1.0, 2.0, 0.5), EPSILON); - assertEquals(1.777777777777778, Interpolator.EASE_IN.interpolate(1.0, 2.0, 0.8), EPSILON); - assertEquals(2.0, Interpolator.EASE_IN.interpolate(1.0, 2.0, 1.0), EPSILON); - - assertEquals(-3, Interpolator.EASE_IN.interpolate(-3, 7, 0.0)); - assertEquals(-2, Interpolator.EASE_IN.interpolate(-3, 7, 0.2)); - assertEquals( 1, Interpolator.EASE_IN.interpolate(-3, 7, 0.5)); - assertEquals( 5, Interpolator.EASE_IN.interpolate(-3, 7, 0.8)); - assertEquals( 7, Interpolator.EASE_IN.interpolate(-3, 7, 1.0)); - - assertEquals(-3L, Interpolator.EASE_IN.interpolate(-3L, 7L, 0.0)); - assertEquals(-2L, Interpolator.EASE_IN.interpolate(-3L, 7L, 0.2)); - assertEquals( 1L, Interpolator.EASE_IN.interpolate(-3L, 7L, 0.5)); - assertEquals( 5L, Interpolator.EASE_IN.interpolate(-3L, 7L, 0.8)); - assertEquals( 7L, Interpolator.EASE_IN.interpolate(-3L, 7L, 1.0)); - - assertEquals( 0, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 0.0)).value, EPSILON); - assertEquals( 1.1111111111111114, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 0.2)).value, EPSILON); - assertEquals( 4.444444444444445, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 0.5)).value, EPSILON); - assertEquals( 7.777777777777779, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 0.8)).value, EPSILON); - assertEquals(10, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 1.0)).value, EPSILON); - } - - @Test - public void testEASE_OUT() { - // Expected results calculated with JavaFX SDK 1.3 - - assertEquals(false, Interpolator.EASE_OUT.interpolate(false, true, 0.0)); - assertEquals(false, Interpolator.EASE_OUT.interpolate(false, true, 0.1)); - assertEquals(false, Interpolator.EASE_OUT.interpolate(false, true, 0.5)); - assertEquals(false, Interpolator.EASE_OUT.interpolate(false, true, 0.9)); - assertEquals(true, Interpolator.EASE_OUT.interpolate(false, true, 1.0)); - - assertEquals(1.0, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 0.0), EPSILON); - assertEquals(1.2222222222222223, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 0.2), EPSILON); - assertEquals(1.5555555555555556, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 0.5), EPSILON); - assertEquals(1.8888888888888888, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 0.8), EPSILON); - assertEquals(2.0, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 1.0), EPSILON); - - assertEquals(-3, Interpolator.EASE_OUT.interpolate(-3, 7, 0.0)); - assertEquals(-1, Interpolator.EASE_OUT.interpolate(-3, 7, 0.2)); - assertEquals( 3, Interpolator.EASE_OUT.interpolate(-3, 7, 0.5)); - assertEquals( 6, Interpolator.EASE_OUT.interpolate(-3, 7, 0.8)); - assertEquals( 7, Interpolator.EASE_OUT.interpolate(-3, 7, 1.0)); - - assertEquals(-3L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 0.0)); - assertEquals(-1L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 0.2)); - assertEquals( 3L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 0.5)); - assertEquals( 6L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 0.8)); - assertEquals( 7L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 1.0)); - - assertEquals( 0, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 0.0)).value, EPSILON); - assertEquals( 2.2222222222222223, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 0.2)).value, EPSILON); - assertEquals( 5.555555555555555, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 0.5)).value, EPSILON); - assertEquals( 8.88888888888889, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 0.8)).value, EPSILON); - assertEquals(10, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 1.0)).value, EPSILON); - } - - @Test - public void testSPLINE_Concave() { - Interpolator i = Interpolator.SPLINE(0.0, 0.5, 0.5, 1.0); - assertEquals(1.0, i.interpolate(1.0, 2.0, 0.0), EPSILON); - assertEquals(1.5573742287206063, i.interpolate(1.0, 2.0, 0.2), EPSILON); - assertEquals(1.8400223953585164, i.interpolate(1.0, 2.0, 0.5), EPSILON); - assertEquals(1.9742173260814238, i.interpolate(1.0, 2.0, 0.8), EPSILON); - assertEquals(2.0, i.interpolate(1.0, 2.0, 1.0), EPSILON); - } - - @Test - public void testSPLINE_Convex() { - Interpolator i = Interpolator.SPLINE(0.5, 0.0, 1.0, 0.5); - assertEquals(1.0, i.interpolate(1.0, 2.0, 0.0), EPSILON); - assertEquals(1.0257826739185762, i.interpolate(1.0, 2.0, 0.2), EPSILON); - assertEquals(1.1599776046414838, i.interpolate(1.0, 2.0, 0.5), EPSILON); - assertEquals(1.4426257712793937, i.interpolate(1.0, 2.0, 0.8), EPSILON); - assertEquals(2.0, i.interpolate(1.0, 2.0, 1.0), EPSILON); - } - - @Test - public void testSPLINE_WithInflectionPoint() { - Interpolator i = Interpolator.SPLINE(0.0, 1.0, 1.0, 0.0); - - assertEquals(1.0, i.interpolate(1.0, 2.0, 0.0), EPSILON); - assertEquals(1.4614221762502215, i.interpolate(1.0, 2.0, 0.2), EPSILON); - assertEquals(1.5, i.interpolate(1.0, 2.0, 0.5), EPSILON); - assertEquals(1.5385778237497787, i.interpolate(1.0, 2.0, 0.8), EPSILON); - assertEquals(2.0, i.interpolate(1.0, 2.0, 1.0), EPSILON); - } - - @Test - public void testSPLINE_Linear() { - Interpolator i = Interpolator.SPLINE(1/3, 1/3, 2/3, 2/3); - - assertEquals(1.0, i.interpolate(1.0, 2.0, 0.0), EPSILON); - assertEquals(1.2, i.interpolate(1.0, 2.0, 0.2), EPSILON); - assertEquals(1.5, i.interpolate(1.0, 2.0, 0.5), EPSILON); - assertEquals(1.8, i.interpolate(1.0, 2.0, 0.8), EPSILON); - assertEquals(2.0, i.interpolate(1.0, 2.0, 1.0), EPSILON); - } - - @Test - public void testTANGENT_Linear() { - SimpleLongProperty property = new SimpleLongProperty(); - - Interpolator i0 = Interpolator.TANGENT(Duration.seconds(1), 20); - Interpolator i1 = Interpolator.TANGENT(Duration.seconds(1), 40); - - InterpolationInterval interval = InterpolationInterval.create(new KeyValue(property, 60L, i1), - TickCalculation.fromDuration(Duration.seconds(3)), - new KeyValue(property, 0L, i0), TickCalculation.fromDuration(Duration.seconds(3))); - - interval.interpolate(1.0/3.0); - assertEquals(20L, (long)property.getValue()); - interval.interpolate(1.0/2.0); - assertEquals(30L, (long)property.getValue()); - interval.interpolate(2.0/3.0); - assertEquals(40L, (long)property.getValue()); - } - - private static class DummyInterpolatable implements Interpolatable { - - final double value; - - private DummyInterpolatable(double value) { - this.value = value; - } - - @Override - public DummyInterpolatable interpolate(DummyInterpolatable endVal, double t) { - if (Math.abs(t) < EPSILON) { - return this; - } else if (Math.abs(t-1.0) < EPSILON) { - return endVal; - } else { - return new DummyInterpolatable(value + t * (endVal.value - value)); - } - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/InterpolatorTest.java 2015-09-11 21:25:20.149286363 -0400 @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import com.sun.javafx.animation.TickCalculation; +import com.sun.scenario.animation.shared.InterpolationInterval; +import javafx.animation.Interpolatable; +import javafx.animation.Interpolator; +import javafx.animation.KeyValue; +import javafx.beans.property.Property; +import javafx.beans.property.SimpleLongProperty; +import javafx.util.Duration; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class InterpolatorTest { + + private static final double EPSILON = 1e-12; + private static final float EPSILON_FLOAT = 1e-6f; + private static final DummyInterpolatable START = new DummyInterpolatable(0); + private static final DummyInterpolatable END = new DummyInterpolatable(10); + + @Test + public void testInterpolateWithObjects() { + final DummyInterpolatable i1 = new DummyInterpolatable(1); + final DummyInterpolatable i2 = new DummyInterpolatable(4); + final Object o = new Object(); + + assertEquals(Double.valueOf(2.5), (Double)Interpolator.LINEAR.interpolate(Double.valueOf(1), Integer.valueOf(4), 0.5), EPSILON); + assertEquals(Double.valueOf(2.5), (Double)Interpolator.LINEAR.interpolate(Integer.valueOf(4), Double.valueOf(1), 0.5), EPSILON); + assertEquals(Float.valueOf(2.5f), (Float)Interpolator.LINEAR.interpolate(Float.valueOf(1), Integer.valueOf(4), 0.5), EPSILON_FLOAT); + assertEquals(Float.valueOf(2.5f), (Float)Interpolator.LINEAR.interpolate(Integer.valueOf(4), Float.valueOf(1), 0.5), EPSILON_FLOAT); + assertEquals(Long.valueOf(3L), Interpolator.LINEAR.interpolate(Long.valueOf(1), Integer.valueOf(4), 0.5)); + assertEquals(Long.valueOf(3L), Interpolator.LINEAR.interpolate(Integer.valueOf(4), Long.valueOf(1), 0.5)); + assertEquals(Integer.valueOf(3), Interpolator.LINEAR.interpolate(Integer.valueOf(1), Integer.valueOf(4), 0.5)); + assertEquals(2.5, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(i1, i2, 0.5)).value, EPSILON); + + assertEquals(o, Interpolator.LINEAR.interpolate(o, Integer.MIN_VALUE, 1.0-2*EPSILON)); + assertEquals(Integer.MIN_VALUE, Interpolator.LINEAR.interpolate(o, Integer.MIN_VALUE, 1.0)); + + assertEquals(Integer.MIN_VALUE, Interpolator.LINEAR.interpolate(Integer.MIN_VALUE, o, 1.0-2*EPSILON)); + assertEquals(o, Interpolator.LINEAR.interpolate(Integer.MIN_VALUE, o, 1.0)); + + assertEquals(i1, Interpolator.LINEAR.interpolate(i1, o, 1.0-2*EPSILON)); + assertEquals(o, Interpolator.LINEAR.interpolate(i1, o, 1.0)); + } + + @Test + public void testDISCRETE() { + assertEquals(false, Interpolator.DISCRETE.interpolate(false, true, 1.0-2*EPSILON)); + assertEquals(true, Interpolator.DISCRETE.interpolate(false, true, 1.0)); + + assertEquals(1.0, Interpolator.DISCRETE.interpolate(1.0, 2.0, 1.0-2*EPSILON), EPSILON); + assertEquals(2.0, Interpolator.DISCRETE.interpolate(1.0, 2.0, 1.0), EPSILON); + + assertEquals(-3, Interpolator.DISCRETE.interpolate(-3, 7, 1.0-2*EPSILON)); + assertEquals( 7, Interpolator.DISCRETE.interpolate(-3, 7, 1.0)); + + assertEquals( 12L, Interpolator.DISCRETE.interpolate(12L, -201L, 1.0-2*EPSILON)); + assertEquals(-201L, Interpolator.DISCRETE.interpolate(12L, -201L, 1.0)); + + assertEquals( 0, ((DummyInterpolatable)Interpolator.DISCRETE.interpolate(START, END, 1.0-2*EPSILON)).value, EPSILON); + assertEquals(10, ((DummyInterpolatable)Interpolator.DISCRETE.interpolate(START, END, 1.0)).value, EPSILON); + } + + @Test + public void testLINEAR() { + assertEquals(false, Interpolator.LINEAR.interpolate(false, true, 0.0)); + assertEquals(false, Interpolator.LINEAR.interpolate(false, true, 0.1)); + assertEquals(false, Interpolator.LINEAR.interpolate(false, true, 0.5)); + assertEquals(false, Interpolator.LINEAR.interpolate(false, true, 0.9)); + assertEquals(true, Interpolator.LINEAR.interpolate(false, true, 1.0)); + + assertEquals(1.0, Interpolator.LINEAR.interpolate(1.0, 2.0, 0.0), EPSILON); + assertEquals(1.1, Interpolator.LINEAR.interpolate(1.0, 2.0, 0.1), EPSILON); + assertEquals(1.5, Interpolator.LINEAR.interpolate(1.0, 2.0, 0.5), EPSILON); + assertEquals(1.9, Interpolator.LINEAR.interpolate(1.0, 2.0, 0.9), EPSILON); + assertEquals(2.0, Interpolator.LINEAR.interpolate(1.0, 2.0, 1.0), EPSILON); + + assertEquals(-3, Interpolator.LINEAR.interpolate(-3, 7, 0.0)); + assertEquals(-2, Interpolator.LINEAR.interpolate(-3, 7, 0.1)); + assertEquals( 2, Interpolator.LINEAR.interpolate(-3, 7, 0.5)); + assertEquals( 6, Interpolator.LINEAR.interpolate(-3, 7, 0.9)); + assertEquals( 7, Interpolator.LINEAR.interpolate(-3, 7, 1.0)); + + assertEquals(-3L, Interpolator.LINEAR.interpolate(-3L, 7L, 0.0)); + assertEquals(-2L, Interpolator.LINEAR.interpolate(-3L, 7L, 0.1)); + assertEquals( 2L, Interpolator.LINEAR.interpolate(-3L, 7L, 0.5)); + assertEquals( 6L, Interpolator.LINEAR.interpolate(-3L, 7L, 0.9)); + assertEquals( 7L, Interpolator.LINEAR.interpolate(-3L, 7L, 1.0)); + + assertEquals( 0, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 0.0)).value, EPSILON); + assertEquals( 1, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 0.1)).value, EPSILON); + assertEquals( 5, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 0.5)).value, EPSILON); + assertEquals( 9, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 0.9)).value, EPSILON); + assertEquals(10, ((DummyInterpolatable)Interpolator.LINEAR.interpolate(START, END, 1.0)).value, EPSILON); + } + + @Test + public void testEASE_BOTH() { + // Expected results calculated with JavaFX SDK 1.3 + + assertEquals(false, Interpolator.EASE_BOTH.interpolate(false, true, 0.0)); + assertEquals(false, Interpolator.EASE_BOTH.interpolate(false, true, 0.1)); + assertEquals(false, Interpolator.EASE_BOTH.interpolate(false, true, 0.5)); + assertEquals(false, Interpolator.EASE_BOTH.interpolate(false, true, 0.9)); + assertEquals(true, Interpolator.EASE_BOTH.interpolate(false, true, 1.0)); + + assertEquals(1.0, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 0.0), EPSILON); + assertEquals(1.125, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 0.2), EPSILON); + assertEquals(1.5, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 0.5), EPSILON); + assertEquals(1.875, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 0.8), EPSILON); + assertEquals(2.0, Interpolator.EASE_BOTH.interpolate(1.0, 2.0, 1.0), EPSILON); + + assertEquals(-3, Interpolator.EASE_BOTH.interpolate(-3, 7, 0.0)); + assertEquals(-2, Interpolator.EASE_BOTH.interpolate(-3, 7, 0.2)); + assertEquals( 2, Interpolator.EASE_BOTH.interpolate(-3, 7, 0.5)); + assertEquals( 6, Interpolator.EASE_BOTH.interpolate(-3, 7, 0.8)); + assertEquals( 7, Interpolator.EASE_BOTH.interpolate(-3, 7, 1.0)); + + assertEquals(-3L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 0.0)); + assertEquals(-2L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 0.2)); + assertEquals( 2L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 0.5)); + assertEquals( 6L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 0.8)); + assertEquals( 7L, Interpolator.EASE_BOTH.interpolate(-3L, 7L, 1.0)); + + assertEquals( 0, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 0.0)).value, EPSILON); + assertEquals( 1.25, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 0.2)).value, EPSILON); + assertEquals( 5, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 0.5)).value, EPSILON); + assertEquals( 8.75, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 0.8)).value, EPSILON); + assertEquals(10, ((DummyInterpolatable)Interpolator.EASE_BOTH.interpolate(START, END, 1.0)).value, EPSILON); + } + + @Test + public void testEASE_IN() { + // Expected results calculated with JavaFX SDK 1.3 + + assertEquals(false, Interpolator.EASE_IN.interpolate(false, true, 0.0)); + assertEquals(false, Interpolator.EASE_IN.interpolate(false, true, 0.1)); + assertEquals(false, Interpolator.EASE_IN.interpolate(false, true, 0.5)); + assertEquals(false, Interpolator.EASE_IN.interpolate(false, true, 0.9)); + assertEquals(true, Interpolator.EASE_IN.interpolate(false, true, 1.0)); + + assertEquals(1.0, Interpolator.EASE_IN.interpolate(1.0, 2.0, 0.0), EPSILON); + assertEquals(1.1111111111111112, Interpolator.EASE_IN.interpolate(1.0, 2.0, 0.2), EPSILON); + assertEquals(1.4444444444444444, Interpolator.EASE_IN.interpolate(1.0, 2.0, 0.5), EPSILON); + assertEquals(1.777777777777778, Interpolator.EASE_IN.interpolate(1.0, 2.0, 0.8), EPSILON); + assertEquals(2.0, Interpolator.EASE_IN.interpolate(1.0, 2.0, 1.0), EPSILON); + + assertEquals(-3, Interpolator.EASE_IN.interpolate(-3, 7, 0.0)); + assertEquals(-2, Interpolator.EASE_IN.interpolate(-3, 7, 0.2)); + assertEquals( 1, Interpolator.EASE_IN.interpolate(-3, 7, 0.5)); + assertEquals( 5, Interpolator.EASE_IN.interpolate(-3, 7, 0.8)); + assertEquals( 7, Interpolator.EASE_IN.interpolate(-3, 7, 1.0)); + + assertEquals(-3L, Interpolator.EASE_IN.interpolate(-3L, 7L, 0.0)); + assertEquals(-2L, Interpolator.EASE_IN.interpolate(-3L, 7L, 0.2)); + assertEquals( 1L, Interpolator.EASE_IN.interpolate(-3L, 7L, 0.5)); + assertEquals( 5L, Interpolator.EASE_IN.interpolate(-3L, 7L, 0.8)); + assertEquals( 7L, Interpolator.EASE_IN.interpolate(-3L, 7L, 1.0)); + + assertEquals( 0, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 0.0)).value, EPSILON); + assertEquals( 1.1111111111111114, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 0.2)).value, EPSILON); + assertEquals( 4.444444444444445, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 0.5)).value, EPSILON); + assertEquals( 7.777777777777779, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 0.8)).value, EPSILON); + assertEquals(10, ((DummyInterpolatable)Interpolator.EASE_IN.interpolate(START, END, 1.0)).value, EPSILON); + } + + @Test + public void testEASE_OUT() { + // Expected results calculated with JavaFX SDK 1.3 + + assertEquals(false, Interpolator.EASE_OUT.interpolate(false, true, 0.0)); + assertEquals(false, Interpolator.EASE_OUT.interpolate(false, true, 0.1)); + assertEquals(false, Interpolator.EASE_OUT.interpolate(false, true, 0.5)); + assertEquals(false, Interpolator.EASE_OUT.interpolate(false, true, 0.9)); + assertEquals(true, Interpolator.EASE_OUT.interpolate(false, true, 1.0)); + + assertEquals(1.0, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 0.0), EPSILON); + assertEquals(1.2222222222222223, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 0.2), EPSILON); + assertEquals(1.5555555555555556, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 0.5), EPSILON); + assertEquals(1.8888888888888888, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 0.8), EPSILON); + assertEquals(2.0, Interpolator.EASE_OUT.interpolate(1.0, 2.0, 1.0), EPSILON); + + assertEquals(-3, Interpolator.EASE_OUT.interpolate(-3, 7, 0.0)); + assertEquals(-1, Interpolator.EASE_OUT.interpolate(-3, 7, 0.2)); + assertEquals( 3, Interpolator.EASE_OUT.interpolate(-3, 7, 0.5)); + assertEquals( 6, Interpolator.EASE_OUT.interpolate(-3, 7, 0.8)); + assertEquals( 7, Interpolator.EASE_OUT.interpolate(-3, 7, 1.0)); + + assertEquals(-3L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 0.0)); + assertEquals(-1L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 0.2)); + assertEquals( 3L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 0.5)); + assertEquals( 6L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 0.8)); + assertEquals( 7L, Interpolator.EASE_OUT.interpolate(-3L, 7L, 1.0)); + + assertEquals( 0, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 0.0)).value, EPSILON); + assertEquals( 2.2222222222222223, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 0.2)).value, EPSILON); + assertEquals( 5.555555555555555, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 0.5)).value, EPSILON); + assertEquals( 8.88888888888889, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 0.8)).value, EPSILON); + assertEquals(10, ((DummyInterpolatable)Interpolator.EASE_OUT.interpolate(START, END, 1.0)).value, EPSILON); + } + + @Test + public void testSPLINE_Concave() { + Interpolator i = Interpolator.SPLINE(0.0, 0.5, 0.5, 1.0); + assertEquals(1.0, i.interpolate(1.0, 2.0, 0.0), EPSILON); + assertEquals(1.5573742287206063, i.interpolate(1.0, 2.0, 0.2), EPSILON); + assertEquals(1.8400223953585164, i.interpolate(1.0, 2.0, 0.5), EPSILON); + assertEquals(1.9742173260814238, i.interpolate(1.0, 2.0, 0.8), EPSILON); + assertEquals(2.0, i.interpolate(1.0, 2.0, 1.0), EPSILON); + } + + @Test + public void testSPLINE_Convex() { + Interpolator i = Interpolator.SPLINE(0.5, 0.0, 1.0, 0.5); + assertEquals(1.0, i.interpolate(1.0, 2.0, 0.0), EPSILON); + assertEquals(1.0257826739185762, i.interpolate(1.0, 2.0, 0.2), EPSILON); + assertEquals(1.1599776046414838, i.interpolate(1.0, 2.0, 0.5), EPSILON); + assertEquals(1.4426257712793937, i.interpolate(1.0, 2.0, 0.8), EPSILON); + assertEquals(2.0, i.interpolate(1.0, 2.0, 1.0), EPSILON); + } + + @Test + public void testSPLINE_WithInflectionPoint() { + Interpolator i = Interpolator.SPLINE(0.0, 1.0, 1.0, 0.0); + + assertEquals(1.0, i.interpolate(1.0, 2.0, 0.0), EPSILON); + assertEquals(1.4614221762502215, i.interpolate(1.0, 2.0, 0.2), EPSILON); + assertEquals(1.5, i.interpolate(1.0, 2.0, 0.5), EPSILON); + assertEquals(1.5385778237497787, i.interpolate(1.0, 2.0, 0.8), EPSILON); + assertEquals(2.0, i.interpolate(1.0, 2.0, 1.0), EPSILON); + } + + @Test + public void testSPLINE_Linear() { + Interpolator i = Interpolator.SPLINE(1/3, 1/3, 2/3, 2/3); + + assertEquals(1.0, i.interpolate(1.0, 2.0, 0.0), EPSILON); + assertEquals(1.2, i.interpolate(1.0, 2.0, 0.2), EPSILON); + assertEquals(1.5, i.interpolate(1.0, 2.0, 0.5), EPSILON); + assertEquals(1.8, i.interpolate(1.0, 2.0, 0.8), EPSILON); + assertEquals(2.0, i.interpolate(1.0, 2.0, 1.0), EPSILON); + } + + @Test + public void testTANGENT_Linear() { + SimpleLongProperty property = new SimpleLongProperty(); + + Interpolator i0 = Interpolator.TANGENT(Duration.seconds(1), 20); + Interpolator i1 = Interpolator.TANGENT(Duration.seconds(1), 40); + + InterpolationInterval interval = InterpolationInterval.create(new KeyValue(property, 60L, i1), + TickCalculation.fromDuration(Duration.seconds(3)), + new KeyValue(property, 0L, i0), TickCalculation.fromDuration(Duration.seconds(3))); + + interval.interpolate(1.0/3.0); + assertEquals(20L, (long)property.getValue()); + interval.interpolate(1.0/2.0); + assertEquals(30L, (long)property.getValue()); + interval.interpolate(2.0/3.0); + assertEquals(40L, (long)property.getValue()); + } + + private static class DummyInterpolatable implements Interpolatable { + + final double value; + + private DummyInterpolatable(double value) { + this.value = value; + } + + @Override + public DummyInterpolatable interpolate(DummyInterpolatable endVal, double t) { + if (Math.abs(t) < EPSILON) { + return this; + } else if (Math.abs(t-1.0) < EPSILON) { + return endVal; + } else { + return new DummyInterpolatable(value + t * (endVal.value - value)); + } + } + } +} --- old/modules/graphics/src/test/java/javafx/animation/KeyFrameTest.java 2015-09-11 21:25:21.061286353 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,251 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Set; - -import javafx.beans.property.IntegerProperty; -import javafx.beans.property.SimpleIntegerProperty; -import javafx.event.ActionEvent; -import javafx.event.EventHandler; -import javafx.util.Duration; - -import org.junit.Test; - -public class KeyFrameTest { - private static final Duration TIME = Duration.ONE; - private static final KeyValue[] NO_KEYVALUES = new KeyValue[0]; - private static final List NO_KEYVALUES_COL = Arrays.asList(NO_KEYVALUES); - private static final String NAME = "KeyFrameName"; - private static final EventHandler ACTION = event -> {}; - - private final IntegerProperty TARGET = new SimpleIntegerProperty(); - private final KeyValue[] ONE_KEYVALUE = new KeyValue[] { - new KeyValue(TARGET, 1) - }; - private final KeyValue[] TWO_KEYVALUES = new KeyValue[] { - new KeyValue(TARGET, 0), - new KeyValue(TARGET, 1) - }; - private final List ONE_KEYVALUE_COL = Arrays.asList(ONE_KEYVALUE); - private final List TWO_KEYVALUES_COL = Arrays.asList(TWO_KEYVALUES); - - private void assertSetEquals(T[] expected, Set result) { - assertEquals(expected.length, result.size()); - for (final T element : expected) { - assertTrue(result.contains(element)); - } - } - - @Test public void testConstructor_ObservableList() { - // test no values - final KeyFrame kf0 = new KeyFrame(TIME, NAME, ACTION, NO_KEYVALUES_COL); - assertEquals(TIME, kf0.getTime()); - assertEquals(NAME, kf0.getName()); - assertEquals(ACTION, kf0.getOnFinished()); - assertSetEquals(NO_KEYVALUES, kf0.getValues()); - - // test two values - final KeyFrame kf1 = new KeyFrame(TIME, NAME, ACTION, ONE_KEYVALUE_COL); - assertEquals(TIME, kf1.getTime()); - assertEquals(NAME, kf1.getName()); - assertEquals(ACTION, kf1.getOnFinished()); - assertSetEquals(ONE_KEYVALUE, kf1.getValues()); - - // test two values - final KeyFrame kf2 = new KeyFrame(TIME, NAME, ACTION, TWO_KEYVALUES_COL); - assertEquals(TIME, kf2.getTime()); - assertEquals(NAME, kf2.getName()); - assertEquals(ACTION, kf2.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf2.getValues()); - } - - @Test public void testConstructor_ObservableList_SpecialCases() { - // name is null - final KeyFrame kf1 = new KeyFrame(TIME, null, ACTION, TWO_KEYVALUES_COL); - assertEquals(TIME, kf1.getTime()); - assertNull(kf1.getName()); - assertEquals(ACTION, kf1.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf1.getValues()); - - // action is null - final KeyFrame kf2 = new KeyFrame(TIME, NAME, null, TWO_KEYVALUES_COL); - assertEquals(TIME, kf2.getTime()); - assertEquals(NAME, kf2.getName()); - assertNull(kf2.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf2.getValues()); - - // observableArrayList is null - final KeyFrame kf3 = new KeyFrame(TIME, NAME, ACTION, (Collection)null); - assertEquals(TIME, kf3.getTime()); - assertEquals(NAME, kf3.getName()); - assertEquals(ACTION, kf3.getOnFinished()); - assertSetEquals(NO_KEYVALUES, kf3.getValues()); - - // empty observableArrayList - final KeyFrame kf4 = new KeyFrame(TIME, NAME, ACTION, (Collection)null); - assertEquals(TIME, kf4.getTime()); - assertEquals(NAME, kf4.getName()); - assertEquals(ACTION, kf4.getOnFinished()); - assertSetEquals(NO_KEYVALUES, kf4.getValues()); - - // a value is null - final KeyFrame kf5 = new KeyFrame(TIME, NAME, ACTION, Arrays.asList(TWO_KEYVALUES[0], null, TWO_KEYVALUES[1])); - assertEquals(TIME, kf5.getTime()); - assertEquals(NAME, kf5.getName()); - assertEquals(ACTION, kf5.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf2.getValues()); - }; - - @Test(expected=NullPointerException.class) - public void testConstructor_ObservableList_DurationIsNull(){ - new KeyFrame(null, NAME, ACTION, TWO_KEYVALUES_COL); - }; - - @Test(expected=IllegalArgumentException.class) - public void testConstructor_ObservableList_DurationIsNegative(){ - new KeyFrame(Duration.millis(-1), NAME, ACTION, TWO_KEYVALUES_COL); - }; - - @Test(expected=IllegalArgumentException.class) - public void testConstructor_ObservableList_DuratinIsUnknown(){ - new KeyFrame(Duration.UNKNOWN, NAME, ACTION, TWO_KEYVALUES_COL); - }; - - @Test public void testConstructor_Time_Name_Action_Valus() { - // no values - final KeyFrame kf0 = new KeyFrame(TIME, NAME, ACTION, NO_KEYVALUES); - assertEquals(TIME, kf0.getTime()); - assertEquals(NAME, kf0.getName()); - assertEquals(ACTION, kf0.getOnFinished()); - assertSetEquals(NO_KEYVALUES, kf0.getValues()); - - // one value - final KeyFrame kf1 = new KeyFrame(TIME, NAME, ACTION, ONE_KEYVALUE); - assertEquals(TIME, kf1.getTime()); - assertEquals(NAME, kf1.getName()); - assertEquals(ACTION, kf1.getOnFinished()); - assertSetEquals(ONE_KEYVALUE, kf1.getValues()); - - // two values - final KeyFrame kf2 = new KeyFrame(TIME, NAME, ACTION, TWO_KEYVALUES); - assertEquals(TIME, kf2.getTime()); - assertEquals(NAME, kf2.getName()); - assertEquals(ACTION, kf2.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf2.getValues()); - } - - @Test public void testConstructor_Time_Name_Action_Valus_SpecialCases() { - // name is null - final KeyFrame kf1 = new KeyFrame(TIME, null, ACTION, TWO_KEYVALUES); - assertEquals(TIME, kf1.getTime()); - assertNull(kf1.getName()); - assertEquals(ACTION, kf1.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf1.getValues()); - - // action is null - final KeyFrame kf2 = new KeyFrame(TIME, NAME, null, TWO_KEYVALUES); - assertEquals(TIME, kf2.getTime()); - assertEquals(NAME, kf2.getName()); - assertNull(kf2.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf2.getValues()); - - // values are empty - final KeyFrame kf3 = new KeyFrame(TIME, NAME, ACTION, new KeyValue[0]); - assertEquals(TIME, kf3.getTime()); - assertEquals(NAME, kf3.getName()); - assertEquals(ACTION, kf3.getOnFinished()); - assertSetEquals(NO_KEYVALUES, kf3.getValues()); - - // values are null - final KeyFrame kf4 = new KeyFrame(TIME, NAME, ACTION, (KeyValue[])null); - assertEquals(TIME, kf4.getTime()); - assertEquals(NAME, kf4.getName()); - assertEquals(ACTION, kf4.getOnFinished()); - assertSetEquals(NO_KEYVALUES, kf4.getValues()); - - // a value is null - final KeyFrame kf5 = new KeyFrame(TIME, NAME, ACTION, TWO_KEYVALUES[0], null, TWO_KEYVALUES[1]); - assertEquals(TIME, kf5.getTime()); - assertEquals(NAME, kf5.getName()); - assertEquals(ACTION, kf5.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf5.getValues()); - - // only value is null - final KeyFrame kf6 = new KeyFrame(TIME, NAME, ACTION, (KeyValue)null); - assertEquals(TIME, kf6.getTime()); - assertEquals(NAME, kf6.getName()); - assertEquals(ACTION, kf6.getOnFinished()); - assertSetEquals(NO_KEYVALUES, kf6.getValues()); - } - - @Test(expected=NullPointerException.class) - public void testConstructor_KeyValues_DurationIsNull(){ - new KeyFrame(null, NAME, ACTION, TWO_KEYVALUES); - }; - - @Test(expected=IllegalArgumentException.class) - public void testConstructor_KeyValues_DurationIsNegative(){ - new KeyFrame(Duration.millis(-1), NAME, ACTION, TWO_KEYVALUES); - }; - - @Test(expected=IllegalArgumentException.class) - public void testConstructor_KeyValues_DurationIsUnknown(){ - new KeyFrame(Duration.UNKNOWN, NAME, ACTION, TWO_KEYVALUES); - }; - - @Test public void testConstructor_Time_Action_Valus() { - final KeyFrame kf0 = new KeyFrame(TIME, ACTION, TWO_KEYVALUES); - assertEquals(TIME, kf0.getTime()); - assertNull(kf0.getName()); - assertEquals(ACTION, kf0.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf0.getValues()); - } - - @Test public void testConstructor_Time_Name_Valus() { - final KeyFrame kf0 = new KeyFrame(TIME, NAME, TWO_KEYVALUES); - assertEquals(TIME, kf0.getTime()); - assertEquals(NAME, kf0.getName()); - assertNull(kf0.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf0.getValues()); - } - - @Test public void testConstructor_Time_Valus() { - final KeyFrame kf0 = new KeyFrame(TIME, TWO_KEYVALUES); - assertEquals(TIME, kf0.getTime()); - assertNull(kf0.getName()); - assertNull(kf0.getOnFinished()); - assertSetEquals(TWO_KEYVALUES, kf0.getValues()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/KeyFrameTest.java 2015-09-11 21:25:20.921286355 -0400 @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import javafx.animation.KeyFrame; +import javafx.animation.KeyValue; + +import javafx.beans.property.IntegerProperty; +import javafx.beans.property.SimpleIntegerProperty; +import javafx.event.ActionEvent; +import javafx.event.EventHandler; +import javafx.util.Duration; + +import org.junit.Test; + +public class KeyFrameTest { + private static final Duration TIME = Duration.ONE; + private static final KeyValue[] NO_KEYVALUES = new KeyValue[0]; + private static final List NO_KEYVALUES_COL = Arrays.asList(NO_KEYVALUES); + private static final String NAME = "KeyFrameName"; + private static final EventHandler ACTION = event -> {}; + + private final IntegerProperty TARGET = new SimpleIntegerProperty(); + private final KeyValue[] ONE_KEYVALUE = new KeyValue[] { + new KeyValue(TARGET, 1) + }; + private final KeyValue[] TWO_KEYVALUES = new KeyValue[] { + new KeyValue(TARGET, 0), + new KeyValue(TARGET, 1) + }; + private final List ONE_KEYVALUE_COL = Arrays.asList(ONE_KEYVALUE); + private final List TWO_KEYVALUES_COL = Arrays.asList(TWO_KEYVALUES); + + private void assertSetEquals(T[] expected, Set result) { + assertEquals(expected.length, result.size()); + for (final T element : expected) { + assertTrue(result.contains(element)); + } + } + + @Test public void testConstructor_ObservableList() { + // test no values + final KeyFrame kf0 = new KeyFrame(TIME, NAME, ACTION, NO_KEYVALUES_COL); + assertEquals(TIME, kf0.getTime()); + assertEquals(NAME, kf0.getName()); + assertEquals(ACTION, kf0.getOnFinished()); + assertSetEquals(NO_KEYVALUES, kf0.getValues()); + + // test two values + final KeyFrame kf1 = new KeyFrame(TIME, NAME, ACTION, ONE_KEYVALUE_COL); + assertEquals(TIME, kf1.getTime()); + assertEquals(NAME, kf1.getName()); + assertEquals(ACTION, kf1.getOnFinished()); + assertSetEquals(ONE_KEYVALUE, kf1.getValues()); + + // test two values + final KeyFrame kf2 = new KeyFrame(TIME, NAME, ACTION, TWO_KEYVALUES_COL); + assertEquals(TIME, kf2.getTime()); + assertEquals(NAME, kf2.getName()); + assertEquals(ACTION, kf2.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf2.getValues()); + } + + @Test public void testConstructor_ObservableList_SpecialCases() { + // name is null + final KeyFrame kf1 = new KeyFrame(TIME, null, ACTION, TWO_KEYVALUES_COL); + assertEquals(TIME, kf1.getTime()); + assertNull(kf1.getName()); + assertEquals(ACTION, kf1.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf1.getValues()); + + // action is null + final KeyFrame kf2 = new KeyFrame(TIME, NAME, null, TWO_KEYVALUES_COL); + assertEquals(TIME, kf2.getTime()); + assertEquals(NAME, kf2.getName()); + assertNull(kf2.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf2.getValues()); + + // observableArrayList is null + final KeyFrame kf3 = new KeyFrame(TIME, NAME, ACTION, (Collection)null); + assertEquals(TIME, kf3.getTime()); + assertEquals(NAME, kf3.getName()); + assertEquals(ACTION, kf3.getOnFinished()); + assertSetEquals(NO_KEYVALUES, kf3.getValues()); + + // empty observableArrayList + final KeyFrame kf4 = new KeyFrame(TIME, NAME, ACTION, (Collection)null); + assertEquals(TIME, kf4.getTime()); + assertEquals(NAME, kf4.getName()); + assertEquals(ACTION, kf4.getOnFinished()); + assertSetEquals(NO_KEYVALUES, kf4.getValues()); + + // a value is null + final KeyFrame kf5 = new KeyFrame(TIME, NAME, ACTION, Arrays.asList(TWO_KEYVALUES[0], null, TWO_KEYVALUES[1])); + assertEquals(TIME, kf5.getTime()); + assertEquals(NAME, kf5.getName()); + assertEquals(ACTION, kf5.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf2.getValues()); + }; + + @Test(expected=NullPointerException.class) + public void testConstructor_ObservableList_DurationIsNull(){ + new KeyFrame(null, NAME, ACTION, TWO_KEYVALUES_COL); + }; + + @Test(expected=IllegalArgumentException.class) + public void testConstructor_ObservableList_DurationIsNegative(){ + new KeyFrame(Duration.millis(-1), NAME, ACTION, TWO_KEYVALUES_COL); + }; + + @Test(expected=IllegalArgumentException.class) + public void testConstructor_ObservableList_DuratinIsUnknown(){ + new KeyFrame(Duration.UNKNOWN, NAME, ACTION, TWO_KEYVALUES_COL); + }; + + @Test public void testConstructor_Time_Name_Action_Valus() { + // no values + final KeyFrame kf0 = new KeyFrame(TIME, NAME, ACTION, NO_KEYVALUES); + assertEquals(TIME, kf0.getTime()); + assertEquals(NAME, kf0.getName()); + assertEquals(ACTION, kf0.getOnFinished()); + assertSetEquals(NO_KEYVALUES, kf0.getValues()); + + // one value + final KeyFrame kf1 = new KeyFrame(TIME, NAME, ACTION, ONE_KEYVALUE); + assertEquals(TIME, kf1.getTime()); + assertEquals(NAME, kf1.getName()); + assertEquals(ACTION, kf1.getOnFinished()); + assertSetEquals(ONE_KEYVALUE, kf1.getValues()); + + // two values + final KeyFrame kf2 = new KeyFrame(TIME, NAME, ACTION, TWO_KEYVALUES); + assertEquals(TIME, kf2.getTime()); + assertEquals(NAME, kf2.getName()); + assertEquals(ACTION, kf2.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf2.getValues()); + } + + @Test public void testConstructor_Time_Name_Action_Valus_SpecialCases() { + // name is null + final KeyFrame kf1 = new KeyFrame(TIME, null, ACTION, TWO_KEYVALUES); + assertEquals(TIME, kf1.getTime()); + assertNull(kf1.getName()); + assertEquals(ACTION, kf1.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf1.getValues()); + + // action is null + final KeyFrame kf2 = new KeyFrame(TIME, NAME, null, TWO_KEYVALUES); + assertEquals(TIME, kf2.getTime()); + assertEquals(NAME, kf2.getName()); + assertNull(kf2.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf2.getValues()); + + // values are empty + final KeyFrame kf3 = new KeyFrame(TIME, NAME, ACTION, new KeyValue[0]); + assertEquals(TIME, kf3.getTime()); + assertEquals(NAME, kf3.getName()); + assertEquals(ACTION, kf3.getOnFinished()); + assertSetEquals(NO_KEYVALUES, kf3.getValues()); + + // values are null + final KeyFrame kf4 = new KeyFrame(TIME, NAME, ACTION, (KeyValue[])null); + assertEquals(TIME, kf4.getTime()); + assertEquals(NAME, kf4.getName()); + assertEquals(ACTION, kf4.getOnFinished()); + assertSetEquals(NO_KEYVALUES, kf4.getValues()); + + // a value is null + final KeyFrame kf5 = new KeyFrame(TIME, NAME, ACTION, TWO_KEYVALUES[0], null, TWO_KEYVALUES[1]); + assertEquals(TIME, kf5.getTime()); + assertEquals(NAME, kf5.getName()); + assertEquals(ACTION, kf5.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf5.getValues()); + + // only value is null + final KeyFrame kf6 = new KeyFrame(TIME, NAME, ACTION, (KeyValue)null); + assertEquals(TIME, kf6.getTime()); + assertEquals(NAME, kf6.getName()); + assertEquals(ACTION, kf6.getOnFinished()); + assertSetEquals(NO_KEYVALUES, kf6.getValues()); + } + + @Test(expected=NullPointerException.class) + public void testConstructor_KeyValues_DurationIsNull(){ + new KeyFrame(null, NAME, ACTION, TWO_KEYVALUES); + }; + + @Test(expected=IllegalArgumentException.class) + public void testConstructor_KeyValues_DurationIsNegative(){ + new KeyFrame(Duration.millis(-1), NAME, ACTION, TWO_KEYVALUES); + }; + + @Test(expected=IllegalArgumentException.class) + public void testConstructor_KeyValues_DurationIsUnknown(){ + new KeyFrame(Duration.UNKNOWN, NAME, ACTION, TWO_KEYVALUES); + }; + + @Test public void testConstructor_Time_Action_Valus() { + final KeyFrame kf0 = new KeyFrame(TIME, ACTION, TWO_KEYVALUES); + assertEquals(TIME, kf0.getTime()); + assertNull(kf0.getName()); + assertEquals(ACTION, kf0.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf0.getValues()); + } + + @Test public void testConstructor_Time_Name_Valus() { + final KeyFrame kf0 = new KeyFrame(TIME, NAME, TWO_KEYVALUES); + assertEquals(TIME, kf0.getTime()); + assertEquals(NAME, kf0.getName()); + assertNull(kf0.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf0.getValues()); + } + + @Test public void testConstructor_Time_Valus() { + final KeyFrame kf0 = new KeyFrame(TIME, TWO_KEYVALUES); + assertEquals(TIME, kf0.getTime()); + assertNull(kf0.getName()); + assertNull(kf0.getOnFinished()); + assertSetEquals(TWO_KEYVALUES, kf0.getValues()); + } +} --- old/modules/graphics/src/test/java/javafx/animation/KeyValueTest.java 2015-09-11 21:25:21.741286345 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,275 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - - -import static org.junit.Assert.assertEquals; -import javafx.beans.property.BooleanProperty; -import javafx.beans.property.DoubleProperty; -import javafx.beans.property.FloatProperty; -import javafx.beans.property.IntegerProperty; -import javafx.beans.property.LongProperty; -import javafx.beans.property.SimpleBooleanProperty; -import javafx.beans.property.SimpleDoubleProperty; -import javafx.beans.property.SimpleFloatProperty; -import javafx.beans.property.SimpleIntegerProperty; -import javafx.beans.property.SimpleLongProperty; -import javafx.beans.property.SimpleStringProperty; -import javafx.beans.property.StringProperty; -import javafx.beans.value.WritableFloatValue; -import javafx.beans.value.WritableIntegerValue; -import javafx.beans.value.WritableLongValue; -import javafx.beans.value.WritableValue; - -import org.junit.Test; - -public class KeyValueTest { - - private static final double EPSILON_DOUBLE = 1e-12; - private static final float EPSILON_FLOAT = 1e-6f; - - private void assertKeyValue(KeyValue.Type type, WritableValue target, Object endValue, Interpolator interpolator, KeyValue kv) { - assertEquals(type, kv.getType()); - assertEquals(target, kv.getTarget()); - assertEquals(endValue, kv.getEndValue()); - assertEquals(interpolator, kv.getInterpolator()); - } - - private void assertKeyValue(KeyValue.Type type, WritableValue target, Interpolator interpolator, KeyValue kv) { - assertEquals(type, kv.getType()); - assertEquals(target, kv.getTarget()); - assertEquals(interpolator, kv.getInterpolator()); - } - - - - @Test - public void testBooleanFactory_Interpolator() { - final BooleanProperty v = new SimpleBooleanProperty(); - final KeyValue kv = new KeyValue(v, true, Interpolator.EASE_BOTH); - assertKeyValue(KeyValue.Type.BOOLEAN, v, Boolean.TRUE, Interpolator.EASE_BOTH, kv); - } - - @Test(expected=NullPointerException.class) - public void testBooleanFactory_Interpolator_NullTarget() { - new KeyValue(null, true, Interpolator.EASE_BOTH); - } - - @Test(expected=NullPointerException.class) - public void testBooleanFactory_Interpolator_NullInterpolator() { - final BooleanProperty v = new SimpleBooleanProperty(); - new KeyValue(v, true, null); - } - - - - @Test - public void testBooleanFactory() { - final BooleanProperty v = new SimpleBooleanProperty(); - final KeyValue kv = new KeyValue(v, true); - assertKeyValue(KeyValue.Type.BOOLEAN, v, Boolean.TRUE, Interpolator.LINEAR, kv); - } - - @Test(expected=NullPointerException.class) - public void testBooleanFactory_NullTarget() { - new KeyValue(null, true); - } - - - - @Test - public void testDoubleFactory_Interpolator() { - final DoubleProperty v = new SimpleDoubleProperty(); - final KeyValue kv = new KeyValue(v, Math.PI, Interpolator.EASE_BOTH); - assertKeyValue(KeyValue.Type.DOUBLE, v, Interpolator.EASE_BOTH, kv); - assertEquals(Math.PI, ((Number)kv.getEndValue()).doubleValue(), EPSILON_DOUBLE); - } - - @Test(expected=NullPointerException.class) - public void testDoubleFactory_Interpolator_NullTarget() { - new KeyValue(null, Math.PI, Interpolator.EASE_BOTH); - } - - @Test(expected=NullPointerException.class) - public void testDoubleFactory_Interpolator_NullInterpolator() { - final DoubleProperty v = new SimpleDoubleProperty(); - new KeyValue(v, Math.PI, null); - } - - - - @Test - public void testDoubleFactory() { - final DoubleProperty v = new SimpleDoubleProperty(); - final KeyValue kv = new KeyValue(v, Math.E); - assertKeyValue(KeyValue.Type.DOUBLE, v, Interpolator.LINEAR, kv); - assertEquals(Math.E, ((Number)kv.getEndValue()).doubleValue(), EPSILON_DOUBLE); - } - - @Test(expected=NullPointerException.class) - public void testDoubleFactory_NullTarget() { - new KeyValue(null, Math.E); - } - - - - @Test - public void testFloatFactory_Interpolator() { - final FloatProperty v = new SimpleFloatProperty(); - final KeyValue kv = new KeyValue(v, (float)Math.E, Interpolator.EASE_BOTH); - assertKeyValue(KeyValue.Type.FLOAT, v, Interpolator.EASE_BOTH, kv); - assertEquals((float)Math.E, ((Number)kv.getEndValue()).floatValue(), EPSILON_FLOAT); - } - - @Test(expected=NullPointerException.class) - public void testFloatFactory_Interpolator_NullTarget() { - new KeyValue((WritableFloatValue)null, (float)Math.E, Interpolator.EASE_BOTH); - } - - @Test(expected=NullPointerException.class) - public void testFloatFactory_Interpolator_NullInterpolator() { - final FloatProperty v = new SimpleFloatProperty(); - new KeyValue(v, (float)Math.E, null); - } - - - - @Test - public void testFloatFactory() { - final FloatProperty v = new SimpleFloatProperty(); - final KeyValue kv = new KeyValue(v, (float)Math.PI); - assertKeyValue(KeyValue.Type.FLOAT, v, Interpolator.LINEAR, kv); - assertEquals((float)Math.PI, ((Number)kv.getEndValue()).floatValue(), EPSILON_FLOAT); - } - - @Test(expected=NullPointerException.class) - public void testFloatFactory_NullTarget() { - new KeyValue((WritableFloatValue)null, (float)Math.PI); - } - - - - @Test - public void testIntegerFactory_Interpolator() { - final IntegerProperty v = new SimpleIntegerProperty(); - final KeyValue kv = new KeyValue(v, Integer.MAX_VALUE, Interpolator.EASE_BOTH); - assertKeyValue(KeyValue.Type.INTEGER, v, Integer.MAX_VALUE, Interpolator.EASE_BOTH, kv); - } - - @Test(expected=NullPointerException.class) - public void testIntegerFactory_Interpolator_NullTarget() { - new KeyValue((WritableIntegerValue)null, 1, Interpolator.EASE_BOTH); - } - - @Test(expected=NullPointerException.class) - public void testIntegerFactory_Interpolator_NullInterpolator() { - final IntegerProperty v = new SimpleIntegerProperty(); - new KeyValue(v, 1, null); - } - - - - @Test - public void testIntegerFactory() { - final IntegerProperty v = new SimpleIntegerProperty(); - final KeyValue kv = new KeyValue(v, Integer.MIN_VALUE); - assertKeyValue(KeyValue.Type.INTEGER, v, Integer.MIN_VALUE, Interpolator.LINEAR, kv); - } - - @Test(expected=NullPointerException.class) - public void testIntegerFactory_NullTarget() { - new KeyValue((WritableIntegerValue)null, Integer.MIN_VALUE); - } - - - - @Test - public void testLongFactory_Interpolator() { - final LongProperty v = new SimpleLongProperty(); - final KeyValue kv = new KeyValue(v, Long.MAX_VALUE, Interpolator.EASE_BOTH); - assertKeyValue(KeyValue.Type.LONG, v, Long.MAX_VALUE, Interpolator.EASE_BOTH, kv); - } - - @Test(expected=NullPointerException.class) - public void testLongFactory_Interpolator_NullTarget() { - new KeyValue((WritableLongValue)null, 1L, Interpolator.EASE_BOTH); - } - - @Test(expected=NullPointerException.class) - public void testLongFactory_Interpolator_NullInterpolator() { - final LongProperty v = new SimpleLongProperty(); - new KeyValue(v, 1L, null); - } - - - - @Test - public void testLongFactory() { - final LongProperty v = new SimpleLongProperty(); - final KeyValue kv = new KeyValue(v, Long.MIN_VALUE); - assertKeyValue(KeyValue.Type.LONG, v, Long.MIN_VALUE, Interpolator.LINEAR, kv); - } - - @Test(expected=NullPointerException.class) - public void testLongFactory_NullTarget() { - new KeyValue((WritableLongValue)null, Long.MIN_VALUE); - } - - - - @Test - public void testObjectFactory_Interpolator() { - final StringProperty v = new SimpleStringProperty(); - final KeyValue kv = new KeyValue(v, "Hello World", Interpolator.EASE_BOTH); - assertKeyValue(KeyValue.Type.OBJECT, v, "Hello World", Interpolator.EASE_BOTH, kv); - } - - @Test(expected=NullPointerException.class) - public void testObjectFactory_Interpolator_NullTarget() { - new KeyValue(null, "Hello World", Interpolator.EASE_BOTH); - } - - @Test(expected=NullPointerException.class) - public void testObjectFactory_Interpolator_NullInterpolator() { - final StringProperty v = new SimpleStringProperty(); - new KeyValue(v, "Hello World", null); - } - - - - @Test - public void testObjectFactory() { - final StringProperty v = new SimpleStringProperty(); - final KeyValue kv = new KeyValue(v, "Goodbye World"); - assertKeyValue(KeyValue.Type.OBJECT, v, "Goodbye World", Interpolator.LINEAR, kv); - } - - @Test(expected=NullPointerException.class) - public void testObjectFactory_NullTarget() { - new KeyValue(null, "Goodbye World"); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/KeyValueTest.java 2015-09-11 21:25:21.601286347 -0400 @@ -0,0 +1,277 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + + +import javafx.animation.Interpolator; +import javafx.animation.KeyValue; +import static org.junit.Assert.assertEquals; +import javafx.beans.property.BooleanProperty; +import javafx.beans.property.DoubleProperty; +import javafx.beans.property.FloatProperty; +import javafx.beans.property.IntegerProperty; +import javafx.beans.property.LongProperty; +import javafx.beans.property.SimpleBooleanProperty; +import javafx.beans.property.SimpleDoubleProperty; +import javafx.beans.property.SimpleFloatProperty; +import javafx.beans.property.SimpleIntegerProperty; +import javafx.beans.property.SimpleLongProperty; +import javafx.beans.property.SimpleStringProperty; +import javafx.beans.property.StringProperty; +import javafx.beans.value.WritableFloatValue; +import javafx.beans.value.WritableIntegerValue; +import javafx.beans.value.WritableLongValue; +import javafx.beans.value.WritableValue; + +import org.junit.Test; + +public class KeyValueTest { + + private static final double EPSILON_DOUBLE = 1e-12; + private static final float EPSILON_FLOAT = 1e-6f; + + private void assertKeyValue(KeyValue.Type type, WritableValue target, Object endValue, Interpolator interpolator, KeyValue kv) { + assertEquals(type, kv.getType()); + assertEquals(target, kv.getTarget()); + assertEquals(endValue, kv.getEndValue()); + assertEquals(interpolator, kv.getInterpolator()); + } + + private void assertKeyValue(KeyValue.Type type, WritableValue target, Interpolator interpolator, KeyValue kv) { + assertEquals(type, kv.getType()); + assertEquals(target, kv.getTarget()); + assertEquals(interpolator, kv.getInterpolator()); + } + + + + @Test + public void testBooleanFactory_Interpolator() { + final BooleanProperty v = new SimpleBooleanProperty(); + final KeyValue kv = new KeyValue(v, true, Interpolator.EASE_BOTH); + assertKeyValue(KeyValue.Type.BOOLEAN, v, Boolean.TRUE, Interpolator.EASE_BOTH, kv); + } + + @Test(expected=NullPointerException.class) + public void testBooleanFactory_Interpolator_NullTarget() { + new KeyValue(null, true, Interpolator.EASE_BOTH); + } + + @Test(expected=NullPointerException.class) + public void testBooleanFactory_Interpolator_NullInterpolator() { + final BooleanProperty v = new SimpleBooleanProperty(); + new KeyValue(v, true, null); + } + + + + @Test + public void testBooleanFactory() { + final BooleanProperty v = new SimpleBooleanProperty(); + final KeyValue kv = new KeyValue(v, true); + assertKeyValue(KeyValue.Type.BOOLEAN, v, Boolean.TRUE, Interpolator.LINEAR, kv); + } + + @Test(expected=NullPointerException.class) + public void testBooleanFactory_NullTarget() { + new KeyValue(null, true); + } + + + + @Test + public void testDoubleFactory_Interpolator() { + final DoubleProperty v = new SimpleDoubleProperty(); + final KeyValue kv = new KeyValue(v, Math.PI, Interpolator.EASE_BOTH); + assertKeyValue(KeyValue.Type.DOUBLE, v, Interpolator.EASE_BOTH, kv); + assertEquals(Math.PI, ((Number)kv.getEndValue()).doubleValue(), EPSILON_DOUBLE); + } + + @Test(expected=NullPointerException.class) + public void testDoubleFactory_Interpolator_NullTarget() { + new KeyValue(null, Math.PI, Interpolator.EASE_BOTH); + } + + @Test(expected=NullPointerException.class) + public void testDoubleFactory_Interpolator_NullInterpolator() { + final DoubleProperty v = new SimpleDoubleProperty(); + new KeyValue(v, Math.PI, null); + } + + + + @Test + public void testDoubleFactory() { + final DoubleProperty v = new SimpleDoubleProperty(); + final KeyValue kv = new KeyValue(v, Math.E); + assertKeyValue(KeyValue.Type.DOUBLE, v, Interpolator.LINEAR, kv); + assertEquals(Math.E, ((Number)kv.getEndValue()).doubleValue(), EPSILON_DOUBLE); + } + + @Test(expected=NullPointerException.class) + public void testDoubleFactory_NullTarget() { + new KeyValue(null, Math.E); + } + + + + @Test + public void testFloatFactory_Interpolator() { + final FloatProperty v = new SimpleFloatProperty(); + final KeyValue kv = new KeyValue(v, (float)Math.E, Interpolator.EASE_BOTH); + assertKeyValue(KeyValue.Type.FLOAT, v, Interpolator.EASE_BOTH, kv); + assertEquals((float)Math.E, ((Number)kv.getEndValue()).floatValue(), EPSILON_FLOAT); + } + + @Test(expected=NullPointerException.class) + public void testFloatFactory_Interpolator_NullTarget() { + new KeyValue((WritableFloatValue)null, (float)Math.E, Interpolator.EASE_BOTH); + } + + @Test(expected=NullPointerException.class) + public void testFloatFactory_Interpolator_NullInterpolator() { + final FloatProperty v = new SimpleFloatProperty(); + new KeyValue(v, (float)Math.E, null); + } + + + + @Test + public void testFloatFactory() { + final FloatProperty v = new SimpleFloatProperty(); + final KeyValue kv = new KeyValue(v, (float)Math.PI); + assertKeyValue(KeyValue.Type.FLOAT, v, Interpolator.LINEAR, kv); + assertEquals((float)Math.PI, ((Number)kv.getEndValue()).floatValue(), EPSILON_FLOAT); + } + + @Test(expected=NullPointerException.class) + public void testFloatFactory_NullTarget() { + new KeyValue((WritableFloatValue)null, (float)Math.PI); + } + + + + @Test + public void testIntegerFactory_Interpolator() { + final IntegerProperty v = new SimpleIntegerProperty(); + final KeyValue kv = new KeyValue(v, Integer.MAX_VALUE, Interpolator.EASE_BOTH); + assertKeyValue(KeyValue.Type.INTEGER, v, Integer.MAX_VALUE, Interpolator.EASE_BOTH, kv); + } + + @Test(expected=NullPointerException.class) + public void testIntegerFactory_Interpolator_NullTarget() { + new KeyValue((WritableIntegerValue)null, 1, Interpolator.EASE_BOTH); + } + + @Test(expected=NullPointerException.class) + public void testIntegerFactory_Interpolator_NullInterpolator() { + final IntegerProperty v = new SimpleIntegerProperty(); + new KeyValue(v, 1, null); + } + + + + @Test + public void testIntegerFactory() { + final IntegerProperty v = new SimpleIntegerProperty(); + final KeyValue kv = new KeyValue(v, Integer.MIN_VALUE); + assertKeyValue(KeyValue.Type.INTEGER, v, Integer.MIN_VALUE, Interpolator.LINEAR, kv); + } + + @Test(expected=NullPointerException.class) + public void testIntegerFactory_NullTarget() { + new KeyValue((WritableIntegerValue)null, Integer.MIN_VALUE); + } + + + + @Test + public void testLongFactory_Interpolator() { + final LongProperty v = new SimpleLongProperty(); + final KeyValue kv = new KeyValue(v, Long.MAX_VALUE, Interpolator.EASE_BOTH); + assertKeyValue(KeyValue.Type.LONG, v, Long.MAX_VALUE, Interpolator.EASE_BOTH, kv); + } + + @Test(expected=NullPointerException.class) + public void testLongFactory_Interpolator_NullTarget() { + new KeyValue((WritableLongValue)null, 1L, Interpolator.EASE_BOTH); + } + + @Test(expected=NullPointerException.class) + public void testLongFactory_Interpolator_NullInterpolator() { + final LongProperty v = new SimpleLongProperty(); + new KeyValue(v, 1L, null); + } + + + + @Test + public void testLongFactory() { + final LongProperty v = new SimpleLongProperty(); + final KeyValue kv = new KeyValue(v, Long.MIN_VALUE); + assertKeyValue(KeyValue.Type.LONG, v, Long.MIN_VALUE, Interpolator.LINEAR, kv); + } + + @Test(expected=NullPointerException.class) + public void testLongFactory_NullTarget() { + new KeyValue((WritableLongValue)null, Long.MIN_VALUE); + } + + + + @Test + public void testObjectFactory_Interpolator() { + final StringProperty v = new SimpleStringProperty(); + final KeyValue kv = new KeyValue(v, "Hello World", Interpolator.EASE_BOTH); + assertKeyValue(KeyValue.Type.OBJECT, v, "Hello World", Interpolator.EASE_BOTH, kv); + } + + @Test(expected=NullPointerException.class) + public void testObjectFactory_Interpolator_NullTarget() { + new KeyValue(null, "Hello World", Interpolator.EASE_BOTH); + } + + @Test(expected=NullPointerException.class) + public void testObjectFactory_Interpolator_NullInterpolator() { + final StringProperty v = new SimpleStringProperty(); + new KeyValue(v, "Hello World", null); + } + + + + @Test + public void testObjectFactory() { + final StringProperty v = new SimpleStringProperty(); + final KeyValue kv = new KeyValue(v, "Goodbye World"); + assertKeyValue(KeyValue.Type.OBJECT, v, "Goodbye World", Interpolator.LINEAR, kv); + } + + @Test(expected=NullPointerException.class) + public void testObjectFactory_NullTarget() { + new KeyValue(null, "Goodbye World"); + } + +} --- old/modules/graphics/src/test/java/javafx/animation/ParallelTransitionPlayTest.java 2015-09-11 21:25:22.341286339 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,969 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import com.sun.javafx.animation.TickCalculation; -import javafx.animation.Animation.Status; -import javafx.beans.property.LongProperty; -import javafx.beans.property.SimpleLongProperty; -import javafx.util.Duration; -import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; - -public class ParallelTransitionPlayTest { - public static final double TICK_MILLIS = TickCalculation.toMillis(100); - public static final long TICK_STEP = Math.round(TICK_MILLIS); - - LongProperty xProperty = new SimpleLongProperty(); - LongProperty yProperty = new SimpleLongProperty(); - - AbstractMasterTimerMock amt; - ParallelTransition pt; - - Transition child1X; - Transition child2X; - Transition child1Y; - Transition childByX; - - @Before - public void setUp() { - amt = new AbstractMasterTimerMock(); - pt = new ParallelTransition(amt); - child1X = new Transition() { - - { - setCycleDuration(Duration.minutes(1)); - setInterpolator(Interpolator.LINEAR); - } - - @Override - protected void interpolate(double d) { - xProperty.set(Math.round(d * 60000)); - } - }; - child1Y = new Transition() { - - { - setCycleDuration(Duration.seconds(10)); - setInterpolator(Interpolator.LINEAR); - } - - @Override - protected void interpolate(double d) { - yProperty.set(Math.round(d * 10000)); - } - }; - childByX = new Transition() { - { - setCycleDuration(Duration.seconds(1)); - setInterpolator(Interpolator.LINEAR); - } - - long lastX; - - @Override - protected void interpolate(double frac) { - xProperty.set(Math.round(lastX + frac * 1000)); - } - - @Override - void impl_sync(boolean forceSync) { - super.impl_sync(forceSync); - if (forceSync) { - lastX = xProperty.get(); - } - } - - - }; - } - - - @Test - public void testSimplePlay() { - pt.getChildren().addAll(child1X, child1Y); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - amt.pulse(); - assertEquals(TickCalculation.toDuration(100), pt.getCurrentTime()); - assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); - assertEquals(TickCalculation.toDuration(100), child1Y.getCurrentTime()); - assertEquals(TICK_STEP, xProperty.get()); - assertEquals(TICK_STEP, yProperty.get()); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - - pt.jumpTo(Duration.seconds(10).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(10000 - TICK_STEP, xProperty.get()); - assertEquals(10000 - TICK_STEP, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.jumpTo(Duration.minutes(1).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - } - - @Test - public void testSimplePlayReversed() { - pt.getChildren().addAll(child1X, child1Y); - - pt.setRate(-1.0); - pt.jumpTo(Duration.seconds(60)); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - amt.pulse(); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - pt.jumpTo(Duration.seconds(10).add(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(10000 - TICK_STEP, xProperty.get()); - assertEquals(10000 - TICK_STEP, yProperty.get()); - - pt.jumpTo(TickCalculation.toDuration(100)); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(TICK_STEP, xProperty.get()); - assertEquals(TICK_STEP, yProperty.get()); - - amt.pulse(); - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - } - - @Test - public void testCycle() { - pt.getChildren().addAll(child1X, child1Y); - pt.setCycleCount(2); - - pt.play(); - - pt.jumpTo(Duration.minutes(1).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - - pt.jumpTo(Duration.seconds(65).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(5000 - TICK_STEP, xProperty.get()); - assertEquals(5000 - TICK_STEP, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(5000, xProperty.get()); - assertEquals(5000, yProperty.get()); - - pt.jumpTo(Duration.minutes(2).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - } - - @Test - public void testCycleReversed() { - pt.getChildren().addAll(child1X, child1Y); - pt.setCycleCount(2); - pt.setRate(-1.0); - pt.jumpTo(Duration.seconds(60)); - - pt.play(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.jumpTo(Duration.seconds(60).add(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(TICK_STEP, xProperty.get()); - assertEquals(TICK_STEP, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.jumpTo(Duration.minutes(2).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - Math.round(2 * TICK_MILLIS), xProperty.get()); - assertEquals(10000, yProperty.get()); - - } - - @Test - public void testAutoReverse() { - pt.getChildren().addAll(child1X, child1Y); - pt.setAutoReverse(true); - pt.setCycleCount(-1); - - pt.play(); - - for (int i = 0; i < TickCalculation.fromDuration(Duration.seconds(60)) / 100 - 1; ++i) { - amt.pulse(); - } - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - } - - @Test - public void testAutoReverseWithJump() { - pt.getChildren().addAll(child1X, child1Y); - pt.setAutoReverse(true); - pt.setCycleCount(-1); - - pt.play(); - - pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - } - - @Test - public void testJump() { - pt.getChildren().addAll(child1X, child1Y); - - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - - pt.jumpTo(Duration.seconds(10)); - - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - - pt.play(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); //Note: Not sure if we need to have also child1X running at this point - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.jumpTo(Duration.seconds(55)); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(55000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.jumpTo(Duration.seconds(10)); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.stop(); - - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - } - - @Test - public void testToggleRate() { - pt.getChildren().addAll(child1X, child1Y); - - pt.play(); - - pt.jumpTo(Duration.seconds(10)); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(10000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.setRate(-1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - - assertEquals(10000 - TICK_STEP, xProperty.get()); - assertEquals(10000 - TICK_STEP, yProperty.get()); - - pt.setRate(1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(10000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - } - - @Test - public void testToggleRate_2() { - pt.getChildren().addAll(child1X, child1Y); - - pt.play(); - - pt.jumpTo(Duration.seconds(20)); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(20000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.setRate(-1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(20000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.setRate(1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(20000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - } - - - @Test - public void testChildWithDifferentRate() { - pt.getChildren().addAll(child1X, child1Y); - child1X.setRate(2.0); - - pt.play(); - - amt.pulse(); - - assertEquals(Math.round(TICK_MILLIS * 2), xProperty.get()); - - pt.jumpTo(Duration.seconds(30)); - - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.jumpTo(Duration.seconds(40)); - - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.jumpTo(Duration.seconds(5)); - amt.pulse(); - - pt.setRate(-1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(10000 - Math.round(TICK_MILLIS * 2), xProperty.get()); - assertEquals(5000 - TICK_STEP, yProperty.get()); - - pt.setRate(1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(10000 + Math.round(TICK_MILLIS * 2), xProperty.get()); - assertEquals(5000 + TICK_STEP, yProperty.get()); - - } - - @Test - public void testPauseForward1() { - pt.getChildren().addAll(child1X, child1Y); - - pt.play(); - pt.jumpTo(Duration.seconds(5)); - amt.pulse(); - pt.pause(); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(5000 + TICK_STEP, xProperty.get()); - assertEquals(5000 + TICK_STEP, yProperty.get()); - - pt.jumpTo(Duration.seconds(6)); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(6000, xProperty.get()); - assertEquals(6000, yProperty.get()); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(6000, xProperty.get()); - assertEquals(6000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(6000 + TICK_STEP, xProperty.get()); - assertEquals(6000 + TICK_STEP, yProperty.get()); - - pt.pause(); - pt.jumpTo(Duration.seconds(7)); - pt.jumpTo(Duration.seconds(9)); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(9000, xProperty.get()); - assertEquals(9000, yProperty.get()); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(9000, xProperty.get()); - assertEquals(9000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(9000 + TICK_STEP, xProperty.get()); - assertEquals(9000 + TICK_STEP, yProperty.get()); - - pt.pause(); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(9000 + TICK_STEP, xProperty.get()); - assertEquals(9000 + TICK_STEP, yProperty.get()); - - pt.jumpTo(Duration.seconds(10).subtract(TickCalculation.toDuration(100))); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(10000 - TICK_STEP, xProperty.get()); - assertEquals(10000 - TICK_STEP, yProperty.get()); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(10000 - TICK_STEP, xProperty.get()); - assertEquals(10000 - TICK_STEP, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.pause(); - pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - } - - @Test - public void testPauseForward2() { - pt.getChildren().addAll(child1X, child1Y); - - pt.play(); - pt.jumpTo(Duration.seconds(5)); - amt.pulse(); - pt.pause(); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(5000 + TICK_STEP, xProperty.get()); - assertEquals(5000 + TICK_STEP, yProperty.get()); - - pt.jumpTo(Duration.seconds(30)); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(30000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(30000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(30000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.pause(); - pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - } - - @Test - public void testPauseAutoReverse() { - pt.getChildren().addAll(child1X, child1Y); - pt.setAutoReverse(true); - pt.setCycleCount(-1); - - pt.play(); - pt.jumpTo(Duration.seconds(5)); - amt.pulse(); - pt.pause(); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(5000 + TICK_STEP, xProperty.get()); - assertEquals(5000 + TICK_STEP, yProperty.get()); - - pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.pause(); - pt.jumpTo(Duration.seconds(110).subtract(TickCalculation.toDuration(100))); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000 + TICK_STEP, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(10000 - TICK_STEP, xProperty.get()); - assertEquals(10000 - TICK_STEP, yProperty.get()); - - pt.pause(); - pt.jumpTo(Duration.seconds(120).subtract(TickCalculation.toDuration(100))); - assertEquals(Status.PAUSED, pt.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(0 + TICK_STEP, xProperty.get()); - assertEquals(0 + TICK_STEP, yProperty.get()); - - pt.play(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(0 + TICK_STEP, xProperty.get()); - assertEquals(0 + TICK_STEP, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(0 + TICK_STEP, xProperty.get()); - assertEquals(0 + TICK_STEP, yProperty.get()); - } - - - @Test public void testNestedParallelTransition() { - ParallelTransition pt2 = new ParallelTransition(); - - pt.getChildren().addAll(pt2, child1X); - pt2.getChildren().add(child1Y); - - pt.play(); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, pt2.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(TICK_STEP, xProperty.get()); - assertEquals(TICK_STEP, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, pt2.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(Math.round(TICK_MILLIS * 2), xProperty.get()); - assertEquals(Math.round(TICK_MILLIS * 2), yProperty.get()); - - - pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); - - amt.pulse(); - - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, pt2.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - pt.play(); - - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, pt2.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(TICK_STEP, xProperty.get()); - assertEquals(TICK_STEP, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, pt.getStatus()); - assertEquals(Status.RUNNING, pt2.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(Math.round(TICK_MILLIS * 2), xProperty.get()); - assertEquals(Math.round(TICK_MILLIS * 2), yProperty.get()); - - - pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); - - amt.pulse(); - - assertEquals(Status.STOPPED, pt.getStatus()); - assertEquals(Status.STOPPED, pt2.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - } - - @Test - public void testPlayFromStartSynchronization() { - pt.getChildren().addAll(child1Y, childByX); - - pt.play(); - - assertEquals(0, yProperty.get()); - assertEquals(0, xProperty.get()); - - pt.jumpTo(Duration.seconds(10)); - amt.pulse(); - - pt.play(); - assertEquals(0, yProperty.get()); - assertEquals(1000, xProperty.get()); - - pt.jumpTo(Duration.seconds(10)); - amt.pulse(); - - assertEquals(10000, yProperty.get()); - assertEquals(2000, xProperty.get()); - - } - - @Test - public void testCycleSynchronization() { - pt.setCycleCount(2); - pt.getChildren().addAll(childByX); - - pt.play(); - - assertEquals(0, xProperty.get()); - - pt.jumpTo(Duration.seconds(1)); - amt.pulse(); - - assertEquals(TICK_STEP, xProperty.get()); - - pt.jumpTo(Duration.seconds(2)); - amt.pulse(); - - assertEquals(1000, xProperty.get()); - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/ParallelTransitionPlayTest.java 2015-09-11 21:25:22.205286340 -0400 @@ -0,0 +1,974 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import com.sun.javafx.animation.TickCalculation; +import javafx.animation.Animation.Status; +import javafx.animation.Interpolator; +import javafx.animation.ParallelTransition; +import javafx.animation.ParallelTransitionShim; +import javafx.animation.Transition; +import javafx.animation.TransitionShim; +import javafx.beans.property.LongProperty; +import javafx.beans.property.SimpleLongProperty; +import javafx.util.Duration; +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; + +public class ParallelTransitionPlayTest { + public static final double TICK_MILLIS = TickCalculation.toMillis(100); + public static final long TICK_STEP = Math.round(TICK_MILLIS); + + LongProperty xProperty = new SimpleLongProperty(); + LongProperty yProperty = new SimpleLongProperty(); + + AbstractMasterTimerMock amt; + ParallelTransition pt; + + Transition child1X; + Transition child2X; + Transition child1Y; + Transition childByX; + + @Before + public void setUp() { + amt = new AbstractMasterTimerMock(); + pt = ParallelTransitionShim.getParallelTransition(amt); + child1X = new TransitionShim() { + + { + setCycleDuration(Duration.minutes(1)); + setInterpolator(Interpolator.LINEAR); + } + + @Override + protected void interpolate(double d) { + xProperty.set(Math.round(d * 60000)); + } + }; + child1Y = new TransitionShim() { + + { + setCycleDuration(Duration.seconds(10)); + setInterpolator(Interpolator.LINEAR); + } + + @Override + protected void interpolate(double d) { + yProperty.set(Math.round(d * 10000)); + } + }; + childByX = new TransitionShim() { + { + setCycleDuration(Duration.seconds(1)); + setInterpolator(Interpolator.LINEAR); + } + + long lastX; + + @Override + protected void interpolate(double frac) { + xProperty.set(Math.round(lastX + frac * 1000)); + } + + @Override + public void impl_sync(boolean forceSync) { + super.impl_sync(forceSync); + if (forceSync) { + lastX = xProperty.get(); + } + } + + + }; + } + + + @Test + public void testSimplePlay() { + pt.getChildren().addAll(child1X, child1Y); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + amt.pulse(); + assertEquals(TickCalculation.toDuration(100), pt.getCurrentTime()); + assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); + assertEquals(TickCalculation.toDuration(100), child1Y.getCurrentTime()); + assertEquals(TICK_STEP, xProperty.get()); + assertEquals(TICK_STEP, yProperty.get()); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + + pt.jumpTo(Duration.seconds(10).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(10000 - TICK_STEP, xProperty.get()); + assertEquals(10000 - TICK_STEP, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.jumpTo(Duration.minutes(1).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + } + + @Test + public void testSimplePlayReversed() { + pt.getChildren().addAll(child1X, child1Y); + + pt.setRate(-1.0); + pt.jumpTo(Duration.seconds(60)); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + amt.pulse(); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + pt.jumpTo(Duration.seconds(10).add(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(10000 - TICK_STEP, xProperty.get()); + assertEquals(10000 - TICK_STEP, yProperty.get()); + + pt.jumpTo(TickCalculation.toDuration(100)); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(TICK_STEP, xProperty.get()); + assertEquals(TICK_STEP, yProperty.get()); + + amt.pulse(); + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + } + + @Test + public void testCycle() { + pt.getChildren().addAll(child1X, child1Y); + pt.setCycleCount(2); + + pt.play(); + + pt.jumpTo(Duration.minutes(1).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + + pt.jumpTo(Duration.seconds(65).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(5000 - TICK_STEP, xProperty.get()); + assertEquals(5000 - TICK_STEP, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(5000, xProperty.get()); + assertEquals(5000, yProperty.get()); + + pt.jumpTo(Duration.minutes(2).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + } + + @Test + public void testCycleReversed() { + pt.getChildren().addAll(child1X, child1Y); + pt.setCycleCount(2); + pt.setRate(-1.0); + pt.jumpTo(Duration.seconds(60)); + + pt.play(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.jumpTo(Duration.seconds(60).add(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(TICK_STEP, xProperty.get()); + assertEquals(TICK_STEP, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.jumpTo(Duration.minutes(2).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - Math.round(2 * TICK_MILLIS), xProperty.get()); + assertEquals(10000, yProperty.get()); + + } + + @Test + public void testAutoReverse() { + pt.getChildren().addAll(child1X, child1Y); + pt.setAutoReverse(true); + pt.setCycleCount(-1); + + pt.play(); + + for (int i = 0; i < TickCalculation.fromDuration(Duration.seconds(60)) / 100 - 1; ++i) { + amt.pulse(); + } + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + } + + @Test + public void testAutoReverseWithJump() { + pt.getChildren().addAll(child1X, child1Y); + pt.setAutoReverse(true); + pt.setCycleCount(-1); + + pt.play(); + + pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + } + + @Test + public void testJump() { + pt.getChildren().addAll(child1X, child1Y); + + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + + pt.jumpTo(Duration.seconds(10)); + + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + + pt.play(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); //Note: Not sure if we need to have also child1X running at this point + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.jumpTo(Duration.seconds(55)); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(55000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.jumpTo(Duration.seconds(10)); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.stop(); + + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + } + + @Test + public void testToggleRate() { + pt.getChildren().addAll(child1X, child1Y); + + pt.play(); + + pt.jumpTo(Duration.seconds(10)); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(10000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.setRate(-1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + + assertEquals(10000 - TICK_STEP, xProperty.get()); + assertEquals(10000 - TICK_STEP, yProperty.get()); + + pt.setRate(1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(10000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + } + + @Test + public void testToggleRate_2() { + pt.getChildren().addAll(child1X, child1Y); + + pt.play(); + + pt.jumpTo(Duration.seconds(20)); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(20000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.setRate(-1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(20000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.setRate(1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(20000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + } + + + @Test + public void testChildWithDifferentRate() { + pt.getChildren().addAll(child1X, child1Y); + child1X.setRate(2.0); + + pt.play(); + + amt.pulse(); + + assertEquals(Math.round(TICK_MILLIS * 2), xProperty.get()); + + pt.jumpTo(Duration.seconds(30)); + + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.jumpTo(Duration.seconds(40)); + + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.jumpTo(Duration.seconds(5)); + amt.pulse(); + + pt.setRate(-1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(10000 - Math.round(TICK_MILLIS * 2), xProperty.get()); + assertEquals(5000 - TICK_STEP, yProperty.get()); + + pt.setRate(1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(10000 + Math.round(TICK_MILLIS * 2), xProperty.get()); + assertEquals(5000 + TICK_STEP, yProperty.get()); + + } + + @Test + public void testPauseForward1() { + pt.getChildren().addAll(child1X, child1Y); + + pt.play(); + pt.jumpTo(Duration.seconds(5)); + amt.pulse(); + pt.pause(); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(5000 + TICK_STEP, xProperty.get()); + assertEquals(5000 + TICK_STEP, yProperty.get()); + + pt.jumpTo(Duration.seconds(6)); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(6000, xProperty.get()); + assertEquals(6000, yProperty.get()); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(6000, xProperty.get()); + assertEquals(6000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(6000 + TICK_STEP, xProperty.get()); + assertEquals(6000 + TICK_STEP, yProperty.get()); + + pt.pause(); + pt.jumpTo(Duration.seconds(7)); + pt.jumpTo(Duration.seconds(9)); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(9000, xProperty.get()); + assertEquals(9000, yProperty.get()); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(9000, xProperty.get()); + assertEquals(9000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(9000 + TICK_STEP, xProperty.get()); + assertEquals(9000 + TICK_STEP, yProperty.get()); + + pt.pause(); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(9000 + TICK_STEP, xProperty.get()); + assertEquals(9000 + TICK_STEP, yProperty.get()); + + pt.jumpTo(Duration.seconds(10).subtract(TickCalculation.toDuration(100))); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(10000 - TICK_STEP, xProperty.get()); + assertEquals(10000 - TICK_STEP, yProperty.get()); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(10000 - TICK_STEP, xProperty.get()); + assertEquals(10000 - TICK_STEP, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.pause(); + pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + } + + @Test + public void testPauseForward2() { + pt.getChildren().addAll(child1X, child1Y); + + pt.play(); + pt.jumpTo(Duration.seconds(5)); + amt.pulse(); + pt.pause(); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(5000 + TICK_STEP, xProperty.get()); + assertEquals(5000 + TICK_STEP, yProperty.get()); + + pt.jumpTo(Duration.seconds(30)); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(30000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(30000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(30000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.pause(); + pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + } + + @Test + public void testPauseAutoReverse() { + pt.getChildren().addAll(child1X, child1Y); + pt.setAutoReverse(true); + pt.setCycleCount(-1); + + pt.play(); + pt.jumpTo(Duration.seconds(5)); + amt.pulse(); + pt.pause(); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(5000 + TICK_STEP, xProperty.get()); + assertEquals(5000 + TICK_STEP, yProperty.get()); + + pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.pause(); + pt.jumpTo(Duration.seconds(110).subtract(TickCalculation.toDuration(100))); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000 + TICK_STEP, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(10000 - TICK_STEP, xProperty.get()); + assertEquals(10000 - TICK_STEP, yProperty.get()); + + pt.pause(); + pt.jumpTo(Duration.seconds(120).subtract(TickCalculation.toDuration(100))); + assertEquals(Status.PAUSED, pt.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(0 + TICK_STEP, xProperty.get()); + assertEquals(0 + TICK_STEP, yProperty.get()); + + pt.play(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(0 + TICK_STEP, xProperty.get()); + assertEquals(0 + TICK_STEP, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(0 + TICK_STEP, xProperty.get()); + assertEquals(0 + TICK_STEP, yProperty.get()); + } + + + @Test public void testNestedParallelTransition() { + ParallelTransition pt2 = new ParallelTransition(); + + pt.getChildren().addAll(pt2, child1X); + pt2.getChildren().add(child1Y); + + pt.play(); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, pt2.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(TICK_STEP, xProperty.get()); + assertEquals(TICK_STEP, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, pt2.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(Math.round(TICK_MILLIS * 2), xProperty.get()); + assertEquals(Math.round(TICK_MILLIS * 2), yProperty.get()); + + + pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); + + amt.pulse(); + + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, pt2.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + pt.play(); + + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, pt2.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(TICK_STEP, xProperty.get()); + assertEquals(TICK_STEP, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, pt.getStatus()); + assertEquals(Status.RUNNING, pt2.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(Math.round(TICK_MILLIS * 2), xProperty.get()); + assertEquals(Math.round(TICK_MILLIS * 2), yProperty.get()); + + + pt.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); + + amt.pulse(); + + assertEquals(Status.STOPPED, pt.getStatus()); + assertEquals(Status.STOPPED, pt2.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + } + + @Test + public void testPlayFromStartSynchronization() { + pt.getChildren().addAll(child1Y, childByX); + + pt.play(); + + assertEquals(0, yProperty.get()); + assertEquals(0, xProperty.get()); + + pt.jumpTo(Duration.seconds(10)); + amt.pulse(); + + pt.play(); + assertEquals(0, yProperty.get()); + assertEquals(1000, xProperty.get()); + + pt.jumpTo(Duration.seconds(10)); + amt.pulse(); + + assertEquals(10000, yProperty.get()); + assertEquals(2000, xProperty.get()); + + } + + @Test + public void testCycleSynchronization() { + pt.setCycleCount(2); + pt.getChildren().addAll(childByX); + + pt.play(); + + assertEquals(0, xProperty.get()); + + pt.jumpTo(Duration.seconds(1)); + amt.pulse(); + + assertEquals(TICK_STEP, xProperty.get()); + + pt.jumpTo(Duration.seconds(2)); + amt.pulse(); + + assertEquals(1000, xProperty.get()); + + } + +} --- old/modules/graphics/src/test/java/javafx/animation/ParallelTransitionTest.java 2015-09-11 21:25:23.061286331 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; - -import javafx.scene.Node; -import javafx.scene.shape.Rectangle; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - -public class ParallelTransitionTest { - - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.LINEAR; - - private static Duration ONE_SEC = Duration.millis(1000); - private static Duration TWO_SECS = Duration.millis(2000); - private static Duration THREE_SECS = Duration.millis(3000); - - private Node node; - private Animation child1; - private Animation child2; - private Animation child3; - - @Before - public void setUp() { - node = new Rectangle(); - child1 = new AnimationDummy(ONE_SEC); - child2 = new AnimationDummy(TWO_SECS); - child3 = new AnimationDummy(THREE_SECS); - } - - @Test - public void testDefaultValues() { - // empty ctor - final ParallelTransition t0 = new ParallelTransition(); - assertEquals(Duration.ZERO, t0.getTotalDuration()); - assertNull(t0.getNode()); - assertNull(t0.nodeProperty().get()); - assertTrue(t0.getChildren().isEmpty()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // node only - final ParallelTransition t1 = new ParallelTransition(node); - assertEquals(Duration.ZERO, t1.getTotalDuration()); - assertEquals(node, t1.getNode()); - assertEquals(node, t1.nodeProperty().get()); - assertTrue(t1.getChildren().isEmpty()); - assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); - assertNull(t1.getOnFinished()); - - // child animations only - final ParallelTransition t2 = new ParallelTransition(child1, child2, child3); - assertEquals(THREE_SECS, t2.getTotalDuration()); - assertNull(t2.getNode()); - assertNull(t2.nodeProperty().get()); - assertEquals(Arrays.asList(child1, child2, child3), t2.getChildren()); - assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); - assertNull(t2.getOnFinished()); - - // node and child animations - final ParallelTransition t3 = new ParallelTransition(node, child1, child2, child3); - assertEquals(THREE_SECS, t3.getTotalDuration()); - assertEquals(node, t3.getNode()); - assertEquals(node, t3.nodeProperty().get()); - assertEquals(Arrays.asList(child1, child2, child3), t3.getChildren()); - assertEquals(DEFAULT_INTERPOLATOR, t3.getInterpolator()); - assertNull(t3.getOnFinished()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/ParallelTransitionTest.java 2015-09-11 21:25:22.921286332 -0400 @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import javafx.animation.Animation; +import javafx.animation.Interpolator; +import javafx.animation.ParallelTransition; + +import javafx.scene.Node; +import javafx.scene.shape.Rectangle; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + +public class ParallelTransitionTest { + + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.LINEAR; + + private static Duration ONE_SEC = Duration.millis(1000); + private static Duration TWO_SECS = Duration.millis(2000); + private static Duration THREE_SECS = Duration.millis(3000); + + private Node node; + private Animation child1; + private Animation child2; + private Animation child3; + + @Before + public void setUp() { + node = new Rectangle(); + child1 = new AnimationDummy(ONE_SEC); + child2 = new AnimationDummy(TWO_SECS); + child3 = new AnimationDummy(THREE_SECS); + } + + @Test + public void testDefaultValues() { + // empty ctor + final ParallelTransition t0 = new ParallelTransition(); + assertEquals(Duration.ZERO, t0.getTotalDuration()); + assertNull(t0.getNode()); + assertNull(t0.nodeProperty().get()); + assertTrue(t0.getChildren().isEmpty()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // node only + final ParallelTransition t1 = new ParallelTransition(node); + assertEquals(Duration.ZERO, t1.getTotalDuration()); + assertEquals(node, t1.getNode()); + assertEquals(node, t1.nodeProperty().get()); + assertTrue(t1.getChildren().isEmpty()); + assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); + assertNull(t1.getOnFinished()); + + // child animations only + final ParallelTransition t2 = new ParallelTransition(child1, child2, child3); + assertEquals(THREE_SECS, t2.getTotalDuration()); + assertNull(t2.getNode()); + assertNull(t2.nodeProperty().get()); + assertEquals(Arrays.asList(child1, child2, child3), t2.getChildren()); + assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); + assertNull(t2.getOnFinished()); + + // node and child animations + final ParallelTransition t3 = new ParallelTransition(node, child1, child2, child3); + assertEquals(THREE_SECS, t3.getTotalDuration()); + assertEquals(node, t3.getNode()); + assertEquals(node, t3.nodeProperty().get()); + assertEquals(Arrays.asList(child1, child2, child3), t3.getChildren()); + assertEquals(DEFAULT_INTERPOLATOR, t3.getInterpolator()); + assertNull(t3.getOnFinished()); + } +} --- old/modules/graphics/src/test/java/javafx/animation/PathTransitionTest.java 2015-09-11 21:25:23.753286323 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import javafx.scene.Node; -import javafx.scene.shape.Circle; -import javafx.scene.shape.Rectangle; -import javafx.scene.shape.Shape; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - -public class PathTransitionTest { - - private static Duration DEFAULT_DURATION = Duration.millis(400); - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; - - private static Duration ONE_SEC = Duration.millis(1000); - - private Shape path; - private Node node; - - @Before - public void setUp() { - path = new Circle(); - node = new Rectangle(); - } - - @Test - public void testDefaultValues() { - // empty ctor - final PathTransition t0 = new PathTransition(); - assertEquals(DEFAULT_DURATION, t0.getDuration()); - assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); - assertNull(t0.getNode()); - assertNull(t0.nodeProperty().get()); - assertNull(t0.getPath()); - assertNull(t0.pathProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration and path - final PathTransition t1 = new PathTransition(ONE_SEC, path); - assertEquals(ONE_SEC, t1.getTotalDuration()); - assertNull(t1.getNode()); - assertNull(t1.nodeProperty().get()); - assertEquals(path, t1.getPath()); - assertEquals(path, t1.pathProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); - assertNull(t1.getOnFinished()); - - // duration, path, and node - final PathTransition t2 = new PathTransition(ONE_SEC, path, node); - assertEquals(ONE_SEC, t2.getTotalDuration()); - assertEquals(node, t2.getNode()); - assertEquals(node, t2.nodeProperty().get()); - assertEquals(path, t2.getPath()); - assertEquals(path, t2.pathProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); - assertNull(t2.getOnFinished()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/PathTransitionTest.java 2015-09-11 21:25:23.617286324 -0400 @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.animation.Interpolator; +import javafx.animation.PathTransition; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import javafx.scene.Node; +import javafx.scene.shape.Circle; +import javafx.scene.shape.Rectangle; +import javafx.scene.shape.Shape; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + +public class PathTransitionTest { + + private static Duration DEFAULT_DURATION = Duration.millis(400); + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; + + private static Duration ONE_SEC = Duration.millis(1000); + + private Shape path; + private Node node; + + @Before + public void setUp() { + path = new Circle(); + node = new Rectangle(); + } + + @Test + public void testDefaultValues() { + // empty ctor + final PathTransition t0 = new PathTransition(); + assertEquals(DEFAULT_DURATION, t0.getDuration()); + assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); + assertNull(t0.getNode()); + assertNull(t0.nodeProperty().get()); + assertNull(t0.getPath()); + assertNull(t0.pathProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration and path + final PathTransition t1 = new PathTransition(ONE_SEC, path); + assertEquals(ONE_SEC, t1.getTotalDuration()); + assertNull(t1.getNode()); + assertNull(t1.nodeProperty().get()); + assertEquals(path, t1.getPath()); + assertEquals(path, t1.pathProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); + assertNull(t1.getOnFinished()); + + // duration, path, and node + final PathTransition t2 = new PathTransition(ONE_SEC, path, node); + assertEquals(ONE_SEC, t2.getTotalDuration()); + assertEquals(node, t2.getNode()); + assertEquals(node, t2.nodeProperty().get()); + assertEquals(path, t2.getPath()); + assertEquals(path, t2.pathProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); + assertNull(t2.getOnFinished()); + } +} --- old/modules/graphics/src/test/java/javafx/animation/PauseTransitionTest.java 2015-09-11 21:25:24.565286314 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import javafx.util.Duration; - -import org.junit.Test; - -public class PauseTransitionTest { - - private static Duration DEFAULT_DURATION = Duration.millis(400); - - private static double EPSILON = 1e-12; - private static Duration ONE_SEC = Duration.millis(1000); - private static Duration TWO_SECS = Duration.millis(2000); - - - @Test - public void testDefaultValues() { - // empty ctor - final PauseTransition t0 = new PauseTransition(); - assertEquals(DEFAULT_DURATION, t0.getDuration()); - assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); - assertNull(t0.getOnFinished()); - - // duration only - final PauseTransition t1 = new PauseTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.getDuration()); - assertNull(t1.getOnFinished()); - } - - @Test - public void testDefaultValuesFromProperties() { - // empty ctor - final PauseTransition t0 = new PauseTransition(); - assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); - assertNull(t0.onFinishedProperty().get()); - - // duration only - final PauseTransition t1 = new PauseTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.durationProperty().get()); - assertNull(t1.onFinishedProperty().get()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/PauseTransitionTest.java 2015-09-11 21:25:24.357286316 -0400 @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.animation.PauseTransition; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import javafx.util.Duration; + +import org.junit.Test; + +public class PauseTransitionTest { + + private static Duration DEFAULT_DURATION = Duration.millis(400); + + private static double EPSILON = 1e-12; + private static Duration ONE_SEC = Duration.millis(1000); + private static Duration TWO_SECS = Duration.millis(2000); + + + @Test + public void testDefaultValues() { + // empty ctor + final PauseTransition t0 = new PauseTransition(); + assertEquals(DEFAULT_DURATION, t0.getDuration()); + assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); + assertNull(t0.getOnFinished()); + + // duration only + final PauseTransition t1 = new PauseTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.getDuration()); + assertNull(t1.getOnFinished()); + } + + @Test + public void testDefaultValuesFromProperties() { + // empty ctor + final PauseTransition t0 = new PauseTransition(); + assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); + assertNull(t0.onFinishedProperty().get()); + + // duration only + final PauseTransition t1 = new PauseTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.durationProperty().get()); + assertNull(t1.onFinishedProperty().get()); + } +} --- old/modules/graphics/src/test/java/javafx/animation/RotateTransitionTest.java 2015-09-11 21:25:25.509286303 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,403 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import javafx.geometry.Point3D; -import javafx.scene.Node; -import javafx.scene.shape.Rectangle; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - -public class RotateTransitionTest { - - private static Duration DEFAULT_DURATION = Duration.millis(400); - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; - - private static double EPSILON = 1e-12; - private static Duration ONE_SEC = Duration.millis(1000); - private static Duration TWO_SECS = Duration.millis(2000); - - private Node node; - - @Before - public void setUp() { - node = new Rectangle(); - } - - @Test - public void testDefaultValues() { - // empty ctor - final RotateTransition t0 = new RotateTransition(); - assertEquals(DEFAULT_DURATION, t0.getDuration()); - assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); - assertTrue(Double.isNaN(t0.getFromAngle())); - assertTrue(Double.isNaN(t0.getToAngle())); - assertEquals(0.0, t0.getByAngle(), EPSILON); - assertNull(t0.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - assertNull(t0.getAxis()); - - // duration only - final RotateTransition t1 = new RotateTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.getDuration()); - assertTrue(Double.isNaN(t1.getFromAngle())); - assertTrue(Double.isNaN(t1.getToAngle())); - assertEquals(0.0, t1.getByAngle(), EPSILON); - assertNull(t1.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); - assertNull(t1.getOnFinished()); - assertNull(t1.getAxis()); - - // duration and node - final RotateTransition t2 = new RotateTransition(TWO_SECS, node); - assertEquals(TWO_SECS, t2.getDuration()); - assertTrue(Double.isNaN(t2.getFromAngle())); - assertTrue(Double.isNaN(t2.getToAngle())); - assertEquals(0.0, t2.getByAngle(), EPSILON); - assertEquals(node, t2.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); - assertNull(t2.getOnFinished()); - assertNull(t2.getAxis()); - } - - @Test - public void testDefaultValuesFromProperties() { - // empty ctor - final RotateTransition t0 = new RotateTransition(); - assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); - assertTrue(Double.isNaN(t0.fromAngleProperty().get())); - assertTrue(Double.isNaN(t0.toAngleProperty().get())); - assertEquals(0.0, t0.byAngleProperty().get(), EPSILON); - assertNull(t0.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t0.interpolatorProperty().get()); - assertNull(t0.onFinishedProperty().get()); - assertNull(t0.axisProperty().get()); - - // duration only - final RotateTransition t1 = new RotateTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.durationProperty().get()); - assertTrue(Double.isNaN(t1.fromAngleProperty().get())); - assertTrue(Double.isNaN(t1.toAngleProperty().get())); - assertEquals(0.0, t1.byAngleProperty().get(), EPSILON); - assertNull(t1.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t1.interpolatorProperty().get()); - assertNull(t1.onFinishedProperty().get()); - assertNull(t1.axisProperty().get()); - - // duration and node - final RotateTransition t2 = new RotateTransition(TWO_SECS, node); - assertEquals(TWO_SECS, t2.durationProperty().get()); - assertTrue(Double.isNaN(t2.fromAngleProperty().get())); - assertTrue(Double.isNaN(t2.toAngleProperty().get())); - assertEquals(0.0, t2.byAngleProperty().get(), EPSILON); - assertEquals(node, t2.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t2.interpolatorProperty().get()); - assertNull(t2.onFinishedProperty().get()); - assertNull(t2.axisProperty().get()); - } - - @Test - public void testInterpolate() { - final RotateTransition t0 = new RotateTransition(ONE_SEC, node); - t0.setFromAngle(0.5); - t0.setToAngle(1.0); - - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(0.5, node.getRotate(), EPSILON); - t0.interpolate(0.4); - assertEquals(0.7, node.getRotate(), EPSILON); - t0.interpolate(1.0); - assertEquals(1.0, node.getRotate(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testAxis() { - final Point3D defaultAxis = new Point3D(0.0, 0.0, 1.0); - final Point3D axis = new Point3D(1.0, 0.0, 0.0); - final RotateTransition t0 = new RotateTransition(ONE_SEC, node); - t0.setAxis(axis); - node.setRotationAxis(defaultAxis); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - assertEquals(axis, node.getRotationAxis()); - t0.impl_finished(); - - t0.setAxis(null); - node.setRotationAxis(defaultAxis); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - assertEquals(defaultAxis, node.getRotationAxis()); - t0.impl_finished(); - } - - @Test - public void testValueCombinations() { - final RotateTransition t0 = new RotateTransition(ONE_SEC, node); - final double originalAngle = 0.6; - final double fromAngle = 0.4; - final double toAngle = 0.9; - final double byAngle = -0.2; - - // no value set - node.setRotate(originalAngle); - t0.setFromAngle(Double.NaN); - t0.setToAngle(Double.NaN); - t0.setByAngle(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalAngle, node.getRotate(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalAngle, node.getRotate(), EPSILON); - t0.impl_finished(); - - // only from-value set - node.setRotate(originalAngle); - t0.setFromAngle(fromAngle); - t0.setToAngle(Double.NaN); - t0.setByAngle(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromAngle, node.getRotate(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromAngle, node.getRotate(), EPSILON); - t0.impl_finished(); - - // only to-value set - node.setRotate(originalAngle); - t0.setFromAngle(Double.NaN); - t0.setToAngle(toAngle); - t0.setByAngle(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalAngle, node.getRotate(), EPSILON); - t0.interpolate(1.0); - assertEquals(toAngle, node.getRotate(), EPSILON); - t0.impl_finished(); - - // only by-value set - node.setRotate(originalAngle); - t0.setFromAngle(Double.NaN); - t0.setToAngle(Double.NaN); - t0.setByAngle(byAngle); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalAngle, node.getRotate(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalAngle + byAngle, node.getRotate(), EPSILON); - t0.impl_finished(); - - // from- and to-values set - node.setRotate(originalAngle); - t0.setFromAngle(fromAngle); - t0.setToAngle(toAngle); - t0.setByAngle(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromAngle, node.getRotate(), EPSILON); - t0.interpolate(1.0); - assertEquals(toAngle, node.getRotate(), EPSILON); - t0.impl_finished(); - - // from- and by-values set - node.setRotate(originalAngle); - t0.setFromAngle(fromAngle); - t0.setToAngle(Double.NaN); - t0.setByAngle(byAngle); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromAngle, node.getRotate(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromAngle + byAngle, node.getRotate(), EPSILON); - t0.impl_finished(); - - // to- and by-values set - node.setRotate(originalAngle); - t0.setFromAngle(Double.NaN); - t0.setToAngle(toAngle); - t0.setByAngle(byAngle); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalAngle, node.getRotate(), EPSILON); - t0.interpolate(1.0); - assertEquals(toAngle, node.getRotate(), EPSILON); - t0.impl_finished(); - - // all values set - node.setRotate(originalAngle); - t0.setFromAngle(fromAngle); - t0.setToAngle(toAngle); - t0.setByAngle(byAngle); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromAngle, node.getRotate(), EPSILON); - t0.interpolate(1.0); - assertEquals(toAngle, node.getRotate(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testGetTargetNode() { - final RotateTransition rt = new RotateTransition(ONE_SEC, node); - rt.setInterpolator(Interpolator.LINEAR); - rt.setFromAngle(0.5); - rt.setToAngle(1.0); - final Rectangle node2 = new Rectangle(); - final ParallelTransition pt = new ParallelTransition(); - pt.getChildren().add(rt); - pt.setNode(node2); - - // node set, parent set - assertTrue(rt.impl_startable(true)); - rt.impl_start(true); - rt.interpolate(0.5); - assertEquals(0.75, node.getRotate(), EPSILON); - assertEquals(0.0, node2.getRotate(), EPSILON); - rt.impl_finished(); - - // node null, parent set - rt.setNode(null); - assertTrue(rt.impl_startable(true)); - rt.impl_start(true); - rt.interpolate(0.4); - assertEquals(0.75, node.getRotate(), EPSILON); - assertEquals(0.7, node2.getRotate(), EPSILON); - rt.impl_finished(); - - // node null, parent null - pt.setNode(null); - assertFalse(rt.impl_startable(true)); - } - - @Test - public void testCachedValues() { - final RotateTransition rt = new RotateTransition(ONE_SEC, node); - rt.setInterpolator(Interpolator.LINEAR); - rt.setFromAngle(0.5); - rt.setToAngle(1.0); - - // start - assertTrue(rt.impl_startable(true)); - rt.impl_start(true); - rt.setFromAngle(0.0); - rt.interpolate(0.5); - assertEquals(0.75, node.getRotate(), EPSILON); - rt.impl_finished(); - rt.setFromAngle(0.5); - - // end - assertTrue(rt.impl_startable(true)); - rt.impl_start(true); - rt.setToAngle(0.0); - rt.interpolate(0.2); - assertEquals(0.6, node.getRotate(), EPSILON); - rt.impl_finished(); - rt.setToAngle(1.0); - - // node - assertTrue(rt.impl_startable(true)); - rt.impl_start(true); - rt.setNode(null); - rt.interpolate(0.7); - assertEquals(0.85, node.getRotate(), EPSILON); - rt.impl_finished(); - rt.setNode(node); - - // interpolator - assertTrue(rt.impl_startable(true)); - rt.impl_start(true); - rt.setInterpolator(null); - rt.interpolate(0.1); - assertEquals(0.55, node.getRotate(), EPSILON); - rt.impl_finished(); - rt.setInterpolator(Interpolator.LINEAR); - } - - @Test - public void testStartable() { - final RotateTransition t0 = new RotateTransition(Duration.ONE, node); - assertTrue(t0.impl_startable(true)); - - // duration is 0 - t0.setDuration(Duration.ZERO); - assertFalse(t0.impl_startable(true)); - t0.setDuration(Duration.ONE); - assertTrue(t0.impl_startable(true)); - - // node is null - t0.setNode(null); - assertFalse(t0.impl_startable(true)); - t0.setNode(node); - assertTrue(t0.impl_startable(true)); - - // interpolator is null - t0.setInterpolator(null); - assertFalse(t0.impl_startable(true)); - t0.setInterpolator(Interpolator.LINEAR); - assertTrue(t0.impl_startable(true)); - } - - @Test - public void testEvaluateStartValue() { - final RotateTransition t0 = new RotateTransition(Duration.INDEFINITE, node); - - // first run - node.setRotate(0.6); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - node.setRotate(0.8); - t0.interpolate(0.0); - assertEquals(0.6, node.getRotate(), EPSILON); - t0.impl_finished(); - - // second run - node.setRotate(0.2); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - node.setRotate(0.8); - t0.interpolate(0.0); - assertEquals(0.2, node.getRotate(), EPSILON); - t0.impl_finished(); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/RotateTransitionTest.java 2015-09-11 21:25:25.297286305 -0400 @@ -0,0 +1,408 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.animation.AnimationShim; +import javafx.animation.Interpolator; +import javafx.animation.ParallelTransition; +import javafx.animation.RotateTransition; +import javafx.animation.TransitionShim; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import javafx.geometry.Point3D; +import javafx.scene.Node; +import javafx.scene.shape.Rectangle; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + +public class RotateTransitionTest { + + private static Duration DEFAULT_DURATION = Duration.millis(400); + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; + + private static double EPSILON = 1e-12; + private static Duration ONE_SEC = Duration.millis(1000); + private static Duration TWO_SECS = Duration.millis(2000); + + private Node node; + + @Before + public void setUp() { + node = new Rectangle(); + } + + @Test + public void testDefaultValues() { + // empty ctor + final RotateTransition t0 = new RotateTransition(); + assertEquals(DEFAULT_DURATION, t0.getDuration()); + assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); + assertTrue(Double.isNaN(t0.getFromAngle())); + assertTrue(Double.isNaN(t0.getToAngle())); + assertEquals(0.0, t0.getByAngle(), EPSILON); + assertNull(t0.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + assertNull(t0.getAxis()); + + // duration only + final RotateTransition t1 = new RotateTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.getDuration()); + assertTrue(Double.isNaN(t1.getFromAngle())); + assertTrue(Double.isNaN(t1.getToAngle())); + assertEquals(0.0, t1.getByAngle(), EPSILON); + assertNull(t1.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); + assertNull(t1.getOnFinished()); + assertNull(t1.getAxis()); + + // duration and node + final RotateTransition t2 = new RotateTransition(TWO_SECS, node); + assertEquals(TWO_SECS, t2.getDuration()); + assertTrue(Double.isNaN(t2.getFromAngle())); + assertTrue(Double.isNaN(t2.getToAngle())); + assertEquals(0.0, t2.getByAngle(), EPSILON); + assertEquals(node, t2.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); + assertNull(t2.getOnFinished()); + assertNull(t2.getAxis()); + } + + @Test + public void testDefaultValuesFromProperties() { + // empty ctor + final RotateTransition t0 = new RotateTransition(); + assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); + assertTrue(Double.isNaN(t0.fromAngleProperty().get())); + assertTrue(Double.isNaN(t0.toAngleProperty().get())); + assertEquals(0.0, t0.byAngleProperty().get(), EPSILON); + assertNull(t0.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t0.interpolatorProperty().get()); + assertNull(t0.onFinishedProperty().get()); + assertNull(t0.axisProperty().get()); + + // duration only + final RotateTransition t1 = new RotateTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.durationProperty().get()); + assertTrue(Double.isNaN(t1.fromAngleProperty().get())); + assertTrue(Double.isNaN(t1.toAngleProperty().get())); + assertEquals(0.0, t1.byAngleProperty().get(), EPSILON); + assertNull(t1.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t1.interpolatorProperty().get()); + assertNull(t1.onFinishedProperty().get()); + assertNull(t1.axisProperty().get()); + + // duration and node + final RotateTransition t2 = new RotateTransition(TWO_SECS, node); + assertEquals(TWO_SECS, t2.durationProperty().get()); + assertTrue(Double.isNaN(t2.fromAngleProperty().get())); + assertTrue(Double.isNaN(t2.toAngleProperty().get())); + assertEquals(0.0, t2.byAngleProperty().get(), EPSILON); + assertEquals(node, t2.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t2.interpolatorProperty().get()); + assertNull(t2.onFinishedProperty().get()); + assertNull(t2.axisProperty().get()); + } + + @Test + public void testInterpolate() { + final RotateTransition t0 = new RotateTransition(ONE_SEC, node); + t0.setFromAngle(0.5); + t0.setToAngle(1.0); + + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.5, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,0.4); + assertEquals(0.7, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(1.0, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testAxis() { + final Point3D defaultAxis = new Point3D(0.0, 0.0, 1.0); + final Point3D axis = new Point3D(1.0, 0.0, 0.0); + final RotateTransition t0 = new RotateTransition(ONE_SEC, node); + t0.setAxis(axis); + node.setRotationAxis(defaultAxis); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + assertEquals(axis, node.getRotationAxis()); + AnimationShim.impl_finished(t0); + + t0.setAxis(null); + node.setRotationAxis(defaultAxis); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + assertEquals(defaultAxis, node.getRotationAxis()); + AnimationShim.impl_finished(t0); + } + + @Test + public void testValueCombinations() { + final RotateTransition t0 = new RotateTransition(ONE_SEC, node); + final double originalAngle = 0.6; + final double fromAngle = 0.4; + final double toAngle = 0.9; + final double byAngle = -0.2; + + // no value set + node.setRotate(originalAngle); + t0.setFromAngle(Double.NaN); + t0.setToAngle(Double.NaN); + t0.setByAngle(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalAngle, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalAngle, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + + // only from-value set + node.setRotate(originalAngle); + t0.setFromAngle(fromAngle); + t0.setToAngle(Double.NaN); + t0.setByAngle(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromAngle, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromAngle, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + + // only to-value set + node.setRotate(originalAngle); + t0.setFromAngle(Double.NaN); + t0.setToAngle(toAngle); + t0.setByAngle(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalAngle, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toAngle, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + + // only by-value set + node.setRotate(originalAngle); + t0.setFromAngle(Double.NaN); + t0.setToAngle(Double.NaN); + t0.setByAngle(byAngle); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalAngle, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalAngle + byAngle, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and to-values set + node.setRotate(originalAngle); + t0.setFromAngle(fromAngle); + t0.setToAngle(toAngle); + t0.setByAngle(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromAngle, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toAngle, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and by-values set + node.setRotate(originalAngle); + t0.setFromAngle(fromAngle); + t0.setToAngle(Double.NaN); + t0.setByAngle(byAngle); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromAngle, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromAngle + byAngle, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + + // to- and by-values set + node.setRotate(originalAngle); + t0.setFromAngle(Double.NaN); + t0.setToAngle(toAngle); + t0.setByAngle(byAngle); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalAngle, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toAngle, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + + // all values set + node.setRotate(originalAngle); + t0.setFromAngle(fromAngle); + t0.setToAngle(toAngle); + t0.setByAngle(byAngle); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromAngle, node.getRotate(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toAngle, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testGetTargetNode() { + final RotateTransition rt = new RotateTransition(ONE_SEC, node); + rt.setInterpolator(Interpolator.LINEAR); + rt.setFromAngle(0.5); + rt.setToAngle(1.0); + final Rectangle node2 = new Rectangle(); + final ParallelTransition pt = new ParallelTransition(); + pt.getChildren().add(rt); + pt.setNode(node2); + + // node set, parent set + assertTrue(AnimationShim.impl_startable(rt,true)); + AnimationShim.impl_start(rt,true); + TransitionShim.interpolate(rt,0.5); + assertEquals(0.75, node.getRotate(), EPSILON); + assertEquals(0.0, node2.getRotate(), EPSILON); + AnimationShim.impl_finished(rt); + + // node null, parent set + rt.setNode(null); + assertTrue(AnimationShim.impl_startable(rt,true)); + AnimationShim.impl_start(rt,true); + TransitionShim.interpolate(rt,0.4); + assertEquals(0.75, node.getRotate(), EPSILON); + assertEquals(0.7, node2.getRotate(), EPSILON); + AnimationShim.impl_finished(rt); + + // node null, parent null + pt.setNode(null); + assertFalse(AnimationShim.impl_startable(rt,true)); + } + + @Test + public void testCachedValues() { + final RotateTransition rt = new RotateTransition(ONE_SEC, node); + rt.setInterpolator(Interpolator.LINEAR); + rt.setFromAngle(0.5); + rt.setToAngle(1.0); + + // start + assertTrue(AnimationShim.impl_startable(rt,true)); + AnimationShim.impl_start(rt,true); + rt.setFromAngle(0.0); + TransitionShim.interpolate(rt,0.5); + assertEquals(0.75, node.getRotate(), EPSILON); + AnimationShim.impl_finished(rt); + rt.setFromAngle(0.5); + + // end + assertTrue(AnimationShim.impl_startable(rt,true)); + AnimationShim.impl_start(rt,true); + rt.setToAngle(0.0); + TransitionShim.interpolate(rt,0.2); + assertEquals(0.6, node.getRotate(), EPSILON); + AnimationShim.impl_finished(rt); + rt.setToAngle(1.0); + + // node + assertTrue(AnimationShim.impl_startable(rt,true)); + AnimationShim.impl_start(rt,true); + rt.setNode(null); + TransitionShim.interpolate(rt,0.7); + assertEquals(0.85, node.getRotate(), EPSILON); + AnimationShim.impl_finished(rt); + rt.setNode(node); + + // interpolator + assertTrue(AnimationShim.impl_startable(rt,true)); + AnimationShim.impl_start(rt,true); + rt.setInterpolator(null); + TransitionShim.interpolate(rt,0.1); + assertEquals(0.55, node.getRotate(), EPSILON); + AnimationShim.impl_finished(rt); + rt.setInterpolator(Interpolator.LINEAR); + } + + @Test + public void testStartable() { + final RotateTransition t0 = new RotateTransition(Duration.ONE, node); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // duration is 0 + t0.setDuration(Duration.ZERO); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setDuration(Duration.ONE); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // node is null + t0.setNode(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setNode(node); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // interpolator is null + t0.setInterpolator(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setInterpolator(Interpolator.LINEAR); + assertTrue(AnimationShim.impl_startable(t0,true)); + } + + @Test + public void testEvaluateStartValue() { + final RotateTransition t0 = new RotateTransition(Duration.INDEFINITE, node); + + // first run + node.setRotate(0.6); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + node.setRotate(0.8); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.6, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + + // second run + node.setRotate(0.2); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + node.setRotate(0.8); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.2, node.getRotate(), EPSILON); + AnimationShim.impl_finished(t0); + } + +} --- old/modules/graphics/src/test/java/javafx/animation/ScaleTransitionTest.java 2015-09-11 21:25:26.265286295 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,679 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import javafx.scene.Node; -import javafx.scene.shape.Rectangle; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - -public class ScaleTransitionTest { - - private static Duration DEFAULT_DURATION = Duration.millis(400); - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; - - private static double EPSILON = 1e-12; - private static Duration ONE_SEC = Duration.millis(1000); - private static Duration TWO_SECS = Duration.millis(2000); - - private Node node; - - @Before - public void setUp() { - node = new Rectangle(); - } - - @Test - public void testDefaultValues() { - // empty ctor - final ScaleTransition t0 = new ScaleTransition(); - assertEquals(DEFAULT_DURATION, t0.getDuration()); - assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); - assertTrue(Double.isNaN(t0.getFromX())); - assertTrue(Double.isNaN(t0.getFromY())); - assertTrue(Double.isNaN(t0.getFromZ())); - assertTrue(Double.isNaN(t0.getToX())); - assertTrue(Double.isNaN(t0.getToY())); - assertTrue(Double.isNaN(t0.getToZ())); - assertEquals(0.0, t0.getByX(), EPSILON); - assertEquals(0.0, t0.getByY(), EPSILON); - assertEquals(0.0, t0.getByZ(), EPSILON); - assertNull(t0.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration only - final ScaleTransition t1 = new ScaleTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.getDuration()); - assertTrue(Double.isNaN(t1.getFromX())); - assertTrue(Double.isNaN(t1.getFromY())); - assertTrue(Double.isNaN(t1.getFromZ())); - assertTrue(Double.isNaN(t1.getToX())); - assertTrue(Double.isNaN(t1.getToY())); - assertTrue(Double.isNaN(t1.getToZ())); - assertEquals(0.0, t1.getByX(), EPSILON); - assertEquals(0.0, t1.getByY(), EPSILON); - assertEquals(0.0, t1.getByZ(), EPSILON); - assertNull(t1.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); - assertNull(t1.getOnFinished()); - - // duration and node - final ScaleTransition t2 = new ScaleTransition(TWO_SECS, node); - assertEquals(TWO_SECS, t2.getDuration()); - assertTrue(Double.isNaN(t2.getFromX())); - assertTrue(Double.isNaN(t2.getFromY())); - assertTrue(Double.isNaN(t2.getFromZ())); - assertTrue(Double.isNaN(t2.getToX())); - assertTrue(Double.isNaN(t2.getToY())); - assertTrue(Double.isNaN(t2.getToZ())); - assertEquals(0.0, t2.getByX(), EPSILON); - assertEquals(0.0, t2.getByY(), EPSILON); - assertEquals(0.0, t2.getByZ(), EPSILON); - assertEquals(node, t2.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); - assertNull(t2.getOnFinished()); - } - - @Test - public void testDefaultValuesFromProperties() { - // empty ctor - final ScaleTransition t0 = new ScaleTransition(); - assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); - assertTrue(Double.isNaN(t0.fromXProperty().get())); - assertTrue(Double.isNaN(t0.fromYProperty().get())); - assertTrue(Double.isNaN(t0.fromZProperty().get())); - assertTrue(Double.isNaN(t0.toXProperty().get())); - assertTrue(Double.isNaN(t0.toYProperty().get())); - assertTrue(Double.isNaN(t0.toZProperty().get())); - assertEquals(0.0, t0.byXProperty().get(), EPSILON); - assertEquals(0.0, t0.byYProperty().get(), EPSILON); - assertEquals(0.0, t0.byZProperty().get(), EPSILON); - assertNull(t0.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t0.interpolatorProperty().get()); - assertNull(t0.onFinishedProperty().get()); - - // duration only - final ScaleTransition t1 = new ScaleTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.durationProperty().get()); - assertTrue(Double.isNaN(t1.fromXProperty().get())); - assertTrue(Double.isNaN(t1.fromYProperty().get())); - assertTrue(Double.isNaN(t1.fromZProperty().get())); - assertTrue(Double.isNaN(t1.toXProperty().get())); - assertTrue(Double.isNaN(t1.toYProperty().get())); - assertTrue(Double.isNaN(t1.toZProperty().get())); - assertEquals(0.0, t1.byXProperty().get(), EPSILON); - assertEquals(0.0, t1.byYProperty().get(), EPSILON); - assertEquals(0.0, t1.byZProperty().get(), EPSILON); - assertNull(t1.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t1.interpolatorProperty().get()); - assertNull(t1.onFinishedProperty().get()); - - // duration and node - final ScaleTransition t2 = new ScaleTransition(TWO_SECS, node); - assertEquals(TWO_SECS, t2.durationProperty().get()); - assertTrue(Double.isNaN(t2.fromXProperty().get())); - assertTrue(Double.isNaN(t2.fromYProperty().get())); - assertTrue(Double.isNaN(t2.fromZProperty().get())); - assertTrue(Double.isNaN(t2.toXProperty().get())); - assertTrue(Double.isNaN(t2.toYProperty().get())); - assertTrue(Double.isNaN(t2.toZProperty().get())); - assertEquals(0.0, t2.byXProperty().get(), EPSILON); - assertEquals(0.0, t2.byYProperty().get(), EPSILON); - assertEquals(0.0, t2.byZProperty().get(), EPSILON); - assertEquals(node, t2.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t2.interpolatorProperty().get()); - assertNull(t2.onFinishedProperty().get()); - } - - @Test - public void testInterpolate() { - final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); - t0.setFromX(0.5); - t0.setToX(1.0); - t0.setFromY(1.5); - t0.setToY(2.0); - t0.setFromZ(1.5); - t0.setToZ(0.5); - - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(0.5, node.getScaleX(), EPSILON); - assertEquals(1.5, node.getScaleY(), EPSILON); - assertEquals(1.5, node.getScaleZ(), EPSILON); - t0.interpolate(0.4); - assertEquals(0.7, node.getScaleX(), EPSILON); - assertEquals(1.7, node.getScaleY(), EPSILON); - assertEquals(1.1, node.getScaleZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(1.0, node.getScaleX(), EPSILON); - assertEquals(2.0, node.getScaleY(), EPSILON); - assertEquals(0.5, node.getScaleZ(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testXValueCombinations() { - final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); - final double originalValue = 0.6; - final double fromValue = 0.4; - final double toValue = 0.9; - final double byValue = -0.2; - - // no value set - node.setScaleX(originalValue); - t0.setFromX(Double.NaN); - t0.setToX(Double.NaN); - t0.setByX(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleX(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue, node.getScaleX(), EPSILON); - t0.impl_finished(); - - // only from-value set - node.setScaleX(originalValue); - t0.setFromX(fromValue); - t0.setToX(Double.NaN); - t0.setByX(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleX(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue, node.getScaleX(), EPSILON); - t0.impl_finished(); - - // only to-value set - node.setScaleX(originalValue); - t0.setFromX(Double.NaN); - t0.setToX(toValue); - t0.setByX(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleX(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleX(), EPSILON); - t0.impl_finished(); - - // only by-value set - node.setScaleX(originalValue); - t0.setFromX(Double.NaN); - t0.setToX(Double.NaN); - t0.setByX(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleX(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue + byValue, node.getScaleX(), EPSILON); - t0.impl_finished(); - - // from- and to-values set - node.setScaleX(originalValue); - t0.setFromX(fromValue); - t0.setToX(toValue); - t0.setByX(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleX(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleX(), EPSILON); - t0.impl_finished(); - - // from- and by-values set - node.setScaleX(originalValue); - t0.setFromX(fromValue); - t0.setToX(Double.NaN); - t0.setByX(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleX(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue + byValue, node.getScaleX(), EPSILON); - t0.impl_finished(); - - // to- and by-values set - node.setScaleX(originalValue); - t0.setFromX(Double.NaN); - t0.setToX(toValue); - t0.setByX(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleX(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleX(), EPSILON); - t0.impl_finished(); - - // all values set - node.setScaleX(originalValue); - t0.setFromX(fromValue); - t0.setToX(toValue); - t0.setByX(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleX(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleX(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testYValueCombinations() { - final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); - final double originalValue = 0.6; - final double fromValue = 0.4; - final double toValue = 0.9; - final double byValue = -0.2; - - // no value set - node.setScaleY(originalValue); - t0.setFromY(Double.NaN); - t0.setToY(Double.NaN); - t0.setByY(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleY(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue, node.getScaleY(), EPSILON); - t0.impl_finished(); - - // only from-value set - node.setScaleY(originalValue); - t0.setFromY(fromValue); - t0.setToY(Double.NaN); - t0.setByY(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleY(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue, node.getScaleY(), EPSILON); - t0.impl_finished(); - - // only to-value set - node.setScaleY(originalValue); - t0.setFromY(Double.NaN); - t0.setToY(toValue); - t0.setByY(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleY(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleY(), EPSILON); - t0.impl_finished(); - - // only by-value set - node.setScaleY(originalValue); - t0.setFromY(Double.NaN); - t0.setToY(Double.NaN); - t0.setByY(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleY(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue + byValue, node.getScaleY(), EPSILON); - t0.impl_finished(); - - // from- and to-values set - node.setScaleY(originalValue); - t0.setFromY(fromValue); - t0.setToY(toValue); - t0.setByY(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleY(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleY(), EPSILON); - t0.impl_finished(); - - // from- and by-values set - node.setScaleY(originalValue); - t0.setFromY(fromValue); - t0.setToY(Double.NaN); - t0.setByY(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleY(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue + byValue, node.getScaleY(), EPSILON); - t0.impl_finished(); - - // to- and by-values set - node.setScaleY(originalValue); - t0.setFromY(Double.NaN); - t0.setToY(toValue); - t0.setByY(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleY(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleY(), EPSILON); - t0.impl_finished(); - - // all values set - node.setScaleY(originalValue); - t0.setFromY(fromValue); - t0.setToY(toValue); - t0.setByY(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleY(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleY(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testZValueCombinations() { - final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); - final double originalValue = 0.6; - final double fromValue = 0.4; - final double toValue = 0.9; - final double byValue = -0.2; - - // no value set - node.setScaleZ(originalValue); - t0.setFromZ(Double.NaN); - t0.setToZ(Double.NaN); - t0.setByZ(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue, node.getScaleZ(), EPSILON); - t0.impl_finished(); - - // only from-value set - node.setScaleZ(originalValue); - t0.setFromZ(fromValue); - t0.setToZ(Double.NaN); - t0.setByZ(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue, node.getScaleZ(), EPSILON); - t0.impl_finished(); - - // only to-value set - node.setScaleZ(originalValue); - t0.setFromZ(Double.NaN); - t0.setToZ(toValue); - t0.setByZ(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleZ(), EPSILON); - t0.impl_finished(); - - // only by-value set - node.setScaleZ(originalValue); - t0.setFromZ(Double.NaN); - t0.setToZ(Double.NaN); - t0.setByZ(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue + byValue, node.getScaleZ(), EPSILON); - t0.impl_finished(); - - // from- and to-values set - node.setScaleZ(originalValue); - t0.setFromZ(fromValue); - t0.setToZ(toValue); - t0.setByZ(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleZ(), EPSILON); - t0.impl_finished(); - - // from- and by-values set - node.setScaleZ(originalValue); - t0.setFromZ(fromValue); - t0.setToZ(Double.NaN); - t0.setByZ(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue + byValue, node.getScaleZ(), EPSILON); - t0.impl_finished(); - - // to- and by-values set - node.setScaleZ(originalValue); - t0.setFromZ(Double.NaN); - t0.setToZ(toValue); - t0.setByZ(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getScaleZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleZ(), EPSILON); - t0.impl_finished(); - - // all values set - node.setScaleZ(originalValue); - t0.setFromZ(fromValue); - t0.setToZ(toValue); - t0.setByZ(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getScaleZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getScaleZ(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testGetTargetNode() { - final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); - t0.setInterpolator(Interpolator.LINEAR); - t0.setFromX(0.5); - t0.setToX(1.0); - final Rectangle node2 = new Rectangle(); - final ParallelTransition pt = new ParallelTransition(); - pt.getChildren().add(t0); - pt.setNode(node2); - - // node set, parent set - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.5); - assertEquals(0.75, node.getScaleX(), EPSILON); - assertEquals(1.0, node2.getScaleX(), EPSILON); - t0.impl_finished(); - - // node null, parent set - t0.setNode(null); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.4); - assertEquals(0.75, node.getScaleX(), EPSILON); - assertEquals(0.7, node2.getScaleX(), EPSILON); - t0.impl_finished(); - - // node null, parent null - pt.setNode(null); - assertFalse(t0.impl_startable(true)); - } - - @Test - public void testCachedValues() { - final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); - t0.setInterpolator(Interpolator.LINEAR); - t0.setFromX(0.5); - t0.setToX(1.0); - t0.setFromY(1.5); - t0.setToY(2.0); - t0.setFromZ(1.5); - t0.setToZ(0.5); - - // start - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.setFromX(0.0); - t0.setFromY(-1.0); - t0.setFromZ(0.5); - t0.interpolate(0.5); - assertEquals(0.75, node.getScaleX(), EPSILON); - assertEquals(1.75, node.getScaleY(), EPSILON); - assertEquals(1.0, node.getScaleZ(), EPSILON); - t0.impl_finished(); - t0.setFromX(0.5); - t0.setFromY(1.5); - t0.setFromZ(1.5); - - // end - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.setToX(0.0); - t0.setFromY(-1.0); - t0.setFromZ(1.5); - t0.interpolate(0.2); - assertEquals(0.6, node.getScaleX(), EPSILON); - assertEquals(1.6, node.getScaleY(), EPSILON); - assertEquals(1.3, node.getScaleZ(), EPSILON); - t0.impl_finished(); - t0.setToX(1.0); - t0.setToY(2.0); - t0.setToZ(0.5); - - // node - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.setNode(null); - t0.interpolate(0.7); - assertEquals(0.85, node.getScaleX(), EPSILON); - t0.impl_finished(); - t0.setNode(node); - - // interpolator - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.setInterpolator(null); - t0.interpolate(0.1); - assertEquals(0.55, node.getScaleX(), EPSILON); - t0.impl_finished(); - t0.setInterpolator(Interpolator.LINEAR); - } - - @Test - public void testStartable() { - final ScaleTransition t0 = new ScaleTransition(Duration.ONE, node); - assertTrue(t0.impl_startable(true)); - - // duration is 0 - t0.setDuration(Duration.ZERO); - assertFalse(t0.impl_startable(true)); - t0.setDuration(Duration.ONE); - assertTrue(t0.impl_startable(true)); - - // node is null - t0.setNode(null); - assertFalse(t0.impl_startable(true)); - t0.setNode(node); - assertTrue(t0.impl_startable(true)); - - // interpolator is null - t0.setInterpolator(null); - assertFalse(t0.impl_startable(true)); - t0.setInterpolator(Interpolator.LINEAR); - assertTrue(t0.impl_startable(true)); - } - - @Test - public void testEvaluateStartValue() { - final ScaleTransition t0 = new ScaleTransition(Duration.INDEFINITE, node); - t0.setToX(2.0); - t0.setToY(2.0); - t0.setToZ(2.0); - - // first run - node.setScaleX( 0.6); - node.setScaleY( 1.6); - node.setScaleZ(-0.6); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - node.setScaleX(0.8); - node.setScaleY(0.8); - node.setScaleZ(0.8); - t0.interpolate(0.0); - assertEquals( 0.6, node.getScaleX(), EPSILON); - assertEquals( 1.6, node.getScaleY(), EPSILON); - assertEquals(-0.6, node.getScaleZ(), EPSILON); - t0.impl_finished(); - - // second run - node.setScaleX( 0.2); - node.setScaleY(-2.2); - node.setScaleZ(11.2); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - node.setScaleX(0.8); - node.setScaleY(0.8); - node.setScaleZ(0.8); - t0.interpolate(0.0); - assertEquals( 0.2, node.getScaleX(), EPSILON); - assertEquals(-2.2, node.getScaleY(), EPSILON); - assertEquals(11.2, node.getScaleZ(), EPSILON); - t0.impl_finished(); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/ScaleTransitionTest.java 2015-09-11 21:25:26.089286297 -0400 @@ -0,0 +1,684 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.animation.AnimationShim; +import javafx.animation.Interpolator; +import javafx.animation.ParallelTransition; +import javafx.animation.ScaleTransition; +import javafx.animation.TransitionShim; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import javafx.scene.Node; +import javafx.scene.shape.Rectangle; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + +public class ScaleTransitionTest { + + private static Duration DEFAULT_DURATION = Duration.millis(400); + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; + + private static double EPSILON = 1e-12; + private static Duration ONE_SEC = Duration.millis(1000); + private static Duration TWO_SECS = Duration.millis(2000); + + private Node node; + + @Before + public void setUp() { + node = new Rectangle(); + } + + @Test + public void testDefaultValues() { + // empty ctor + final ScaleTransition t0 = new ScaleTransition(); + assertEquals(DEFAULT_DURATION, t0.getDuration()); + assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); + assertTrue(Double.isNaN(t0.getFromX())); + assertTrue(Double.isNaN(t0.getFromY())); + assertTrue(Double.isNaN(t0.getFromZ())); + assertTrue(Double.isNaN(t0.getToX())); + assertTrue(Double.isNaN(t0.getToY())); + assertTrue(Double.isNaN(t0.getToZ())); + assertEquals(0.0, t0.getByX(), EPSILON); + assertEquals(0.0, t0.getByY(), EPSILON); + assertEquals(0.0, t0.getByZ(), EPSILON); + assertNull(t0.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration only + final ScaleTransition t1 = new ScaleTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.getDuration()); + assertTrue(Double.isNaN(t1.getFromX())); + assertTrue(Double.isNaN(t1.getFromY())); + assertTrue(Double.isNaN(t1.getFromZ())); + assertTrue(Double.isNaN(t1.getToX())); + assertTrue(Double.isNaN(t1.getToY())); + assertTrue(Double.isNaN(t1.getToZ())); + assertEquals(0.0, t1.getByX(), EPSILON); + assertEquals(0.0, t1.getByY(), EPSILON); + assertEquals(0.0, t1.getByZ(), EPSILON); + assertNull(t1.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); + assertNull(t1.getOnFinished()); + + // duration and node + final ScaleTransition t2 = new ScaleTransition(TWO_SECS, node); + assertEquals(TWO_SECS, t2.getDuration()); + assertTrue(Double.isNaN(t2.getFromX())); + assertTrue(Double.isNaN(t2.getFromY())); + assertTrue(Double.isNaN(t2.getFromZ())); + assertTrue(Double.isNaN(t2.getToX())); + assertTrue(Double.isNaN(t2.getToY())); + assertTrue(Double.isNaN(t2.getToZ())); + assertEquals(0.0, t2.getByX(), EPSILON); + assertEquals(0.0, t2.getByY(), EPSILON); + assertEquals(0.0, t2.getByZ(), EPSILON); + assertEquals(node, t2.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); + assertNull(t2.getOnFinished()); + } + + @Test + public void testDefaultValuesFromProperties() { + // empty ctor + final ScaleTransition t0 = new ScaleTransition(); + assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); + assertTrue(Double.isNaN(t0.fromXProperty().get())); + assertTrue(Double.isNaN(t0.fromYProperty().get())); + assertTrue(Double.isNaN(t0.fromZProperty().get())); + assertTrue(Double.isNaN(t0.toXProperty().get())); + assertTrue(Double.isNaN(t0.toYProperty().get())); + assertTrue(Double.isNaN(t0.toZProperty().get())); + assertEquals(0.0, t0.byXProperty().get(), EPSILON); + assertEquals(0.0, t0.byYProperty().get(), EPSILON); + assertEquals(0.0, t0.byZProperty().get(), EPSILON); + assertNull(t0.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t0.interpolatorProperty().get()); + assertNull(t0.onFinishedProperty().get()); + + // duration only + final ScaleTransition t1 = new ScaleTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.durationProperty().get()); + assertTrue(Double.isNaN(t1.fromXProperty().get())); + assertTrue(Double.isNaN(t1.fromYProperty().get())); + assertTrue(Double.isNaN(t1.fromZProperty().get())); + assertTrue(Double.isNaN(t1.toXProperty().get())); + assertTrue(Double.isNaN(t1.toYProperty().get())); + assertTrue(Double.isNaN(t1.toZProperty().get())); + assertEquals(0.0, t1.byXProperty().get(), EPSILON); + assertEquals(0.0, t1.byYProperty().get(), EPSILON); + assertEquals(0.0, t1.byZProperty().get(), EPSILON); + assertNull(t1.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t1.interpolatorProperty().get()); + assertNull(t1.onFinishedProperty().get()); + + // duration and node + final ScaleTransition t2 = new ScaleTransition(TWO_SECS, node); + assertEquals(TWO_SECS, t2.durationProperty().get()); + assertTrue(Double.isNaN(t2.fromXProperty().get())); + assertTrue(Double.isNaN(t2.fromYProperty().get())); + assertTrue(Double.isNaN(t2.fromZProperty().get())); + assertTrue(Double.isNaN(t2.toXProperty().get())); + assertTrue(Double.isNaN(t2.toYProperty().get())); + assertTrue(Double.isNaN(t2.toZProperty().get())); + assertEquals(0.0, t2.byXProperty().get(), EPSILON); + assertEquals(0.0, t2.byYProperty().get(), EPSILON); + assertEquals(0.0, t2.byZProperty().get(), EPSILON); + assertEquals(node, t2.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t2.interpolatorProperty().get()); + assertNull(t2.onFinishedProperty().get()); + } + + @Test + public void testInterpolate() { + final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); + t0.setFromX(0.5); + t0.setToX(1.0); + t0.setFromY(1.5); + t0.setToY(2.0); + t0.setFromZ(1.5); + t0.setToZ(0.5); + + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.5, node.getScaleX(), EPSILON); + assertEquals(1.5, node.getScaleY(), EPSILON); + assertEquals(1.5, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,0.4); + assertEquals(0.7, node.getScaleX(), EPSILON); + assertEquals(1.7, node.getScaleY(), EPSILON); + assertEquals(1.1, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(1.0, node.getScaleX(), EPSILON); + assertEquals(2.0, node.getScaleY(), EPSILON); + assertEquals(0.5, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testXValueCombinations() { + final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); + final double originalValue = 0.6; + final double fromValue = 0.4; + final double toValue = 0.9; + final double byValue = -0.2; + + // no value set + node.setScaleX(originalValue); + t0.setFromX(Double.NaN); + t0.setToX(Double.NaN); + t0.setByX(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + + // only from-value set + node.setScaleX(originalValue); + t0.setFromX(fromValue); + t0.setToX(Double.NaN); + t0.setByX(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + + // only to-value set + node.setScaleX(originalValue); + t0.setFromX(Double.NaN); + t0.setToX(toValue); + t0.setByX(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + + // only by-value set + node.setScaleX(originalValue); + t0.setFromX(Double.NaN); + t0.setToX(Double.NaN); + t0.setByX(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue + byValue, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and to-values set + node.setScaleX(originalValue); + t0.setFromX(fromValue); + t0.setToX(toValue); + t0.setByX(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and by-values set + node.setScaleX(originalValue); + t0.setFromX(fromValue); + t0.setToX(Double.NaN); + t0.setByX(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue + byValue, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + + // to- and by-values set + node.setScaleX(originalValue); + t0.setFromX(Double.NaN); + t0.setToX(toValue); + t0.setByX(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + + // all values set + node.setScaleX(originalValue); + t0.setFromX(fromValue); + t0.setToX(toValue); + t0.setByX(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testYValueCombinations() { + final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); + final double originalValue = 0.6; + final double fromValue = 0.4; + final double toValue = 0.9; + final double byValue = -0.2; + + // no value set + node.setScaleY(originalValue); + t0.setFromY(Double.NaN); + t0.setToY(Double.NaN); + t0.setByY(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue, node.getScaleY(), EPSILON); + AnimationShim.impl_finished(t0); + + // only from-value set + node.setScaleY(originalValue); + t0.setFromY(fromValue); + t0.setToY(Double.NaN); + t0.setByY(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue, node.getScaleY(), EPSILON); + AnimationShim.impl_finished(t0); + + // only to-value set + node.setScaleY(originalValue); + t0.setFromY(Double.NaN); + t0.setToY(toValue); + t0.setByY(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleY(), EPSILON); + AnimationShim.impl_finished(t0); + + // only by-value set + node.setScaleY(originalValue); + t0.setFromY(Double.NaN); + t0.setToY(Double.NaN); + t0.setByY(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue + byValue, node.getScaleY(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and to-values set + node.setScaleY(originalValue); + t0.setFromY(fromValue); + t0.setToY(toValue); + t0.setByY(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleY(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and by-values set + node.setScaleY(originalValue); + t0.setFromY(fromValue); + t0.setToY(Double.NaN); + t0.setByY(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue + byValue, node.getScaleY(), EPSILON); + AnimationShim.impl_finished(t0); + + // to- and by-values set + node.setScaleY(originalValue); + t0.setFromY(Double.NaN); + t0.setToY(toValue); + t0.setByY(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleY(), EPSILON); + AnimationShim.impl_finished(t0); + + // all values set + node.setScaleY(originalValue); + t0.setFromY(fromValue); + t0.setToY(toValue); + t0.setByY(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleY(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testZValueCombinations() { + final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); + final double originalValue = 0.6; + final double fromValue = 0.4; + final double toValue = 0.9; + final double byValue = -0.2; + + // no value set + node.setScaleZ(originalValue); + t0.setFromZ(Double.NaN); + t0.setToZ(Double.NaN); + t0.setByZ(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // only from-value set + node.setScaleZ(originalValue); + t0.setFromZ(fromValue); + t0.setToZ(Double.NaN); + t0.setByZ(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // only to-value set + node.setScaleZ(originalValue); + t0.setFromZ(Double.NaN); + t0.setToZ(toValue); + t0.setByZ(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // only by-value set + node.setScaleZ(originalValue); + t0.setFromZ(Double.NaN); + t0.setToZ(Double.NaN); + t0.setByZ(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue + byValue, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and to-values set + node.setScaleZ(originalValue); + t0.setFromZ(fromValue); + t0.setToZ(toValue); + t0.setByZ(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and by-values set + node.setScaleZ(originalValue); + t0.setFromZ(fromValue); + t0.setToZ(Double.NaN); + t0.setByZ(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue + byValue, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // to- and by-values set + node.setScaleZ(originalValue); + t0.setFromZ(Double.NaN); + t0.setToZ(toValue); + t0.setByZ(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // all values set + node.setScaleZ(originalValue); + t0.setFromZ(fromValue); + t0.setToZ(toValue); + t0.setByZ(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getScaleZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testGetTargetNode() { + final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); + t0.setInterpolator(Interpolator.LINEAR); + t0.setFromX(0.5); + t0.setToX(1.0); + final Rectangle node2 = new Rectangle(); + final ParallelTransition pt = new ParallelTransition(); + pt.getChildren().add(t0); + pt.setNode(node2); + + // node set, parent set + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.5); + assertEquals(0.75, node.getScaleX(), EPSILON); + assertEquals(1.0, node2.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + + // node null, parent set + t0.setNode(null); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.4); + assertEquals(0.75, node.getScaleX(), EPSILON); + assertEquals(0.7, node2.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + + // node null, parent null + pt.setNode(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + } + + @Test + public void testCachedValues() { + final ScaleTransition t0 = new ScaleTransition(ONE_SEC, node); + t0.setInterpolator(Interpolator.LINEAR); + t0.setFromX(0.5); + t0.setToX(1.0); + t0.setFromY(1.5); + t0.setToY(2.0); + t0.setFromZ(1.5); + t0.setToZ(0.5); + + // start + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + t0.setFromX(0.0); + t0.setFromY(-1.0); + t0.setFromZ(0.5); + TransitionShim.interpolate(t0,0.5); + assertEquals(0.75, node.getScaleX(), EPSILON); + assertEquals(1.75, node.getScaleY(), EPSILON); + assertEquals(1.0, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + t0.setFromX(0.5); + t0.setFromY(1.5); + t0.setFromZ(1.5); + + // end + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + t0.setToX(0.0); + t0.setFromY(-1.0); + t0.setFromZ(1.5); + TransitionShim.interpolate(t0,0.2); + assertEquals(0.6, node.getScaleX(), EPSILON); + assertEquals(1.6, node.getScaleY(), EPSILON); + assertEquals(1.3, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + t0.setToX(1.0); + t0.setToY(2.0); + t0.setToZ(0.5); + + // node + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + t0.setNode(null); + TransitionShim.interpolate(t0,0.7); + assertEquals(0.85, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + t0.setNode(node); + + // interpolator + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + t0.setInterpolator(null); + TransitionShim.interpolate(t0,0.1); + assertEquals(0.55, node.getScaleX(), EPSILON); + AnimationShim.impl_finished(t0); + t0.setInterpolator(Interpolator.LINEAR); + } + + @Test + public void testStartable() { + final ScaleTransition t0 = new ScaleTransition(Duration.ONE, node); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // duration is 0 + t0.setDuration(Duration.ZERO); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setDuration(Duration.ONE); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // node is null + t0.setNode(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setNode(node); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // interpolator is null + t0.setInterpolator(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setInterpolator(Interpolator.LINEAR); + assertTrue(AnimationShim.impl_startable(t0,true)); + } + + @Test + public void testEvaluateStartValue() { + final ScaleTransition t0 = new ScaleTransition(Duration.INDEFINITE, node); + t0.setToX(2.0); + t0.setToY(2.0); + t0.setToZ(2.0); + + // first run + node.setScaleX( 0.6); + node.setScaleY( 1.6); + node.setScaleZ(-0.6); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + node.setScaleX(0.8); + node.setScaleY(0.8); + node.setScaleZ(0.8); + TransitionShim.interpolate(t0,0.0); + assertEquals( 0.6, node.getScaleX(), EPSILON); + assertEquals( 1.6, node.getScaleY(), EPSILON); + assertEquals(-0.6, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // second run + node.setScaleX( 0.2); + node.setScaleY(-2.2); + node.setScaleZ(11.2); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + node.setScaleX(0.8); + node.setScaleY(0.8); + node.setScaleZ(0.8); + TransitionShim.interpolate(t0,0.0); + assertEquals( 0.2, node.getScaleX(), EPSILON); + assertEquals(-2.2, node.getScaleY(), EPSILON); + assertEquals(11.2, node.getScaleZ(), EPSILON); + AnimationShim.impl_finished(t0); + } + +} --- old/modules/graphics/src/test/java/javafx/animation/SequentialTransitionPlayTest.java 2015-09-11 21:25:27.049286286 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,1011 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import com.sun.javafx.animation.TickCalculation; -import javafx.animation.Animation.Status; -import javafx.beans.property.LongProperty; -import javafx.beans.property.SimpleLongProperty; -import javafx.util.Duration; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - -public class SequentialTransitionPlayTest { - - public static final double TICK_MILLIS = TickCalculation.toMillis(100); - public static final long TICK_STEP = Math.round(TICK_MILLIS); - - LongProperty xProperty = new SimpleLongProperty(); - LongProperty yProperty = new SimpleLongProperty(); - AbstractMasterTimerMock amt; - SequentialTransition st; - Transition child1X; - Transition child1Y; - Transition childByX; - Transition childByX2; - - @Before - public void setUp() { - amt = new AbstractMasterTimerMock(); - st = new SequentialTransition(amt); - child1X = new Transition() { - { - setCycleDuration(Duration.minutes(1)); - setInterpolator(Interpolator.LINEAR); - } - - @Override - protected void interpolate(double d) { - xProperty.set(Math.round(d * 60000)); - } - }; - child1Y = new Transition() { - { - setCycleDuration(Duration.seconds(10)); - setInterpolator(Interpolator.LINEAR); - } - - @Override - protected void interpolate(double d) { - yProperty.set(Math.round(d * 10000)); - } - }; - childByX = createByXChild(); - childByX2 = createByXChild(); - } - - private Transition createByXChild() { - return new Transition() { - { - setCycleDuration(Duration.seconds(1)); - setInterpolator(Interpolator.LINEAR); - } - - long lastX; - - @Override - protected void interpolate(double frac) { - xProperty.set(Math.round(lastX + frac * 1000)); - } - - @Override - void impl_sync(boolean forceSync) { - super.impl_sync(forceSync); - if (forceSync) { - lastX = xProperty.get(); - } - } - - - }; - } - - @Test - public void testSimplePlay() { - st.getChildren().addAll(child1X, child1Y); - - st.play(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - amt.pulse(); - assertEquals(TickCalculation.toDuration(100), st.getCurrentTime()); - assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); - assertEquals(Duration.ZERO, child1Y.getCurrentTime()); - assertEquals(Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - st.jumpTo(Duration.minutes(1).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(Math.round(TICK_MILLIS), yProperty.get()); - - st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); - - amt.pulse(); - - assertEquals(Status.STOPPED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - } - - - @Test - public void testSimplePlayReversed() { - st.getChildren().addAll(child1X, child1Y); - st.setRate(-1.0); - st.jumpTo(Duration.seconds(70)); - - st.play(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(Duration.seconds(70), st.getCurrentTime()); - assertEquals(Duration.seconds(60), child1X.getCurrentTime()); - assertEquals(Duration.seconds(10), child1Y.getCurrentTime()); - - amt.pulse(); - assertEquals(Duration.seconds(70).subtract(TickCalculation.toDuration(100)), st.getCurrentTime()); - assertEquals(Duration.seconds(60), child1X.getCurrentTime()); - assertEquals(Duration.seconds(10).subtract(TickCalculation.toDuration(100)), child1Y.getCurrentTime()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - - st.jumpTo(Duration.minutes(1).add(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(Math.round(TICK_MILLIS), yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000 - Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.jumpTo(TickCalculation.toDuration(100)); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.STOPPED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - } - - @Test - public void testPauseAndJump() { - st.getChildren().addAll(child1X, child1Y); - - st.play(); - st.jumpTo(Duration.seconds(10)); - st.pause(); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - assertEquals(Duration.seconds(10), st.getCurrentTime()); - assertEquals(Duration.seconds(10), child1X.getCurrentTime()); - assertEquals(Duration.ZERO, child1Y.getCurrentTime()); - assertEquals(10000, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.play(); - st.jumpTo(Duration.seconds(50)); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(Duration.seconds(50), st.getCurrentTime()); - assertEquals(Duration.seconds(50), child1X.getCurrentTime()); - assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); - assertEquals(50000, xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(50000 + Math.round(TickCalculation.toMillis(100)), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.pause(); - st.jumpTo(Duration.seconds(65)); - assertEquals(Duration.seconds(65), st.getCurrentTime()); - assertEquals(Duration.seconds(60), child1X.getCurrentTime()); - assertEquals(Duration.seconds(5), child1Y.getCurrentTime()); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000, yProperty.get()); - - amt.pulse(); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000, yProperty.get()); - - st.play(); - st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); - assertEquals(Duration.seconds(70).subtract(TickCalculation.toDuration(100)), st.getCurrentTime()); - assertEquals(Duration.seconds(60), child1X.getCurrentTime()); - assertEquals(Duration.seconds(10).subtract(TickCalculation.toDuration(100)), child1Y.getCurrentTime()); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); - - - amt.pulse(); - assertEquals(Duration.seconds(70), st.getCurrentTime()); - assertEquals(Duration.seconds(60), child1X.getCurrentTime()); - assertEquals(Duration.seconds(10), child1Y.getCurrentTime()); - assertEquals(Status.STOPPED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - } - - @Test - public void testPauseAndJumpReversed1() { - st.getChildren().addAll(child1X, child1Y); - st.setRate(-1.0); - - st.jumpTo(Duration.seconds(70)); - st.play(); - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); - - st.pause(); - st.jumpTo(Duration.minutes(1).add(Duration.seconds(5)).add(TickCalculation.toDuration(100))); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(Duration.seconds(65).add(TickCalculation.toDuration(100)), st.getCurrentTime()); - assertEquals(60000, xProperty.get()); - assertEquals(5000 + Math.round(TickCalculation.toMillis(100)), yProperty.get()); - - st.play(); - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000, yProperty.get()); - - st.pause(); - st.jumpTo(Duration.seconds(10)); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.play(); - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.pause(); - st.jumpTo(Duration.seconds(0).add(TickCalculation.toDuration(100))); - assertEquals(TickCalculation.toDuration(100), st.getCurrentTime()); - assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); - assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(Math.round(TickCalculation.toMillis(100)), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.play(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(Math.round(TickCalculation.toMillis(100)), xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - assertEquals(Duration.seconds(0), st.getCurrentTime()); - assertEquals(Duration.seconds(0), child1X.getCurrentTime()); - assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); - assertEquals(Status.STOPPED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - } - - @Test - public void testPauseAndJumpReversed2() { - st.getChildren().addAll(child1X, child1Y); - st.setRate(-1.0); - - st.jumpTo(Duration.seconds(70)); - st.play(); - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); - - st.pause(); - st.jumpTo(Duration.seconds(50)); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(Duration.seconds(50), st.getCurrentTime()); - assertEquals(50000, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.play(); - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(50000 - Math.round(TickCalculation.toMillis(100)), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.pause(); - st.jumpTo(Duration.minutes(1).add(Duration.seconds(5)).add(TickCalculation.toDuration(100))); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000 + Math.round(TickCalculation.toMillis(100)), yProperty.get()); - - st.play(); - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000, yProperty.get()); - } - - @Test - public void testPauseAndJumpAutoReverse() { - st.getChildren().addAll(child1X, child1Y); - st.setAutoReverse(true); - st.setCycleCount(2); - - st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); - st.play(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); - - amt.pulse(); - assertEquals(Duration.seconds(70), st.getCurrentTime()); - assertEquals(Duration.seconds(60), child1X.getCurrentTime()); - assertEquals(Duration.seconds(10), child1Y.getCurrentTime()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - st.pause(); - st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).add(TickCalculation.toDuration(100))); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.PAUSED, child1Y.getStatus()); - assertEquals(Duration.seconds(70).subtract(TickCalculation.toDuration(100)), st.getCurrentTime()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); - - st.play(); - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TickCalculation.toMillis(2 * 100)), yProperty.get()); - - st.pause(); - st.jumpTo(Duration.seconds(100)); - assertEquals(Duration.seconds(40), st.getCurrentTime()); - assertEquals(Duration.seconds(40), child1X.getCurrentTime()); - assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(40000, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.play(); - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(40000 - Math.round(TickCalculation.toMillis(100)), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.pause(); - st.jumpTo(Duration.minutes(2).add(Duration.seconds(20)).subtract(TickCalculation.toDuration(100))); - assertEquals(TickCalculation.toDuration(100), st.getCurrentTime()); - assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); - assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); - assertEquals(Status.PAUSED, st.getStatus()); - assertEquals(Status.PAUSED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(Math.round(TickCalculation.toMillis(100)), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.play(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(Math.round(TickCalculation.toMillis(100)), xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - assertEquals(Duration.seconds(0), st.getCurrentTime()); - assertEquals(Duration.seconds(0), child1X.getCurrentTime()); - assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); - assertEquals(Status.STOPPED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - } - - @Test - public void testJumpAndPlay() { - st.getChildren().addAll(child1X, child1Y); - - st.jumpTo(Duration.seconds(65)); - st.play(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000, yProperty.get()); - - - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000 + Math.round(TICK_MILLIS), yProperty.get()); - - } - - @Test - public void testJumpAndPlayReversed() { - st.getChildren().addAll(child1X, child1Y); - st.setRate(-1.0); - - st.jumpTo(Duration.seconds(65)); - st.play(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000, yProperty.get()); - - - amt.pulse(); - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000 - Math.round(TICK_MILLIS), yProperty.get()); - - } - - - @Test - public void testCycle() { - st.getChildren().addAll(child1X, child1Y); - st.setCycleCount(2); - - st.play(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - - assertEquals(TickCalculation.toDuration(100), st.getCurrentTime()); - assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); - assertEquals(Duration.ZERO, child1Y.getCurrentTime()); - assertEquals(Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.jumpTo(Duration.minutes(2).add(Duration.seconds(20)).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); - - amt.pulse(); - - assertEquals(Status.STOPPED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - } - - @Test - public void testCycleReverse() { - st.getChildren().addAll(child1X, child1Y); - st.setCycleCount(-1); - st.setRate(-1.0); - - st.play(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.jumpTo(TickCalculation.toDuration(100)); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); - - st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TickCalculation.toMillis(200)), yProperty.get()); - - } - - @Test - public void testJump() { - st.getChildren().addAll(child1X, child1Y); - - assertEquals(Status.STOPPED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.jumpTo(Duration.seconds(10)); - - assertEquals(Status.STOPPED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(0, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.play(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); //Note: Not sure if we need to have also child1X running at this point - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(0, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000 + Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.jumpTo(Duration.seconds(65)); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - assertEquals(60000, xProperty.get()); - assertEquals(5000, yProperty.get()); - - st.jumpTo(Duration.seconds(10)); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.stop(); - - assertEquals(Status.STOPPED, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - assertEquals(10000, xProperty.get()); - assertEquals(0, yProperty.get()); - - } - - @Test - public void testAutoReverse() { - st.getChildren().addAll(child1X, child1Y); - st.setAutoReverse(true); - st.setCycleCount(-1); - - st.play(); - - for (int i = 0; i < TickCalculation.fromDuration(Duration.seconds(70)) / 100 - 1; ++i) { - amt.pulse(); - } - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); - - } - - @Test - public void testAutoReverseWithJump() { - st.getChildren().addAll(child1X, child1Y); - st.setAutoReverse(true); - st.setCycleCount(-1); - - st.play(); - - st.jumpTo(Duration.seconds(70).subtract(TickCalculation.toDuration(100))); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - - assertEquals(60000, xProperty.get()); - assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); - - } - - @Test - public void testChildWithDifferentRate() { - st.getChildren().addAll(child1X, child1Y); - child1X.setRate(2.0); - - st.play(); - - amt.pulse(); - - assertEquals(Math.round(TICK_MILLIS * 2), xProperty.get()); - - st.jumpTo(Duration.seconds(30)); - - assertEquals(60000, xProperty.get()); - assertEquals(0, yProperty.get()); - - st.jumpTo(Duration.seconds(40)); - - assertEquals(60000, xProperty.get()); - assertEquals(10000, yProperty.get()); - - - st.jumpTo(Duration.seconds(5)); - amt.pulse(); - - st.setRate(-1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(10000 - Math.round(TICK_MILLIS * 2), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.setRate(1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(10000 + Math.round(TICK_MILLIS * 2), xProperty.get()); - assertEquals(0, yProperty.get()); - - } - - @Test - public void testToggleRate() { - st.getChildren().addAll(child1X, child1Y); - - st.play(); - - st.jumpTo(Duration.seconds(60)); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - - assertEquals(60000, xProperty.get()); - assertEquals(Math.round(TICK_MILLIS), yProperty.get()); - - st.setRate(-1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(60000 - Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.setRate(1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.RUNNING, child1Y.getStatus()); - - assertEquals(60000, xProperty.get()); - assertEquals(Math.round(TICK_MILLIS), yProperty.get()); - - } - - @Test - public void testToggleRate_2() { - st.getChildren().addAll(child1X, child1Y); - - st.play(); - - st.jumpTo(Duration.seconds(10)); - - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(10000 + Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.setRate(-1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(10000 - Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - st.setRate(1.0); - - amt.pulse(); - amt.pulse(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.RUNNING, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - assertEquals(10000 + Math.round(TICK_MILLIS), xProperty.get()); - assertEquals(0, yProperty.get()); - - } - - @Test - public void testPlayFromStartSynchronization() { - st.getChildren().addAll(child1Y, childByX); - - st.play(); - - assertEquals(0, yProperty.get()); - assertEquals(0, xProperty.get()); - - st.jumpTo(Duration.seconds(11)); - amt.pulse(); - - st.play(); - assertEquals(0, yProperty.get()); - assertEquals(1000, xProperty.get()); - - st.jumpTo(Duration.seconds(11)); - amt.pulse(); - - - assertEquals(10000, yProperty.get()); - assertEquals(2000, xProperty.get()); - - } - - @Test - public void testCycleSynchronization() { - st.getChildren().addAll(childByX, childByX2); - - st.play(); - - assertEquals(0, xProperty.get()); - - st.jumpTo(Duration.seconds(11)); - amt.pulse(); - - st.play(); - assertEquals(2000, xProperty.get()); - - st.jumpTo(Duration.seconds(11)); - amt.pulse(); - - assertEquals(4000, xProperty.get()); - - } - - @Test - public void testJumpToDelay() { - child1X.setDelay(Duration.seconds(2)); - st.getChildren().addAll(child1X); - - st.jumpTo(Duration.seconds(2).subtract(TickCalculation.toDuration(100))); - st.play(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - - amt.pulse(); amt.pulse(); - - assertEquals(Math.round(TICK_MILLIS), xProperty.get(), 1e-10); - } - - @Test - public void testJumpToSecondDelay() { - child1Y.setDelay(Duration.seconds(2)); - st.getChildren().addAll(child1X, child1Y); - - st.jumpTo(Duration.seconds(62).subtract(TickCalculation.toDuration(100))); - st.play(); - - assertEquals(Status.RUNNING, st.getStatus()); - assertEquals(Status.STOPPED, child1X.getStatus()); - assertEquals(Status.STOPPED, child1Y.getStatus()); - - amt.pulse(); amt.pulse(); - - assertEquals(Math.round(TICK_MILLIS), yProperty.get(), 1e-10); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/SequentialTransitionPlayTest.java 2015-09-11 21:25:26.833286288 -0400 @@ -0,0 +1,1017 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import com.sun.javafx.animation.TickCalculation; +import javafx.animation.Animation.Status; +import javafx.animation.AnimationShim; +import javafx.animation.Interpolator; +import javafx.animation.SequentialTransition; +import javafx.animation.SequentialTransitionShim; +import javafx.animation.Transition; +import javafx.animation.TransitionShim; +import javafx.beans.property.LongProperty; +import javafx.beans.property.SimpleLongProperty; +import javafx.util.Duration; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + +public class SequentialTransitionPlayTest { + + public static final double TICK_MILLIS = TickCalculation.toMillis(100); + public static final long TICK_STEP = Math.round(TICK_MILLIS); + + LongProperty xProperty = new SimpleLongProperty(); + LongProperty yProperty = new SimpleLongProperty(); + AbstractMasterTimerMock amt; + SequentialTransition st; + Transition child1X; + Transition child1Y; + Transition childByX; + Transition childByX2; + + @Before + public void setUp() { + amt = new AbstractMasterTimerMock(); + st = SequentialTransitionShim.getSequentialTransition(amt); + child1X = new TransitionShim() { + { + setCycleDuration(Duration.minutes(1)); + setInterpolator(Interpolator.LINEAR); + } + + @Override + protected void interpolate(double d) { + xProperty.set(Math.round(d * 60000)); + } + }; + child1Y = new TransitionShim() { + { + setCycleDuration(Duration.seconds(10)); + setInterpolator(Interpolator.LINEAR); + } + + @Override + protected void interpolate(double d) { + yProperty.set(Math.round(d * 10000)); + } + }; + childByX = createByXChild(); + childByX2 = createByXChild(); + } + + private Transition createByXChild() { + return new TransitionShim() { + { + setCycleDuration(Duration.seconds(1)); + setInterpolator(Interpolator.LINEAR); + } + + long lastX; + + @Override + protected void interpolate(double frac) { + xProperty.set(Math.round(lastX + frac * 1000)); + } + + @Override + public void impl_sync(boolean forceSync) { + super.impl_sync(forceSync); + if (forceSync) { + lastX = xProperty.get(); + } + } + + + }; + } + + @Test + public void testSimplePlay() { + st.getChildren().addAll(child1X, child1Y); + + st.play(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + amt.pulse(); + assertEquals(TickCalculation.toDuration(100), st.getCurrentTime()); + assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); + assertEquals(Duration.ZERO, child1Y.getCurrentTime()); + assertEquals(Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + st.jumpTo(Duration.minutes(1).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(Math.round(TICK_MILLIS), yProperty.get()); + + st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); + + amt.pulse(); + + assertEquals(Status.STOPPED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + } + + + @Test + public void testSimplePlayReversed() { + st.getChildren().addAll(child1X, child1Y); + st.setRate(-1.0); + st.jumpTo(Duration.seconds(70)); + + st.play(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(Duration.seconds(70), st.getCurrentTime()); + assertEquals(Duration.seconds(60), child1X.getCurrentTime()); + assertEquals(Duration.seconds(10), child1Y.getCurrentTime()); + + amt.pulse(); + assertEquals(Duration.seconds(70).subtract(TickCalculation.toDuration(100)), st.getCurrentTime()); + assertEquals(Duration.seconds(60), child1X.getCurrentTime()); + assertEquals(Duration.seconds(10).subtract(TickCalculation.toDuration(100)), child1Y.getCurrentTime()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + + st.jumpTo(Duration.minutes(1).add(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(Math.round(TICK_MILLIS), yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000 - Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.jumpTo(TickCalculation.toDuration(100)); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.STOPPED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + } + + @Test + public void testPauseAndJump() { + st.getChildren().addAll(child1X, child1Y); + + st.play(); + st.jumpTo(Duration.seconds(10)); + st.pause(); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + assertEquals(Duration.seconds(10), st.getCurrentTime()); + assertEquals(Duration.seconds(10), child1X.getCurrentTime()); + assertEquals(Duration.ZERO, child1Y.getCurrentTime()); + assertEquals(10000, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.play(); + st.jumpTo(Duration.seconds(50)); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(Duration.seconds(50), st.getCurrentTime()); + assertEquals(Duration.seconds(50), child1X.getCurrentTime()); + assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); + assertEquals(50000, xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(50000 + Math.round(TickCalculation.toMillis(100)), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.pause(); + st.jumpTo(Duration.seconds(65)); + assertEquals(Duration.seconds(65), st.getCurrentTime()); + assertEquals(Duration.seconds(60), child1X.getCurrentTime()); + assertEquals(Duration.seconds(5), child1Y.getCurrentTime()); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000, yProperty.get()); + + amt.pulse(); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000, yProperty.get()); + + st.play(); + st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); + assertEquals(Duration.seconds(70).subtract(TickCalculation.toDuration(100)), st.getCurrentTime()); + assertEquals(Duration.seconds(60), child1X.getCurrentTime()); + assertEquals(Duration.seconds(10).subtract(TickCalculation.toDuration(100)), child1Y.getCurrentTime()); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); + + + amt.pulse(); + assertEquals(Duration.seconds(70), st.getCurrentTime()); + assertEquals(Duration.seconds(60), child1X.getCurrentTime()); + assertEquals(Duration.seconds(10), child1Y.getCurrentTime()); + assertEquals(Status.STOPPED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + } + + @Test + public void testPauseAndJumpReversed1() { + st.getChildren().addAll(child1X, child1Y); + st.setRate(-1.0); + + st.jumpTo(Duration.seconds(70)); + st.play(); + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); + + st.pause(); + st.jumpTo(Duration.minutes(1).add(Duration.seconds(5)).add(TickCalculation.toDuration(100))); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(Duration.seconds(65).add(TickCalculation.toDuration(100)), st.getCurrentTime()); + assertEquals(60000, xProperty.get()); + assertEquals(5000 + Math.round(TickCalculation.toMillis(100)), yProperty.get()); + + st.play(); + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000, yProperty.get()); + + st.pause(); + st.jumpTo(Duration.seconds(10)); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.play(); + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.pause(); + st.jumpTo(Duration.seconds(0).add(TickCalculation.toDuration(100))); + assertEquals(TickCalculation.toDuration(100), st.getCurrentTime()); + assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); + assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(Math.round(TickCalculation.toMillis(100)), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.play(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(Math.round(TickCalculation.toMillis(100)), xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + assertEquals(Duration.seconds(0), st.getCurrentTime()); + assertEquals(Duration.seconds(0), child1X.getCurrentTime()); + assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); + assertEquals(Status.STOPPED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + } + + @Test + public void testPauseAndJumpReversed2() { + st.getChildren().addAll(child1X, child1Y); + st.setRate(-1.0); + + st.jumpTo(Duration.seconds(70)); + st.play(); + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); + + st.pause(); + st.jumpTo(Duration.seconds(50)); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(Duration.seconds(50), st.getCurrentTime()); + assertEquals(50000, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.play(); + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(50000 - Math.round(TickCalculation.toMillis(100)), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.pause(); + st.jumpTo(Duration.minutes(1).add(Duration.seconds(5)).add(TickCalculation.toDuration(100))); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000 + Math.round(TickCalculation.toMillis(100)), yProperty.get()); + + st.play(); + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000, yProperty.get()); + } + + @Test + public void testPauseAndJumpAutoReverse() { + st.getChildren().addAll(child1X, child1Y); + st.setAutoReverse(true); + st.setCycleCount(2); + + st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); + st.play(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); + + amt.pulse(); + assertEquals(Duration.seconds(70), st.getCurrentTime()); + assertEquals(Duration.seconds(60), child1X.getCurrentTime()); + assertEquals(Duration.seconds(10), child1Y.getCurrentTime()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + st.pause(); + st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).add(TickCalculation.toDuration(100))); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.PAUSED, child1Y.getStatus()); + assertEquals(Duration.seconds(70).subtract(TickCalculation.toDuration(100)), st.getCurrentTime()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TickCalculation.toMillis(100)), yProperty.get()); + + st.play(); + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TickCalculation.toMillis(2 * 100)), yProperty.get()); + + st.pause(); + st.jumpTo(Duration.seconds(100)); + assertEquals(Duration.seconds(40), st.getCurrentTime()); + assertEquals(Duration.seconds(40), child1X.getCurrentTime()); + assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(40000, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.play(); + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(40000 - Math.round(TickCalculation.toMillis(100)), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.pause(); + st.jumpTo(Duration.minutes(2).add(Duration.seconds(20)).subtract(TickCalculation.toDuration(100))); + assertEquals(TickCalculation.toDuration(100), st.getCurrentTime()); + assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); + assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); + assertEquals(Status.PAUSED, st.getStatus()); + assertEquals(Status.PAUSED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(Math.round(TickCalculation.toMillis(100)), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.play(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(Math.round(TickCalculation.toMillis(100)), xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + assertEquals(Duration.seconds(0), st.getCurrentTime()); + assertEquals(Duration.seconds(0), child1X.getCurrentTime()); + assertEquals(Duration.seconds(0), child1Y.getCurrentTime()); + assertEquals(Status.STOPPED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + } + + @Test + public void testJumpAndPlay() { + st.getChildren().addAll(child1X, child1Y); + + st.jumpTo(Duration.seconds(65)); + st.play(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000, yProperty.get()); + + + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000 + Math.round(TICK_MILLIS), yProperty.get()); + + } + + @Test + public void testJumpAndPlayReversed() { + st.getChildren().addAll(child1X, child1Y); + st.setRate(-1.0); + + st.jumpTo(Duration.seconds(65)); + st.play(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000, yProperty.get()); + + + amt.pulse(); + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000 - Math.round(TICK_MILLIS), yProperty.get()); + + } + + + @Test + public void testCycle() { + st.getChildren().addAll(child1X, child1Y); + st.setCycleCount(2); + + st.play(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + + assertEquals(TickCalculation.toDuration(100), st.getCurrentTime()); + assertEquals(TickCalculation.toDuration(100), child1X.getCurrentTime()); + assertEquals(Duration.ZERO, child1Y.getCurrentTime()); + assertEquals(Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.jumpTo(Duration.minutes(2).add(Duration.seconds(20)).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); + + amt.pulse(); + + assertEquals(Status.STOPPED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + } + + @Test + public void testCycleReverse() { + st.getChildren().addAll(child1X, child1Y); + st.setCycleCount(-1); + st.setRate(-1.0); + + st.play(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.jumpTo(TickCalculation.toDuration(100)); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); + + st.jumpTo(Duration.minutes(1).add(Duration.seconds(10)).subtract(TickCalculation.toDuration(100))); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TickCalculation.toMillis(200)), yProperty.get()); + + } + + @Test + public void testJump() { + st.getChildren().addAll(child1X, child1Y); + + assertEquals(Status.STOPPED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.jumpTo(Duration.seconds(10)); + + assertEquals(Status.STOPPED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(0, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.play(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); //Note: Not sure if we need to have also child1X running at this point + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(0, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000 + Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.jumpTo(Duration.seconds(65)); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + assertEquals(60000, xProperty.get()); + assertEquals(5000, yProperty.get()); + + st.jumpTo(Duration.seconds(10)); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.stop(); + + assertEquals(Status.STOPPED, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + assertEquals(10000, xProperty.get()); + assertEquals(0, yProperty.get()); + + } + + @Test + public void testAutoReverse() { + st.getChildren().addAll(child1X, child1Y); + st.setAutoReverse(true); + st.setCycleCount(-1); + + st.play(); + + for (int i = 0; i < TickCalculation.fromDuration(Duration.seconds(70)) / 100 - 1; ++i) { + amt.pulse(); + } + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); + + } + + @Test + public void testAutoReverseWithJump() { + st.getChildren().addAll(child1X, child1Y); + st.setAutoReverse(true); + st.setCycleCount(-1); + + st.play(); + + st.jumpTo(Duration.seconds(70).subtract(TickCalculation.toDuration(100))); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + + assertEquals(60000, xProperty.get()); + assertEquals(10000 - Math.round(TICK_MILLIS), yProperty.get()); + + } + + @Test + public void testChildWithDifferentRate() { + st.getChildren().addAll(child1X, child1Y); + child1X.setRate(2.0); + + st.play(); + + amt.pulse(); + + assertEquals(Math.round(TICK_MILLIS * 2), xProperty.get()); + + st.jumpTo(Duration.seconds(30)); + + assertEquals(60000, xProperty.get()); + assertEquals(0, yProperty.get()); + + st.jumpTo(Duration.seconds(40)); + + assertEquals(60000, xProperty.get()); + assertEquals(10000, yProperty.get()); + + + st.jumpTo(Duration.seconds(5)); + amt.pulse(); + + st.setRate(-1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(10000 - Math.round(TICK_MILLIS * 2), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.setRate(1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(10000 + Math.round(TICK_MILLIS * 2), xProperty.get()); + assertEquals(0, yProperty.get()); + + } + + @Test + public void testToggleRate() { + st.getChildren().addAll(child1X, child1Y); + + st.play(); + + st.jumpTo(Duration.seconds(60)); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + + assertEquals(60000, xProperty.get()); + assertEquals(Math.round(TICK_MILLIS), yProperty.get()); + + st.setRate(-1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(60000 - Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.setRate(1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.RUNNING, child1Y.getStatus()); + + assertEquals(60000, xProperty.get()); + assertEquals(Math.round(TICK_MILLIS), yProperty.get()); + + } + + @Test + public void testToggleRate_2() { + st.getChildren().addAll(child1X, child1Y); + + st.play(); + + st.jumpTo(Duration.seconds(10)); + + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(10000 + Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.setRate(-1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(10000 - Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + st.setRate(1.0); + + amt.pulse(); + amt.pulse(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.RUNNING, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + assertEquals(10000 + Math.round(TICK_MILLIS), xProperty.get()); + assertEquals(0, yProperty.get()); + + } + + @Test + public void testPlayFromStartSynchronization() { + st.getChildren().addAll(child1Y, childByX); + + st.play(); + + assertEquals(0, yProperty.get()); + assertEquals(0, xProperty.get()); + + st.jumpTo(Duration.seconds(11)); + amt.pulse(); + + st.play(); + assertEquals(0, yProperty.get()); + assertEquals(1000, xProperty.get()); + + st.jumpTo(Duration.seconds(11)); + amt.pulse(); + + + assertEquals(10000, yProperty.get()); + assertEquals(2000, xProperty.get()); + + } + + @Test + public void testCycleSynchronization() { + st.getChildren().addAll(childByX, childByX2); + + st.play(); + + assertEquals(0, xProperty.get()); + + st.jumpTo(Duration.seconds(11)); + amt.pulse(); + + st.play(); + assertEquals(2000, xProperty.get()); + + st.jumpTo(Duration.seconds(11)); + amt.pulse(); + + assertEquals(4000, xProperty.get()); + + } + + @Test + public void testJumpToDelay() { + child1X.setDelay(Duration.seconds(2)); + st.getChildren().addAll(child1X); + + st.jumpTo(Duration.seconds(2).subtract(TickCalculation.toDuration(100))); + st.play(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + + amt.pulse(); amt.pulse(); + + assertEquals(Math.round(TICK_MILLIS), xProperty.get(), 1e-10); + } + + @Test + public void testJumpToSecondDelay() { + child1Y.setDelay(Duration.seconds(2)); + st.getChildren().addAll(child1X, child1Y); + + st.jumpTo(Duration.seconds(62).subtract(TickCalculation.toDuration(100))); + st.play(); + + assertEquals(Status.RUNNING, st.getStatus()); + assertEquals(Status.STOPPED, child1X.getStatus()); + assertEquals(Status.STOPPED, child1Y.getStatus()); + + amt.pulse(); amt.pulse(); + + assertEquals(Math.round(TICK_MILLIS), yProperty.get(), 1e-10); + } + +} --- old/modules/graphics/src/test/java/javafx/animation/SequentialTransitionTest.java 2015-09-11 21:25:27.669286279 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; - -import javafx.scene.Node; -import javafx.scene.shape.Rectangle; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - -public class SequentialTransitionTest { - - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.LINEAR; - - private static Duration ONE_SEC = Duration.millis(1000); - private static Duration TWO_SECS = Duration.millis(2000); - private static Duration THREE_SECS = Duration.millis(3000); - private static Duration SIX_SECS = Duration.millis(6000); - - private Node node; - private Animation child1; - private Animation child2; - private Animation child3; - - @Before - public void setUp() { - node = new Rectangle(); - child1 = new AnimationDummy(ONE_SEC); - child2 = new AnimationDummy(TWO_SECS); - child3 = new AnimationDummy(THREE_SECS); - } - - @Test - public void testDefaultValues() { - // empty ctor - final SequentialTransition t0 = new SequentialTransition(); - assertEquals(Duration.ZERO, t0.getTotalDuration()); - assertNull(t0.getNode()); - assertNull(t0.nodeProperty().get()); - assertTrue(t0.getChildren().isEmpty()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // node only - final SequentialTransition t1 = new SequentialTransition(node); - assertEquals(Duration.ZERO, t1.getTotalDuration()); - assertEquals(node, t1.getNode()); - assertEquals(node, t1.nodeProperty().get()); - assertTrue(t1.getChildren().isEmpty()); - assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); - assertNull(t1.getOnFinished()); - - // child animations only - final SequentialTransition t2 = new SequentialTransition(child1, child2, child3); - assertEquals(SIX_SECS, t2.getTotalDuration()); - assertNull(t2.getNode()); - assertNull(t2.nodeProperty().get()); - assertEquals(Arrays.asList(child1, child2, child3), t2.getChildren()); - assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); - assertNull(t2.getOnFinished()); - - // node and child animations - final SequentialTransition t3 = new SequentialTransition(node, child1, child2, child3); - assertEquals(SIX_SECS, t3.getTotalDuration()); - assertEquals(node, t3.getNode()); - assertEquals(node, t3.nodeProperty().get()); - assertEquals(Arrays.asList(child1, child2, child3), t3.getChildren()); - assertEquals(DEFAULT_INTERPOLATOR, t3.getInterpolator()); - assertNull(t3.getOnFinished()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/SequentialTransitionTest.java 2015-09-11 21:25:27.529286280 -0400 @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import javafx.animation.Animation; +import javafx.animation.Interpolator; +import javafx.animation.SequentialTransition; + +import javafx.scene.Node; +import javafx.scene.shape.Rectangle; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + +public class SequentialTransitionTest { + + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.LINEAR; + + private static Duration ONE_SEC = Duration.millis(1000); + private static Duration TWO_SECS = Duration.millis(2000); + private static Duration THREE_SECS = Duration.millis(3000); + private static Duration SIX_SECS = Duration.millis(6000); + + private Node node; + private Animation child1; + private Animation child2; + private Animation child3; + + @Before + public void setUp() { + node = new Rectangle(); + child1 = new AnimationDummy(ONE_SEC); + child2 = new AnimationDummy(TWO_SECS); + child3 = new AnimationDummy(THREE_SECS); + } + + @Test + public void testDefaultValues() { + // empty ctor + final SequentialTransition t0 = new SequentialTransition(); + assertEquals(Duration.ZERO, t0.getTotalDuration()); + assertNull(t0.getNode()); + assertNull(t0.nodeProperty().get()); + assertTrue(t0.getChildren().isEmpty()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // node only + final SequentialTransition t1 = new SequentialTransition(node); + assertEquals(Duration.ZERO, t1.getTotalDuration()); + assertEquals(node, t1.getNode()); + assertEquals(node, t1.nodeProperty().get()); + assertTrue(t1.getChildren().isEmpty()); + assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); + assertNull(t1.getOnFinished()); + + // child animations only + final SequentialTransition t2 = new SequentialTransition(child1, child2, child3); + assertEquals(SIX_SECS, t2.getTotalDuration()); + assertNull(t2.getNode()); + assertNull(t2.nodeProperty().get()); + assertEquals(Arrays.asList(child1, child2, child3), t2.getChildren()); + assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); + assertNull(t2.getOnFinished()); + + // node and child animations + final SequentialTransition t3 = new SequentialTransition(node, child1, child2, child3); + assertEquals(SIX_SECS, t3.getTotalDuration()); + assertEquals(node, t3.getNode()); + assertEquals(node, t3.nodeProperty().get()); + assertEquals(Arrays.asList(child1, child2, child3), t3.getChildren()); + assertEquals(DEFAULT_INTERPOLATOR, t3.getInterpolator()); + assertNull(t3.getOnFinished()); + } +} --- old/modules/graphics/src/test/java/javafx/animation/StrokeTransitionTest.java 2015-09-11 21:25:28.417286270 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,310 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import javafx.scene.Group; -import javafx.scene.paint.Color; -import javafx.scene.paint.LinearGradient; -import javafx.scene.paint.Paint; -import javafx.scene.paint.Stop; -import javafx.scene.shape.Rectangle; -import javafx.scene.shape.Shape; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - -public class StrokeTransitionTest { - - private static Duration DEFAULT_DURATION = Duration.millis(400); - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; - - private static float EPSILON = 1e-6f; - private static Duration ONE_SEC = Duration.millis(1000); - private static Duration TWO_SECS = Duration.millis(2000); - - private Shape shape; - - @Before - public void setUp() { - shape = new Rectangle(); - } - - private void assertColorEquals(Color expected, Paint actualPaint) { - assertTrue(actualPaint instanceof Color); - final Color actual = (Color)actualPaint; - assertEquals(expected.getRed(), actual.getRed(), EPSILON); - assertEquals(expected.getGreen(), actual.getGreen(), EPSILON); - assertEquals(expected.getBlue(), actual.getBlue(), EPSILON); - assertEquals(expected.getOpacity(), actual.getOpacity(), EPSILON); - } - - @Test - public void testDefaultValues() { - // empty ctor - StrokeTransition t0 = new StrokeTransition(); - assertEquals(DEFAULT_DURATION, t0.getDuration()); - assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); - assertNull(t0.getFromValue()); - assertNull(t0.getToValue()); - assertNull(t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration only - t0 = new StrokeTransition(ONE_SEC); - assertEquals(ONE_SEC, t0.getDuration()); - assertNull(t0.getFromValue()); - assertNull(t0.getToValue()); - assertNull(t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration and shape - t0 = new StrokeTransition(TWO_SECS, shape); - assertEquals(TWO_SECS, t0.getDuration()); - assertNull(t0.getFromValue()); - assertNull(t0.getToValue()); - assertEquals(shape, t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration and values - t0 = new StrokeTransition(TWO_SECS, null, Color.BLACK, Color.WHITE); - assertEquals(TWO_SECS, t0.getDuration()); - assertColorEquals(Color.BLACK, t0.getFromValue()); - assertColorEquals(Color.WHITE, t0.getToValue()); - assertNull(t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration, shape, and values - t0 = new StrokeTransition(TWO_SECS, shape, Color.BLACK, Color.WHITE); - assertEquals(TWO_SECS, t0.getDuration()); - assertColorEquals(Color.BLACK, t0.getFromValue()); - assertColorEquals(Color.WHITE, t0.getToValue()); - assertEquals(shape, t0.getShape()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - } - - @Test - public void testInterpolate() { - final Color fromValue = Color.color(0.2, 0.3, 0.7, 0.1); - final Color toValue = Color.color(0.8, 0.4, 0.2, 0.9); - final StrokeTransition t0 = new StrokeTransition(ONE_SEC, shape, fromValue, toValue); - - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertColorEquals(Color.color(0.2, 0.3, 0.7, 0.1), shape.getStroke()); - t0.interpolate(0.4); - assertColorEquals(Color.color(0.44, 0.34, 0.5, 0.42), shape.getStroke()); - t0.interpolate(1.0); - assertColorEquals(Color.color(0.8, 0.4, 0.2, 0.9), shape.getStroke()); - t0.impl_finished(); - } - - @Test - public void testRedValueCombinations() { - final StrokeTransition t0 = new StrokeTransition(ONE_SEC, shape, null, Color.WHITE); - final double originalRed = 0.6; - final double fromRed = 0.4; - final Color originalValue = Color.color(originalRed, 1.0, 1.0); - final Color fromValue = Color.color(fromRed, 1.0, 1.0); - - // no from value set - shape.setStroke(originalValue); - t0.setFromValue(null); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertColorEquals(originalValue, shape.getStroke()); - t0.impl_finished(); - - // from-value set - shape.setStroke(originalValue); - t0.setFromValue(fromValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertColorEquals(fromValue, shape.getStroke()); - t0.impl_finished(); - } - - @Test - public void testGetTargetNode() { - final Color fromValue = Color.color(0.0, 0.4, 0.8, 1.0); - final Color toValue = Color.color(1.0, 0.8, 0.6, 0.4); - final StrokeTransition ft = new StrokeTransition(ONE_SEC, shape, fromValue, toValue); - ft.setInterpolator(Interpolator.LINEAR); - final Shape shape2 = new Rectangle(); - final ParallelTransition pt = new ParallelTransition(); - pt.getChildren().add(ft); - pt.setNode(shape2); - shape.setStroke(Color.WHITE); - shape2.setStroke(Color.WHITE); - - // node set, parent set - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.interpolate(0.5); - assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.7), shape.getStroke()); - assertColorEquals(Color.WHITE, shape2.getStroke()); - ft.impl_finished(); - - // node null, parent set - ft.setShape(null); - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.interpolate(0.4); - assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.7), shape.getStroke()); - assertColorEquals(Color.color(0.4, 0.56, 0.72, 0.76), shape2.getStroke()); - ft.impl_finished(); - - // node null, parent not shape set - pt.setNode(new Group()); - assertFalse(ft.impl_startable(true)); - - // node null, parent null - pt.setNode(null); - assertFalse(ft.impl_startable(true)); - } - - @Test - public void testCachedValues() { - final Color fromValue = Color.color(0.0, 0.4, 0.8, 0.2); - final Color toValue = Color.color(1.0, 0.8, 0.6, 0.4); - final StrokeTransition ft = new StrokeTransition(ONE_SEC, shape, fromValue, toValue); - ft.setInterpolator(Interpolator.LINEAR); - - // start - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setFromValue(Color.WHITE); - ft.interpolate(0.5); - assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.3), shape.getStroke()); - ft.impl_finished(); - ft.setFromValue(fromValue); - - // end - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setToValue(Color.BLACK); - ft.interpolate(0.2); - assertColorEquals(Color.color(0.2, 0.48, 0.76, 0.24), shape.getStroke()); - ft.impl_finished(); - ft.setToValue(toValue); - - // shape - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setShape(null); - ft.interpolate(0.7); - assertColorEquals(Color.color(0.7, 0.68, 0.66, 0.34), shape.getStroke()); - ft.impl_finished(); - ft.setShape(shape); - - // interpolator - assertTrue(ft.impl_startable(true)); - ft.impl_start(true); - ft.setInterpolator(null); - ft.interpolate(0.1); - assertColorEquals(Color.color(0.1, 0.44, 0.78, 0.22), shape.getStroke()); - ft.impl_finished(); - ft.setInterpolator(Interpolator.LINEAR); - } - - @Test - public void testStartable() { - final StrokeTransition t0 = new StrokeTransition(Duration.ONE, shape, Color.WHITE, Color.BLACK); - final Paint paint2 = new LinearGradient(0, 0, 1, 1, false, null, - new Stop[] { new Stop(0, Color.RED) }); - assertTrue(t0.impl_startable(true)); - - // duration is 0 - t0.setDuration(Duration.ZERO); - assertFalse(t0.impl_startable(true)); - t0.setDuration(Duration.ONE); - assertTrue(t0.impl_startable(true)); - - // shape is null - t0.setShape(null); - assertFalse(t0.impl_startable(true)); - t0.setShape(shape); - assertTrue(t0.impl_startable(true)); - - // interpolator is null - t0.setInterpolator(null); - assertFalse(t0.impl_startable(true)); - t0.setInterpolator(Interpolator.LINEAR); - assertTrue(t0.impl_startable(true)); - - // fromValue - t0.setFromValue(null); - shape.setStroke(paint2); - assertFalse(t0.impl_startable(true)); - shape.setStroke(Color.BLACK); - assertTrue(t0.impl_startable(true)); - t0.setFromValue(Color.WHITE); - shape.setStroke(paint2); - assertTrue(t0.impl_startable(true)); - - // toValue - t0.setToValue(null); - assertFalse(t0.impl_startable(true)); - t0.setToValue(Color.BLACK); - assertTrue(t0.impl_startable(true)); - } - - @Test - public void testEvaluateStartValue() { - final StrokeTransition t0 = new StrokeTransition(Duration.INDEFINITE, shape, null, Color.WHITE); - - // first run - shape.setStroke(Color.GREY); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - shape.setStroke(Color.TRANSPARENT); - t0.interpolate(0.0); - assertColorEquals(Color.GREY, shape.getStroke()); - t0.impl_finished(); - - // second run - shape.setStroke(Color.BLACK); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - shape.setStroke(Color.WHITE); - t0.interpolate(0.0); - assertColorEquals(Color.BLACK, shape.getStroke()); - t0.impl_finished(); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/StrokeTransitionTest.java 2015-09-11 21:25:28.221286273 -0400 @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.animation.AnimationShim; +import javafx.animation.Interpolator; +import javafx.animation.ParallelTransition; +import javafx.animation.StrokeTransition; +import javafx.animation.TransitionShim; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import javafx.scene.Group; +import javafx.scene.paint.Color; +import javafx.scene.paint.LinearGradient; +import javafx.scene.paint.Paint; +import javafx.scene.paint.Stop; +import javafx.scene.shape.Rectangle; +import javafx.scene.shape.Shape; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + +public class StrokeTransitionTest { + + private static Duration DEFAULT_DURATION = Duration.millis(400); + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; + + private static float EPSILON = 1e-6f; + private static Duration ONE_SEC = Duration.millis(1000); + private static Duration TWO_SECS = Duration.millis(2000); + + private Shape shape; + + @Before + public void setUp() { + shape = new Rectangle(); + } + + private void assertColorEquals(Color expected, Paint actualPaint) { + assertTrue(actualPaint instanceof Color); + final Color actual = (Color)actualPaint; + assertEquals(expected.getRed(), actual.getRed(), EPSILON); + assertEquals(expected.getGreen(), actual.getGreen(), EPSILON); + assertEquals(expected.getBlue(), actual.getBlue(), EPSILON); + assertEquals(expected.getOpacity(), actual.getOpacity(), EPSILON); + } + + @Test + public void testDefaultValues() { + // empty ctor + StrokeTransition t0 = new StrokeTransition(); + assertEquals(DEFAULT_DURATION, t0.getDuration()); + assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); + assertNull(t0.getFromValue()); + assertNull(t0.getToValue()); + assertNull(t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration only + t0 = new StrokeTransition(ONE_SEC); + assertEquals(ONE_SEC, t0.getDuration()); + assertNull(t0.getFromValue()); + assertNull(t0.getToValue()); + assertNull(t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration and shape + t0 = new StrokeTransition(TWO_SECS, shape); + assertEquals(TWO_SECS, t0.getDuration()); + assertNull(t0.getFromValue()); + assertNull(t0.getToValue()); + assertEquals(shape, t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration and values + t0 = new StrokeTransition(TWO_SECS, null, Color.BLACK, Color.WHITE); + assertEquals(TWO_SECS, t0.getDuration()); + assertColorEquals(Color.BLACK, t0.getFromValue()); + assertColorEquals(Color.WHITE, t0.getToValue()); + assertNull(t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration, shape, and values + t0 = new StrokeTransition(TWO_SECS, shape, Color.BLACK, Color.WHITE); + assertEquals(TWO_SECS, t0.getDuration()); + assertColorEquals(Color.BLACK, t0.getFromValue()); + assertColorEquals(Color.WHITE, t0.getToValue()); + assertEquals(shape, t0.getShape()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + } + + @Test + public void testInterpolate() { + final Color fromValue = Color.color(0.2, 0.3, 0.7, 0.1); + final Color toValue = Color.color(0.8, 0.4, 0.2, 0.9); + final StrokeTransition t0 = new StrokeTransition(ONE_SEC, shape, fromValue, toValue); + + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(Color.color(0.2, 0.3, 0.7, 0.1), shape.getStroke()); + TransitionShim.interpolate(t0,0.4); + assertColorEquals(Color.color(0.44, 0.34, 0.5, 0.42), shape.getStroke()); + TransitionShim.interpolate(t0,1.0); + assertColorEquals(Color.color(0.8, 0.4, 0.2, 0.9), shape.getStroke()); + AnimationShim.impl_finished(t0); + } + + @Test + public void testRedValueCombinations() { + final StrokeTransition t0 = new StrokeTransition(ONE_SEC, shape, null, Color.WHITE); + final double originalRed = 0.6; + final double fromRed = 0.4; + final Color originalValue = Color.color(originalRed, 1.0, 1.0); + final Color fromValue = Color.color(fromRed, 1.0, 1.0); + + // no from value set + shape.setStroke(originalValue); + t0.setFromValue(null); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(originalValue, shape.getStroke()); + AnimationShim.impl_finished(t0); + + // from-value set + shape.setStroke(originalValue); + t0.setFromValue(fromValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(fromValue, shape.getStroke()); + AnimationShim.impl_finished(t0); + } + + @Test + public void testGetTargetNode() { + final Color fromValue = Color.color(0.0, 0.4, 0.8, 1.0); + final Color toValue = Color.color(1.0, 0.8, 0.6, 0.4); + final StrokeTransition ft = new StrokeTransition(ONE_SEC, shape, fromValue, toValue); + ft.setInterpolator(Interpolator.LINEAR); + final Shape shape2 = new Rectangle(); + final ParallelTransition pt = new ParallelTransition(); + pt.getChildren().add(ft); + pt.setNode(shape2); + shape.setStroke(Color.WHITE); + shape2.setStroke(Color.WHITE); + + // node set, parent set + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + TransitionShim.interpolate(ft,0.5); + assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.7), shape.getStroke()); + assertColorEquals(Color.WHITE, shape2.getStroke()); + AnimationShim.impl_finished(ft); + + // node null, parent set + ft.setShape(null); + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + TransitionShim.interpolate(ft,0.4); + assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.7), shape.getStroke()); + assertColorEquals(Color.color(0.4, 0.56, 0.72, 0.76), shape2.getStroke()); + AnimationShim.impl_finished(ft); + + // node null, parent not shape set + pt.setNode(new Group()); + assertFalse(AnimationShim.impl_startable(ft,true)); + + // node null, parent null + pt.setNode(null); + assertFalse(AnimationShim.impl_startable(ft,true)); + } + + @Test + public void testCachedValues() { + final Color fromValue = Color.color(0.0, 0.4, 0.8, 0.2); + final Color toValue = Color.color(1.0, 0.8, 0.6, 0.4); + final StrokeTransition ft = new StrokeTransition(ONE_SEC, shape, fromValue, toValue); + ft.setInterpolator(Interpolator.LINEAR); + + // start + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setFromValue(Color.WHITE); + TransitionShim.interpolate(ft,0.5); + assertColorEquals(Color.color(0.5, 0.6, 0.7, 0.3), shape.getStroke()); + AnimationShim.impl_finished(ft); + ft.setFromValue(fromValue); + + // end + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setToValue(Color.BLACK); + TransitionShim.interpolate(ft,0.2); + assertColorEquals(Color.color(0.2, 0.48, 0.76, 0.24), shape.getStroke()); + AnimationShim.impl_finished(ft); + ft.setToValue(toValue); + + // shape + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setShape(null); + TransitionShim.interpolate(ft,0.7); + assertColorEquals(Color.color(0.7, 0.68, 0.66, 0.34), shape.getStroke()); + AnimationShim.impl_finished(ft); + ft.setShape(shape); + + // interpolator + assertTrue(AnimationShim.impl_startable(ft,true)); + AnimationShim.impl_start(ft,true); + ft.setInterpolator(null); + TransitionShim.interpolate(ft,0.1); + assertColorEquals(Color.color(0.1, 0.44, 0.78, 0.22), shape.getStroke()); + AnimationShim.impl_finished(ft); + ft.setInterpolator(Interpolator.LINEAR); + } + + @Test + public void testStartable() { + final StrokeTransition t0 = new StrokeTransition(Duration.ONE, shape, Color.WHITE, Color.BLACK); + final Paint paint2 = new LinearGradient(0, 0, 1, 1, false, null, + new Stop[] { new Stop(0, Color.RED) }); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // duration is 0 + t0.setDuration(Duration.ZERO); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setDuration(Duration.ONE); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // shape is null + t0.setShape(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setShape(shape); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // interpolator is null + t0.setInterpolator(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setInterpolator(Interpolator.LINEAR); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // fromValue + t0.setFromValue(null); + shape.setStroke(paint2); + assertFalse(AnimationShim.impl_startable(t0,true)); + shape.setStroke(Color.BLACK); + assertTrue(AnimationShim.impl_startable(t0,true)); + t0.setFromValue(Color.WHITE); + shape.setStroke(paint2); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // toValue + t0.setToValue(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setToValue(Color.BLACK); + assertTrue(AnimationShim.impl_startable(t0,true)); + } + + @Test + public void testEvaluateStartValue() { + final StrokeTransition t0 = new StrokeTransition(Duration.INDEFINITE, shape, null, Color.WHITE); + + // first run + shape.setStroke(Color.GREY); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + shape.setStroke(Color.TRANSPARENT); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(Color.GREY, shape.getStroke()); + AnimationShim.impl_finished(t0); + + // second run + shape.setStroke(Color.BLACK); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + shape.setStroke(Color.WHITE); + TransitionShim.interpolate(t0,0.0); + assertColorEquals(Color.BLACK, shape.getStroke()); + AnimationShim.impl_finished(t0); + } + +} --- old/modules/graphics/src/test/java/javafx/animation/TimelinePlayTest.java 2015-09-11 21:25:29.161286262 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,338 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import com.sun.javafx.animation.TickCalculation; -import com.sun.scenario.animation.AbstractMasterTimerMock; -import javafx.beans.property.LongProperty; -import javafx.beans.property.SimpleLongProperty; -import javafx.collections.ObservableList; -import javafx.util.Duration; -import javafx.util.Pair; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class TimelinePlayTest { - - private AbstractMasterTimerMock amt; - private Timeline timeline; - private LongProperty property = new SimpleLongProperty(); - - - private static final double EPSILON = 1e-12; - - - @Before - public void setUp() { - amt = new AbstractMasterTimerMock(); - timeline = new Timeline(amt); - } - - public void setupTimeline(Timeline a, LongProperty property, Pair... values) { - ObservableList keyFrames = ((Timeline) a).getKeyFrames(); - for (Pair v : values) { - keyFrames.add(new KeyFrame(v.getKey(), new KeyValue(property, v.getValue()))); - } - } - - @Test - public void testJump() { - setupTimeline(timeline, property, new Pair(Duration.minutes(1), 60000)); - - timeline.jumpTo(Duration.seconds(10)); - assertEquals(Duration.seconds(10), timeline.getCurrentTime()); - assertEquals(0, property.get()); - - timeline.play(); - assertEquals(Duration.seconds(10), timeline.getCurrentTime()); - assertEquals(10000, property.get()); - - timeline.jumpTo(Duration.seconds(30)); - assertEquals(Duration.seconds(30), timeline.getCurrentTime()); - assertEquals(30000, property.get()); - amt.pulse(); - assertEquals(Duration.seconds(30).add(TickCalculation.toDuration(100)), timeline.getCurrentTime()); - assertEquals(30000 + Math.round(TickCalculation.toMillis(100)), property.get()); - - timeline.jumpTo("start"); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - assertEquals(0, property.get()); - - timeline.jumpTo("end"); - assertEquals(Duration.minutes(1), timeline.getCurrentTime()); - assertEquals(60000, property.get()); - - amt.pulse(); - assertEquals(Animation.Status.STOPPED, timeline.getStatus()); - assertEquals(Duration.minutes(1), timeline.getCurrentTime()); - assertEquals(60000, property.get()); - - } - - @Test - public void testPlay() { - // play animation without keyframes - timeline.play(); - assertEquals(Animation.Status.STOPPED, timeline.getStatus()); - assertEquals(0, (long)timeline.getCurrentTime().toMillis()); - - setupTimeline(timeline, property, new Pair(Duration.ZERO, 0), new Pair(Duration.minutes(1), 60000)); - - // play animation with rate == 0 - timeline.setRate(0.0); - timeline.play(); - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - assertEquals(0, (long)timeline.getCurrentTime().toMillis()); - assertEquals(0, property.get()); - amt.pulse(); - assertEquals(0, (long)timeline.getCurrentTime().toMillis()); - assertEquals(0, property.get()); - timeline.stop(); - - // normal play - timeline.setRate(1.0); - timeline.play(); - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - assertEquals(0, (long)timeline.getCurrentTime().toMillis()); - assertEquals(0, property.get()); - amt.pulse(); - assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); - - // calling play on a playing animation - timeline.play(); - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); - amt.pulse(); - assertEquals(TickCalculation.toDuration(200), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(200)), property.get()); - - // calling play on a paused animation - timeline.pause(); - assertEquals(Animation.Status.PAUSED, timeline.getStatus()); - amt.pulse(); - assertEquals(TickCalculation.toDuration(200), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(200)), property.get()); - timeline.play(); - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - amt.pulse(); - assertEquals(TickCalculation.toDuration(300), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(300)), property.get()); - - // jump and play - timeline.stop(); - timeline.jumpTo(Duration.seconds(4)); - assertEquals(Duration.seconds(4), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(300)), property.get()); // Previous value - timeline.play(); - assertEquals(Duration.seconds(4), timeline.getCurrentTime()); - assertEquals(4000, property.get()); - amt.pulse(); - assertEquals(Duration.seconds(4).add(TickCalculation.toDuration(100)), timeline.getCurrentTime()); - assertEquals(4000 + Math.round(TickCalculation.toMillis(100)), property.get()); - - // calling play on a toggled animation - timeline.jumpTo(Duration.minutes(1)); - timeline.setRate(-1.0); - timeline.play(); - assertEquals(-1.0, timeline.getRate(), EPSILON); - assertEquals(-1.0, timeline.getCurrentRate(), EPSILON); - assertEquals(TickCalculation.toDuration(TickCalculation.fromMillis(60 * 1000)), timeline.getCurrentTime()); - assertEquals(60000, property.get()); - amt.pulse(); - assertEquals(TickCalculation.toDuration(TickCalculation.fromMillis(60 * 1000)).subtract(TickCalculation.toDuration(100)), timeline.getCurrentTime()); - assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); - - //stop and play (no jump) - timeline.setRate(1.0); - timeline.stop(); - timeline.play(); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); // previous value just after play - amt.pulse(); - assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); - - // double play - - timeline.stop(); - timeline.play(); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - for (int i = 0 ; i < Duration.minutes(1).toSeconds() * 60 + 1; ++i) { - amt.pulse(); - } - assertEquals(Duration.minutes(1), timeline.getCurrentTime()); - assertEquals(60000, property.get()); - timeline.stop(); - timeline.play(); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - assertEquals(60000, property.get()); // previous value just after play - amt.pulse(); - assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); - - } - - @Test - public void testPlayFromStart() { - final Duration oneSec = Duration.millis(1000); - - // play animation without keyframes - timeline.setRate(-1.0); - timeline.playFromStart(); - assertEquals(Animation.Status.STOPPED, timeline.getStatus()); - assertEquals(1.0, timeline.getRate(), EPSILON); - assertEquals(0.0, timeline.getCurrentRate(), EPSILON); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - - // play animation with rate == 0 - setupTimeline(timeline, property, new Pair(Duration.ZERO, 0), new Pair(Duration.minutes(1), 60000)); - timeline.jumpTo(oneSec); - - assertEquals(oneSec, timeline.getCurrentTime()); - assertEquals(0, property.get()); //not running - - timeline.setRate(0.0); - timeline.playFromStart(); - amt.pulse(); - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - assertEquals(0.0, timeline.getRate(), EPSILON); - assertEquals(0.0, timeline.getCurrentRate(), EPSILON); - amt.pulse(); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - assertEquals(0, property.get()); - timeline.stop(); - - // normal play - timeline.setRate(1.0); - timeline.play(); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - assertEquals(0, property.get()); - amt.pulse(); - assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); - timeline.playFromStart(); - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - assertEquals(1.0, timeline.getRate(), EPSILON); - assertEquals(1.0, timeline.getCurrentRate(), EPSILON); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); // still old value - amt.pulse(); - assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); - - // calling playFromStart on a stopped - timeline.stop(); - timeline.playFromStart(); - assertEquals(1.0, timeline.getRate(), EPSILON); - assertEquals(1.0, timeline.getCurrentRate(), EPSILON); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); // still old value - amt.pulse(); - assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); - - // calling playFromStart on a toggled animation - timeline.jumpTo(Duration.minutes(1)); - timeline.setRate(-1.0); - amt.pulse(); - assertEquals(Duration.minutes(1).subtract(TickCalculation.toDuration(100)), timeline.getCurrentTime()); - assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); - timeline.playFromStart(); - assertEquals(1.0, timeline.getRate(), EPSILON); - assertEquals(1.0, timeline.getCurrentRate(), EPSILON); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); // still old value - - // jump and playFromStart - timeline.stop(); - timeline.setRate(1.0); - timeline.jumpTo(Duration.seconds(4)); - assertEquals(Duration.seconds(4), timeline.getCurrentTime()); - assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); // still old value, not playing - timeline.playFromStart(); - assertEquals(Duration.ZERO, timeline.getCurrentTime()); - assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); // still old value - amt.pulse(); - assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); - assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); - - } - - @Test - public void testAutoReverse() { - setupTimeline(timeline, property, new Pair(Duration.minutes(1), 60000)); - timeline.setAutoReverse(true); - timeline.setCycleCount(-1); - - timeline.play(); - - for (int i = 0; i < TickCalculation.fromDuration(Duration.seconds(60)) / 100 - 1; ++i) { - amt.pulse(); - } - - amt.pulse(); - - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - - assertEquals(60000, property.get()); - - amt.pulse(); - - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - - assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); - - } - - @Test - public void testAutoReverseWithJump() { - setupTimeline(timeline, property, new Pair(Duration.minutes(1), 60000)); - timeline.setAutoReverse(true); - timeline.setCycleCount(-1); - - timeline.play(); - - timeline.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); - - amt.pulse(); - - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - - assertEquals(60000, property.get()); - - amt.pulse(); - - assertEquals(Animation.Status.RUNNING, timeline.getStatus()); - - assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); - - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/TimelinePlayTest.java 2015-09-11 21:25:28.969286264 -0400 @@ -0,0 +1,342 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import com.sun.javafx.animation.TickCalculation; +import javafx.animation.Animation; +import javafx.animation.KeyFrame; +import javafx.animation.KeyValue; +import javafx.animation.Timeline; +import javafx.animation.TimelineShim; +import javafx.beans.property.LongProperty; +import javafx.beans.property.SimpleLongProperty; +import javafx.collections.ObservableList; +import javafx.util.Duration; +import javafx.util.Pair; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class TimelinePlayTest { + + private AbstractMasterTimerMock amt; + private Timeline timeline; + private LongProperty property = new SimpleLongProperty(); + + + private static final double EPSILON = 1e-12; + + + @Before + public void setUp() { + amt = new AbstractMasterTimerMock(); + timeline = TimelineShim.getTimeline(amt); + } + + public void setupTimeline(Timeline a, LongProperty property, Pair... values) { + ObservableList keyFrames = ((Timeline) a).getKeyFrames(); + for (Pair v : values) { + keyFrames.add(new KeyFrame(v.getKey(), new KeyValue(property, v.getValue()))); + } + } + + @Test + public void testJump() { + setupTimeline(timeline, property, new Pair(Duration.minutes(1), 60000)); + + timeline.jumpTo(Duration.seconds(10)); + assertEquals(Duration.seconds(10), timeline.getCurrentTime()); + assertEquals(0, property.get()); + + timeline.play(); + assertEquals(Duration.seconds(10), timeline.getCurrentTime()); + assertEquals(10000, property.get()); + + timeline.jumpTo(Duration.seconds(30)); + assertEquals(Duration.seconds(30), timeline.getCurrentTime()); + assertEquals(30000, property.get()); + amt.pulse(); + assertEquals(Duration.seconds(30).add(TickCalculation.toDuration(100)), timeline.getCurrentTime()); + assertEquals(30000 + Math.round(TickCalculation.toMillis(100)), property.get()); + + timeline.jumpTo("start"); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + assertEquals(0, property.get()); + + timeline.jumpTo("end"); + assertEquals(Duration.minutes(1), timeline.getCurrentTime()); + assertEquals(60000, property.get()); + + amt.pulse(); + assertEquals(Animation.Status.STOPPED, timeline.getStatus()); + assertEquals(Duration.minutes(1), timeline.getCurrentTime()); + assertEquals(60000, property.get()); + + } + + @Test + public void testPlay() { + // play animation without keyframes + timeline.play(); + assertEquals(Animation.Status.STOPPED, timeline.getStatus()); + assertEquals(0, (long)timeline.getCurrentTime().toMillis()); + + setupTimeline(timeline, property, new Pair(Duration.ZERO, 0), new Pair(Duration.minutes(1), 60000)); + + // play animation with rate == 0 + timeline.setRate(0.0); + timeline.play(); + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + assertEquals(0, (long)timeline.getCurrentTime().toMillis()); + assertEquals(0, property.get()); + amt.pulse(); + assertEquals(0, (long)timeline.getCurrentTime().toMillis()); + assertEquals(0, property.get()); + timeline.stop(); + + // normal play + timeline.setRate(1.0); + timeline.play(); + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + assertEquals(0, (long)timeline.getCurrentTime().toMillis()); + assertEquals(0, property.get()); + amt.pulse(); + assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); + + // calling play on a playing animation + timeline.play(); + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); + amt.pulse(); + assertEquals(TickCalculation.toDuration(200), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(200)), property.get()); + + // calling play on a paused animation + timeline.pause(); + assertEquals(Animation.Status.PAUSED, timeline.getStatus()); + amt.pulse(); + assertEquals(TickCalculation.toDuration(200), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(200)), property.get()); + timeline.play(); + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + amt.pulse(); + assertEquals(TickCalculation.toDuration(300), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(300)), property.get()); + + // jump and play + timeline.stop(); + timeline.jumpTo(Duration.seconds(4)); + assertEquals(Duration.seconds(4), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(300)), property.get()); // Previous value + timeline.play(); + assertEquals(Duration.seconds(4), timeline.getCurrentTime()); + assertEquals(4000, property.get()); + amt.pulse(); + assertEquals(Duration.seconds(4).add(TickCalculation.toDuration(100)), timeline.getCurrentTime()); + assertEquals(4000 + Math.round(TickCalculation.toMillis(100)), property.get()); + + // calling play on a toggled animation + timeline.jumpTo(Duration.minutes(1)); + timeline.setRate(-1.0); + timeline.play(); + assertEquals(-1.0, timeline.getRate(), EPSILON); + assertEquals(-1.0, timeline.getCurrentRate(), EPSILON); + assertEquals(TickCalculation.toDuration(TickCalculation.fromMillis(60 * 1000)), timeline.getCurrentTime()); + assertEquals(60000, property.get()); + amt.pulse(); + assertEquals(TickCalculation.toDuration(TickCalculation.fromMillis(60 * 1000)).subtract(TickCalculation.toDuration(100)), timeline.getCurrentTime()); + assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); + + //stop and play (no jump) + timeline.setRate(1.0); + timeline.stop(); + timeline.play(); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); // previous value just after play + amt.pulse(); + assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); + + // double play + + timeline.stop(); + timeline.play(); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + for (int i = 0 ; i < Duration.minutes(1).toSeconds() * 60 + 1; ++i) { + amt.pulse(); + } + assertEquals(Duration.minutes(1), timeline.getCurrentTime()); + assertEquals(60000, property.get()); + timeline.stop(); + timeline.play(); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + assertEquals(60000, property.get()); // previous value just after play + amt.pulse(); + assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); + + } + + @Test + public void testPlayFromStart() { + final Duration oneSec = Duration.millis(1000); + + // play animation without keyframes + timeline.setRate(-1.0); + timeline.playFromStart(); + assertEquals(Animation.Status.STOPPED, timeline.getStatus()); + assertEquals(1.0, timeline.getRate(), EPSILON); + assertEquals(0.0, timeline.getCurrentRate(), EPSILON); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + + // play animation with rate == 0 + setupTimeline(timeline, property, new Pair(Duration.ZERO, 0), new Pair(Duration.minutes(1), 60000)); + timeline.jumpTo(oneSec); + + assertEquals(oneSec, timeline.getCurrentTime()); + assertEquals(0, property.get()); //not running + + timeline.setRate(0.0); + timeline.playFromStart(); + amt.pulse(); + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + assertEquals(0.0, timeline.getRate(), EPSILON); + assertEquals(0.0, timeline.getCurrentRate(), EPSILON); + amt.pulse(); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + assertEquals(0, property.get()); + timeline.stop(); + + // normal play + timeline.setRate(1.0); + timeline.play(); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + assertEquals(0, property.get()); + amt.pulse(); + assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); + timeline.playFromStart(); + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + assertEquals(1.0, timeline.getRate(), EPSILON); + assertEquals(1.0, timeline.getCurrentRate(), EPSILON); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); // still old value + amt.pulse(); + assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); + + // calling playFromStart on a stopped + timeline.stop(); + timeline.playFromStart(); + assertEquals(1.0, timeline.getRate(), EPSILON); + assertEquals(1.0, timeline.getCurrentRate(), EPSILON); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); // still old value + amt.pulse(); + assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); + + // calling playFromStart on a toggled animation + timeline.jumpTo(Duration.minutes(1)); + timeline.setRate(-1.0); + amt.pulse(); + assertEquals(Duration.minutes(1).subtract(TickCalculation.toDuration(100)), timeline.getCurrentTime()); + assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); + timeline.playFromStart(); + assertEquals(1.0, timeline.getRate(), EPSILON); + assertEquals(1.0, timeline.getCurrentRate(), EPSILON); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); // still old value + + // jump and playFromStart + timeline.stop(); + timeline.setRate(1.0); + timeline.jumpTo(Duration.seconds(4)); + assertEquals(Duration.seconds(4), timeline.getCurrentTime()); + assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); // still old value, not playing + timeline.playFromStart(); + assertEquals(Duration.ZERO, timeline.getCurrentTime()); + assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); // still old value + amt.pulse(); + assertEquals(TickCalculation.toDuration(100), timeline.getCurrentTime()); + assertEquals(Math.round(TickCalculation.toMillis(100)), property.get()); + + } + + @Test + public void testAutoReverse() { + setupTimeline(timeline, property, new Pair(Duration.minutes(1), 60000)); + timeline.setAutoReverse(true); + timeline.setCycleCount(-1); + + timeline.play(); + + for (int i = 0; i < TickCalculation.fromDuration(Duration.seconds(60)) / 100 - 1; ++i) { + amt.pulse(); + } + + amt.pulse(); + + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + + assertEquals(60000, property.get()); + + amt.pulse(); + + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + + assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); + + } + + @Test + public void testAutoReverseWithJump() { + setupTimeline(timeline, property, new Pair(Duration.minutes(1), 60000)); + timeline.setAutoReverse(true); + timeline.setCycleCount(-1); + + timeline.play(); + + timeline.jumpTo(Duration.seconds(60).subtract(TickCalculation.toDuration(100))); + + amt.pulse(); + + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + + assertEquals(60000, property.get()); + + amt.pulse(); + + assertEquals(Animation.Status.RUNNING, timeline.getStatus()); + + assertEquals(60000 - Math.round(TickCalculation.toMillis(100)), property.get()); + + } + +} --- old/modules/graphics/src/test/java/javafx/animation/TimelineTest.java 2015-09-11 21:25:30.005286253 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collections; - -import com.sun.javafx.tk.Toolkit; -import javafx.animation.Animation.Status; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - - -/** - * - */ -public class TimelineTest { - - private static final double DEFAULT_RATE = 1.0; - private static final int DEFAULT_REPEAT_COUNT = 1; - private static final boolean DEFAULT_AUTO_REVERSE = false; - - private static final double EPSILON = 1e-12; - - private Timeline timeline; - - @Before - public void setUp() { - timeline = new Timeline(); - } - - @Test - public void testDefaultValues() { - final Duration oneSec = Duration.millis(1000); - final KeyFrame kf0 = new KeyFrame(Duration.ZERO); - final KeyFrame kf1 = new KeyFrame(oneSec, "oneSec"); - - // empty ctor - final Timeline timeline0 = new Timeline(); - assertTrue(timeline0.getKeyFrames().isEmpty()); - assertEquals(DEFAULT_RATE, timeline0.getRate(), EPSILON); - assertEquals(0.0, timeline0.getCurrentRate(), EPSILON); - assertEquals(Duration.ZERO, timeline0.getCycleDuration()); - assertEquals(Duration.ZERO, timeline0.getTotalDuration()); - assertEquals(Duration.ZERO, timeline0.getCurrentTime()); - assertEquals(DEFAULT_REPEAT_COUNT, timeline0.getCycleCount()); - assertEquals(DEFAULT_AUTO_REVERSE, timeline0.isAutoReverse()); - assertEquals(Status.STOPPED, timeline0.getStatus()); - assertEquals(6000.0 / Toolkit.getToolkit().getMasterTimer().getDefaultResolution(), timeline0.getTargetFramerate(), EPSILON); - assertEquals(null, timeline0.getOnFinished()); - assertTrue(timeline0.getCuePoints().isEmpty()); - - // only target framerate - final Timeline timeline1 = new Timeline(42.0); - assertTrue(timeline1.getKeyFrames().isEmpty()); - assertEquals(DEFAULT_RATE, timeline1.getRate(), EPSILON); - assertEquals(0.0, timeline1.getCurrentRate(), EPSILON); - assertEquals(Duration.ZERO, timeline1.getCycleDuration()); - assertEquals(Duration.ZERO, timeline1.getTotalDuration()); - assertEquals(Duration.ZERO, timeline1.getCurrentTime()); - assertEquals(DEFAULT_REPEAT_COUNT, timeline1.getCycleCount()); - assertEquals(DEFAULT_AUTO_REVERSE, timeline1.isAutoReverse()); - assertEquals(Status.STOPPED, timeline1.getStatus()); - assertEquals(42.0, timeline1.getTargetFramerate(), EPSILON); - assertEquals(null, timeline1.getOnFinished()); - assertTrue(timeline1.getCuePoints().isEmpty()); - - // only keyframes - final Timeline timeline2 = new Timeline(kf0, kf1); - assertEquals(Arrays.asList(kf0, kf1), timeline2.getKeyFrames()); - assertEquals(DEFAULT_RATE, timeline2.getRate(), EPSILON); - assertEquals(0.0, timeline2.getCurrentRate(), EPSILON); - assertEquals(oneSec, timeline2.getCycleDuration()); - assertEquals(oneSec, timeline2.getTotalDuration()); - assertEquals(Duration.ZERO, timeline2.getCurrentTime()); - assertEquals(DEFAULT_REPEAT_COUNT, timeline2.getCycleCount()); - assertEquals(DEFAULT_AUTO_REVERSE, timeline2.isAutoReverse()); - assertEquals(Status.STOPPED, timeline2.getStatus()); - assertEquals(6000.0 / Toolkit.getToolkit().getMasterTimer().getDefaultResolution(), timeline2.getTargetFramerate(), EPSILON); - assertEquals(null, timeline2.getOnFinished()); - assertEquals(Collections.singletonMap("oneSec", oneSec), timeline2.getCuePoints()); - - // target framerate and keyframes - final Timeline timeline3 = new Timeline(42.0, kf0, kf1); - assertEquals(Arrays.asList(kf0, kf1), timeline3.getKeyFrames()); - assertEquals(DEFAULT_RATE, timeline3.getRate(), EPSILON); - assertEquals(0.0, timeline3.getCurrentRate(), EPSILON); - assertEquals(oneSec, timeline3.getCycleDuration()); - assertEquals(oneSec, timeline3.getTotalDuration()); - assertEquals(Duration.ZERO, timeline3.getCurrentTime()); - assertEquals(DEFAULT_REPEAT_COUNT, timeline3.getCycleCount()); - assertEquals(DEFAULT_AUTO_REVERSE, timeline3.isAutoReverse()); - assertEquals(Status.STOPPED, timeline3.getStatus()); - assertEquals(42.0, timeline1.getTargetFramerate(), EPSILON); - assertEquals(null, timeline3.getOnFinished()); - assertEquals(Collections.singletonMap("oneSec", oneSec), timeline2.getCuePoints()); - } - - @Test - public void testKeyFrames() { - final Duration oneSec = Duration.millis(1000); - final KeyFrame kf0 = new KeyFrame(Duration.ZERO); - final KeyFrame kf1 = new KeyFrame(oneSec, "oneSec"); - - // insert key frame - timeline.getKeyFrames().add(kf1); - assertEquals(Collections.singletonList(kf1), timeline.getKeyFrames()); - assertEquals(Collections.singletonMap("oneSec", oneSec), timeline.getCuePoints()); - assertEquals(oneSec, timeline.getCycleDuration()); - - // remove key frame - timeline.getKeyFrames().clear(); - assertTrue(timeline.getKeyFrames().isEmpty()); - assertEquals(Collections.emptyMap(), timeline.getCuePoints()); - assertEquals(Duration.ZERO, timeline.getCycleDuration()); - - // insert two key frames - timeline.getKeyFrames().addAll(kf1, kf0); - assertEquals(Arrays.asList(kf1, kf0), timeline.getKeyFrames()); - assertEquals(Collections.singletonMap("oneSec", oneSec), timeline.getCuePoints()); - assertEquals(oneSec, timeline.getCycleDuration()); - - // remove key frame - timeline.getKeyFrames().remove(kf1); - assertEquals(Collections.singletonList(kf0), timeline.getKeyFrames()); - assertEquals(Collections.emptyMap(), timeline.getCuePoints()); - assertEquals(Duration.ZERO, timeline.getCycleDuration()); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/TimelineTest.java 2015-09-11 21:25:29.801286255 -0400 @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; + +import com.sun.javafx.tk.Toolkit; +import javafx.animation.Animation.Status; +import javafx.animation.KeyFrame; +import javafx.animation.Timeline; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + + +/** + * + */ +public class TimelineTest { + + private static final double DEFAULT_RATE = 1.0; + private static final int DEFAULT_REPEAT_COUNT = 1; + private static final boolean DEFAULT_AUTO_REVERSE = false; + + private static final double EPSILON = 1e-12; + + private Timeline timeline; + + @Before + public void setUp() { + timeline = new Timeline(); + } + + @Test + public void testDefaultValues() { + final Duration oneSec = Duration.millis(1000); + final KeyFrame kf0 = new KeyFrame(Duration.ZERO); + final KeyFrame kf1 = new KeyFrame(oneSec, "oneSec"); + + // empty ctor + final Timeline timeline0 = new Timeline(); + assertTrue(timeline0.getKeyFrames().isEmpty()); + assertEquals(DEFAULT_RATE, timeline0.getRate(), EPSILON); + assertEquals(0.0, timeline0.getCurrentRate(), EPSILON); + assertEquals(Duration.ZERO, timeline0.getCycleDuration()); + assertEquals(Duration.ZERO, timeline0.getTotalDuration()); + assertEquals(Duration.ZERO, timeline0.getCurrentTime()); + assertEquals(DEFAULT_REPEAT_COUNT, timeline0.getCycleCount()); + assertEquals(DEFAULT_AUTO_REVERSE, timeline0.isAutoReverse()); + assertEquals(Status.STOPPED, timeline0.getStatus()); + assertEquals(6000.0 / Toolkit.getToolkit().getMasterTimer().getDefaultResolution(), timeline0.getTargetFramerate(), EPSILON); + assertEquals(null, timeline0.getOnFinished()); + assertTrue(timeline0.getCuePoints().isEmpty()); + + // only target framerate + final Timeline timeline1 = new Timeline(42.0); + assertTrue(timeline1.getKeyFrames().isEmpty()); + assertEquals(DEFAULT_RATE, timeline1.getRate(), EPSILON); + assertEquals(0.0, timeline1.getCurrentRate(), EPSILON); + assertEquals(Duration.ZERO, timeline1.getCycleDuration()); + assertEquals(Duration.ZERO, timeline1.getTotalDuration()); + assertEquals(Duration.ZERO, timeline1.getCurrentTime()); + assertEquals(DEFAULT_REPEAT_COUNT, timeline1.getCycleCount()); + assertEquals(DEFAULT_AUTO_REVERSE, timeline1.isAutoReverse()); + assertEquals(Status.STOPPED, timeline1.getStatus()); + assertEquals(42.0, timeline1.getTargetFramerate(), EPSILON); + assertEquals(null, timeline1.getOnFinished()); + assertTrue(timeline1.getCuePoints().isEmpty()); + + // only keyframes + final Timeline timeline2 = new Timeline(kf0, kf1); + assertEquals(Arrays.asList(kf0, kf1), timeline2.getKeyFrames()); + assertEquals(DEFAULT_RATE, timeline2.getRate(), EPSILON); + assertEquals(0.0, timeline2.getCurrentRate(), EPSILON); + assertEquals(oneSec, timeline2.getCycleDuration()); + assertEquals(oneSec, timeline2.getTotalDuration()); + assertEquals(Duration.ZERO, timeline2.getCurrentTime()); + assertEquals(DEFAULT_REPEAT_COUNT, timeline2.getCycleCount()); + assertEquals(DEFAULT_AUTO_REVERSE, timeline2.isAutoReverse()); + assertEquals(Status.STOPPED, timeline2.getStatus()); + assertEquals(6000.0 / Toolkit.getToolkit().getMasterTimer().getDefaultResolution(), timeline2.getTargetFramerate(), EPSILON); + assertEquals(null, timeline2.getOnFinished()); + assertEquals(Collections.singletonMap("oneSec", oneSec), timeline2.getCuePoints()); + + // target framerate and keyframes + final Timeline timeline3 = new Timeline(42.0, kf0, kf1); + assertEquals(Arrays.asList(kf0, kf1), timeline3.getKeyFrames()); + assertEquals(DEFAULT_RATE, timeline3.getRate(), EPSILON); + assertEquals(0.0, timeline3.getCurrentRate(), EPSILON); + assertEquals(oneSec, timeline3.getCycleDuration()); + assertEquals(oneSec, timeline3.getTotalDuration()); + assertEquals(Duration.ZERO, timeline3.getCurrentTime()); + assertEquals(DEFAULT_REPEAT_COUNT, timeline3.getCycleCount()); + assertEquals(DEFAULT_AUTO_REVERSE, timeline3.isAutoReverse()); + assertEquals(Status.STOPPED, timeline3.getStatus()); + assertEquals(42.0, timeline1.getTargetFramerate(), EPSILON); + assertEquals(null, timeline3.getOnFinished()); + assertEquals(Collections.singletonMap("oneSec", oneSec), timeline2.getCuePoints()); + } + + @Test + public void testKeyFrames() { + final Duration oneSec = Duration.millis(1000); + final KeyFrame kf0 = new KeyFrame(Duration.ZERO); + final KeyFrame kf1 = new KeyFrame(oneSec, "oneSec"); + + // insert key frame + timeline.getKeyFrames().add(kf1); + assertEquals(Collections.singletonList(kf1), timeline.getKeyFrames()); + assertEquals(Collections.singletonMap("oneSec", oneSec), timeline.getCuePoints()); + assertEquals(oneSec, timeline.getCycleDuration()); + + // remove key frame + timeline.getKeyFrames().clear(); + assertTrue(timeline.getKeyFrames().isEmpty()); + assertEquals(Collections.emptyMap(), timeline.getCuePoints()); + assertEquals(Duration.ZERO, timeline.getCycleDuration()); + + // insert two key frames + timeline.getKeyFrames().addAll(kf1, kf0); + assertEquals(Arrays.asList(kf1, kf0), timeline.getKeyFrames()); + assertEquals(Collections.singletonMap("oneSec", oneSec), timeline.getCuePoints()); + assertEquals(oneSec, timeline.getCycleDuration()); + + // remove key frame + timeline.getKeyFrames().remove(kf1); + assertEquals(Collections.singletonList(kf0), timeline.getKeyFrames()); + assertEquals(Collections.emptyMap(), timeline.getCuePoints()); + assertEquals(Duration.ZERO, timeline.getCycleDuration()); + } + +} --- old/modules/graphics/src/test/java/javafx/animation/TransitionTest.java 2015-09-11 21:25:30.633286245 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,240 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.sun.javafx.tk.Toolkit; -import javafx.scene.shape.Rectangle; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - - -public class TransitionTest { - - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; - private static double EPSILON = 1e-12; - - private TransitionImpl transition; - - @Before - public void setUp() { - transition = new TransitionImpl(Duration.millis(1000)); - } - - @Test - public void testDefaultValues() { - // emtpy ctor - Transition t0 = new TransitionImpl(Duration.millis(1000)); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertEquals(6000.0 / Toolkit.getToolkit().getMasterTimer().getDefaultResolution(), t0.getTargetFramerate(), EPSILON); - - // setting targetFramerate - Transition t1 = new TransitionImpl(Duration.millis(1000), 10); - assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); - assertEquals(10, t1.getTargetFramerate(), EPSILON); - } - - @Test - public void testDefaultValuesFromProperties() { - assertEquals(DEFAULT_INTERPOLATOR, transition.interpolatorProperty().get()); - } - - @Test - public void testGetParentTargetNode() { - final Rectangle node = new Rectangle(); - - // parent and parent node set - final ParallelTransition parent = new ParallelTransition(); - parent.getChildren().add(transition); - parent.setNode(node); - assertEquals(node, transition.getParentTargetNode()); - - // parent set, parent node null - parent.setNode(null); - assertNull(transition.getParentTargetNode()); - - // parent null, parent node set - parent.setNode(node); - parent.getChildren().clear(); - assertNull(transition.getParentTargetNode()); - } - - @Test - public void testStart() { - transition.impl_start(true); - transition.setInterpolator(Interpolator.DISCRETE); - assertEquals(DEFAULT_INTERPOLATOR, transition.getCachedInterpolator()); - transition.impl_finished(); - - transition.impl_start(true); - assertEquals(Interpolator.DISCRETE, transition.getCachedInterpolator()); - transition.impl_finished(); - } - - @Test - public void testPlayTo() { - assertTrue(transition.impl_startable(true)); - - // normal play with linear interpolator - transition.setInterpolator(Interpolator.LINEAR); - transition.impl_start(true); - transition.impl_playTo(0, 2); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_playTo(1, 2); - assertEquals(0.5, transition.frac, EPSILON); - transition.impl_playTo(2, 2); - assertEquals(1.0, transition.frac, EPSILON); - transition.impl_finished(); - - // normal play with discrete interpolator - transition.setInterpolator(Interpolator.DISCRETE); - transition.impl_start(true); - transition.impl_playTo(0, 2); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_playTo(1, 2); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_playTo(2, 2); - assertEquals(1.0, transition.frac, EPSILON); - - transition.impl_finished(); - } - - @Test - public void testJumpTo() { - // not running - transition.impl_jumpTo(0, 2, false); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(1, 2, false); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(2, 2, false); - assertEquals(0.0, transition.frac, EPSILON); - - // running with linear interpolator - transition.setInterpolator(Interpolator.LINEAR); - assertTrue(transition.impl_startable(true)); - transition.impl_start(true); - transition.impl_jumpTo(0, 2, false); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(1, 2, false); - assertEquals(0.5, transition.frac, EPSILON); - transition.impl_jumpTo(2, 2, false); - assertEquals(1.0, transition.frac, EPSILON); - - // paused with linear interpolator - transition.impl_pause(); - transition.impl_jumpTo(0, 2, false); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(1, 2, false); - assertEquals(0.5, transition.frac, EPSILON); - transition.impl_jumpTo(2, 2, false); - assertEquals(1.0, transition.frac, EPSILON); - transition.impl_finished(); - - // running with discrete interpolator - transition.setInterpolator(Interpolator.DISCRETE); - assertTrue(transition.impl_startable(true)); - transition.impl_start(true); - transition.impl_jumpTo(0, 2, false); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(1, 2, false); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(2, 2, false); - assertEquals(1.0, transition.frac, EPSILON); - - // paused with discrete interpolator - transition.impl_pause(); - transition.impl_jumpTo(0, 2, false); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(1, 2, false); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(2, 2, false); - assertEquals(1.0, transition.frac, EPSILON); - transition.impl_finished(); - } - - - - @Test - public void testForcedJumpTo() { - transition.setInterpolator(Interpolator.LINEAR); - // not running - transition.impl_jumpTo(0, 2, true); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(1, 2, true); - assertEquals(0.5, transition.frac, EPSILON); - transition.impl_jumpTo(2, 2, true); - assertEquals(1.0, transition.frac, EPSILON); - - // running with linear interpolator - assertTrue(transition.impl_startable(true)); - transition.impl_start(true); - transition.impl_jumpTo(0, 2, true); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(1, 2, true); - assertEquals(0.5, transition.frac, EPSILON); - transition.impl_jumpTo(2, 2, true); - assertEquals(1.0, transition.frac, EPSILON); - - // paused with linear interpolator - transition.impl_pause(); - transition.impl_jumpTo(0, 2, true); - assertEquals(0.0, transition.frac, EPSILON); - transition.impl_jumpTo(1, 2, true); - assertEquals(0.5, transition.frac, EPSILON); - transition.impl_jumpTo(2, 2, true); - assertEquals(1.0, transition.frac, EPSILON); - transition.impl_finished(); - - } - - private static class TransitionImpl extends Transition { - private double frac; - - private TransitionImpl(Duration duration) { - setCycleDuration(duration); - } - - private TransitionImpl(Duration duration, double targetFramerate) { - super(targetFramerate); - setCycleDuration(duration); - } - - @Override - public void impl_setCurrentTicks(long ticks) { - // no-op - } - - @Override - protected void interpolate(double frac) { - this.frac = frac; - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/TransitionTest.java 2015-09-11 21:25:30.497286247 -0400 @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.sun.javafx.tk.Toolkit; +import javafx.animation.Interpolator; +import javafx.animation.ParallelTransition; +import javafx.animation.Transition; +import javafx.animation.TransitionShim; +import javafx.scene.shape.Rectangle; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + + +public class TransitionTest { + + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; + private static double EPSILON = 1e-12; + + private TransitionImpl transition; + + @Before + public void setUp() { + transition = new TransitionImpl(Duration.millis(1000)); + } + + @Test + public void testDefaultValues() { + // emtpy ctor + Transition t0 = new TransitionImpl(Duration.millis(1000)); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertEquals(6000.0 / Toolkit.getToolkit().getMasterTimer().getDefaultResolution(), t0.getTargetFramerate(), EPSILON); + + // setting targetFramerate + Transition t1 = new TransitionImpl(Duration.millis(1000), 10); + assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); + assertEquals(10, t1.getTargetFramerate(), EPSILON); + } + + @Test + public void testDefaultValuesFromProperties() { + assertEquals(DEFAULT_INTERPOLATOR, transition.interpolatorProperty().get()); + } + + @Test + public void testGetParentTargetNode() { + final Rectangle node = new Rectangle(); + + // parent and parent node set + final ParallelTransition parent = new ParallelTransition(); + parent.getChildren().add(transition); + parent.setNode(node); + assertEquals(node, transition.getParentTargetNode()); + + // parent set, parent node null + parent.setNode(null); + assertNull(transition.getParentTargetNode()); + + // parent null, parent node set + parent.setNode(node); + parent.getChildren().clear(); + assertNull(transition.getParentTargetNode()); + } + + @Test + public void testStart() { + transition.impl_start(true); + transition.setInterpolator(Interpolator.DISCRETE); + assertEquals(DEFAULT_INTERPOLATOR, transition.getCachedInterpolator()); + transition.shim_impl_finished(); + + transition.impl_start(true); + assertEquals(Interpolator.DISCRETE, transition.getCachedInterpolator()); + transition.shim_impl_finished(); + } + + @Test + public void testPlayTo() { + assertTrue(transition.impl_startable(true)); + + // normal play with linear interpolator + transition.setInterpolator(Interpolator.LINEAR); + transition.impl_start(true); + transition.impl_playTo(0, 2); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_playTo(1, 2); + assertEquals(0.5, transition.frac, EPSILON); + transition.impl_playTo(2, 2); + assertEquals(1.0, transition.frac, EPSILON); + transition.shim_impl_finished(); + + // normal play with discrete interpolator + transition.setInterpolator(Interpolator.DISCRETE); + transition.impl_start(true); + transition.impl_playTo(0, 2); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_playTo(1, 2); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_playTo(2, 2); + assertEquals(1.0, transition.frac, EPSILON); + + transition.shim_impl_finished(); + } + + @Test + public void testJumpTo() { + // not running + transition.impl_jumpTo(0, 2, false); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(1, 2, false); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(2, 2, false); + assertEquals(0.0, transition.frac, EPSILON); + + // running with linear interpolator + transition.setInterpolator(Interpolator.LINEAR); + assertTrue(transition.impl_startable(true)); + transition.impl_start(true); + transition.impl_jumpTo(0, 2, false); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(1, 2, false); + assertEquals(0.5, transition.frac, EPSILON); + transition.impl_jumpTo(2, 2, false); + assertEquals(1.0, transition.frac, EPSILON); + + // paused with linear interpolator + transition.impl_pause(); + transition.impl_jumpTo(0, 2, false); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(1, 2, false); + assertEquals(0.5, transition.frac, EPSILON); + transition.impl_jumpTo(2, 2, false); + assertEquals(1.0, transition.frac, EPSILON); + transition.shim_impl_finished(); + + // running with discrete interpolator + transition.setInterpolator(Interpolator.DISCRETE); + assertTrue(transition.impl_startable(true)); + transition.impl_start(true); + transition.impl_jumpTo(0, 2, false); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(1, 2, false); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(2, 2, false); + assertEquals(1.0, transition.frac, EPSILON); + + // paused with discrete interpolator + transition.impl_pause(); + transition.impl_jumpTo(0, 2, false); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(1, 2, false); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(2, 2, false); + assertEquals(1.0, transition.frac, EPSILON); + transition.shim_impl_finished(); + } + + + + @Test + public void testForcedJumpTo() { + transition.setInterpolator(Interpolator.LINEAR); + // not running + transition.impl_jumpTo(0, 2, true); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(1, 2, true); + assertEquals(0.5, transition.frac, EPSILON); + transition.impl_jumpTo(2, 2, true); + assertEquals(1.0, transition.frac, EPSILON); + + // running with linear interpolator + assertTrue(transition.impl_startable(true)); + transition.impl_start(true); + transition.impl_jumpTo(0, 2, true); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(1, 2, true); + assertEquals(0.5, transition.frac, EPSILON); + transition.impl_jumpTo(2, 2, true); + assertEquals(1.0, transition.frac, EPSILON); + + // paused with linear interpolator + transition.impl_pause(); + transition.impl_jumpTo(0, 2, true); + assertEquals(0.0, transition.frac, EPSILON); + transition.impl_jumpTo(1, 2, true); + assertEquals(0.5, transition.frac, EPSILON); + transition.impl_jumpTo(2, 2, true); + assertEquals(1.0, transition.frac, EPSILON); + transition.shim_impl_finished(); + + } + + private static class TransitionImpl extends TransitionShim { + private double frac; + + private TransitionImpl(Duration duration) { + setCycleDuration(duration); + } + + private TransitionImpl(Duration duration, double targetFramerate) { + super(targetFramerate); + setCycleDuration(duration); + } + + public void impl_setCurrentTicks(long ticks) { + // no-op + } + + @Override + protected void interpolate(double frac) { + this.frac = frac; + } + } +} --- old/modules/graphics/src/test/java/javafx/animation/TranslateTransitionTest.java 2015-09-11 21:25:31.241286239 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,679 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.animation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import javafx.scene.Node; -import javafx.scene.shape.Rectangle; -import javafx.util.Duration; - -import org.junit.Before; -import org.junit.Test; - -public class TranslateTransitionTest { - - private static Duration DEFAULT_DURATION = Duration.millis(400); - private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; - - private static double EPSILON = 1e-12; - private static Duration ONE_SEC = Duration.millis(1000); - private static Duration TWO_SECS = Duration.millis(2000); - - private Node node; - - @Before - public void setUp() { - node = new Rectangle(); - } - - @Test - public void testDefaultValues() { - // empty ctor - final TranslateTransition t0 = new TranslateTransition(); - assertEquals(DEFAULT_DURATION, t0.getDuration()); - assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); - assertTrue(Double.isNaN(t0.getFromX())); - assertTrue(Double.isNaN(t0.getFromY())); - assertTrue(Double.isNaN(t0.getFromZ())); - assertTrue(Double.isNaN(t0.getToX())); - assertTrue(Double.isNaN(t0.getToY())); - assertTrue(Double.isNaN(t0.getToZ())); - assertEquals(0.0, t0.getByX(), EPSILON); - assertEquals(0.0, t0.getByY(), EPSILON); - assertEquals(0.0, t0.getByZ(), EPSILON); - assertNull(t0.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); - assertNull(t0.getOnFinished()); - - // duration only - final TranslateTransition t1 = new TranslateTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.getDuration()); - assertTrue(Double.isNaN(t1.getFromX())); - assertTrue(Double.isNaN(t1.getFromY())); - assertTrue(Double.isNaN(t1.getFromZ())); - assertTrue(Double.isNaN(t1.getToX())); - assertTrue(Double.isNaN(t1.getToY())); - assertTrue(Double.isNaN(t1.getToZ())); - assertEquals(0.0, t1.getByX(), EPSILON); - assertEquals(0.0, t1.getByY(), EPSILON); - assertEquals(0.0, t1.getByZ(), EPSILON); - assertNull(t1.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); - assertNull(t1.getOnFinished()); - - // duration and node - final TranslateTransition t2 = new TranslateTransition(TWO_SECS, node); - assertEquals(TWO_SECS, t2.getDuration()); - assertTrue(Double.isNaN(t2.getFromX())); - assertTrue(Double.isNaN(t2.getFromY())); - assertTrue(Double.isNaN(t2.getFromZ())); - assertTrue(Double.isNaN(t2.getToX())); - assertTrue(Double.isNaN(t2.getToY())); - assertTrue(Double.isNaN(t2.getToZ())); - assertEquals(0.0, t2.getByX(), EPSILON); - assertEquals(0.0, t2.getByY(), EPSILON); - assertEquals(0.0, t2.getByZ(), EPSILON); - assertEquals(node, t2.getNode()); - assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); - assertNull(t2.getOnFinished()); - } - - @Test - public void testDefaultValuesFromProperties() { - // empty ctor - final TranslateTransition t0 = new TranslateTransition(); - assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); - assertTrue(Double.isNaN(t0.fromXProperty().get())); - assertTrue(Double.isNaN(t0.fromYProperty().get())); - assertTrue(Double.isNaN(t0.fromZProperty().get())); - assertTrue(Double.isNaN(t0.toXProperty().get())); - assertTrue(Double.isNaN(t0.toYProperty().get())); - assertTrue(Double.isNaN(t0.toZProperty().get())); - assertEquals(0.0, t0.byXProperty().get(), EPSILON); - assertEquals(0.0, t0.byYProperty().get(), EPSILON); - assertEquals(0.0, t0.byZProperty().get(), EPSILON); - assertNull(t0.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t0.interpolatorProperty().get()); - assertNull(t0.onFinishedProperty().get()); - - // duration only - final TranslateTransition t1 = new TranslateTransition(ONE_SEC); - assertEquals(ONE_SEC, t1.durationProperty().get()); - assertTrue(Double.isNaN(t1.fromXProperty().get())); - assertTrue(Double.isNaN(t1.fromYProperty().get())); - assertTrue(Double.isNaN(t1.fromZProperty().get())); - assertTrue(Double.isNaN(t1.toXProperty().get())); - assertTrue(Double.isNaN(t1.toYProperty().get())); - assertTrue(Double.isNaN(t1.toZProperty().get())); - assertEquals(0.0, t1.byXProperty().get(), EPSILON); - assertEquals(0.0, t1.byYProperty().get(), EPSILON); - assertEquals(0.0, t1.byZProperty().get(), EPSILON); - assertNull(t1.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t1.interpolatorProperty().get()); - assertNull(t1.onFinishedProperty().get()); - - // duration and node - final TranslateTransition t2 = new TranslateTransition(TWO_SECS, node); - assertEquals(TWO_SECS, t2.durationProperty().get()); - assertTrue(Double.isNaN(t2.fromXProperty().get())); - assertTrue(Double.isNaN(t2.fromYProperty().get())); - assertTrue(Double.isNaN(t2.fromZProperty().get())); - assertTrue(Double.isNaN(t2.toXProperty().get())); - assertTrue(Double.isNaN(t2.toYProperty().get())); - assertTrue(Double.isNaN(t2.toZProperty().get())); - assertEquals(0.0, t2.byXProperty().get(), EPSILON); - assertEquals(0.0, t2.byYProperty().get(), EPSILON); - assertEquals(0.0, t2.byZProperty().get(), EPSILON); - assertEquals(node, t2.nodeProperty().get()); - assertEquals(DEFAULT_INTERPOLATOR, t2.interpolatorProperty().get()); - assertNull(t2.onFinishedProperty().get()); - } - - @Test - public void testInterpolate() { - final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); - t0.setFromX(0.5); - t0.setToX(1.0); - t0.setFromY(1.5); - t0.setToY(2.0); - t0.setFromZ(1.5); - t0.setToZ(0.5); - - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(0.5, node.getTranslateX(), EPSILON); - assertEquals(1.5, node.getTranslateY(), EPSILON); - assertEquals(1.5, node.getTranslateZ(), EPSILON); - t0.interpolate(0.4); - assertEquals(0.7, node.getTranslateX(), EPSILON); - assertEquals(1.7, node.getTranslateY(), EPSILON); - assertEquals(1.1, node.getTranslateZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(1.0, node.getTranslateX(), EPSILON); - assertEquals(2.0, node.getTranslateY(), EPSILON); - assertEquals(0.5, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testXValueCombinations() { - final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); - final double originalValue = 0.6; - final double fromValue = 0.4; - final double toValue = 0.9; - final double byValue = -0.2; - - // no value set - node.setTranslateX(originalValue); - t0.setFromX(Double.NaN); - t0.setToX(Double.NaN); - t0.setByX(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateX(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue, node.getTranslateX(), EPSILON); - t0.impl_finished(); - - // only from-value set - node.setTranslateX(originalValue); - t0.setFromX(fromValue); - t0.setToX(Double.NaN); - t0.setByX(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateX(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue, node.getTranslateX(), EPSILON); - t0.impl_finished(); - - // only to-value set - node.setTranslateX(originalValue); - t0.setFromX(Double.NaN); - t0.setToX(toValue); - t0.setByX(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateX(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateX(), EPSILON); - t0.impl_finished(); - - // only by-value set - node.setTranslateX(originalValue); - t0.setFromX(Double.NaN); - t0.setToX(Double.NaN); - t0.setByX(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateX(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue + byValue, node.getTranslateX(), EPSILON); - t0.impl_finished(); - - // from- and to-values set - node.setTranslateX(originalValue); - t0.setFromX(fromValue); - t0.setToX(toValue); - t0.setByX(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateX(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateX(), EPSILON); - t0.impl_finished(); - - // from- and by-values set - node.setTranslateX(originalValue); - t0.setFromX(fromValue); - t0.setToX(Double.NaN); - t0.setByX(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateX(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue + byValue, node.getTranslateX(), EPSILON); - t0.impl_finished(); - - // to- and by-values set - node.setTranslateX(originalValue); - t0.setFromX(Double.NaN); - t0.setToX(toValue); - t0.setByX(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateX(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateX(), EPSILON); - t0.impl_finished(); - - // all values set - node.setTranslateX(originalValue); - t0.setFromX(fromValue); - t0.setToX(toValue); - t0.setByX(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateX(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateX(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testYValueCombinations() { - final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); - final double originalValue = 0.6; - final double fromValue = 0.4; - final double toValue = 0.9; - final double byValue = -0.2; - - // no value set - node.setTranslateY(originalValue); - t0.setFromY(Double.NaN); - t0.setToY(Double.NaN); - t0.setByY(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateY(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue, node.getTranslateY(), EPSILON); - t0.impl_finished(); - - // only from-value set - node.setTranslateY(originalValue); - t0.setFromY(fromValue); - t0.setToY(Double.NaN); - t0.setByY(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateY(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue, node.getTranslateY(), EPSILON); - t0.impl_finished(); - - // only to-value set - node.setTranslateY(originalValue); - t0.setFromY(Double.NaN); - t0.setToY(toValue); - t0.setByY(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateY(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateY(), EPSILON); - t0.impl_finished(); - - // only by-value set - node.setTranslateY(originalValue); - t0.setFromY(Double.NaN); - t0.setToY(Double.NaN); - t0.setByY(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateY(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue + byValue, node.getTranslateY(), EPSILON); - t0.impl_finished(); - - // from- and to-values set - node.setTranslateY(originalValue); - t0.setFromY(fromValue); - t0.setToY(toValue); - t0.setByY(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateY(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateY(), EPSILON); - t0.impl_finished(); - - // from- and by-values set - node.setTranslateY(originalValue); - t0.setFromY(fromValue); - t0.setToY(Double.NaN); - t0.setByY(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateY(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue + byValue, node.getTranslateY(), EPSILON); - t0.impl_finished(); - - // to- and by-values set - node.setTranslateY(originalValue); - t0.setFromY(Double.NaN); - t0.setToY(toValue); - t0.setByY(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateY(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateY(), EPSILON); - t0.impl_finished(); - - // all values set - node.setTranslateY(originalValue); - t0.setFromY(fromValue); - t0.setToY(toValue); - t0.setByY(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateY(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateY(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testZValueCombinations() { - final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); - final double originalValue = 0.6; - final double fromValue = 0.4; - final double toValue = 0.9; - final double byValue = -0.2; - - // no value set - node.setTranslateZ(originalValue); - t0.setFromZ(Double.NaN); - t0.setToZ(Double.NaN); - t0.setByZ(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - - // only from-value set - node.setTranslateZ(originalValue); - t0.setFromZ(fromValue); - t0.setToZ(Double.NaN); - t0.setByZ(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - - // only to-value set - node.setTranslateZ(originalValue); - t0.setFromZ(Double.NaN); - t0.setToZ(toValue); - t0.setByZ(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - - // only by-value set - node.setTranslateZ(originalValue); - t0.setFromZ(Double.NaN); - t0.setToZ(Double.NaN); - t0.setByZ(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(originalValue + byValue, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - - // from- and to-values set - node.setTranslateZ(originalValue); - t0.setFromZ(fromValue); - t0.setToZ(toValue); - t0.setByZ(0.0); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - - // from- and by-values set - node.setTranslateZ(originalValue); - t0.setFromZ(fromValue); - t0.setToZ(Double.NaN); - t0.setByZ(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(fromValue + byValue, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - - // to- and by-values set - node.setTranslateZ(originalValue); - t0.setFromZ(Double.NaN); - t0.setToZ(toValue); - t0.setByZ(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(originalValue, node.getTranslateZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - - // all values set - node.setTranslateZ(originalValue); - t0.setFromZ(fromValue); - t0.setToZ(toValue); - t0.setByZ(byValue); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.0); - assertEquals(fromValue, node.getTranslateZ(), EPSILON); - t0.interpolate(1.0); - assertEquals(toValue, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - } - - @Test - public void testGetTargetNode() { - final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); - t0.setInterpolator(Interpolator.LINEAR); - t0.setFromX(0.5); - t0.setToX(1.0); - final Rectangle node2 = new Rectangle(); - final ParallelTransition pt = new ParallelTransition(); - pt.getChildren().add(t0); - pt.setNode(node2); - - // node set, parent set - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.5); - assertEquals(0.75, node.getTranslateX(), EPSILON); - assertEquals(0.0, node2.getTranslateX(), EPSILON); - t0.impl_finished(); - - // node null, parent set - t0.setNode(null); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.interpolate(0.4); - assertEquals(0.75, node.getTranslateX(), EPSILON); - assertEquals(0.7, node2.getTranslateX(), EPSILON); - t0.impl_finished(); - - // node null, parent null - pt.setNode(null); - assertFalse(t0.impl_startable(true)); - } - - @Test - public void testCachedValues() { - final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); - t0.setInterpolator(Interpolator.LINEAR); - t0.setFromX(0.5); - t0.setToX(1.0); - t0.setFromY(1.5); - t0.setToY(2.0); - t0.setFromZ(1.5); - t0.setToZ(0.5); - - // start - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.setFromX(0.0); - t0.setFromY(-1.0); - t0.setFromZ(0.5); - t0.interpolate(0.5); - assertEquals(0.75, node.getTranslateX(), EPSILON); - assertEquals(1.75, node.getTranslateY(), EPSILON); - assertEquals(1.0, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - t0.setFromX(0.5); - t0.setFromY(1.5); - t0.setFromZ(1.5); - - // end - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.setToX(0.0); - t0.setFromY(-1.0); - t0.setFromZ(1.5); - t0.interpolate(0.2); - assertEquals(0.6, node.getTranslateX(), EPSILON); - assertEquals(1.6, node.getTranslateY(), EPSILON); - assertEquals(1.3, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - t0.setToX(1.0); - t0.setToY(2.0); - t0.setToZ(0.5); - - // node - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.setNode(null); - t0.interpolate(0.7); - assertEquals(0.85, node.getTranslateX(), EPSILON); - t0.impl_finished(); - t0.setNode(node); - - // interpolator - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - t0.setInterpolator(null); - t0.interpolate(0.1); - assertEquals(0.55, node.getTranslateX(), EPSILON); - t0.impl_finished(); - t0.setInterpolator(Interpolator.LINEAR); - } - - @Test - public void testStartable() { - final TranslateTransition t0 = new TranslateTransition(Duration.ONE, node); - assertTrue(t0.impl_startable(true)); - - // duration is 0 - t0.setDuration(Duration.ZERO); - assertFalse(t0.impl_startable(true)); - t0.setDuration(Duration.ONE); - assertTrue(t0.impl_startable(true)); - - // node is null - t0.setNode(null); - assertFalse(t0.impl_startable(true)); - t0.setNode(node); - assertTrue(t0.impl_startable(true)); - - // interpolator is null - t0.setInterpolator(null); - assertFalse(t0.impl_startable(true)); - t0.setInterpolator(Interpolator.LINEAR); - assertTrue(t0.impl_startable(true)); - } - - @Test - public void testEvaluateStartValue() { - final TranslateTransition t0 = new TranslateTransition(Duration.INDEFINITE, node); - t0.setToX(2.0); - t0.setToY(2.0); - t0.setToZ(2.0); - - // first run - node.setTranslateX( 0.6); - node.setTranslateY( 1.6); - node.setTranslateZ(-0.6); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - node.setTranslateX(0.8); - node.setTranslateY(0.8); - node.setTranslateZ(0.8); - t0.interpolate(0.0); - assertEquals( 0.6, node.getTranslateX(), EPSILON); - assertEquals( 1.6, node.getTranslateY(), EPSILON); - assertEquals(-0.6, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - - // second run - node.setTranslateX( 0.2); - node.setTranslateY(-2.2); - node.setTranslateZ(11.2); - assertTrue(t0.impl_startable(true)); - t0.impl_start(true); - node.setTranslateX(0.8); - node.setTranslateY(0.8); - node.setTranslateZ(0.8); - t0.interpolate(0.0); - assertEquals( 0.2, node.getTranslateX(), EPSILON); - assertEquals(-2.2, node.getTranslateY(), EPSILON); - assertEquals(11.2, node.getTranslateZ(), EPSILON); - t0.impl_finished(); - } - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/animation/TranslateTransitionTest.java 2015-09-11 21:25:31.105286240 -0400 @@ -0,0 +1,684 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.animation; + +import javafx.animation.AnimationShim; +import javafx.animation.Interpolator; +import javafx.animation.ParallelTransition; +import javafx.animation.TransitionShim; +import javafx.animation.TranslateTransition; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import javafx.scene.Node; +import javafx.scene.shape.Rectangle; +import javafx.util.Duration; + +import org.junit.Before; +import org.junit.Test; + +public class TranslateTransitionTest { + + private static Duration DEFAULT_DURATION = Duration.millis(400); + private static Interpolator DEFAULT_INTERPOLATOR = Interpolator.EASE_BOTH; + + private static double EPSILON = 1e-12; + private static Duration ONE_SEC = Duration.millis(1000); + private static Duration TWO_SECS = Duration.millis(2000); + + private Node node; + + @Before + public void setUp() { + node = new Rectangle(); + } + + @Test + public void testDefaultValues() { + // empty ctor + final TranslateTransition t0 = new TranslateTransition(); + assertEquals(DEFAULT_DURATION, t0.getDuration()); + assertEquals(DEFAULT_DURATION, t0.getCycleDuration()); + assertTrue(Double.isNaN(t0.getFromX())); + assertTrue(Double.isNaN(t0.getFromY())); + assertTrue(Double.isNaN(t0.getFromZ())); + assertTrue(Double.isNaN(t0.getToX())); + assertTrue(Double.isNaN(t0.getToY())); + assertTrue(Double.isNaN(t0.getToZ())); + assertEquals(0.0, t0.getByX(), EPSILON); + assertEquals(0.0, t0.getByY(), EPSILON); + assertEquals(0.0, t0.getByZ(), EPSILON); + assertNull(t0.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t0.getInterpolator()); + assertNull(t0.getOnFinished()); + + // duration only + final TranslateTransition t1 = new TranslateTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.getDuration()); + assertTrue(Double.isNaN(t1.getFromX())); + assertTrue(Double.isNaN(t1.getFromY())); + assertTrue(Double.isNaN(t1.getFromZ())); + assertTrue(Double.isNaN(t1.getToX())); + assertTrue(Double.isNaN(t1.getToY())); + assertTrue(Double.isNaN(t1.getToZ())); + assertEquals(0.0, t1.getByX(), EPSILON); + assertEquals(0.0, t1.getByY(), EPSILON); + assertEquals(0.0, t1.getByZ(), EPSILON); + assertNull(t1.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t1.getInterpolator()); + assertNull(t1.getOnFinished()); + + // duration and node + final TranslateTransition t2 = new TranslateTransition(TWO_SECS, node); + assertEquals(TWO_SECS, t2.getDuration()); + assertTrue(Double.isNaN(t2.getFromX())); + assertTrue(Double.isNaN(t2.getFromY())); + assertTrue(Double.isNaN(t2.getFromZ())); + assertTrue(Double.isNaN(t2.getToX())); + assertTrue(Double.isNaN(t2.getToY())); + assertTrue(Double.isNaN(t2.getToZ())); + assertEquals(0.0, t2.getByX(), EPSILON); + assertEquals(0.0, t2.getByY(), EPSILON); + assertEquals(0.0, t2.getByZ(), EPSILON); + assertEquals(node, t2.getNode()); + assertEquals(DEFAULT_INTERPOLATOR, t2.getInterpolator()); + assertNull(t2.getOnFinished()); + } + + @Test + public void testDefaultValuesFromProperties() { + // empty ctor + final TranslateTransition t0 = new TranslateTransition(); + assertEquals(DEFAULT_DURATION, t0.durationProperty().get()); + assertTrue(Double.isNaN(t0.fromXProperty().get())); + assertTrue(Double.isNaN(t0.fromYProperty().get())); + assertTrue(Double.isNaN(t0.fromZProperty().get())); + assertTrue(Double.isNaN(t0.toXProperty().get())); + assertTrue(Double.isNaN(t0.toYProperty().get())); + assertTrue(Double.isNaN(t0.toZProperty().get())); + assertEquals(0.0, t0.byXProperty().get(), EPSILON); + assertEquals(0.0, t0.byYProperty().get(), EPSILON); + assertEquals(0.0, t0.byZProperty().get(), EPSILON); + assertNull(t0.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t0.interpolatorProperty().get()); + assertNull(t0.onFinishedProperty().get()); + + // duration only + final TranslateTransition t1 = new TranslateTransition(ONE_SEC); + assertEquals(ONE_SEC, t1.durationProperty().get()); + assertTrue(Double.isNaN(t1.fromXProperty().get())); + assertTrue(Double.isNaN(t1.fromYProperty().get())); + assertTrue(Double.isNaN(t1.fromZProperty().get())); + assertTrue(Double.isNaN(t1.toXProperty().get())); + assertTrue(Double.isNaN(t1.toYProperty().get())); + assertTrue(Double.isNaN(t1.toZProperty().get())); + assertEquals(0.0, t1.byXProperty().get(), EPSILON); + assertEquals(0.0, t1.byYProperty().get(), EPSILON); + assertEquals(0.0, t1.byZProperty().get(), EPSILON); + assertNull(t1.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t1.interpolatorProperty().get()); + assertNull(t1.onFinishedProperty().get()); + + // duration and node + final TranslateTransition t2 = new TranslateTransition(TWO_SECS, node); + assertEquals(TWO_SECS, t2.durationProperty().get()); + assertTrue(Double.isNaN(t2.fromXProperty().get())); + assertTrue(Double.isNaN(t2.fromYProperty().get())); + assertTrue(Double.isNaN(t2.fromZProperty().get())); + assertTrue(Double.isNaN(t2.toXProperty().get())); + assertTrue(Double.isNaN(t2.toYProperty().get())); + assertTrue(Double.isNaN(t2.toZProperty().get())); + assertEquals(0.0, t2.byXProperty().get(), EPSILON); + assertEquals(0.0, t2.byYProperty().get(), EPSILON); + assertEquals(0.0, t2.byZProperty().get(), EPSILON); + assertEquals(node, t2.nodeProperty().get()); + assertEquals(DEFAULT_INTERPOLATOR, t2.interpolatorProperty().get()); + assertNull(t2.onFinishedProperty().get()); + } + + @Test + public void testInterpolate() { + final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); + t0.setFromX(0.5); + t0.setToX(1.0); + t0.setFromY(1.5); + t0.setToY(2.0); + t0.setFromZ(1.5); + t0.setToZ(0.5); + + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(0.5, node.getTranslateX(), EPSILON); + assertEquals(1.5, node.getTranslateY(), EPSILON); + assertEquals(1.5, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,0.4); + assertEquals(0.7, node.getTranslateX(), EPSILON); + assertEquals(1.7, node.getTranslateY(), EPSILON); + assertEquals(1.1, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(1.0, node.getTranslateX(), EPSILON); + assertEquals(2.0, node.getTranslateY(), EPSILON); + assertEquals(0.5, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testXValueCombinations() { + final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); + final double originalValue = 0.6; + final double fromValue = 0.4; + final double toValue = 0.9; + final double byValue = -0.2; + + // no value set + node.setTranslateX(originalValue); + t0.setFromX(Double.NaN); + t0.setToX(Double.NaN); + t0.setByX(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + + // only from-value set + node.setTranslateX(originalValue); + t0.setFromX(fromValue); + t0.setToX(Double.NaN); + t0.setByX(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + + // only to-value set + node.setTranslateX(originalValue); + t0.setFromX(Double.NaN); + t0.setToX(toValue); + t0.setByX(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + + // only by-value set + node.setTranslateX(originalValue); + t0.setFromX(Double.NaN); + t0.setToX(Double.NaN); + t0.setByX(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue + byValue, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and to-values set + node.setTranslateX(originalValue); + t0.setFromX(fromValue); + t0.setToX(toValue); + t0.setByX(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and by-values set + node.setTranslateX(originalValue); + t0.setFromX(fromValue); + t0.setToX(Double.NaN); + t0.setByX(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue + byValue, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + + // to- and by-values set + node.setTranslateX(originalValue); + t0.setFromX(Double.NaN); + t0.setToX(toValue); + t0.setByX(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + + // all values set + node.setTranslateX(originalValue); + t0.setFromX(fromValue); + t0.setToX(toValue); + t0.setByX(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateX(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testYValueCombinations() { + final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); + final double originalValue = 0.6; + final double fromValue = 0.4; + final double toValue = 0.9; + final double byValue = -0.2; + + // no value set + node.setTranslateY(originalValue); + t0.setFromY(Double.NaN); + t0.setToY(Double.NaN); + t0.setByY(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue, node.getTranslateY(), EPSILON); + AnimationShim.impl_finished(t0); + + // only from-value set + node.setTranslateY(originalValue); + t0.setFromY(fromValue); + t0.setToY(Double.NaN); + t0.setByY(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue, node.getTranslateY(), EPSILON); + AnimationShim.impl_finished(t0); + + // only to-value set + node.setTranslateY(originalValue); + t0.setFromY(Double.NaN); + t0.setToY(toValue); + t0.setByY(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateY(), EPSILON); + AnimationShim.impl_finished(t0); + + // only by-value set + node.setTranslateY(originalValue); + t0.setFromY(Double.NaN); + t0.setToY(Double.NaN); + t0.setByY(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue + byValue, node.getTranslateY(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and to-values set + node.setTranslateY(originalValue); + t0.setFromY(fromValue); + t0.setToY(toValue); + t0.setByY(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateY(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and by-values set + node.setTranslateY(originalValue); + t0.setFromY(fromValue); + t0.setToY(Double.NaN); + t0.setByY(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue + byValue, node.getTranslateY(), EPSILON); + AnimationShim.impl_finished(t0); + + // to- and by-values set + node.setTranslateY(originalValue); + t0.setFromY(Double.NaN); + t0.setToY(toValue); + t0.setByY(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateY(), EPSILON); + AnimationShim.impl_finished(t0); + + // all values set + node.setTranslateY(originalValue); + t0.setFromY(fromValue); + t0.setToY(toValue); + t0.setByY(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateY(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateY(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testZValueCombinations() { + final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); + final double originalValue = 0.6; + final double fromValue = 0.4; + final double toValue = 0.9; + final double byValue = -0.2; + + // no value set + node.setTranslateZ(originalValue); + t0.setFromZ(Double.NaN); + t0.setToZ(Double.NaN); + t0.setByZ(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // only from-value set + node.setTranslateZ(originalValue); + t0.setFromZ(fromValue); + t0.setToZ(Double.NaN); + t0.setByZ(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // only to-value set + node.setTranslateZ(originalValue); + t0.setFromZ(Double.NaN); + t0.setToZ(toValue); + t0.setByZ(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // only by-value set + node.setTranslateZ(originalValue); + t0.setFromZ(Double.NaN); + t0.setToZ(Double.NaN); + t0.setByZ(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(originalValue + byValue, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and to-values set + node.setTranslateZ(originalValue); + t0.setFromZ(fromValue); + t0.setToZ(toValue); + t0.setByZ(0.0); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // from- and by-values set + node.setTranslateZ(originalValue); + t0.setFromZ(fromValue); + t0.setToZ(Double.NaN); + t0.setByZ(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(fromValue + byValue, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // to- and by-values set + node.setTranslateZ(originalValue); + t0.setFromZ(Double.NaN); + t0.setToZ(toValue); + t0.setByZ(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(originalValue, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // all values set + node.setTranslateZ(originalValue); + t0.setFromZ(fromValue); + t0.setToZ(toValue); + t0.setByZ(byValue); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.0); + assertEquals(fromValue, node.getTranslateZ(), EPSILON); + TransitionShim.interpolate(t0,1.0); + assertEquals(toValue, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + } + + @Test + public void testGetTargetNode() { + final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); + t0.setInterpolator(Interpolator.LINEAR); + t0.setFromX(0.5); + t0.setToX(1.0); + final Rectangle node2 = new Rectangle(); + final ParallelTransition pt = new ParallelTransition(); + pt.getChildren().add(t0); + pt.setNode(node2); + + // node set, parent set + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.5); + assertEquals(0.75, node.getTranslateX(), EPSILON); + assertEquals(0.0, node2.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + + // node null, parent set + t0.setNode(null); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + TransitionShim.interpolate(t0,0.4); + assertEquals(0.75, node.getTranslateX(), EPSILON); + assertEquals(0.7, node2.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + + // node null, parent null + pt.setNode(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + } + + @Test + public void testCachedValues() { + final TranslateTransition t0 = new TranslateTransition(ONE_SEC, node); + t0.setInterpolator(Interpolator.LINEAR); + t0.setFromX(0.5); + t0.setToX(1.0); + t0.setFromY(1.5); + t0.setToY(2.0); + t0.setFromZ(1.5); + t0.setToZ(0.5); + + // start + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + t0.setFromX(0.0); + t0.setFromY(-1.0); + t0.setFromZ(0.5); + TransitionShim.interpolate(t0,0.5); + assertEquals(0.75, node.getTranslateX(), EPSILON); + assertEquals(1.75, node.getTranslateY(), EPSILON); + assertEquals(1.0, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + t0.setFromX(0.5); + t0.setFromY(1.5); + t0.setFromZ(1.5); + + // end + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + t0.setToX(0.0); + t0.setFromY(-1.0); + t0.setFromZ(1.5); + TransitionShim.interpolate(t0,0.2); + assertEquals(0.6, node.getTranslateX(), EPSILON); + assertEquals(1.6, node.getTranslateY(), EPSILON); + assertEquals(1.3, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + t0.setToX(1.0); + t0.setToY(2.0); + t0.setToZ(0.5); + + // node + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + t0.setNode(null); + TransitionShim.interpolate(t0,0.7); + assertEquals(0.85, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + t0.setNode(node); + + // interpolator + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + t0.setInterpolator(null); + TransitionShim.interpolate(t0,0.1); + assertEquals(0.55, node.getTranslateX(), EPSILON); + AnimationShim.impl_finished(t0); + t0.setInterpolator(Interpolator.LINEAR); + } + + @Test + public void testStartable() { + final TranslateTransition t0 = new TranslateTransition(Duration.ONE, node); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // duration is 0 + t0.setDuration(Duration.ZERO); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setDuration(Duration.ONE); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // node is null + t0.setNode(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setNode(node); + assertTrue(AnimationShim.impl_startable(t0,true)); + + // interpolator is null + t0.setInterpolator(null); + assertFalse(AnimationShim.impl_startable(t0,true)); + t0.setInterpolator(Interpolator.LINEAR); + assertTrue(AnimationShim.impl_startable(t0,true)); + } + + @Test + public void testEvaluateStartValue() { + final TranslateTransition t0 = new TranslateTransition(Duration.INDEFINITE, node); + t0.setToX(2.0); + t0.setToY(2.0); + t0.setToZ(2.0); + + // first run + node.setTranslateX( 0.6); + node.setTranslateY( 1.6); + node.setTranslateZ(-0.6); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + node.setTranslateX(0.8); + node.setTranslateY(0.8); + node.setTranslateZ(0.8); + TransitionShim.interpolate(t0,0.0); + assertEquals( 0.6, node.getTranslateX(), EPSILON); + assertEquals( 1.6, node.getTranslateY(), EPSILON); + assertEquals(-0.6, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + + // second run + node.setTranslateX( 0.2); + node.setTranslateY(-2.2); + node.setTranslateZ(11.2); + assertTrue(AnimationShim.impl_startable(t0,true)); + AnimationShim.impl_start(t0,true); + node.setTranslateX(0.8); + node.setTranslateY(0.8); + node.setTranslateZ(0.8); + TransitionShim.interpolate(t0,0.0); + assertEquals( 0.2, node.getTranslateX(), EPSILON); + assertEquals(-2.2, node.getTranslateY(), EPSILON); + assertEquals(11.2, node.getTranslateZ(), EPSILON); + AnimationShim.impl_finished(t0); + } + +} --- old/modules/graphics/src/test/java/javafx/concurrent/AbstractTask.java 2015-09-11 21:25:31.901286231 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import java.util.concurrent.Semaphore; - -/** - * For testing purposes, we use this subclass of Task that will fake out the - * runLater and isFxApplicationThread calls, such that we can actually run - * and test Task in a single-threaded manner. - *

- * In addition, for many tests I need to be able to put the task into a specific - * state and then check properties. For example, put the task into the - * scheduled state, then check whether listeners have fired. Or put the task - * into the cancelled state after it had been in the running state, and then - * check some properties. - *

- * Because we will actually run the task in some background thread some times, - * but will run the task sequentially in other tests, we need to have a - * mechanism where either can happen. What we will do is use a semaphore for - * each state. As the state is entered, we will give back a permit for that - * state. Any code wishing to pick up at the right point can then just acquire - * the permit to wait for the state to occur and then join. - */ -public abstract class AbstractTask extends Task { - public final Semaphore scheduledSemaphore = new Semaphore(0); - public final Semaphore runningSemaphore = new Semaphore(0); - public final Semaphore succeededSemaphore = new Semaphore(0); - public final Semaphore cancelledSemaphore = new Semaphore(0); - public final Semaphore failedSemaphore = new Semaphore(0); - - Thread appThread; - ServiceTestBase test; - - // Simulates scheduling the concurrent for execution - public void simulateSchedule() { - setState(State.SCHEDULED); - } - - // For most tests, we want to pretend that we are on the FX app thread, always. - @Override boolean isFxApplicationThread() { - return appThread == null || Thread.currentThread() == appThread; - } - - // For most tests, we want to just run this stuff immediately - @Override void runLater(Runnable r) { - if (test != null) { - test.eventQueue.add(r); - } else { - r.run(); - } - } - - @Override protected void scheduled() { - scheduledSemaphore.release(); - } - - @Override protected void running() { - runningSemaphore.release(); - } - - @Override protected void succeeded() { - succeededSemaphore.release(); - } - - @Override protected void cancelled() { - cancelledSemaphore.release(); - } - - @Override protected void failed() { - failedSemaphore.release(); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/AbstractTask.java 2015-09-11 21:25:31.761286233 -0400 @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import java.util.concurrent.Semaphore; +import javafx.concurrent.Task; +import javafx.concurrent.TaskShim; + +/** + * For testing purposes, we use this subclass of Task that will fake out the + * runLater and isFxApplicationThread calls, such that we can actually run + * and test Task in a single-threaded manner. + *

+ * In addition, for many tests I need to be able to put the task into a specific + * state and then check properties. For example, put the task into the + * scheduled state, then check whether listeners have fired. Or put the task + * into the cancelled state after it had been in the running state, and then + * check some properties. + *

+ * Because we will actually run the task in some background thread some times, + * but will run the task sequentially in other tests, we need to have a + * mechanism where either can happen. What we will do is use a semaphore for + * each state. As the state is entered, we will give back a permit for that + * state. Any code wishing to pick up at the right point can then just acquire + * the permit to wait for the state to occur and then join. + */ +public abstract class AbstractTask extends TaskShim { + public final Semaphore scheduledSemaphore = new Semaphore(0); + public final Semaphore runningSemaphore = new Semaphore(0); + public final Semaphore succeededSemaphore = new Semaphore(0); + public final Semaphore cancelledSemaphore = new Semaphore(0); + public final Semaphore failedSemaphore = new Semaphore(0); + + Thread appThread; + ServiceTestBase test; + + // Simulates scheduling the concurrent for execution + public void simulateSchedule() { + shim_setState(State.SCHEDULED); + } + + // For most tests, we want to pretend that we are on the FX app thread, always. + @Override public boolean isFxApplicationThread() { + return appThread == null || Thread.currentThread() == appThread; + } + + // For most tests, we want to just run this stuff immediately + @Override public void runLater(Runnable r) { + if (test != null) { + test.eventQueue.add(r); + } else { + r.run(); + } + } + + @Override protected void scheduled() { + scheduledSemaphore.release(); + } + + @Override protected void running() { + runningSemaphore.release(); + } + + @Override protected void succeeded() { + succeededSemaphore.release(); + } + + @Override protected void cancelled() { + cancelledSemaphore.release(); + } + + @Override protected void failed() { + failedSemaphore.release(); + } + + public ServiceTestBase set_test(ServiceTestBase v) { + return test = v; + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/ScheduledServiceTest.java 2015-09-11 21:25:32.657286223 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,870 +0,0 @@ -/* - * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import javafx.concurrent.mocks.EpicFailTask; -import javafx.concurrent.mocks.SimpleTask; -import javafx.event.EventHandler; -import javafx.util.Callback; -import javafx.util.Duration; -import java.util.TimerTask; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * Tests for the ScheduledService. - */ -public class ScheduledServiceTest extends ServiceTestBase { - private static final Callback EPIC_FAIL_FACTORY = param -> new EpicFailTask(); - - /** - * The service that we're going to test. Because a ScheduledService - * in its default configuration will run forever and because for the - * sake of testing we've essentially caused ScheduledServiceTest to - * run as though it is single threaded, we have to make sure that each - * individual iteration is paused and doesn't occur without an explicit - * call. So in the test code you can call start(), and then read the wall - * clock time, and then call iterate() to cause the scheduled service to - * start the next iteration all without affecting the "wall clock" time - * inappropriately with the test code. In this way we can test with very - * fine tolerances in a consistent manner. - */ - private ScheduledServiceMock s; - - /** - * If specified by the test BEFORE the service is started, then this - * task will be used by the service. Defaults to SimpleTask if null. - */ - private Callback taskFactory = null; - - /** - * A fake "wall clock" time, to keep track of how much - * time was spent executing a task, and how much time was - * spent in the delay. We fake out the delay by overriding the - * "schedule" method in ScheduledServiceMock, and we fake out - * the task execution time by using a custom task which, when - * executed, will add to the wall clock time. - */ - private long wallClock; - - @Override protected TestServiceFactory setupServiceFactory() { - return new TestServiceFactory() { - @Override protected AbstractTask createTestTask() { - return taskFactory == null ? new SimpleTask() : taskFactory.call(null); - } - - @Override protected Service createService() { - return new ScheduledServiceMock(this); - } - }; - } - - @Override public void setup() { - super.setup(); - s = (ScheduledServiceMock) service; - wallClock = 0; - } - - /************************************************************************************************** - * Big pile of tests for making sure setting the cumulative period works in a predictable manner * - * regardless of what kind of output comes from the back-off algorithm, also taking into * - * account the maximum cumulative period value. * - *************************************************************************************************/ - - @Test public void setCumulativePeriod_MaxIsInfinity_TwoSeconds() { - s.setCumulativePeriod(Duration.seconds(2)); - assertEquals(Duration.seconds(2), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsInfinity_Negative() { - s.setCumulativePeriod(Duration.seconds(-2)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsInfinity_NegativeInfinity() { - s.setCumulativePeriod(Duration.seconds(Double.NEGATIVE_INFINITY)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsInfinity_NaN() { - s.setCumulativePeriod(Duration.seconds(Double.NaN)); - assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsInfinity_PositiveInfinity() { - s.setCumulativePeriod(Duration.seconds(Double.POSITIVE_INFINITY)); - assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsInfinity_MAX_VALUE() { - s.setCumulativePeriod(Duration.millis(Double.MAX_VALUE)); - assertEquals(Duration.millis(Double.MAX_VALUE), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNaN_TwoSeconds() { - s.setMaximumCumulativePeriod(Duration.UNKNOWN); - s.setCumulativePeriod(Duration.seconds(2)); - assertEquals(Duration.seconds(2), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNaN_Negative() { - s.setMaximumCumulativePeriod(Duration.UNKNOWN); - s.setCumulativePeriod(Duration.seconds(-2)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNaN_NegativeInfinity() { - s.setMaximumCumulativePeriod(Duration.UNKNOWN); - s.setCumulativePeriod(Duration.seconds(Double.NEGATIVE_INFINITY)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNaN_NaN() { - s.setMaximumCumulativePeriod(Duration.UNKNOWN); - s.setCumulativePeriod(Duration.seconds(Double.NaN)); - assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNaN_PositiveInfinity() { - s.setMaximumCumulativePeriod(Duration.UNKNOWN); - s.setCumulativePeriod(Duration.seconds(Double.POSITIVE_INFINITY)); - assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNaN_MAX_VALUE() { - s.setMaximumCumulativePeriod(Duration.UNKNOWN); - s.setCumulativePeriod(Duration.millis(Double.MAX_VALUE)); - assertEquals(Duration.millis(Double.MAX_VALUE), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNull_TwoSeconds() { - s.setMaximumCumulativePeriod(null); - s.setCumulativePeriod(Duration.seconds(2)); - assertEquals(Duration.seconds(2), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNull_Negative() { - s.setMaximumCumulativePeriod(null); - s.setCumulativePeriod(Duration.seconds(-2)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNull_NegativeInfinity() { - s.setMaximumCumulativePeriod(null); - s.setCumulativePeriod(Duration.seconds(Double.NEGATIVE_INFINITY)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNull_NaN() { - s.setMaximumCumulativePeriod(null); - s.setCumulativePeriod(Duration.seconds(Double.NaN)); - assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNull_PositiveInfinity() { - s.setMaximumCumulativePeriod(null); - s.setCumulativePeriod(Duration.seconds(Double.POSITIVE_INFINITY)); - assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNull_MAX_VALUE() { - s.setMaximumCumulativePeriod(null); - s.setCumulativePeriod(Duration.millis(Double.MAX_VALUE)); - assertEquals(Duration.millis(Double.MAX_VALUE), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs10_TwoSeconds() { - s.setMaximumCumulativePeriod(Duration.seconds(10)); - s.setCumulativePeriod(Duration.seconds(2)); - assertEquals(Duration.seconds(2), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs10_TenSeconds() { - s.setMaximumCumulativePeriod(Duration.seconds(10)); - s.setCumulativePeriod(Duration.seconds(10)); - assertEquals(Duration.seconds(10), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs10_TwelveSeconds() { - s.setMaximumCumulativePeriod(Duration.seconds(10)); - s.setCumulativePeriod(Duration.seconds(12)); - assertEquals(Duration.seconds(10), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs10_Negative() { - s.setMaximumCumulativePeriod(Duration.seconds(10)); - s.setCumulativePeriod(Duration.seconds(-2)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs10_NegativeInfinity() { - s.setMaximumCumulativePeriod(Duration.seconds(10)); - s.setCumulativePeriod(Duration.seconds(Double.NEGATIVE_INFINITY)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs10_NaN() { - s.setMaximumCumulativePeriod(Duration.seconds(10)); - s.setCumulativePeriod(Duration.seconds(Double.NaN)); - assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs10_PositiveInfinity() { - s.setMaximumCumulativePeriod(Duration.seconds(10)); - s.setCumulativePeriod(Duration.seconds(Double.POSITIVE_INFINITY)); - assertEquals(Duration.seconds(10), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs10_MAX_VALUE() { - s.setMaximumCumulativePeriod(Duration.seconds(10)); - s.setCumulativePeriod(Duration.millis(Double.MAX_VALUE)); - assertEquals(Duration.seconds(10), s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs0_TwoSeconds() { - s.setMaximumCumulativePeriod(Duration.ZERO); - s.setCumulativePeriod(Duration.seconds(2)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs0_TenSeconds() { - s.setMaximumCumulativePeriod(Duration.ZERO); - s.setCumulativePeriod(Duration.seconds(10)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs0_TwelveSeconds() { - s.setMaximumCumulativePeriod(Duration.ZERO); - s.setCumulativePeriod(Duration.seconds(12)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs0_Negative() { - s.setMaximumCumulativePeriod(Duration.ZERO); - s.setCumulativePeriod(Duration.seconds(-2)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs0_NegativeInfinity() { - s.setMaximumCumulativePeriod(Duration.ZERO); - s.setCumulativePeriod(Duration.seconds(Double.NEGATIVE_INFINITY)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs0_NaN() { - s.setMaximumCumulativePeriod(Duration.ZERO); - s.setCumulativePeriod(Duration.seconds(Double.NaN)); - assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs0_PositiveInfinity() { - s.setMaximumCumulativePeriod(Duration.ZERO); - s.setCumulativePeriod(Duration.seconds(Double.POSITIVE_INFINITY)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIs0_MAX_VALUE() { - s.setMaximumCumulativePeriod(Duration.ZERO); - s.setCumulativePeriod(Duration.millis(Double.MAX_VALUE)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNegative_TwoSeconds() { - s.setMaximumCumulativePeriod(Duration.seconds(-1)); - s.setCumulativePeriod(Duration.seconds(2)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNegative_TenSeconds() { - s.setMaximumCumulativePeriod(Duration.seconds(-1)); - s.setCumulativePeriod(Duration.seconds(10)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNegative_TwelveSeconds() { - s.setMaximumCumulativePeriod(Duration.seconds(-1)); - s.setCumulativePeriod(Duration.seconds(12)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNegative_Negative() { - s.setMaximumCumulativePeriod(Duration.seconds(-1)); - s.setCumulativePeriod(Duration.seconds(-2)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNegative_NegativeInfinity() { - s.setMaximumCumulativePeriod(Duration.seconds(-1)); - s.setCumulativePeriod(Duration.seconds(Double.NEGATIVE_INFINITY)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNegative_NaN() { - s.setMaximumCumulativePeriod(Duration.seconds(-1)); - s.setCumulativePeriod(Duration.seconds(Double.NaN)); - assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNegative_PositiveInfinity() { - s.setMaximumCumulativePeriod(Duration.seconds(-1)); - s.setCumulativePeriod(Duration.seconds(Double.POSITIVE_INFINITY)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - @Test public void setCumulativePeriod_MaxIsNegative_MAX_VALUE() { - s.setMaximumCumulativePeriod(Duration.seconds(-1)); - s.setCumulativePeriod(Duration.millis(Double.MAX_VALUE)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - } - - // TODO I think Duration boundary condition checking is wrong. It doesn't use isInfinite, but checks - // directly with POSITIVE_INFINITY, neglecting to check NEGATIVE_INFINITY. - - // DELAY - // Test that: - // delay (positive, unknown, zero) works the first time - // delay is not used on the next iteration - // delay works on restart - // delay works on reset / start - - @Test public void delayIsHonored_Positive() throws InterruptedException { - s.setDelay(Duration.seconds(1)); - s.start(); - assertEquals(1000, wallClock); - } - - @Test public void delayIsHonored_Unknown() throws InterruptedException { - s.setDelay(Duration.UNKNOWN); - s.start(); - assertEquals(0, wallClock); - } - - @Test public void delayIsHonored_Infinite() throws InterruptedException { - s.setDelay(Duration.INDEFINITE); - s.start(); - assertEquals(Long.MAX_VALUE, wallClock); - } - - @Test public void delayIsHonored_ZERO() throws InterruptedException { - s.setDelay(Duration.ZERO); - s.start(); - assertEquals(0, wallClock); - } - - @Test public void delayIsNotUsedOnSubsequentIteration() { - s.setDelay(Duration.seconds(1)); - s.setPeriod(Duration.seconds(3)); - s.start(); - s.iterate(); - assertEquals(4000, wallClock); // 1 sec initial delay + 3 second iteration delay - } - - @Test public void delayIsUsedOnRestart() { - s.setDelay(Duration.seconds(1)); - s.setPeriod(Duration.seconds(3)); - s.start(); - s.iterate(); - s.cancel(); - wallClock = 0; - s.restart(); - assertEquals(1000, wallClock); - } - - @Test public void delayIsUsedOnStartFollowingReset() { - s.setDelay(Duration.seconds(1)); - s.setPeriod(Duration.seconds(3)); - s.start(); - s.iterate(); - s.cancel(); - wallClock = 0; - s.reset(); - s.start(); - assertEquals(1000, wallClock); - } - - // PERIOD - // Test that: - // period does not contribute to the delay - // amount of time from start of one iteration (run) to another (run) is never < period - // run time < period - // run time == period - // run time > period - // start of last period is reset after "reset" call (or restart) - - @Test public void periodDoesNotContributeToDelay() { - s.setDelay(Duration.seconds(1)); - s.setPeriod(Duration.seconds(3)); - s.start(); - assertEquals(1000, wallClock); - } - - @Test public void executionTimeLessThanPeriod() { - s.setDelay(Duration.seconds(1)); - s.setPeriod(Duration.seconds(3)); - s.start(); - s.iterate(); - assertEquals(4000, wallClock); // 1 sec initial delay + 3 second iteration delay - } - - @Test public void executionTimeEqualsPeriod() { - s.setDelay(Duration.seconds(1)); - s.setPeriod(Duration.seconds(3)); - s.start(); - wallClock += 3000; // simulate execution time - s.iterate(); - assertEquals(4000, wallClock); - } - - @Test public void executionTimeExceedsPeriod() { - s.setDelay(Duration.seconds(1)); - s.setPeriod(Duration.seconds(3)); - s.start(); - wallClock += 6000; // simulate execution time - s.iterate(); - assertEquals(7000, wallClock); - } - - @Test public void startOfPeriodIsResetAfterReset() { - s.setDelay(Duration.seconds(1)); - s.setPeriod(Duration.seconds(3)); - s.start(); - wallClock += 6000; // simulate execution time - s.iterate(); - s.cancel(); - wallClock = 0; - s.reset(); - s.start(); - s.iterate(); - assertEquals(4000, wallClock); - } - - @Test public void startOfPeriodIsResetAfterRestart() { - s.setDelay(Duration.seconds(1)); - s.setPeriod(Duration.seconds(3)); - s.start(); - wallClock += 6000; // simulate execution time - s.iterate(); - s.cancel(); - wallClock = 0; - s.reset(); - s.start(); - s.iterate(); - assertEquals(4000, wallClock); - } - - // COMPUTE BACKOFF - // Test that: - // on task failure, cumulative period is increased according to compute backoff - // EXPONENTIAL_BACKOFF_STRATEGY, LOGARITHMIC_BACKOFF_STRATEGY, LINEAR_BACKOFF_STRATEGY, custom backoff - - @Test public void onFailureCumulativePeriodIsIncreased_EXPONENTIAL_BACKOFF_zero() { - s.setBackoffStrategy(ScheduledService.EXPONENTIAL_BACKOFF_STRATEGY); - s.setPeriod(Duration.ZERO); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.millis(Math.exp(1)), s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_EXPONENTIAL_BACKOFF_one() { - s.setBackoffStrategy(ScheduledService.EXPONENTIAL_BACKOFF_STRATEGY); - s.setPeriod(Duration.seconds(1)); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.millis(1000 + (1000 * Math.exp(1))), s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_EXPONENTIAL_BACKOFF_indefinite() { - s.setBackoffStrategy(ScheduledService.EXPONENTIAL_BACKOFF_STRATEGY); - s.setPeriod(Duration.INDEFINITE); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_EXPONENTIAL_BACKOFF_unknown() { - s.setBackoffStrategy(ScheduledService.EXPONENTIAL_BACKOFF_STRATEGY); - s.setPeriod(Duration.UNKNOWN); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_LOGARITHMIC_BACKOFF_zero() { - s.setBackoffStrategy(ScheduledService.LOGARITHMIC_BACKOFF_STRATEGY); - s.setPeriod(Duration.ZERO); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.millis(Math.log1p(1)), s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_LOGARITHMIC_BACKOFF_one() { - s.setBackoffStrategy(ScheduledService.LOGARITHMIC_BACKOFF_STRATEGY); - s.setPeriod(Duration.seconds(1)); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.millis(1000 + (1000 * Math.log1p(1))), s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_LOGARITHMIC_BACKOFF_indefinite() { - s.setBackoffStrategy(ScheduledService.LOGARITHMIC_BACKOFF_STRATEGY); - s.setPeriod(Duration.INDEFINITE); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_LOGARITHMIC_BACKOFF_unknown() { - s.setBackoffStrategy(ScheduledService.LOGARITHMIC_BACKOFF_STRATEGY); - s.setPeriod(Duration.UNKNOWN); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_LINEAR_BACKOFF_zero() { - s.setBackoffStrategy(ScheduledService.LINEAR_BACKOFF_STRATEGY); - s.setPeriod(Duration.ZERO); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.millis(1), s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_LINEAR_BACKOFF_one() { - s.setBackoffStrategy(ScheduledService.LINEAR_BACKOFF_STRATEGY); - s.setPeriod(Duration.seconds(1)); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.millis(1000 + (1000 * 1)), s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_LINEAR_BACKOFF_indefinite() { - s.setBackoffStrategy(ScheduledService.LINEAR_BACKOFF_STRATEGY); - s.setPeriod(Duration.INDEFINITE); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); - } - - @Test public void onFailureCumulativePeriodIsIncreased_LINEAR_BACKOFF_unknown() { - s.setBackoffStrategy(ScheduledService.LINEAR_BACKOFF_STRATEGY); - s.setPeriod(Duration.UNKNOWN); - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); - } - - // CUMULATIVE PERIOD - // Test that: - // cumulative period is initially equivalent to period - // Cumulative period is set when the service enters "scheduled" state - // cumulative period is unchanged after successful iteration - // cumulative period is modified on failure (tested in onFailure*** tests) - // cumulative period is not modified on cancel - - @Test public void cumulativePeriodSetWhenScheduled() { - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - s.setPeriod(Duration.seconds(1)); - assertEquals(Duration.ZERO, s.getCumulativePeriod()); - s.start(); - assertEquals(Duration.seconds(1), s.getCumulativePeriod()); - } - - @Test public void cumulativePeriodDoesNotChangeOnSuccessfulRun() { - s.setPeriod(Duration.seconds(1)); - s.start(); - s.iterate(); - assertEquals(Duration.seconds(1), s.getCumulativePeriod()); - } - - @Test public void cumulativePeriodResetOnSuccessfulRun() { - final AtomicInteger counter = new AtomicInteger(); - taskFactory = param -> new AbstractTask() { - @Override protected String call() throws Exception { - int c = counter.incrementAndGet(); - if (c < 10) throw new Exception("Kaboom!"); - return "Success"; - } - }; - s.setPeriod(Duration.seconds(1)); - s.start(); - for (int i=0; i<8; i++) s.iterate(); - assertTrue(Duration.seconds(1).lessThan(s.getCumulativePeriod())); - s.iterate(); - assertEquals(Duration.seconds(1), s.getCumulativePeriod()); - } - - @Test public void cumulativePeriodDoesNotChangeOnCancelRun() { - s.setPeriod(Duration.seconds(1)); - s.start(); - s.iterate(); - s.cancel(); - assertEquals(Duration.seconds(1), s.getCumulativePeriod()); - } - - // RESTART ON FAILURE - // Test that: - // value of true causes a new iteration if the task fails - // value of false causes the Service to enter Failed state if the task fails. - - @Test public void restartOnFailure_True() { - final AtomicInteger counter = new AtomicInteger(); - taskFactory = new Callback() { - @Override public AbstractTask call(Void param) { - return new EpicFailTask() { - @Override protected String call() throws Exception { - counter.incrementAndGet(); - return super.call(); - } - }; - } - }; - s.start(); - assertEquals(Worker.State.SCHEDULED, s.getState()); - s.iterate(); - assertEquals(2, counter.get()); - } - - @Test public void restartOnFailure_False() { - final AtomicInteger counter = new AtomicInteger(); - taskFactory = new Callback() { - @Override public AbstractTask call(Void param) { - return new EpicFailTask() { - @Override protected String call() throws Exception { - counter.incrementAndGet(); - return super.call(); - } - }; - } - }; - s.setRestartOnFailure(false); - s.start(); - assertEquals(Worker.State.FAILED, s.getState()); - assertEquals(1, counter.get()); - } - - // MAXIMUM FAILURE COUNT / CURRENT FAILURE COUNT - // Test that: - // service iterates while currentFailureCount < maximumFailureCount - // service fails after currentFailureCount == maximumFailureCount - // service halts when this happens. - // currentFailureCount increments on each failure by 1 - // currentFailureCount is reset on "reset" and "restart" - - @Test public void serviceIteratesWhile_CurrentFailureCount_IsLessThan_MaximumFailureCount() { - final AtomicInteger counter = new AtomicInteger(); - taskFactory = new Callback() { - @Override public AbstractTask call(Void param) { - return new EpicFailTask() { - @Override protected String call() throws Exception { - counter.incrementAndGet(); - return super.call(); - } - }; - } - }; - s.setMaximumFailureCount(10); - s.start(); - while (s.getState() != Worker.State.FAILED) { - assertEquals(counter.get(), s.getCurrentFailureCount()); - s.iterate(); - } - assertEquals(10, counter.get()); - assertEquals(counter.get(), s.getCurrentFailureCount()); - } - - @Test public void currentFailureCountIsResetOnRestart() { - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - for (int i=0; i<10; i++) s.iterate(); - taskFactory = null; - s.restart(); - assertEquals(0, s.getCurrentFailureCount()); - } - - @Test public void currentFailureCountIsResetOnReset() { - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - for (int i=0; i<10; i++) s.iterate(); - s.cancel(); - s.reset(); - assertEquals(0, s.getCurrentFailureCount()); - } - - @Test public void currentFailureCountIsNotResetOnCancel() { - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - for (int i=0; i<10; i++) s.iterate(); - s.cancel(); - assertEquals(11, s.getCurrentFailureCount()); - } - - // LAST VALUE - // Test that: - // last value starts as null - // last value is still null if first iteration fails - // last value equals value from successful iteration (1 & 2) - // last value is cleared on "restart" / "reset" - - @Test public void lastValueIsInitiallyNull() { - assertNull(s.getLastValue()); - } - - @Test public void lastValueIsNullAfterFailedFirstIteration() { - taskFactory = EPIC_FAIL_FACTORY; - s.start(); - assertNull(s.getLastValue()); - } - - @Test public void lastValueIsSetAfterSuccessfulFirstIteration() { - s.start(); - assertEquals("Sentinel", s.getLastValue()); - assertNull(s.getValue()); - } - - @Test public void lastValueIsSetAfterFailedFirstIterationAndSuccessfulSecondIteration() { - final AtomicInteger counter = new AtomicInteger(); - taskFactory = param -> new AbstractTask() { - @Override protected String call() throws Exception { - int c = counter.incrementAndGet(); - if (c == 1) throw new Exception("Bombed out!"); - return "Success"; - } - }; - s.start(); - assertNull(s.getLastValue()); - assertNull(s.getValue()); - s.iterate(); - assertEquals("Success", s.getLastValue()); - assertNull(s.getValue()); - } - - @Test public void lastValueIsUnchangedAfterSuccessfulFirstIterationAndFailedSecondIteration() { - final AtomicInteger counter = new AtomicInteger(); - taskFactory = param -> new AbstractTask() { - @Override protected String call() throws Exception { - int c = counter.incrementAndGet(); - if (c == 1) return "Success"; - throw new Exception("Bombed out!"); - } - }; - s.start(); - assertEquals("Success", s.getLastValue()); - assertNull(s.getValue()); - s.iterate(); - assertEquals("Success", s.getLastValue()); - assertNull(s.getValue()); - } - - @Test public void lastValueIsClearedOnReset() { - s.start(); - assertEquals("Sentinel", s.getLastValue()); - s.cancel(); - assertEquals("Sentinel", s.getLastValue()); - s.reset(); - assertNull(s.getLastValue()); - } - - @Test public void callingCancelFromOnSucceededEventHandlerShouldStopScheduledService() { - AtomicBoolean onReadyCalled = new AtomicBoolean(); - AtomicBoolean onScheduledCalled = new AtomicBoolean(); - AtomicBoolean onCancelledCalled = new AtomicBoolean(); - s.setOnSucceeded(event -> { - s.cancel(); - // Reset these so that they only get set to true if called - // after the cancel step - onReadyCalled.set(false); - onScheduledCalled.set(false); - onCancelledCalled.set(false); - }); - s.setOnReady(event -> onReadyCalled.set(true)); - s.setOnScheduled(event -> onScheduledCalled.set(true)); - s.setOnCancelled(event -> onCancelledCalled.set(true)); - - s.start(); - assertFalse(s.isRunning()); - assertEquals(Worker.State.CANCELLED, s.getState()); - assertTrue(onReadyCalled.get()); - assertTrue(onScheduledCalled.get()); - assertTrue(onCancelledCalled.get()); - } - - /** - * Allows us to monkey with how the threading works for the sake of testing. - * Basically, you just call start() in order to go through an entire first - * iteration, and a call to iterate() causes it to go through a subsequent - * iteration. At the end of each iteration, you are in the SCHEDULED state, - * unless failures occurred while running the task that caused the service - * to finally enter the FAILED state. - */ - private final class ScheduledServiceMock extends ScheduledService { - private TestServiceFactory factory; - private Task nextTask = null; - - ScheduledServiceMock(TestServiceFactory f) { - this.factory = f; - } - - @Override protected Task createTask() { - factory.currentTask = factory.createTestTask(); - factory.currentTask.test = factory.test; - return factory.currentTask; - } - - @Override void checkThread() { } - - @Override void schedule(TimerTask task, long delay) { - wallClock += delay; - task.run(); - } - - @Override protected void executeTask(Task task) { - nextTask = task; - if (isFreshStart()) iterate(); - } - - @Override long clock() { - return wallClock; - } - - @Override boolean isFxApplicationThread() { - return Thread.currentThread() == factory.appThread; - } - - void iterate() { - assert nextTask != null; - Task task = nextTask; - nextTask = null; - - super.executeTask(task); - handleEvents(); - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/ScheduledServiceTest.java 2015-09-11 21:25:32.517286224 -0400 @@ -0,0 +1,874 @@ +/* + * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import test.javafx.concurrent.mocks.EpicFailTask; +import test.javafx.concurrent.mocks.SimpleTask; +import javafx.util.Callback; +import javafx.util.Duration; +import java.util.TimerTask; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import javafx.concurrent.ScheduledService; +import javafx.concurrent.ScheduledServiceShim; +import javafx.concurrent.Service; +import javafx.concurrent.Task; +import javafx.concurrent.Worker; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * Tests for the ScheduledService. + */ +public class ScheduledServiceTest extends ServiceTestBase { + private static final Callback EPIC_FAIL_FACTORY = param -> new EpicFailTask(); + + /** + * The service that we're going to test. Because a ScheduledService + * in its default configuration will run forever and because for the + * sake of testing we've essentially caused ScheduledServiceTest to + * run as though it is single threaded, we have to make sure that each + * individual iteration is paused and doesn't occur without an explicit + * call. So in the test code you can call start(), and then read the wall + * clock time, and then call iterate() to cause the scheduled service to + * start the next iteration all without affecting the "wall clock" time + * inappropriately with the test code. In this way we can test with very + * fine tolerances in a consistent manner. + */ + private ScheduledServiceMock s; + + /** + * If specified by the test BEFORE the service is started, then this + * task will be used by the service. Defaults to SimpleTask if null. + */ + private Callback taskFactory = null; + + /** + * A fake "wall clock" time, to keep track of how much + * time was spent executing a task, and how much time was + * spent in the delay. We fake out the delay by overriding the + * "schedule" method in ScheduledServiceMock, and we fake out + * the task execution time by using a custom task which, when + * executed, will add to the wall clock time. + */ + private long wallClock; + + @Override protected TestServiceFactory setupServiceFactory() { + return new TestServiceFactory() { + @Override public AbstractTask createTestTask() { + return taskFactory == null ? new SimpleTask() : taskFactory.call(null); + } + + @Override public Service createService() { + return new ScheduledServiceMock(this); + } + }; + } + + @Override public void setup() { + super.setup(); + s = (ScheduledServiceMock) service; + wallClock = 0; + } + + /************************************************************************************************** + * Big pile of tests for making sure setting the cumulative period works in a predictable manner * + * regardless of what kind of output comes from the back-off algorithm, also taking into * + * account the maximum cumulative period value. * + *************************************************************************************************/ + + @Test public void setCumulativePeriod_MaxIsInfinity_TwoSeconds() { + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(2)); + assertEquals(Duration.seconds(2), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsInfinity_Negative() { + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(-2)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsInfinity_NegativeInfinity() { + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NEGATIVE_INFINITY)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsInfinity_NaN() { + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NaN)); + assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsInfinity_PositiveInfinity() { + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.POSITIVE_INFINITY)); + assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsInfinity_MAX_VALUE() { + ScheduledServiceShim.setCumulativePeriod(s, Duration.millis(Double.MAX_VALUE)); + assertEquals(Duration.millis(Double.MAX_VALUE), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNaN_TwoSeconds() { + s.setMaximumCumulativePeriod(Duration.UNKNOWN); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(2)); + assertEquals(Duration.seconds(2), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNaN_Negative() { + s.setMaximumCumulativePeriod(Duration.UNKNOWN); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(-2)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNaN_NegativeInfinity() { + s.setMaximumCumulativePeriod(Duration.UNKNOWN); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NEGATIVE_INFINITY)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNaN_NaN() { + s.setMaximumCumulativePeriod(Duration.UNKNOWN); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NaN)); + assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNaN_PositiveInfinity() { + s.setMaximumCumulativePeriod(Duration.UNKNOWN); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.POSITIVE_INFINITY)); + assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNaN_MAX_VALUE() { + s.setMaximumCumulativePeriod(Duration.UNKNOWN); + ScheduledServiceShim.setCumulativePeriod(s, Duration.millis(Double.MAX_VALUE)); + assertEquals(Duration.millis(Double.MAX_VALUE), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNull_TwoSeconds() { + s.setMaximumCumulativePeriod(null); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(2)); + assertEquals(Duration.seconds(2), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNull_Negative() { + s.setMaximumCumulativePeriod(null); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(-2)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNull_NegativeInfinity() { + s.setMaximumCumulativePeriod(null); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NEGATIVE_INFINITY)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNull_NaN() { + s.setMaximumCumulativePeriod(null); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NaN)); + assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNull_PositiveInfinity() { + s.setMaximumCumulativePeriod(null); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.POSITIVE_INFINITY)); + assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNull_MAX_VALUE() { + s.setMaximumCumulativePeriod(null); + ScheduledServiceShim.setCumulativePeriod(s, Duration.millis(Double.MAX_VALUE)); + assertEquals(Duration.millis(Double.MAX_VALUE), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs10_TwoSeconds() { + s.setMaximumCumulativePeriod(Duration.seconds(10)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(2)); + assertEquals(Duration.seconds(2), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs10_TenSeconds() { + s.setMaximumCumulativePeriod(Duration.seconds(10)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(10)); + assertEquals(Duration.seconds(10), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs10_TwelveSeconds() { + s.setMaximumCumulativePeriod(Duration.seconds(10)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(12)); + assertEquals(Duration.seconds(10), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs10_Negative() { + s.setMaximumCumulativePeriod(Duration.seconds(10)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(-2)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs10_NegativeInfinity() { + s.setMaximumCumulativePeriod(Duration.seconds(10)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NEGATIVE_INFINITY)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs10_NaN() { + s.setMaximumCumulativePeriod(Duration.seconds(10)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NaN)); + assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs10_PositiveInfinity() { + s.setMaximumCumulativePeriod(Duration.seconds(10)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.POSITIVE_INFINITY)); + assertEquals(Duration.seconds(10), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs10_MAX_VALUE() { + s.setMaximumCumulativePeriod(Duration.seconds(10)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.millis(Double.MAX_VALUE)); + assertEquals(Duration.seconds(10), s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs0_TwoSeconds() { + s.setMaximumCumulativePeriod(Duration.ZERO); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(2)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs0_TenSeconds() { + s.setMaximumCumulativePeriod(Duration.ZERO); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(10)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs0_TwelveSeconds() { + s.setMaximumCumulativePeriod(Duration.ZERO); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(12)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs0_Negative() { + s.setMaximumCumulativePeriod(Duration.ZERO); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(-2)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs0_NegativeInfinity() { + s.setMaximumCumulativePeriod(Duration.ZERO); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NEGATIVE_INFINITY)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs0_NaN() { + s.setMaximumCumulativePeriod(Duration.ZERO); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NaN)); + assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs0_PositiveInfinity() { + s.setMaximumCumulativePeriod(Duration.ZERO); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.POSITIVE_INFINITY)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIs0_MAX_VALUE() { + s.setMaximumCumulativePeriod(Duration.ZERO); + ScheduledServiceShim.setCumulativePeriod(s, Duration.millis(Double.MAX_VALUE)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNegative_TwoSeconds() { + s.setMaximumCumulativePeriod(Duration.seconds(-1)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(2)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNegative_TenSeconds() { + s.setMaximumCumulativePeriod(Duration.seconds(-1)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(10)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNegative_TwelveSeconds() { + s.setMaximumCumulativePeriod(Duration.seconds(-1)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(12)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNegative_Negative() { + s.setMaximumCumulativePeriod(Duration.seconds(-1)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(-2)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNegative_NegativeInfinity() { + s.setMaximumCumulativePeriod(Duration.seconds(-1)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NEGATIVE_INFINITY)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNegative_NaN() { + s.setMaximumCumulativePeriod(Duration.seconds(-1)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.NaN)); + assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNegative_PositiveInfinity() { + s.setMaximumCumulativePeriod(Duration.seconds(-1)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.seconds(Double.POSITIVE_INFINITY)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + @Test public void setCumulativePeriod_MaxIsNegative_MAX_VALUE() { + s.setMaximumCumulativePeriod(Duration.seconds(-1)); + ScheduledServiceShim.setCumulativePeriod(s, Duration.millis(Double.MAX_VALUE)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + } + + // TODO I think Duration boundary condition checking is wrong. It doesn't use isInfinite, but checks + // directly with POSITIVE_INFINITY, neglecting to check NEGATIVE_INFINITY. + + // DELAY + // Test that: + // delay (positive, unknown, zero) works the first time + // delay is not used on the next iteration + // delay works on restart + // delay works on reset / start + + @Test public void delayIsHonored_Positive() throws InterruptedException { + s.setDelay(Duration.seconds(1)); + s.start(); + assertEquals(1000, wallClock); + } + + @Test public void delayIsHonored_Unknown() throws InterruptedException { + s.setDelay(Duration.UNKNOWN); + s.start(); + assertEquals(0, wallClock); + } + + @Test public void delayIsHonored_Infinite() throws InterruptedException { + s.setDelay(Duration.INDEFINITE); + s.start(); + assertEquals(Long.MAX_VALUE, wallClock); + } + + @Test public void delayIsHonored_ZERO() throws InterruptedException { + s.setDelay(Duration.ZERO); + s.start(); + assertEquals(0, wallClock); + } + + @Test public void delayIsNotUsedOnSubsequentIteration() { + s.setDelay(Duration.seconds(1)); + s.setPeriod(Duration.seconds(3)); + s.start(); + s.iterate(); + assertEquals(4000, wallClock); // 1 sec initial delay + 3 second iteration delay + } + + @Test public void delayIsUsedOnRestart() { + s.setDelay(Duration.seconds(1)); + s.setPeriod(Duration.seconds(3)); + s.start(); + s.iterate(); + s.cancel(); + wallClock = 0; + s.restart(); + assertEquals(1000, wallClock); + } + + @Test public void delayIsUsedOnStartFollowingReset() { + s.setDelay(Duration.seconds(1)); + s.setPeriod(Duration.seconds(3)); + s.start(); + s.iterate(); + s.cancel(); + wallClock = 0; + s.reset(); + s.start(); + assertEquals(1000, wallClock); + } + + // PERIOD + // Test that: + // period does not contribute to the delay + // amount of time from start of one iteration (run) to another (run) is never < period + // run time < period + // run time == period + // run time > period + // start of last period is reset after "reset" call (or restart) + + @Test public void periodDoesNotContributeToDelay() { + s.setDelay(Duration.seconds(1)); + s.setPeriod(Duration.seconds(3)); + s.start(); + assertEquals(1000, wallClock); + } + + @Test public void executionTimeLessThanPeriod() { + s.setDelay(Duration.seconds(1)); + s.setPeriod(Duration.seconds(3)); + s.start(); + s.iterate(); + assertEquals(4000, wallClock); // 1 sec initial delay + 3 second iteration delay + } + + @Test public void executionTimeEqualsPeriod() { + s.setDelay(Duration.seconds(1)); + s.setPeriod(Duration.seconds(3)); + s.start(); + wallClock += 3000; // simulate execution time + s.iterate(); + assertEquals(4000, wallClock); + } + + @Test public void executionTimeExceedsPeriod() { + s.setDelay(Duration.seconds(1)); + s.setPeriod(Duration.seconds(3)); + s.start(); + wallClock += 6000; // simulate execution time + s.iterate(); + assertEquals(7000, wallClock); + } + + @Test public void startOfPeriodIsResetAfterReset() { + s.setDelay(Duration.seconds(1)); + s.setPeriod(Duration.seconds(3)); + s.start(); + wallClock += 6000; // simulate execution time + s.iterate(); + s.cancel(); + wallClock = 0; + s.reset(); + s.start(); + s.iterate(); + assertEquals(4000, wallClock); + } + + @Test public void startOfPeriodIsResetAfterRestart() { + s.setDelay(Duration.seconds(1)); + s.setPeriod(Duration.seconds(3)); + s.start(); + wallClock += 6000; // simulate execution time + s.iterate(); + s.cancel(); + wallClock = 0; + s.reset(); + s.start(); + s.iterate(); + assertEquals(4000, wallClock); + } + + // COMPUTE BACKOFF + // Test that: + // on task failure, cumulative period is increased according to compute backoff + // EXPONENTIAL_BACKOFF_STRATEGY, LOGARITHMIC_BACKOFF_STRATEGY, LINEAR_BACKOFF_STRATEGY, custom backoff + + @Test public void onFailureCumulativePeriodIsIncreased_EXPONENTIAL_BACKOFF_zero() { + s.setBackoffStrategy(ScheduledService.EXPONENTIAL_BACKOFF_STRATEGY); + s.setPeriod(Duration.ZERO); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.millis(Math.exp(1)), s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_EXPONENTIAL_BACKOFF_one() { + s.setBackoffStrategy(ScheduledService.EXPONENTIAL_BACKOFF_STRATEGY); + s.setPeriod(Duration.seconds(1)); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.millis(1000 + (1000 * Math.exp(1))), s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_EXPONENTIAL_BACKOFF_indefinite() { + s.setBackoffStrategy(ScheduledService.EXPONENTIAL_BACKOFF_STRATEGY); + s.setPeriod(Duration.INDEFINITE); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_EXPONENTIAL_BACKOFF_unknown() { + s.setBackoffStrategy(ScheduledService.EXPONENTIAL_BACKOFF_STRATEGY); + s.setPeriod(Duration.UNKNOWN); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_LOGARITHMIC_BACKOFF_zero() { + s.setBackoffStrategy(ScheduledService.LOGARITHMIC_BACKOFF_STRATEGY); + s.setPeriod(Duration.ZERO); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.millis(Math.log1p(1)), s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_LOGARITHMIC_BACKOFF_one() { + s.setBackoffStrategy(ScheduledService.LOGARITHMIC_BACKOFF_STRATEGY); + s.setPeriod(Duration.seconds(1)); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.millis(1000 + (1000 * Math.log1p(1))), s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_LOGARITHMIC_BACKOFF_indefinite() { + s.setBackoffStrategy(ScheduledService.LOGARITHMIC_BACKOFF_STRATEGY); + s.setPeriod(Duration.INDEFINITE); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_LOGARITHMIC_BACKOFF_unknown() { + s.setBackoffStrategy(ScheduledService.LOGARITHMIC_BACKOFF_STRATEGY); + s.setPeriod(Duration.UNKNOWN); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_LINEAR_BACKOFF_zero() { + s.setBackoffStrategy(ScheduledService.LINEAR_BACKOFF_STRATEGY); + s.setPeriod(Duration.ZERO); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.millis(1), s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_LINEAR_BACKOFF_one() { + s.setBackoffStrategy(ScheduledService.LINEAR_BACKOFF_STRATEGY); + s.setPeriod(Duration.seconds(1)); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.millis(1000 + (1000 * 1)), s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_LINEAR_BACKOFF_indefinite() { + s.setBackoffStrategy(ScheduledService.LINEAR_BACKOFF_STRATEGY); + s.setPeriod(Duration.INDEFINITE); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.INDEFINITE, s.getCumulativePeriod()); + } + + @Test public void onFailureCumulativePeriodIsIncreased_LINEAR_BACKOFF_unknown() { + s.setBackoffStrategy(ScheduledService.LINEAR_BACKOFF_STRATEGY); + s.setPeriod(Duration.UNKNOWN); + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertEquals(Duration.UNKNOWN, s.getCumulativePeriod()); + } + + // CUMULATIVE PERIOD + // Test that: + // cumulative period is initially equivalent to period + // Cumulative period is set when the service enters "scheduled" state + // cumulative period is unchanged after successful iteration + // cumulative period is modified on failure (tested in onFailure*** tests) + // cumulative period is not modified on cancel + + @Test public void cumulativePeriodSetWhenScheduled() { + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + s.setPeriod(Duration.seconds(1)); + assertEquals(Duration.ZERO, s.getCumulativePeriod()); + s.start(); + assertEquals(Duration.seconds(1), s.getCumulativePeriod()); + } + + @Test public void cumulativePeriodDoesNotChangeOnSuccessfulRun() { + s.setPeriod(Duration.seconds(1)); + s.start(); + s.iterate(); + assertEquals(Duration.seconds(1), s.getCumulativePeriod()); + } + + @Test public void cumulativePeriodResetOnSuccessfulRun() { + final AtomicInteger counter = new AtomicInteger(); + taskFactory = param -> new AbstractTask() { + @Override protected String call() throws Exception { + int c = counter.incrementAndGet(); + if (c < 10) throw new Exception("Kaboom!"); + return "Success"; + } + }; + s.setPeriod(Duration.seconds(1)); + s.start(); + for (int i=0; i<8; i++) s.iterate(); + assertTrue(Duration.seconds(1).lessThan(s.getCumulativePeriod())); + s.iterate(); + assertEquals(Duration.seconds(1), s.getCumulativePeriod()); + } + + @Test public void cumulativePeriodDoesNotChangeOnCancelRun() { + s.setPeriod(Duration.seconds(1)); + s.start(); + s.iterate(); + s.cancel(); + assertEquals(Duration.seconds(1), s.getCumulativePeriod()); + } + + // RESTART ON FAILURE + // Test that: + // value of true causes a new iteration if the task fails + // value of false causes the Service to enter Failed state if the task fails. + + @Test public void restartOnFailure_True() { + final AtomicInteger counter = new AtomicInteger(); + taskFactory = new Callback() { + @Override public AbstractTask call(Void param) { + return new EpicFailTask() { + @Override protected String call() throws Exception { + counter.incrementAndGet(); + return super.call(); + } + }; + } + }; + s.start(); + assertEquals(Worker.State.SCHEDULED, s.getState()); + s.iterate(); + assertEquals(2, counter.get()); + } + + @Test public void restartOnFailure_False() { + final AtomicInteger counter = new AtomicInteger(); + taskFactory = new Callback() { + @Override public AbstractTask call(Void param) { + return new EpicFailTask() { + @Override protected String call() throws Exception { + counter.incrementAndGet(); + return super.call(); + } + }; + } + }; + s.setRestartOnFailure(false); + s.start(); + assertEquals(Worker.State.FAILED, s.getState()); + assertEquals(1, counter.get()); + } + + // MAXIMUM FAILURE COUNT / CURRENT FAILURE COUNT + // Test that: + // service iterates while currentFailureCount < maximumFailureCount + // service fails after currentFailureCount == maximumFailureCount + // service halts when this happens. + // currentFailureCount increments on each failure by 1 + // currentFailureCount is reset on "reset" and "restart" + + @Test public void serviceIteratesWhile_CurrentFailureCount_IsLessThan_MaximumFailureCount() { + final AtomicInteger counter = new AtomicInteger(); + taskFactory = new Callback() { + @Override public AbstractTask call(Void param) { + return new EpicFailTask() { + @Override protected String call() throws Exception { + counter.incrementAndGet(); + return super.call(); + } + }; + } + }; + s.setMaximumFailureCount(10); + s.start(); + while (s.getState() != Worker.State.FAILED) { + assertEquals(counter.get(), s.getCurrentFailureCount()); + s.iterate(); + } + assertEquals(10, counter.get()); + assertEquals(counter.get(), s.getCurrentFailureCount()); + } + + @Test public void currentFailureCountIsResetOnRestart() { + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + for (int i=0; i<10; i++) s.iterate(); + taskFactory = null; + s.restart(); + assertEquals(0, s.getCurrentFailureCount()); + } + + @Test public void currentFailureCountIsResetOnReset() { + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + for (int i=0; i<10; i++) s.iterate(); + s.cancel(); + s.reset(); + assertEquals(0, s.getCurrentFailureCount()); + } + + @Test public void currentFailureCountIsNotResetOnCancel() { + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + for (int i=0; i<10; i++) s.iterate(); + s.cancel(); + assertEquals(11, s.getCurrentFailureCount()); + } + + // LAST VALUE + // Test that: + // last value starts as null + // last value is still null if first iteration fails + // last value equals value from successful iteration (1 & 2) + // last value is cleared on "restart" / "reset" + + @Test public void lastValueIsInitiallyNull() { + assertNull(s.getLastValue()); + } + + @Test public void lastValueIsNullAfterFailedFirstIteration() { + taskFactory = EPIC_FAIL_FACTORY; + s.start(); + assertNull(s.getLastValue()); + } + + @Test public void lastValueIsSetAfterSuccessfulFirstIteration() { + s.start(); + assertEquals("Sentinel", s.getLastValue()); + assertNull(s.getValue()); + } + + @Test public void lastValueIsSetAfterFailedFirstIterationAndSuccessfulSecondIteration() { + final AtomicInteger counter = new AtomicInteger(); + taskFactory = param -> new AbstractTask() { + @Override protected String call() throws Exception { + int c = counter.incrementAndGet(); + if (c == 1) throw new Exception("Bombed out!"); + return "Success"; + } + }; + s.start(); + assertNull(s.getLastValue()); + assertNull(s.getValue()); + s.iterate(); + assertEquals("Success", s.getLastValue()); + assertNull(s.getValue()); + } + + @Test public void lastValueIsUnchangedAfterSuccessfulFirstIterationAndFailedSecondIteration() { + final AtomicInteger counter = new AtomicInteger(); + taskFactory = param -> new AbstractTask() { + @Override protected String call() throws Exception { + int c = counter.incrementAndGet(); + if (c == 1) return "Success"; + throw new Exception("Bombed out!"); + } + }; + s.start(); + assertEquals("Success", s.getLastValue()); + assertNull(s.getValue()); + s.iterate(); + assertEquals("Success", s.getLastValue()); + assertNull(s.getValue()); + } + + @Test public void lastValueIsClearedOnReset() { + s.start(); + assertEquals("Sentinel", s.getLastValue()); + s.cancel(); + assertEquals("Sentinel", s.getLastValue()); + s.reset(); + assertNull(s.getLastValue()); + } + + @Test public void callingCancelFromOnSucceededEventHandlerShouldStopScheduledService() { + AtomicBoolean onReadyCalled = new AtomicBoolean(); + AtomicBoolean onScheduledCalled = new AtomicBoolean(); + AtomicBoolean onCancelledCalled = new AtomicBoolean(); + s.setOnSucceeded(event -> { + s.cancel(); + // Reset these so that they only get set to true if called + // after the cancel step + onReadyCalled.set(false); + onScheduledCalled.set(false); + onCancelledCalled.set(false); + }); + s.setOnReady(event -> onReadyCalled.set(true)); + s.setOnScheduled(event -> onScheduledCalled.set(true)); + s.setOnCancelled(event -> onCancelledCalled.set(true)); + + s.start(); + assertFalse(s.isRunning()); + assertEquals(Worker.State.CANCELLED, s.getState()); + assertTrue(onReadyCalled.get()); + assertTrue(onScheduledCalled.get()); + assertTrue(onCancelledCalled.get()); + } + + /** + * Allows us to monkey with how the threading works for the sake of testing. + * Basically, you just call start() in order to go through an entire first + * iteration, and a call to iterate() causes it to go through a subsequent + * iteration. At the end of each iteration, you are in the SCHEDULED state, + * unless failures occurred while running the task that caused the service + * to finally enter the FAILED state. + */ + private final class ScheduledServiceMock extends ScheduledServiceShim { + private TestServiceFactory factory; + private Task nextTask = null; + + ScheduledServiceMock(TestServiceFactory f) { + this.factory = f; + } + + @Override protected Task createTask() { + factory.currentTask = factory.createTestTask(); + factory.currentTask.set_test(factory.test); + return factory.currentTask; + } + + @Override public void checkThread() { } + + @Override public void schedule(TimerTask task, long delay) { + wallClock += delay; + task.run(); + } + + @Override public void executeTask(Task task) { + nextTask = task; + if (isFreshStart()) iterate(); + } + + @Override public long clock() { + return wallClock; + } + + @Override public boolean isFxApplicationThread() { + return Thread.currentThread() == factory.appThread; + } + + void iterate() { + assert nextTask != null; + Task task = nextTask; + nextTask = null; + + super.executeTask(task); + handleEvents(); + } + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/ServiceExceptionTest.java 2015-09-11 21:25:33.417286214 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,208 +0,0 @@ -/* - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import java.util.Arrays; -import java.util.Collection; -import java.util.concurrent.atomic.AtomicBoolean; -import javafx.beans.value.ChangeListener; -import javafx.beans.value.ObservableValue; -import javafx.concurrent.mocks.EpicFailTask; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import static org.junit.Assert.*; - -/** - * This tests that state is correct when a Task throws an exception partway through. - * In this particular case, the progress is updated to 50% before the exception - * occurs. - */ -@RunWith(Parameterized.class) -public class ServiceExceptionTest extends ServiceTestBase { - @Parameterized.Parameters public static Collection implementations() { - return Arrays.asList(new Object[][]{ - { new Exception("Exception") }, - { new IllegalArgumentException("IAE") }, - { new NullPointerException("NPE") }, - { new RuntimeException("RuntimeException") } - }); - } - - private Exception exception; - - public ServiceExceptionTest(Exception th) { - this.exception = th; - } - - @Override protected TestServiceFactory setupServiceFactory() { - return new TestServiceFactory() { - @Override protected AbstractTask createTestTask() { - return new EpicFailTask(ServiceExceptionTest.this.exception); - } - }; - } - - /************************************************************************ - * Run the concurrent and check that the exception property is set, and that - * the value property is null. The progress fields may be in some - * arbitrary state. - ***********************************************************************/ - - /** - * Whenever the exception occurs we should have the exception property set - */ - @Test public void exceptionShouldBeSet() { - service.start(); - handleEvents(); - assertSame(exception, service.getException()); - assertSame(exception, service.exceptionProperty().get()); - } - - @Test public void exceptionPropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.exceptionProperty().addListener((o, oldValue, newValue) -> passed.set(newValue == exception)); - service.start(); - handleEvents(); - assertTrue(passed.get()); - } - - /** - * The value should always be null if an exception occurs before the end of the Task. - */ - @Test public void valueShouldBeNull() { - service.start(); - handleEvents(); - assertNull(service.getValue()); - assertNull(service.valueProperty().get()); - } - - @Test public void runningShouldBeFalse() { - service.start(); - handleEvents(); - assertFalse(service.isRunning()); - assertFalse(service.runningProperty().get()); - } - - @Test public void runningPropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.runningProperty().addListener((o, oldValue, newValue) -> passed.set(!newValue)); - service.start(); - handleEvents(); - assertTrue(passed.get()); - } - - @Test public void workDoneShouldBeTen() { - service.start(); - handleEvents(); - assertEquals(10, service.getWorkDone(), 0); - assertEquals(10, service.workDoneProperty().get(), 0); - } - - @Test public void workDonePropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.workDoneProperty().addListener((observable, oldValue, newValue) -> passed.set(newValue.doubleValue() == 10)); - service.start(); - handleEvents(); - assertTrue(passed.get()); - } - - @Test public void totalWorkShouldBeTwenty() { - service.start(); - handleEvents(); - assertEquals(20, service.getTotalWork(), 0); - assertEquals(20, service.totalWorkProperty().get(), 0); - } - - @Test public void totalWorkPropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.totalWorkProperty().addListener((observable, oldValue, newValue) -> passed.set(newValue.doubleValue() == 20)); - service.start(); - handleEvents(); - assertTrue(passed.get()); - } - - @Test public void afterRunningProgressShouldBe_FiftyPercent() { - service.start(); - handleEvents(); - assertEquals(.5, service.getProgress(), 0); - assertEquals(.5, service.progressProperty().get(), 0); - } - - @Test public void progressPropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.progressProperty().addListener((observable, oldValue, newValue) -> passed.set(newValue.doubleValue() == .5)); - service.start(); - handleEvents(); - assertTrue(passed.get()); - } - - @Test public void stateShouldBe_FAILED() { - service.start(); - handleEvents(); - assertSame(Worker.State.FAILED, service.getState()); - assertSame(Worker.State.FAILED, service.stateProperty().get()); - } - - @Test public void statePropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.stateProperty().addListener((observable, oldValue, newValue) -> passed.set(newValue == Worker.State.FAILED)); - service.start(); - handleEvents(); - assertTrue(passed.get()); - } - - @Test public void messageShouldBeLastSetValue() { - service.start(); - handleEvents(); - assertEquals("About to fail", service.getMessage()); - assertEquals("About to fail", service.messageProperty().get()); - } - - @Test public void messagePropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.messageProperty().addListener((observable, oldValue, newValue) -> passed.set("About to fail".equals(service.getMessage()))); - service.start(); - handleEvents(); - assertTrue(passed.get()); - } - - @Test public void titleShouldBeLastSetValue() { - service.start(); - handleEvents(); - assertEquals("Epic Fail", service.getTitle()); - assertEquals("Epic Fail", service.titleProperty().get()); - } - - @Test public void titlePropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.titleProperty().addListener((observable, oldValue, newValue) -> passed.set("Epic Fail".equals(service.getTitle()))); - service.start(); - handleEvents(); - assertTrue(passed.get()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/ServiceExceptionTest.java 2015-09-11 21:25:33.277286216 -0400 @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.atomic.AtomicBoolean; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.concurrent.Worker; +import test.javafx.concurrent.mocks.EpicFailTask; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import static org.junit.Assert.*; + +/** + * This tests that state is correct when a Task throws an exception partway through. + * In this particular case, the progress is updated to 50% before the exception + * occurs. + */ +@RunWith(Parameterized.class) +public class ServiceExceptionTest extends ServiceTestBase { + @Parameterized.Parameters public static Collection implementations() { + return Arrays.asList(new Object[][]{ + { new Exception("Exception") }, + { new IllegalArgumentException("IAE") }, + { new NullPointerException("NPE") }, + { new RuntimeException("RuntimeException") } + }); + } + + private Exception exception; + + public ServiceExceptionTest(Exception th) { + this.exception = th; + } + + @Override protected TestServiceFactory setupServiceFactory() { + return new TestServiceFactory() { + @Override public AbstractTask createTestTask() { + return new EpicFailTask(ServiceExceptionTest.this.exception); + } + }; + } + + /************************************************************************ + * Run the concurrent and check that the exception property is set, and that + * the value property is null. The progress fields may be in some + * arbitrary state. + ***********************************************************************/ + + /** + * Whenever the exception occurs we should have the exception property set + */ + @Test public void exceptionShouldBeSet() { + service.start(); + handleEvents(); + assertSame(exception, service.getException()); + assertSame(exception, service.exceptionProperty().get()); + } + + @Test public void exceptionPropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.exceptionProperty().addListener((o, oldValue, newValue) -> passed.set(newValue == exception)); + service.start(); + handleEvents(); + assertTrue(passed.get()); + } + + /** + * The value should always be null if an exception occurs before the end of the Task. + */ + @Test public void valueShouldBeNull() { + service.start(); + handleEvents(); + assertNull(service.getValue()); + assertNull(service.valueProperty().get()); + } + + @Test public void runningShouldBeFalse() { + service.start(); + handleEvents(); + assertFalse(service.isRunning()); + assertFalse(service.runningProperty().get()); + } + + @Test public void runningPropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.runningProperty().addListener((o, oldValue, newValue) -> passed.set(!newValue)); + service.start(); + handleEvents(); + assertTrue(passed.get()); + } + + @Test public void workDoneShouldBeTen() { + service.start(); + handleEvents(); + assertEquals(10, service.getWorkDone(), 0); + assertEquals(10, service.workDoneProperty().get(), 0); + } + + @Test public void workDonePropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.workDoneProperty().addListener((observable, oldValue, newValue) -> passed.set(newValue.doubleValue() == 10)); + service.start(); + handleEvents(); + assertTrue(passed.get()); + } + + @Test public void totalWorkShouldBeTwenty() { + service.start(); + handleEvents(); + assertEquals(20, service.getTotalWork(), 0); + assertEquals(20, service.totalWorkProperty().get(), 0); + } + + @Test public void totalWorkPropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.totalWorkProperty().addListener((observable, oldValue, newValue) -> passed.set(newValue.doubleValue() == 20)); + service.start(); + handleEvents(); + assertTrue(passed.get()); + } + + @Test public void afterRunningProgressShouldBe_FiftyPercent() { + service.start(); + handleEvents(); + assertEquals(.5, service.getProgress(), 0); + assertEquals(.5, service.progressProperty().get(), 0); + } + + @Test public void progressPropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.progressProperty().addListener((observable, oldValue, newValue) -> passed.set(newValue.doubleValue() == .5)); + service.start(); + handleEvents(); + assertTrue(passed.get()); + } + + @Test public void stateShouldBe_FAILED() { + service.start(); + handleEvents(); + assertSame(Worker.State.FAILED, service.getState()); + assertSame(Worker.State.FAILED, service.stateProperty().get()); + } + + @Test public void statePropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.stateProperty().addListener((observable, oldValue, newValue) -> passed.set(newValue == Worker.State.FAILED)); + service.start(); + handleEvents(); + assertTrue(passed.get()); + } + + @Test public void messageShouldBeLastSetValue() { + service.start(); + handleEvents(); + assertEquals("About to fail", service.getMessage()); + assertEquals("About to fail", service.messageProperty().get()); + } + + @Test public void messagePropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.messageProperty().addListener((observable, oldValue, newValue) -> passed.set("About to fail".equals(service.getMessage()))); + service.start(); + handleEvents(); + assertTrue(passed.get()); + } + + @Test public void titleShouldBeLastSetValue() { + service.start(); + handleEvents(); + assertEquals("Epic Fail", service.getTitle()); + assertEquals("Epic Fail", service.titleProperty().get()); + } + + @Test public void titlePropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.titleProperty().addListener((observable, oldValue, newValue) -> passed.set("Epic Fail".equals(service.getTitle()))); + service.start(); + handleEvents(); + assertTrue(passed.get()); + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/ServiceLifecycleTest.java 2015-09-11 21:25:34.117286206 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,1953 +0,0 @@ -/* - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import javafx.beans.value.ChangeListener; -import javafx.beans.value.ObservableValue; -import javafx.concurrent.mocks.MythicalEvent; -import javafx.concurrent.mocks.SimpleTask; -import javafx.event.Event; -import javafx.event.EventHandler; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.After; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -/** - * Tests various rules regarding the lifecycle of a Service. - */ -public class ServiceLifecycleTest extends ServiceTestBase { - /** - * The ManualExecutor is used so that there is some time period between - * when something is scheduled and when it actually runs, such that the - * test code has to manually tell it that it can now run. - */ - protected ManualExecutor executor; - - /** - * The task to run, which has methods on it to allow me to manually - * put it into a passing, failed, or whatnot state. - */ - protected ManualTask task; - - @Override protected TestServiceFactory setupServiceFactory() { - return new TestServiceFactory() { - @Override protected AbstractTask createTestTask() { - return task = new ManualTask(); - } - }; - } - - @Override protected Executor createExecutor() { - return executor = new ManualExecutor(super.createExecutor()); - } - - @After public void tearDown() { - if (task != null) task.finish.set(true); - } - - /** - * This class will schedule the task, and then you can execute - * it manually by calling executeScheduled. In this way I can - * test when a Service is scheduled but not yet started. - */ - protected final class ManualExecutor implements Executor { - private Runnable scheduled; - private Executor wrapped; - - ManualExecutor(Executor wrapped) { - this.wrapped = wrapped; - } - - @Override public void execute(Runnable command) { - this.scheduled = command; - } - - public void executeScheduled() { - wrapped.execute(scheduled); - // I need to wait until the next "Sentinel" runnable - // on the queue, which the Task will post when it begins - // execution. - handleEvents(); - } - } - - protected final class ManualTask extends AbstractTask { - private AtomicBoolean finish = new AtomicBoolean(false); - private AtomicReference exception = new AtomicReference<>(); - private boolean failToCancel = false; - - @Override protected String call() throws Exception { - runLater(new Sentinel()); - while (!finish.get()) { - Exception e = exception.get(); - if (e != null) throw e; - } - return "Done"; - } - - public void progress(long done, long max) { - updateProgress(done, max); - } - - public void message(String msg) { - updateMessage(msg); - } - - public void title(String t) { - updateTitle(t); - } - - public void fail(Exception e) { - exception.set(e); - handleEvents(); - } - - public void complete() { - finish.set(true); - handleEvents(); - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - boolean result = failToCancel ? false : super.cancel(mayInterruptIfRunning); - finish.set(true); - return result; - } - } - - /************************************************************************ - * Tests while in the ready state * - ***********************************************************************/ - - @Test public void callingStartInReadyStateSchedulesJob() { - assertNull(executor.scheduled); - service.start(); - assertNotNull(executor.scheduled); - } - - @Test public void callingStartInReadyMovesToScheduledState() { - service.start(); - assertSame(Worker.State.SCHEDULED, service.getState()); - assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); - } - - @Test public void callingRestartInReadyStateSchedulesJob() { - assertNull(executor.scheduled); - service.restart(); - assertNotNull(executor.scheduled); - } - - @Test public void callingRestartInReadyMovesToScheduledState() { - service.restart(); - assertSame(Worker.State.SCHEDULED, service.getState()); - assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); - } - - @Test public void callingCancelInReadyStateMovesToCancelledState() { - service.cancel(); - assertSame(Worker.State.CANCELLED, service.getState()); - assertSame(Worker.State.CANCELLED, service.stateProperty().get()); - } - - @Test public void callingResetInReadyStateHasNoEffect() { - service.reset(); - assertSame(Worker.State.READY, service.getState()); - assertSame(Worker.State.READY, service.stateProperty().get()); - } - - /************************************************************************ - * Tests while in the scheduled state * - ***********************************************************************/ - - @Test(expected = IllegalStateException.class) - public void callingStartInScheduledStateIsISE() { - service.start(); - service.start(); - } - - @Test public void callingCancelInScheduledStateResultsInCancelledState() { - service.start(); - service.cancel(); - assertSame(Worker.State.CANCELLED, service.getState()); - assertSame(Worker.State.CANCELLED, service.stateProperty().get()); - } - - @Test public void callingRestartInScheduledStateShouldCancelAndReschedule() { - service.start(); - service.restart(); - assertSame(Worker.State.SCHEDULED, service.getState()); - assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); - } - - /** - * This test differs from callingRestartInScheduledStateShouldCancelAndReschedule - * in that under some circumstances, the cancel operation on a task may yield - * a task which is not marked as CANCELLED, such as when it is already run - * or cancelled). In such a case, the bindings have not fired yet and the - * state of the service is off. At least, that is what is happening with - * RT-20880. The fix allows this test to pass. - */ - @Test public void callingRestartInScheduledStateShouldCancelAndReschedule_RT_20880() { - service.start(); - task.failToCancel = true; - service.restart(); - assertSame(Worker.State.SCHEDULED, service.getState()); - assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); - } - - @Test(expected = IllegalStateException.class) - public void callingResetInScheduledStateThrowsISE() { - service.start(); - service.reset(); - } - - @Test public void stateChangesToRunningWhenExecutorExecutes() { - service.start(); - executor.executeScheduled(); - assertSame(Worker.State.RUNNING, service.getState()); - assertSame(Worker.State.RUNNING, service.stateProperty().get()); - } - - @Test public void exceptionShouldBeNullInScheduledState() { - service.start(); - assertNull(service.getException()); - assertNull(service.exceptionProperty().get()); - } - - @Test public void valueShouldBeNullInScheduledState() { - service.start(); - assertNull(service.getValue()); - assertNull(service.valueProperty().get()); - } - - @Test public void runningShouldBeTrueInScheduledState() { - service.start(); - assertTrue(service.isRunning()); - assertTrue(service.runningProperty().get()); - } - - @Test public void runningPropertyNotificationInScheduledState() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.runningProperty().addListener((o, oldValue, newValue) -> passed.set(newValue)); - service.start(); - assertTrue(passed.get()); - } - - @Test public void workDoneShouldBeNegativeOneInitiallyInScheduledState() { - service.start(); - assertEquals(-1, service.getWorkDone(), 0); - assertEquals(-1, service.workDoneProperty().get(), 0); - } - - @Test public void totalWorkShouldBeNegativeOneAtStartOfScheduledState() { - service.start(); - assertEquals(-1, service.getTotalWork(), 0); - assertEquals(-1, service.totalWorkProperty().get(), 0); - } - - @Test public void progressShouldBeNegativeOneAtStartOfScheduledState() { - service.start(); - assertEquals(-1, service.getProgress(), 0); - assertEquals(-1, task.progressProperty().get(), 0); - } - - @Test public void messageShouldBeEmptyStringWhenEnteringScheduledState() { - service.start(); - assertEquals("", service.getMessage()); - assertEquals("", task.messageProperty().get()); - } - - @Test public void titleShouldBeEmptyStringAtStartOfScheduledState() { - service.start(); - assertEquals("", service.getTitle()); - assertEquals("", task.titleProperty().get()); - } - - /************************************************************************ - * Tests while in the running state * - ***********************************************************************/ - - @Test(expected = IllegalStateException.class) - public void callingStartInRunningStateIsISE() { - service.start(); - executor.executeScheduled(); - service.start(); - } - - @Test(expected = IllegalStateException.class) - public void callingResetInRunningStateIsISE() { - service.start(); - executor.executeScheduled(); - service.reset(); - } - - @Test public void callingRestartInRunningStateCancelsAndReschedules() { - service.start(); - executor.executeScheduled(); - service.restart(); - assertSame(Worker.State.SCHEDULED, service.getState()); - assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); - } - - @Test public void callingCancelInRunningStateResultsInCancelledState() { - service.start(); - executor.executeScheduled(); - service.cancel(); - assertSame(Worker.State.CANCELLED, service.getState()); - assertSame(Worker.State.CANCELLED, service.stateProperty().get()); - } - - @Test public void exceptionShouldBeNullInRunningState() { - service.start(); - executor.executeScheduled(); - assertNull(service.getException()); - assertNull(service.exceptionProperty().get()); - } - - @Test public void valueShouldBeNullInRunningState() { - service.start(); - executor.executeScheduled(); - assertNull(service.getValue()); - assertNull(service.valueProperty().get()); - } - - @Test public void runningShouldBeTrueInRunningState() { - service.start(); - executor.executeScheduled(); - assertTrue(service.isRunning()); - assertTrue(service.runningProperty().get()); - } - - @Test public void runningPropertyNotificationInRunningState() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.runningProperty().addListener((o, oldValue, newValue) -> passed.set(newValue)); - service.start(); - executor.executeScheduled(); - assertTrue(passed.get()); - } - - @Test public void workDoneShouldBeNegativeOneInitiallyInRunningState() { - service.start(); - executor.executeScheduled(); - assertEquals(-1, service.getWorkDone(), 0); - assertEquals(-1, service.workDoneProperty().get(), 0); - } - - @Test public void workDoneShouldAdvanceTo10() { - service.start(); - executor.executeScheduled(); - task.progress(10, 20); - assertEquals(10, service.getWorkDone(), 0); - assertEquals(10, service.workDoneProperty().get(), 0); - } - - @Test public void workDonePropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.workDoneProperty().addListener((o, oldValue, newValue) -> passed.set(newValue.doubleValue() == 10)); - service.start(); - executor.executeScheduled(); - task.progress(10, 20); - assertTrue(passed.get()); - } - - @Test public void totalWorkShouldBeNegativeOneAtStartOfRunning() { - service.start(); - executor.executeScheduled(); - assertEquals(-1, service.getTotalWork(), 0); - assertEquals(-1, service.totalWorkProperty().get(), 0); - } - - @Test public void totalWorkShouldBeTwenty() { - service.start(); - executor.executeScheduled(); - task.progress(10, 20); - assertEquals(20, service.getTotalWork(), 0); - assertEquals(20, service.totalWorkProperty().get(), 0); - } - - @Test public void totalWorkPropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.totalWorkProperty().addListener((o, oldValue, newValue) -> passed.set(newValue.doubleValue() == 20)); - service.start(); - executor.executeScheduled(); - task.progress(10, 20); - assertTrue(passed.get()); - } - - @Test public void progressShouldBeNegativeOneAtStartOfRunningState() { - service.start(); - executor.executeScheduled(); - assertEquals(-1, service.getProgress(), 0); - assertEquals(-1, task.progressProperty().get(), 0); - } - - @Test public void afterRunningProgressShouldBe_FiftyPercent() { - service.start(); - executor.executeScheduled(); - task.progress(10, 20); - assertEquals(.5, service.getProgress(), 0); - assertEquals(.5, task.progressProperty().get(), 0); - } - - @Test public void progressPropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.start(); - task.progressProperty().addListener((o, oldValue, newValue) -> passed.set(newValue.doubleValue() == .5)); - executor.executeScheduled(); - task.progress(10, 20); - assertTrue(passed.get()); - } - - @Test public void messageShouldBeEmptyStringWhenEnteringRunningState() { - service.start(); - executor.executeScheduled(); - assertEquals("", service.getMessage()); - assertEquals("", task.messageProperty().get()); - } - - @Test public void messageShouldBeLastSetValue() { - service.start(); - executor.executeScheduled(); - task.message("Running"); - assertEquals("Running", service.getMessage()); - assertEquals("Running", task.messageProperty().get()); - } - - @Test public void messagePropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.start(); - task.messageProperty().addListener((o, oldValue, newValue) -> passed.set("Running".equals(service.getMessage()))); - executor.executeScheduled(); - task.message("Running"); - assertTrue(passed.get()); - } - - @Test public void titleShouldBeEmptyStringAtStartOfRunningState() { - service.start(); - executor.executeScheduled(); - assertEquals("", service.getTitle()); - assertEquals("", task.titleProperty().get()); - } - - @Test public void titleShouldBeLastSetValue() { - service.start(); - executor.executeScheduled(); - task.title("Title"); - assertEquals("Title", service.getTitle()); - assertEquals("Title", task.titleProperty().get()); - } - - @Test public void titlePropertyNotification() { - final AtomicBoolean passed = new AtomicBoolean(false); - service.start(); - task.titleProperty().addListener((o, oldValue, newValue) -> passed.set("Title".equals(service.getTitle()))); - executor.executeScheduled(); - task.title("Title"); - assertTrue(passed.get()); - } - - /************************************************************************ - * Throw an exception in the running state * - ***********************************************************************/ - - @Test(expected = IllegalStateException.class) - public void callingStartInFailedStateIsISE() { - service.start(); - executor.executeScheduled(); - task.fail(new Exception("anything")); - service.start(); - } - - @Test public void callingResetInFailedStateResetsStateToREADY() { - service.start(); - executor.executeScheduled(); - task.fail(new Exception("anything")); - service.reset(); - - assertSame(Worker.State.READY, service.getState()); - assertSame(Worker.State.READY, service.stateProperty().get()); - } - - @Test public void callingResetInFailedStateResetsValueToNull() { - service.start(); - executor.executeScheduled(); - task.fail(new Exception("anything")); - service.reset(); - - assertNull(service.getValue()); - assertNull(service.valueProperty().get()); - } - - @Test public void callingResetInFailedStateResetsExceptionToNull() { - service.start(); - executor.executeScheduled(); - task.fail(new Exception("anything")); - service.reset(); - - assertNull(service.getException()); - assertNull(service.exceptionProperty().get()); - } - - @Test public void callingResetInFailedStateResetsWorkDoneToNegativeOne() { - service.start(); - executor.executeScheduled(); - task.progress(10, 20); - task.fail(new Exception("anything")); - service.reset(); - - assertEquals(-1, service.getWorkDone(), 0); - assertEquals(-1, service.workDoneProperty().get(), 0); - } - - @Test public void callingResetInFailedStateResetsTotalWorkToNegativeOne() { - service.start(); - executor.executeScheduled(); - task.progress(10, 20); - task.fail(new Exception("anything")); - service.reset(); - - assertEquals(-1, service.getTotalWork(), 0); - assertEquals(-1, service.totalWorkProperty().get(), 0); - } - - @Test public void callingResetInFailedStateResetsProgressToNegativeOne() { - service.start(); - executor.executeScheduled(); - task.progress(10, 20); - task.fail(new Exception("anything")); - service.reset(); - - assertEquals(-1, service.getProgress(), 0); - assertEquals(-1, service.progressProperty().get(), 0); - } - - @Test public void callingResetInFailedStateResetsRunningToFalse() { - service.start(); - executor.executeScheduled(); - task.fail(new Exception("anything")); - service.reset(); - - assertFalse(service.isRunning()); - assertFalse(service.runningProperty().get()); - } - - @Test public void callingResetInFailedStateResetsMessageToEmptyString() { - service.start(); - executor.executeScheduled(); - task.message("Message"); - task.fail(new Exception("anything")); - service.reset(); - - assertEquals("", service.getMessage()); - assertEquals("", service.messageProperty().get()); - } - - @Test public void callingResetInFailedStateResetsTitleToEmptyString() { - service.start(); - executor.executeScheduled(); - task.title("Title"); - task.fail(new Exception("anything")); - service.reset(); - - assertEquals("", service.getTitle()); - assertEquals("", service.titleProperty().get()); - } - - @Test public void callingRestartInFailedStateReschedules() { - service.start(); - executor.executeScheduled(); - task.fail(new Exception("anything")); - service.restart(); - assertSame(Worker.State.SCHEDULED, service.getState()); - assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); - } - - @Test public void callingCancelInFailedStateResultsInNoChange() { - service.start(); - executor.executeScheduled(); - task.fail(new Exception("anything")); - service.cancel(); - assertSame(Worker.State.FAILED, service.getState()); - assertSame(Worker.State.FAILED, service.stateProperty().get()); - } - - /************************************************************************ - * Proper Completion of a task * - ***********************************************************************/ - - @Test(expected = IllegalStateException.class) - public void callingStartInSucceededStateIsISE() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.start(); - } - - @Test public void callingResetInSucceededStateResetsStateToREADY() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.reset(); - - assertSame(Worker.State.READY, service.getState()); - assertSame(Worker.State.READY, service.stateProperty().get()); - } - - @Test public void callingResetInSucceededStateResetsValueToNull() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.reset(); - - assertNull(service.getValue()); - assertNull(service.valueProperty().get()); - } - - @Test public void callingResetInSucceededStateResetsExceptionToNull() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.reset(); - - assertNull(service.getException()); - assertNull(service.exceptionProperty().get()); - } - - @Test public void callingResetInSucceededStateResetsWorkDoneToNegativeOne() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.reset(); - - assertEquals(-1, service.getWorkDone(), 0); - assertEquals(-1, service.workDoneProperty().get(), 0); - } - - @Test public void callingResetInSucceededStateResetsTotalWorkToNegativeOne() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.reset(); - - assertEquals(-1, service.getTotalWork(), 0); - assertEquals(-1, service.totalWorkProperty().get(), 0); - } - - @Test public void callingResetInSucceededStateResetsProgressToNegativeOne() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.reset(); - - assertEquals(-1, service.getProgress(), 0); - assertEquals(-1, service.progressProperty().get(), 0); - } - - @Test public void callingResetInSucceededStateResetsRunningToFalse() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.reset(); - - assertFalse(service.isRunning()); - assertFalse(service.runningProperty().get()); - } - - @Test public void callingResetInSucceededStateResetsMessageToEmptyString() { - service.start(); - executor.executeScheduled(); - task.message("Message"); - task.progress(20, 20); - task.complete(); - service.reset(); - - assertEquals("", service.getMessage()); - assertEquals("", service.messageProperty().get()); - } - - @Test public void callingResetInSucceededStateResetsTitleToEmptyString() { - service.start(); - executor.executeScheduled(); - task.title("Title"); - task.progress(20, 20); - task.complete(); - service.reset(); - - assertEquals("", service.getTitle()); - assertEquals("", service.titleProperty().get()); - } - - @Test public void callingRestartInSucceededStateReschedules() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.restart(); - assertSame(Worker.State.SCHEDULED, service.getState()); - assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); - } - - @Test public void callingCancelInSucceededStateResultsInNoChange() { - service.start(); - executor.executeScheduled(); - task.progress(20, 20); - task.complete(); - service.cancel(); - assertSame(Worker.State.SUCCEEDED, service.getState()); - assertSame(Worker.State.SUCCEEDED, service.stateProperty().get()); - } - - /*************************************************************************** - * * - * Tests for onReady * - * * - **************************************************************************/ - - @Test public void onReadyPropertyNameShouldMatchMethodName() { - assertEquals("onReady", service.onReadyProperty().getName()); - } - - @Test public void onReadyBeanShouldMatchService() { - assertSame(service, service.onReadyProperty().getBean()); - } - - @Test public void onReadyIsInitializedToNull() { - assertNull(service.getOnReady()); - assertNull(service.onReadyProperty().get()); - } - - @Test public void onReadyFilterCalledBefore_onReady() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - service.start(); - executor.executeScheduled(); - task.complete(); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> filterCalled.set(true)); - service.setOnReady(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - // Transition to Ready state - service.reset(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void onReadyHandlerCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.start(); - executor.executeScheduled(); - task.complete(); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> handlerCalled.set(true)); - - // Transition to Ready state - service.reset(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void removed_onReadyHandlerNotCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - service.start(); - executor.executeScheduled(); - task.complete(); - EventHandler handler = workerStateEvent -> handlerCalled.set(true); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_READY, handler); - service.removeEventHandler(WorkerStateEvent.WORKER_STATE_READY, handler); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> sanity.set(true)); - - service.reset(); - assertTrue(sanity.get()); - assertFalse(handlerCalled.get()); - } - - @Test public void removed_onReadyFilterNotCalled() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - service.start(); - executor.executeScheduled(); - task.complete(); - EventHandler filter = workerStateEvent -> filterCalled.set(true); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_READY, filter); - service.removeEventFilter(WorkerStateEvent.WORKER_STATE_READY, filter); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> sanity.set(true)); - - service.reset(); - assertTrue(sanity.get()); - assertFalse(filterCalled.get()); - } - - @Test public void cancelCalledFromOnReady() { - final AtomicInteger cancelNotificationCount = new AtomicInteger(); - service.start(); - executor.executeScheduled(); - task.complete(); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> { - service.cancel(); - }); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { - cancelNotificationCount.incrementAndGet(); - }); - - service.reset(); - assertEquals(Worker.State.CANCELLED, service.getState()); - assertEquals(1, cancelNotificationCount.get()); - } - - /*************************************************************************** - * * - * Tests for onScheduled * - * * - **************************************************************************/ - - @Test public void onScheduledPropertyNameShouldMatchMethodName() { - assertEquals("onScheduled", service.onScheduledProperty().getName()); - } - - @Test public void onScheduledBeanShouldMatchService() { - assertSame(service, service.onScheduledProperty().getBean()); - } - - @Test public void onScheduledIsInitializedToNull() { - assertNull(service.getOnScheduled()); - assertNull(service.onScheduledProperty().get()); - } - - @Test public void onScheduledFilterCalledBefore_onScheduled() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> filterCalled.set(true)); - service.setOnScheduled(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - // Transition to Scheduled state - service.start(); - executor.executeScheduled(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void scheduledCalledAfterHandler() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnScheduled(workerStateEvent -> handlerCalled.set(true)); - - // Transition to Scheduled state - service.start(); - executor.executeScheduled(); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().scheduledSemaphore.getQueueLength() == 0); - } - - @Test public void scheduledCalledAfterHandlerEvenIfConsumed() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnScheduled(workerStateEvent -> { - handlerCalled.set(true); - workerStateEvent.consume(); - }); - - // Transition to Scheduled state - service.start(); - executor.executeScheduled(); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().scheduledSemaphore.getQueueLength() == 0); - } - - @Test public void onScheduledHandlerCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> handlerCalled.set(true)); - - service.start(); - executor.executeScheduled(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void removed_onScheduledHandlerNotCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler handler = workerStateEvent -> handlerCalled.set(true); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, handler); - service.removeEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, handler); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - assertTrue(sanity.get()); - assertFalse(handlerCalled.get()); - } - - @Test public void removed_onScheduledFilterNotCalled() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler filter = workerStateEvent -> filterCalled.set(true); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, filter); - service.removeEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, filter); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - assertTrue(sanity.get()); - assertFalse(filterCalled.get()); - } - - @Test public void cancelCalledFromOnScheduled() { - final AtomicInteger cancelNotificationCount = new AtomicInteger(); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> { - service.cancel(); - }); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { - cancelNotificationCount.incrementAndGet(); - }); - - service.start(); - executor.executeScheduled(); - assertEquals(Worker.State.CANCELLED, service.getState()); - assertEquals(1, cancelNotificationCount.get()); - } - - /*************************************************************************** - * * - * Tests for onRunning * - * * - **************************************************************************/ - - @Test public void onRunningPropertyNameShouldMatchMethodName() { - assertEquals("onRunning", service.onRunningProperty().getName()); - } - - @Test public void onRunningBeanShouldMatchService() { - assertSame(service, service.onRunningProperty().getBean()); - } - - @Test public void onRunningIsInitializedToNull() { - assertNull(service.getOnRunning()); - assertNull(service.onRunningProperty().get()); - } - - @Test public void onRunningFilterCalledBefore_onRunning() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> filterCalled.set(true)); - service.setOnRunning(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - // Transition to Running state - service.start(); - executor.executeScheduled(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void runningCalledAfterHandler() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnRunning(workerStateEvent -> handlerCalled.set(true)); - - // Transition to Running state - service.start(); - executor.executeScheduled(); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().runningSemaphore.getQueueLength() == 0); - } - - @Test public void runningCalledAfterHandlerEvenIfConsumed() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnRunning(workerStateEvent -> { - handlerCalled.set(true); - workerStateEvent.consume(); - }); - - // Transition to Running state - service.start(); - executor.executeScheduled(); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().runningSemaphore.getQueueLength() == 0); - } - - @Test public void onRunningHandlerCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> handlerCalled.set(true)); - - service.start(); - executor.executeScheduled(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void removed_onRunningHandlerNotCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler handler = workerStateEvent -> handlerCalled.set(true); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_RUNNING, handler); - service.removeEventHandler(WorkerStateEvent.WORKER_STATE_RUNNING, handler); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - assertTrue(sanity.get()); - assertFalse(handlerCalled.get()); - } - - @Test public void removed_onRunningFilterNotCalled() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler filter = workerStateEvent -> filterCalled.set(true); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, filter); - service.removeEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, filter); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - assertTrue(sanity.get()); - assertFalse(filterCalled.get()); - } - - @Test public void cancelCalledFromOnRunning() { - final AtomicInteger cancelNotificationCount = new AtomicInteger(); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> { - service.cancel(); - }); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { - cancelNotificationCount.incrementAndGet(); - }); - - service.start(); - executor.executeScheduled(); - assertEquals(Worker.State.CANCELLED, service.getState()); - assertEquals(1, cancelNotificationCount.get()); - } - - /*************************************************************************** - * * - * Tests for onSucceeded * - * * - **************************************************************************/ - - @Test public void onSucceededPropertyNameShouldMatchMethodName() { - assertEquals("onSucceeded", service.onSucceededProperty().getName()); - } - - @Test public void onSucceededBeanShouldMatchService() { - assertSame(service, service.onSucceededProperty().getBean()); - } - - @Test public void onSucceededIsInitializedToNull() { - assertNull(service.getOnSucceeded()); - assertNull(service.onSucceededProperty().get()); - } - - @Test public void onSucceededFilterCalledBefore_onSucceeded() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> filterCalled.set(true)); - service.setOnSucceeded(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - // Transition to Succeeded state - service.start(); - executor.executeScheduled(); - task.complete(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void succeededCalledAfterHandler() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnSucceeded(workerStateEvent -> handlerCalled.set(true)); - - // Transition to Succeeded state - service.start(); - executor.executeScheduled(); - task.complete(); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().succeededSemaphore.getQueueLength() == 0); - } - - @Test public void succeededCalledAfterHandlerEvenIfConsumed() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnSucceeded(workerStateEvent -> { - handlerCalled.set(true); - workerStateEvent.consume(); - }); - - // Transition to Succeeded state - service.start(); - executor.executeScheduled(); - task.complete(); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().succeededSemaphore.getQueueLength() == 0); - } - - @Test public void onSucceededHandlerCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> handlerCalled.set(true)); - - service.start(); - executor.executeScheduled(); - task.complete(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void removed_onSucceededHandlerNotCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler handler = workerStateEvent -> handlerCalled.set(true); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, handler); - service.removeEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, handler); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - task.complete(); - assertTrue(sanity.get()); - assertFalse(handlerCalled.get()); - } - - @Test public void removed_onSucceededFilterNotCalled() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler filter = workerStateEvent -> filterCalled.set(true); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, filter); - service.removeEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, filter); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - task.complete(); - } - - @Test public void cancelCalledFromOnSucceeded() { - final AtomicInteger cancelNotificationCount = new AtomicInteger(); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> { - service.cancel(); - }); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { - cancelNotificationCount.incrementAndGet(); - }); - - service.start(); - executor.executeScheduled(); - task.complete(); - assertEquals(Worker.State.SUCCEEDED, service.getState()); - assertEquals(0, cancelNotificationCount.get()); - } - - /*************************************************************************** - * * - * Tests for onCancelled * - * * - **************************************************************************/ - - @Test public void onCancelledPropertyNameShouldMatchMethodName() { - assertEquals("onCancelled", service.onCancelledProperty().getName()); - } - - @Test public void onCancelledBeanShouldMatchService() { - assertSame(service, service.onCancelledProperty().getBean()); - } - - @Test public void onCancelledIsInitializedToNull() { - assertNull(service.getOnCancelled()); - assertNull(service.onCancelledProperty().get()); - } - - @Test public void onCancelledFilterCalledBefore_onCancelled() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> filterCalled.set(true)); - service.setOnCancelled(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - // Transition to Cancelled state - service.start(); - executor.executeScheduled(); - task.cancel(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void cancelledCalledAfterHandler() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnCancelled(workerStateEvent -> handlerCalled.set(true)); - - // Transition to Cancelled state - service.start(); - executor.executeScheduled(); - task.cancel(); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().cancelledSemaphore.getQueueLength() == 0); - } - - @Test public void cancelledCalledAfterHandlerEvenIfConsumed() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnCancelled(workerStateEvent -> { - handlerCalled.set(true); - workerStateEvent.consume(); - }); - - // Transition to Cancelled state - service.start(); - executor.executeScheduled(); - task.cancel(); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().cancelledSemaphore.getQueueLength() == 0); - } - - @Test public void onCancelledHandlerCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> handlerCalled.set(true)); - - service.start(); - executor.executeScheduled(); - task.cancel(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void removed_onCancelledHandlerNotCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler handler = workerStateEvent -> handlerCalled.set(true); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, handler); - service.removeEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, handler); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - task.cancel(); - assertTrue(sanity.get()); - assertFalse(handlerCalled.get()); - } - - @Test public void removed_onCancelledFilterNotCalled() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler filter = workerStateEvent -> filterCalled.set(true); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, filter); - service.removeEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, filter); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - task.cancel(); - assertTrue(sanity.get()); - assertFalse(filterCalled.get()); - } - - @Test public void cancelCalledFromOnCancelled() { - final AtomicInteger cancelNotificationCount = new AtomicInteger(); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> { - service.cancel(); - }); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { - cancelNotificationCount.incrementAndGet(); - }); - - service.start(); - executor.executeScheduled(); - task.cancel(); - assertEquals(Worker.State.CANCELLED, service.getState()); - assertEquals(1, cancelNotificationCount.get()); - } - - @Test public void cancelCalledFromOnFailed() { - final AtomicInteger cancelNotificationCount = new AtomicInteger(); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> { - service.cancel(); - }); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { - cancelNotificationCount.incrementAndGet(); - }); - - service.start(); - executor.executeScheduled(); - task.fail(new Exception("Quit")); - assertEquals(Worker.State.FAILED, service.getState()); - assertEquals(0, cancelNotificationCount.get()); - } - - /*************************************************************************** - * * - * Tests for onFailed * - * * - **************************************************************************/ - - @Test public void onFailedPropertyNameShouldMatchMethodName() { - assertEquals("onFailed", service.onFailedProperty().getName()); - } - - @Test public void onFailedBeanShouldMatchService() { - assertSame(service, service.onFailedProperty().getBean()); - } - - @Test public void onFailedIsInitializedToNull() { - assertNull(service.getOnFailed()); - assertNull(service.onFailedProperty().get()); - } - - @Test public void onFailedFilterCalledBefore_onFailed() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> filterCalled.set(true)); - service.setOnFailed(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - // Transition to Succeeded state - service.start(); - executor.executeScheduled(); - task.fail(new Exception("The End")); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void failedCalledAfterHandler() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnFailed(workerStateEvent -> handlerCalled.set(true)); - - // Transition to Succeeded state - service.start(); - executor.executeScheduled(); - task.fail(new Exception("Quit Now")); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().failedSemaphore.getQueueLength() == 0); - } - - @Test public void failedCalledAfterHandlerEvenIfConsumed() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.setOnFailed(workerStateEvent -> handlerCalled.set(true)); - - // Transition to Succeeded state - service.start(); - executor.executeScheduled(); - task.fail(new Exception("Quit Now")); - // Events should have happened - assertTrue(handlerCalled.get() && factory.getCurrentTask().failedSemaphore.getQueueLength() == 0); - } - - @Test public void onFailedHandlerCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> handlerCalled.set(true)); - - service.start(); - executor.executeScheduled(); - task.fail(new Exception("Forget about it")); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void removed_onFailedHandlerNotCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler handler = workerStateEvent -> handlerCalled.set(true); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, handler); - service.removeEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, handler); - service.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - task.fail(new Exception("Quit")); - assertTrue(sanity.get()); - assertFalse(handlerCalled.get()); - } - - @Test public void removed_onFailedFilterNotCalled() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - EventHandler filter = workerStateEvent -> filterCalled.set(true); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, filter); - service.removeEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, filter); - service.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> sanity.set(true)); - - service.start(); - executor.executeScheduled(); - task.fail(new Exception("Quit")); - assertTrue(sanity.get()); - assertFalse(filterCalled.get()); - } - - /*************************************************************************** - * * - * Tests that invoking methods from the wrong thread leads to errors, and * - * that regardless of which thread starts the Service, all notification * - * (events, etc) happen on the FX thread only. * - * * - **************************************************************************/ - - @Test public void canCreateServiceOnRandomThread() { - RandomThread random = new RandomThread(() -> { - DoNothingService s = null; - try { - s = new DoNothingService(); - } finally { - if (s != null) s.shutdown(); - } - }); - random.test(); - } - - @Test public void canGetReferencesToPropertiesOnRandomThread() { - RandomThread random = new RandomThread(() -> { - DoNothingService s = null; - try { - s = new DoNothingService(); - s.exceptionProperty(); - s.executorProperty(); - s.messageProperty(); - s.progressProperty(); - s.onCancelledProperty(); - s.onFailedProperty(); - s.onReadyProperty(); - s.onRunningProperty(); - s.onScheduledProperty(); - s.onSucceededProperty(); - s.runningProperty(); - s.stateProperty(); - s.titleProperty(); - s.totalWorkProperty(); - s.valueProperty(); - s.workDoneProperty(); - } finally { - if (s != null) s.shutdown(); - } - }); - random.test(); - } - - @Test public void canInvokeGettersOnRandomThread() { - RandomThread random = new RandomThread(() -> { - DoNothingService s = null; - try { - s = new DoNothingService(); - s.getException(); - s.getExecutor(); - s.getMessage(); - s.getProgress(); - s.getOnCancelled(); - s.getOnFailed(); - s.getOnReady(); - s.getOnRunning(); - s.getOnScheduled(); - s.getOnSucceeded(); - s.isRunning(); - s.getState(); - s.getTitle(); - s.getTotalWork(); - s.getValue(); - s.getWorkDone(); - } finally { - if (s != null) s.shutdown(); - } - }); - random.test(); - } - - @Test public void canInvokeSettersOnRandomThread() { - RandomThread random = new RandomThread(() -> { - DoNothingService s = null; - try { - s = new DoNothingService(); - s.setEventHandler(WorkerStateEvent.ANY, event -> { - }); - s.setOnCancelled(event -> { - }); - s.setOnFailed(event -> { - }); - s.setOnReady(event -> { - }); - s.setOnRunning(event -> { - }); - s.setOnScheduled(event -> { - }); - s.setOnSucceeded(event -> { - }); - } finally { - if (s != null) s.shutdown(); - } - }); - random.test(); - } - - @Test public void canInvokeStartOnRandomThread() { - RandomThread random = new RandomThread(() -> { - DoNothingService s = null; - try { - s = new DoNothingService(); - s.start(); - } finally { - if (s != null) s.shutdown(); - } - }); - random.test(); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeRestartOnRandomThreadAfterStart() throws Throwable { - assertThrowsException(s -> s.restart()); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeCancelOnRandomThreadAfterStart() throws Throwable { - assertThrowsException(s -> { - s.cancel(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeSettersOnRandomThreadAfterStart_1() throws Throwable { - assertThrowsException(s -> s.setEventHandler(WorkerStateEvent.ANY, event -> { - })); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeSettersOnRandomThreadAfterStart_2() throws Throwable { - assertThrowsException(s -> s.setOnCancelled(event -> { - })); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeSettersOnRandomThreadAfterStart_3() throws Throwable { - assertThrowsException(s -> s.setOnFailed(event -> { })); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeSettersOnRandomThreadAfterStart_4() throws Throwable { - assertThrowsException(s -> s.setOnReady(event -> { })); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeSettersOnRandomThreadAfterStart_5() throws Throwable { - assertThrowsException(s -> s.setOnRunning(event -> { })); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeSettersOnRandomThreadAfterStart_6() throws Throwable { - assertThrowsException(s -> s.setOnScheduled(event -> { - })); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeSettersOnRandomThreadAfterStart_7() throws Throwable { - assertThrowsException(s -> s.setOnSucceeded(event -> { })); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_1() throws Throwable { - assertThrowsException(s -> { - s.getException(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_2() throws Throwable { - assertThrowsException(s -> { - s.getExecutor(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_3() throws Throwable { - assertThrowsException(s -> { - s.getMessage(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_4() throws Throwable { - assertThrowsException(s -> { - s.getProgress(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_5() throws Throwable { - assertThrowsException(s -> { - s.getOnCancelled(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_6() throws Throwable { - assertThrowsException(s -> { - s.getOnFailed(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_7() throws Throwable { - assertThrowsException(s -> { - s.getOnReady(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_8() throws Throwable { - assertThrowsException(s -> { - s.getOnRunning(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_9() throws Throwable { - assertThrowsException(s -> { - s.getOnScheduled(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_10() throws Throwable { - assertThrowsException(s -> { - s.getOnSucceeded(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_11() throws Throwable { - assertThrowsException(s -> { - s.isRunning(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_12() throws Throwable { - assertThrowsException(s -> { - s.getState(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_13() throws Throwable { - assertThrowsException(s -> { - s.getTitle(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_14() throws Throwable { - assertThrowsException(s -> { - s.getTotalWork(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_15() throws Throwable { - assertThrowsException(s -> { - s.getValue(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokeGettersOnRandomThreadAfterStart_16() throws Throwable { - assertThrowsException(s -> { - s.getValue(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_1() throws Throwable { - assertThrowsException(s -> { - s.exceptionProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_2() throws Throwable { - assertThrowsException(s -> { - s.executorProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_3() throws Throwable { - assertThrowsException(s -> { - s.messageProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_4() throws Throwable { - assertThrowsException(s -> { - s.progressProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_5() throws Throwable { - assertThrowsException(s -> { - s.onCancelledProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_6() throws Throwable { - assertThrowsException(s -> { - s.onFailedProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_7() throws Throwable { - assertThrowsException(s -> { - s.onReadyProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_8() throws Throwable { - assertThrowsException(s -> { - s.onRunningProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_9() throws Throwable { - assertThrowsException(s -> { - s.onScheduledProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_10() throws Throwable { - assertThrowsException(s -> { - s.onSucceededProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_11() throws Throwable { - assertThrowsException(s -> { - s.runningProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_12() throws Throwable { - assertThrowsException(s -> { - s.stateProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_13() throws Throwable { - assertThrowsException(s -> { - s.titleProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_14() throws Throwable { - assertThrowsException(s -> { - s.totalWorkProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_15() throws Throwable { - assertThrowsException(s -> { - s.valueProperty(); - }); - } - - @Test (expected = IllegalStateException.class) - public void cannotInvokePropertyGettersOnRandomThreadAfterStart_16() throws Throwable { - assertThrowsException(s -> { - s.workDoneProperty(); - }); - } - - private void assertThrowsException(final ServiceTestExecution c) throws Throwable { - RandomThread random = new RandomThread(() -> { - DoNothingService s = null; - try { - s = new DoNothingService(); - s.start(); - c.test(s); - } finally { - if (s != null) s.shutdown(); - } - }); - - try { - random.test(); - } catch (AssertionError er) { - throw er.getCause(); - } - } - - private interface ServiceTestExecution { - public void test(DoNothingService s); - } - - /** - * Specialized thread used for checking access to various methods from a "random thread" other - * than the FX thread. This class has built into it all the supported needed for handling - * exceptions and so forth, such that assertion errors are raised if an exception occurs - * on the thread, and also handles blocking until the thread body concludes. - */ - private static final class RandomThread extends Thread { - private final CountDownLatch testCompleted = new CountDownLatch(1); - private Throwable error; - - public RandomThread(Runnable target) { - super(target); - } - - @Override public void run() { - try { - super.run(); - } catch (Throwable th) { - error = th; - } finally { - testCompleted.countDown(); - } - } - - public void test() throws AssertionError { - start(); - try { - testCompleted.await(); - } catch (InterruptedException e) { - throw new AssertionError("Test did not complete normally"); - } - if (error != null) { - throw new AssertionError(error); - } - } - } - - /** - * A service which does absolutely nothing and isn't hardwired to believe that - * the test thread is the FX thread (unlike the other services in these tests) - */ - private static final class DoNothingService extends Service { - private Thread pretendFXThread; - private ConcurrentLinkedQueue eventQueue = new ConcurrentLinkedQueue<>(); - private volatile boolean shutdown = false; - - public DoNothingService() { - setExecutor(command -> { - Thread backgroundThread = new Thread(command); - backgroundThread.start(); - }); - } - - void shutdown() { - shutdown = true; - } - - @Override protected Task createTask() { - return new Task() { - @Override protected Object call() throws Exception { - return null; - } - - @Override boolean isFxApplicationThread() { - return Thread.currentThread() == pretendFXThread; - } - - @Override - void runLater(Runnable r) { - DoNothingService.this.runLater(r); - } - }; - } - - @Override void runLater(Runnable r) { - eventQueue.add(r); - if (pretendFXThread == null) { - pretendFXThread = new Thread() { - @Override public void run() { - while (!shutdown) { - Runnable event = eventQueue.poll(); - if (event != null) { - event.run(); - } - } - } - }; - pretendFXThread.start(); - } - } - - @Override boolean isFxApplicationThread() { - return Thread.currentThread() == pretendFXThread; - } - } - - /*************************************************************************** - * * - * A mythical subclass should be able to set an event handler and * - * have events fired on the Service work. * - * * - **************************************************************************/ - - @Test public void eventFiredOnSubclassWorks() { - final AtomicBoolean result = new AtomicBoolean(false); - TestServiceFactory factory = new TestServiceFactory() { - @Override protected AbstractTask createTestTask() { - return new SimpleTask(); - } - - @Override protected Service createService() { - MythicalService svc = new MythicalService(); - svc.setHandler(mythicalEvent -> result.set(true)); - svc.fireEvent(new MythicalEvent()); - return svc; - } - }; - Service svc = factory.createService(); - svc.start(); - assertTrue(result.get()); - } - - private static final class MythicalService extends Service { - public void setHandler(EventHandler h) { - super.setEventHandler(MythicalEvent.ANY, h); - } - - @Override protected Task createTask() { - return new SimpleTask(); - } - - @Override void checkThread() { } - - @Override void runLater(Runnable r) { - r.run(); - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/ServiceLifecycleTest.java 2015-09-11 21:25:33.905286209 -0400 @@ -0,0 +1,1962 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import com.sun.org.apache.xerces.internal.util.DOMUtil; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import test.javafx.concurrent.mocks.MythicalEvent; +import test.javafx.concurrent.mocks.SimpleTask; +import javafx.event.Event; +import javafx.event.EventHandler; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javafx.concurrent.Service; +import javafx.concurrent.ServiceShim; +import javafx.concurrent.Task; +import javafx.concurrent.TaskShim; +import javafx.concurrent.Worker; +import javafx.concurrent.WorkerStateEvent; +import javafx.event.EventType; +import org.junit.After; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + * Tests various rules regarding the lifecycle of a Service. + */ +public class ServiceLifecycleTest extends ServiceTestBase { + /** + * The ManualExecutor is used so that there is some time period between + * when something is scheduled and when it actually runs, such that the + * test code has to manually tell it that it can now run. + */ + protected ManualExecutor executor; + + /** + * The task to run, which has methods on it to allow me to manually + * put it into a passing, failed, or whatnot state. + */ + protected ManualTask task; + + @Override protected TestServiceFactory setupServiceFactory() { + return new TestServiceFactory() { + @Override public AbstractTask createTestTask() { + return task = new ManualTask(); + } + }; + } + + @Override protected Executor createExecutor() { + return executor = new ManualExecutor(super.createExecutor()); + } + + @After public void tearDown() { + if (task != null) task.finish.set(true); + } + + /** + * This class will schedule the task, and then you can execute + * it manually by calling executeScheduled. In this way I can + * test when a Service is scheduled but not yet started. + */ + protected final class ManualExecutor implements Executor { + private Runnable scheduled; + private Executor wrapped; + + ManualExecutor(Executor wrapped) { + this.wrapped = wrapped; + } + + @Override public void execute(Runnable command) { + this.scheduled = command; + } + + public void executeScheduled() { + wrapped.execute(scheduled); + // I need to wait until the next "Sentinel" runnable + // on the queue, which the Task will post when it begins + // execution. + handleEvents(); + } + } + + protected final class ManualTask extends AbstractTask { + private AtomicBoolean finish = new AtomicBoolean(false); + private AtomicReference exception = new AtomicReference<>(); + private boolean failToCancel = false; + + @Override protected String call() throws Exception { + runLater(new Sentinel()); + while (!finish.get()) { + Exception e = exception.get(); + if (e != null) throw e; + } + return "Done"; + } + + public void progress(long done, long max) { + updateProgress(done, max); + } + + public void message(String msg) { + updateMessage(msg); + } + + public void title(String t) { + updateTitle(t); + } + + public void fail(Exception e) { + exception.set(e); + handleEvents(); + } + + public void complete() { + finish.set(true); + handleEvents(); + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + boolean result = failToCancel ? false : super.cancel(mayInterruptIfRunning); + finish.set(true); + return result; + } + } + + /************************************************************************ + * Tests while in the ready state * + ***********************************************************************/ + + @Test public void callingStartInReadyStateSchedulesJob() { + assertNull(executor.scheduled); + service.start(); + assertNotNull(executor.scheduled); + } + + @Test public void callingStartInReadyMovesToScheduledState() { + service.start(); + assertSame(Worker.State.SCHEDULED, service.getState()); + assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); + } + + @Test public void callingRestartInReadyStateSchedulesJob() { + assertNull(executor.scheduled); + service.restart(); + assertNotNull(executor.scheduled); + } + + @Test public void callingRestartInReadyMovesToScheduledState() { + service.restart(); + assertSame(Worker.State.SCHEDULED, service.getState()); + assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); + } + + @Test public void callingCancelInReadyStateMovesToCancelledState() { + service.cancel(); + assertSame(Worker.State.CANCELLED, service.getState()); + assertSame(Worker.State.CANCELLED, service.stateProperty().get()); + } + + @Test public void callingResetInReadyStateHasNoEffect() { + service.reset(); + assertSame(Worker.State.READY, service.getState()); + assertSame(Worker.State.READY, service.stateProperty().get()); + } + + /************************************************************************ + * Tests while in the scheduled state * + ***********************************************************************/ + + @Test(expected = IllegalStateException.class) + public void callingStartInScheduledStateIsISE() { + service.start(); + service.start(); + } + + @Test public void callingCancelInScheduledStateResultsInCancelledState() { + service.start(); + service.cancel(); + assertSame(Worker.State.CANCELLED, service.getState()); + assertSame(Worker.State.CANCELLED, service.stateProperty().get()); + } + + @Test public void callingRestartInScheduledStateShouldCancelAndReschedule() { + service.start(); + service.restart(); + assertSame(Worker.State.SCHEDULED, service.getState()); + assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); + } + + /** + * This test differs from callingRestartInScheduledStateShouldCancelAndReschedule + * in that under some circumstances, the cancel operation on a task may yield + * a task which is not marked as CANCELLED, such as when it is already run + * or cancelled). In such a case, the bindings have not fired yet and the + * state of the service is off. At least, that is what is happening with + * RT-20880. The fix allows this test to pass. + */ + @Test public void callingRestartInScheduledStateShouldCancelAndReschedule_RT_20880() { + service.start(); + task.failToCancel = true; + service.restart(); + assertSame(Worker.State.SCHEDULED, service.getState()); + assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); + } + + @Test(expected = IllegalStateException.class) + public void callingResetInScheduledStateThrowsISE() { + service.start(); + service.reset(); + } + + @Test public void stateChangesToRunningWhenExecutorExecutes() { + service.start(); + executor.executeScheduled(); + assertSame(Worker.State.RUNNING, service.getState()); + assertSame(Worker.State.RUNNING, service.stateProperty().get()); + } + + @Test public void exceptionShouldBeNullInScheduledState() { + service.start(); + assertNull(service.getException()); + assertNull(service.exceptionProperty().get()); + } + + @Test public void valueShouldBeNullInScheduledState() { + service.start(); + assertNull(service.getValue()); + assertNull(service.valueProperty().get()); + } + + @Test public void runningShouldBeTrueInScheduledState() { + service.start(); + assertTrue(service.isRunning()); + assertTrue(service.runningProperty().get()); + } + + @Test public void runningPropertyNotificationInScheduledState() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.runningProperty().addListener((o, oldValue, newValue) -> passed.set(newValue)); + service.start(); + assertTrue(passed.get()); + } + + @Test public void workDoneShouldBeNegativeOneInitiallyInScheduledState() { + service.start(); + assertEquals(-1, service.getWorkDone(), 0); + assertEquals(-1, service.workDoneProperty().get(), 0); + } + + @Test public void totalWorkShouldBeNegativeOneAtStartOfScheduledState() { + service.start(); + assertEquals(-1, service.getTotalWork(), 0); + assertEquals(-1, service.totalWorkProperty().get(), 0); + } + + @Test public void progressShouldBeNegativeOneAtStartOfScheduledState() { + service.start(); + assertEquals(-1, service.getProgress(), 0); + assertEquals(-1, task.progressProperty().get(), 0); + } + + @Test public void messageShouldBeEmptyStringWhenEnteringScheduledState() { + service.start(); + assertEquals("", service.getMessage()); + assertEquals("", task.messageProperty().get()); + } + + @Test public void titleShouldBeEmptyStringAtStartOfScheduledState() { + service.start(); + assertEquals("", service.getTitle()); + assertEquals("", task.titleProperty().get()); + } + + /************************************************************************ + * Tests while in the running state * + ***********************************************************************/ + + @Test(expected = IllegalStateException.class) + public void callingStartInRunningStateIsISE() { + service.start(); + executor.executeScheduled(); + service.start(); + } + + @Test(expected = IllegalStateException.class) + public void callingResetInRunningStateIsISE() { + service.start(); + executor.executeScheduled(); + service.reset(); + } + + @Test public void callingRestartInRunningStateCancelsAndReschedules() { + service.start(); + executor.executeScheduled(); + service.restart(); + assertSame(Worker.State.SCHEDULED, service.getState()); + assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); + } + + @Test public void callingCancelInRunningStateResultsInCancelledState() { + service.start(); + executor.executeScheduled(); + service.cancel(); + assertSame(Worker.State.CANCELLED, service.getState()); + assertSame(Worker.State.CANCELLED, service.stateProperty().get()); + } + + @Test public void exceptionShouldBeNullInRunningState() { + service.start(); + executor.executeScheduled(); + assertNull(service.getException()); + assertNull(service.exceptionProperty().get()); + } + + @Test public void valueShouldBeNullInRunningState() { + service.start(); + executor.executeScheduled(); + assertNull(service.getValue()); + assertNull(service.valueProperty().get()); + } + + @Test public void runningShouldBeTrueInRunningState() { + service.start(); + executor.executeScheduled(); + assertTrue(service.isRunning()); + assertTrue(service.runningProperty().get()); + } + + @Test public void runningPropertyNotificationInRunningState() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.runningProperty().addListener((o, oldValue, newValue) -> passed.set(newValue)); + service.start(); + executor.executeScheduled(); + assertTrue(passed.get()); + } + + @Test public void workDoneShouldBeNegativeOneInitiallyInRunningState() { + service.start(); + executor.executeScheduled(); + assertEquals(-1, service.getWorkDone(), 0); + assertEquals(-1, service.workDoneProperty().get(), 0); + } + + @Test public void workDoneShouldAdvanceTo10() { + service.start(); + executor.executeScheduled(); + task.progress(10, 20); + assertEquals(10, service.getWorkDone(), 0); + assertEquals(10, service.workDoneProperty().get(), 0); + } + + @Test public void workDonePropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.workDoneProperty().addListener((o, oldValue, newValue) -> passed.set(newValue.doubleValue() == 10)); + service.start(); + executor.executeScheduled(); + task.progress(10, 20); + assertTrue(passed.get()); + } + + @Test public void totalWorkShouldBeNegativeOneAtStartOfRunning() { + service.start(); + executor.executeScheduled(); + assertEquals(-1, service.getTotalWork(), 0); + assertEquals(-1, service.totalWorkProperty().get(), 0); + } + + @Test public void totalWorkShouldBeTwenty() { + service.start(); + executor.executeScheduled(); + task.progress(10, 20); + assertEquals(20, service.getTotalWork(), 0); + assertEquals(20, service.totalWorkProperty().get(), 0); + } + + @Test public void totalWorkPropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.totalWorkProperty().addListener((o, oldValue, newValue) -> passed.set(newValue.doubleValue() == 20)); + service.start(); + executor.executeScheduled(); + task.progress(10, 20); + assertTrue(passed.get()); + } + + @Test public void progressShouldBeNegativeOneAtStartOfRunningState() { + service.start(); + executor.executeScheduled(); + assertEquals(-1, service.getProgress(), 0); + assertEquals(-1, task.progressProperty().get(), 0); + } + + @Test public void afterRunningProgressShouldBe_FiftyPercent() { + service.start(); + executor.executeScheduled(); + task.progress(10, 20); + assertEquals(.5, service.getProgress(), 0); + assertEquals(.5, task.progressProperty().get(), 0); + } + + @Test public void progressPropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.start(); + task.progressProperty().addListener((o, oldValue, newValue) -> passed.set(newValue.doubleValue() == .5)); + executor.executeScheduled(); + task.progress(10, 20); + assertTrue(passed.get()); + } + + @Test public void messageShouldBeEmptyStringWhenEnteringRunningState() { + service.start(); + executor.executeScheduled(); + assertEquals("", service.getMessage()); + assertEquals("", task.messageProperty().get()); + } + + @Test public void messageShouldBeLastSetValue() { + service.start(); + executor.executeScheduled(); + task.message("Running"); + assertEquals("Running", service.getMessage()); + assertEquals("Running", task.messageProperty().get()); + } + + @Test public void messagePropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.start(); + task.messageProperty().addListener((o, oldValue, newValue) -> passed.set("Running".equals(service.getMessage()))); + executor.executeScheduled(); + task.message("Running"); + assertTrue(passed.get()); + } + + @Test public void titleShouldBeEmptyStringAtStartOfRunningState() { + service.start(); + executor.executeScheduled(); + assertEquals("", service.getTitle()); + assertEquals("", task.titleProperty().get()); + } + + @Test public void titleShouldBeLastSetValue() { + service.start(); + executor.executeScheduled(); + task.title("Title"); + assertEquals("Title", service.getTitle()); + assertEquals("Title", task.titleProperty().get()); + } + + @Test public void titlePropertyNotification() { + final AtomicBoolean passed = new AtomicBoolean(false); + service.start(); + task.titleProperty().addListener((o, oldValue, newValue) -> passed.set("Title".equals(service.getTitle()))); + executor.executeScheduled(); + task.title("Title"); + assertTrue(passed.get()); + } + + /************************************************************************ + * Throw an exception in the running state * + ***********************************************************************/ + + @Test(expected = IllegalStateException.class) + public void callingStartInFailedStateIsISE() { + service.start(); + executor.executeScheduled(); + task.fail(new Exception("anything")); + service.start(); + } + + @Test public void callingResetInFailedStateResetsStateToREADY() { + service.start(); + executor.executeScheduled(); + task.fail(new Exception("anything")); + service.reset(); + + assertSame(Worker.State.READY, service.getState()); + assertSame(Worker.State.READY, service.stateProperty().get()); + } + + @Test public void callingResetInFailedStateResetsValueToNull() { + service.start(); + executor.executeScheduled(); + task.fail(new Exception("anything")); + service.reset(); + + assertNull(service.getValue()); + assertNull(service.valueProperty().get()); + } + + @Test public void callingResetInFailedStateResetsExceptionToNull() { + service.start(); + executor.executeScheduled(); + task.fail(new Exception("anything")); + service.reset(); + + assertNull(service.getException()); + assertNull(service.exceptionProperty().get()); + } + + @Test public void callingResetInFailedStateResetsWorkDoneToNegativeOne() { + service.start(); + executor.executeScheduled(); + task.progress(10, 20); + task.fail(new Exception("anything")); + service.reset(); + + assertEquals(-1, service.getWorkDone(), 0); + assertEquals(-1, service.workDoneProperty().get(), 0); + } + + @Test public void callingResetInFailedStateResetsTotalWorkToNegativeOne() { + service.start(); + executor.executeScheduled(); + task.progress(10, 20); + task.fail(new Exception("anything")); + service.reset(); + + assertEquals(-1, service.getTotalWork(), 0); + assertEquals(-1, service.totalWorkProperty().get(), 0); + } + + @Test public void callingResetInFailedStateResetsProgressToNegativeOne() { + service.start(); + executor.executeScheduled(); + task.progress(10, 20); + task.fail(new Exception("anything")); + service.reset(); + + assertEquals(-1, service.getProgress(), 0); + assertEquals(-1, service.progressProperty().get(), 0); + } + + @Test public void callingResetInFailedStateResetsRunningToFalse() { + service.start(); + executor.executeScheduled(); + task.fail(new Exception("anything")); + service.reset(); + + assertFalse(service.isRunning()); + assertFalse(service.runningProperty().get()); + } + + @Test public void callingResetInFailedStateResetsMessageToEmptyString() { + service.start(); + executor.executeScheduled(); + task.message("Message"); + task.fail(new Exception("anything")); + service.reset(); + + assertEquals("", service.getMessage()); + assertEquals("", service.messageProperty().get()); + } + + @Test public void callingResetInFailedStateResetsTitleToEmptyString() { + service.start(); + executor.executeScheduled(); + task.title("Title"); + task.fail(new Exception("anything")); + service.reset(); + + assertEquals("", service.getTitle()); + assertEquals("", service.titleProperty().get()); + } + + @Test public void callingRestartInFailedStateReschedules() { + service.start(); + executor.executeScheduled(); + task.fail(new Exception("anything")); + service.restart(); + assertSame(Worker.State.SCHEDULED, service.getState()); + assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); + } + + @Test public void callingCancelInFailedStateResultsInNoChange() { + service.start(); + executor.executeScheduled(); + task.fail(new Exception("anything")); + service.cancel(); + assertSame(Worker.State.FAILED, service.getState()); + assertSame(Worker.State.FAILED, service.stateProperty().get()); + } + + /************************************************************************ + * Proper Completion of a task * + ***********************************************************************/ + + @Test(expected = IllegalStateException.class) + public void callingStartInSucceededStateIsISE() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.start(); + } + + @Test public void callingResetInSucceededStateResetsStateToREADY() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.reset(); + + assertSame(Worker.State.READY, service.getState()); + assertSame(Worker.State.READY, service.stateProperty().get()); + } + + @Test public void callingResetInSucceededStateResetsValueToNull() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.reset(); + + assertNull(service.getValue()); + assertNull(service.valueProperty().get()); + } + + @Test public void callingResetInSucceededStateResetsExceptionToNull() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.reset(); + + assertNull(service.getException()); + assertNull(service.exceptionProperty().get()); + } + + @Test public void callingResetInSucceededStateResetsWorkDoneToNegativeOne() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.reset(); + + assertEquals(-1, service.getWorkDone(), 0); + assertEquals(-1, service.workDoneProperty().get(), 0); + } + + @Test public void callingResetInSucceededStateResetsTotalWorkToNegativeOne() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.reset(); + + assertEquals(-1, service.getTotalWork(), 0); + assertEquals(-1, service.totalWorkProperty().get(), 0); + } + + @Test public void callingResetInSucceededStateResetsProgressToNegativeOne() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.reset(); + + assertEquals(-1, service.getProgress(), 0); + assertEquals(-1, service.progressProperty().get(), 0); + } + + @Test public void callingResetInSucceededStateResetsRunningToFalse() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.reset(); + + assertFalse(service.isRunning()); + assertFalse(service.runningProperty().get()); + } + + @Test public void callingResetInSucceededStateResetsMessageToEmptyString() { + service.start(); + executor.executeScheduled(); + task.message("Message"); + task.progress(20, 20); + task.complete(); + service.reset(); + + assertEquals("", service.getMessage()); + assertEquals("", service.messageProperty().get()); + } + + @Test public void callingResetInSucceededStateResetsTitleToEmptyString() { + service.start(); + executor.executeScheduled(); + task.title("Title"); + task.progress(20, 20); + task.complete(); + service.reset(); + + assertEquals("", service.getTitle()); + assertEquals("", service.titleProperty().get()); + } + + @Test public void callingRestartInSucceededStateReschedules() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.restart(); + assertSame(Worker.State.SCHEDULED, service.getState()); + assertSame(Worker.State.SCHEDULED, service.stateProperty().get()); + } + + @Test public void callingCancelInSucceededStateResultsInNoChange() { + service.start(); + executor.executeScheduled(); + task.progress(20, 20); + task.complete(); + service.cancel(); + assertSame(Worker.State.SUCCEEDED, service.getState()); + assertSame(Worker.State.SUCCEEDED, service.stateProperty().get()); + } + + /*************************************************************************** + * * + * Tests for onReady * + * * + **************************************************************************/ + + @Test public void onReadyPropertyNameShouldMatchMethodName() { + assertEquals("onReady", service.onReadyProperty().getName()); + } + + @Test public void onReadyBeanShouldMatchService() { + assertSame(service, service.onReadyProperty().getBean()); + } + + @Test public void onReadyIsInitializedToNull() { + assertNull(service.getOnReady()); + assertNull(service.onReadyProperty().get()); + } + + @Test public void onReadyFilterCalledBefore_onReady() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + service.start(); + executor.executeScheduled(); + task.complete(); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> filterCalled.set(true)); + service.setOnReady(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + // Transition to Ready state + service.reset(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void onReadyHandlerCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.start(); + executor.executeScheduled(); + task.complete(); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> handlerCalled.set(true)); + + // Transition to Ready state + service.reset(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void removed_onReadyHandlerNotCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + service.start(); + executor.executeScheduled(); + task.complete(); + EventHandler handler = workerStateEvent -> handlerCalled.set(true); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_READY, handler); + service.removeEventHandler(WorkerStateEvent.WORKER_STATE_READY, handler); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> sanity.set(true)); + + service.reset(); + assertTrue(sanity.get()); + assertFalse(handlerCalled.get()); + } + + @Test public void removed_onReadyFilterNotCalled() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + service.start(); + executor.executeScheduled(); + task.complete(); + EventHandler filter = workerStateEvent -> filterCalled.set(true); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_READY, filter); + service.removeEventFilter(WorkerStateEvent.WORKER_STATE_READY, filter); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> sanity.set(true)); + + service.reset(); + assertTrue(sanity.get()); + assertFalse(filterCalled.get()); + } + + @Test public void cancelCalledFromOnReady() { + final AtomicInteger cancelNotificationCount = new AtomicInteger(); + service.start(); + executor.executeScheduled(); + task.complete(); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_READY, workerStateEvent -> { + service.cancel(); + }); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { + cancelNotificationCount.incrementAndGet(); + }); + + service.reset(); + assertEquals(Worker.State.CANCELLED, service.getState()); + assertEquals(1, cancelNotificationCount.get()); + } + + /*************************************************************************** + * * + * Tests for onScheduled * + * * + **************************************************************************/ + + @Test public void onScheduledPropertyNameShouldMatchMethodName() { + assertEquals("onScheduled", service.onScheduledProperty().getName()); + } + + @Test public void onScheduledBeanShouldMatchService() { + assertSame(service, service.onScheduledProperty().getBean()); + } + + @Test public void onScheduledIsInitializedToNull() { + assertNull(service.getOnScheduled()); + assertNull(service.onScheduledProperty().get()); + } + + @Test public void onScheduledFilterCalledBefore_onScheduled() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> filterCalled.set(true)); + service.setOnScheduled(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + // Transition to Scheduled state + service.start(); + executor.executeScheduled(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void scheduledCalledAfterHandler() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnScheduled(workerStateEvent -> handlerCalled.set(true)); + + // Transition to Scheduled state + service.start(); + executor.executeScheduled(); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().scheduledSemaphore.getQueueLength() == 0); + } + + @Test public void scheduledCalledAfterHandlerEvenIfConsumed() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnScheduled(workerStateEvent -> { + handlerCalled.set(true); + workerStateEvent.consume(); + }); + + // Transition to Scheduled state + service.start(); + executor.executeScheduled(); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().scheduledSemaphore.getQueueLength() == 0); + } + + @Test public void onScheduledHandlerCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> handlerCalled.set(true)); + + service.start(); + executor.executeScheduled(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void removed_onScheduledHandlerNotCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler handler = workerStateEvent -> handlerCalled.set(true); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, handler); + service.removeEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, handler); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + assertTrue(sanity.get()); + assertFalse(handlerCalled.get()); + } + + @Test public void removed_onScheduledFilterNotCalled() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler filter = workerStateEvent -> filterCalled.set(true); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, filter); + service.removeEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, filter); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + assertTrue(sanity.get()); + assertFalse(filterCalled.get()); + } + + @Test public void cancelCalledFromOnScheduled() { + final AtomicInteger cancelNotificationCount = new AtomicInteger(); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> { + service.cancel(); + }); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { + cancelNotificationCount.incrementAndGet(); + }); + + service.start(); + executor.executeScheduled(); + assertEquals(Worker.State.CANCELLED, service.getState()); + assertEquals(1, cancelNotificationCount.get()); + } + + /*************************************************************************** + * * + * Tests for onRunning * + * * + **************************************************************************/ + + @Test public void onRunningPropertyNameShouldMatchMethodName() { + assertEquals("onRunning", service.onRunningProperty().getName()); + } + + @Test public void onRunningBeanShouldMatchService() { + assertSame(service, service.onRunningProperty().getBean()); + } + + @Test public void onRunningIsInitializedToNull() { + assertNull(service.getOnRunning()); + assertNull(service.onRunningProperty().get()); + } + + @Test public void onRunningFilterCalledBefore_onRunning() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> filterCalled.set(true)); + service.setOnRunning(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + // Transition to Running state + service.start(); + executor.executeScheduled(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void runningCalledAfterHandler() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnRunning(workerStateEvent -> handlerCalled.set(true)); + + // Transition to Running state + service.start(); + executor.executeScheduled(); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().runningSemaphore.getQueueLength() == 0); + } + + @Test public void runningCalledAfterHandlerEvenIfConsumed() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnRunning(workerStateEvent -> { + handlerCalled.set(true); + workerStateEvent.consume(); + }); + + // Transition to Running state + service.start(); + executor.executeScheduled(); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().runningSemaphore.getQueueLength() == 0); + } + + @Test public void onRunningHandlerCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> handlerCalled.set(true)); + + service.start(); + executor.executeScheduled(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void removed_onRunningHandlerNotCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler handler = workerStateEvent -> handlerCalled.set(true); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_RUNNING, handler); + service.removeEventHandler(WorkerStateEvent.WORKER_STATE_RUNNING, handler); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + assertTrue(sanity.get()); + assertFalse(handlerCalled.get()); + } + + @Test public void removed_onRunningFilterNotCalled() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler filter = workerStateEvent -> filterCalled.set(true); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, filter); + service.removeEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, filter); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + assertTrue(sanity.get()); + assertFalse(filterCalled.get()); + } + + @Test public void cancelCalledFromOnRunning() { + final AtomicInteger cancelNotificationCount = new AtomicInteger(); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> { + service.cancel(); + }); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { + cancelNotificationCount.incrementAndGet(); + }); + + service.start(); + executor.executeScheduled(); + assertEquals(Worker.State.CANCELLED, service.getState()); + assertEquals(1, cancelNotificationCount.get()); + } + + /*************************************************************************** + * * + * Tests for onSucceeded * + * * + **************************************************************************/ + + @Test public void onSucceededPropertyNameShouldMatchMethodName() { + assertEquals("onSucceeded", service.onSucceededProperty().getName()); + } + + @Test public void onSucceededBeanShouldMatchService() { + assertSame(service, service.onSucceededProperty().getBean()); + } + + @Test public void onSucceededIsInitializedToNull() { + assertNull(service.getOnSucceeded()); + assertNull(service.onSucceededProperty().get()); + } + + @Test public void onSucceededFilterCalledBefore_onSucceeded() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> filterCalled.set(true)); + service.setOnSucceeded(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + // Transition to Succeeded state + service.start(); + executor.executeScheduled(); + task.complete(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void succeededCalledAfterHandler() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnSucceeded(workerStateEvent -> handlerCalled.set(true)); + + // Transition to Succeeded state + service.start(); + executor.executeScheduled(); + task.complete(); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().succeededSemaphore.getQueueLength() == 0); + } + + @Test public void succeededCalledAfterHandlerEvenIfConsumed() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnSucceeded(workerStateEvent -> { + handlerCalled.set(true); + workerStateEvent.consume(); + }); + + // Transition to Succeeded state + service.start(); + executor.executeScheduled(); + task.complete(); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().succeededSemaphore.getQueueLength() == 0); + } + + @Test public void onSucceededHandlerCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> handlerCalled.set(true)); + + service.start(); + executor.executeScheduled(); + task.complete(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void removed_onSucceededHandlerNotCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler handler = workerStateEvent -> handlerCalled.set(true); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, handler); + service.removeEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, handler); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + task.complete(); + assertTrue(sanity.get()); + assertFalse(handlerCalled.get()); + } + + @Test public void removed_onSucceededFilterNotCalled() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler filter = workerStateEvent -> filterCalled.set(true); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, filter); + service.removeEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, filter); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + task.complete(); + } + + @Test public void cancelCalledFromOnSucceeded() { + final AtomicInteger cancelNotificationCount = new AtomicInteger(); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> { + service.cancel(); + }); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { + cancelNotificationCount.incrementAndGet(); + }); + + service.start(); + executor.executeScheduled(); + task.complete(); + assertEquals(Worker.State.SUCCEEDED, service.getState()); + assertEquals(0, cancelNotificationCount.get()); + } + + /*************************************************************************** + * * + * Tests for onCancelled * + * * + **************************************************************************/ + + @Test public void onCancelledPropertyNameShouldMatchMethodName() { + assertEquals("onCancelled", service.onCancelledProperty().getName()); + } + + @Test public void onCancelledBeanShouldMatchService() { + assertSame(service, service.onCancelledProperty().getBean()); + } + + @Test public void onCancelledIsInitializedToNull() { + assertNull(service.getOnCancelled()); + assertNull(service.onCancelledProperty().get()); + } + + @Test public void onCancelledFilterCalledBefore_onCancelled() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> filterCalled.set(true)); + service.setOnCancelled(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + // Transition to Cancelled state + service.start(); + executor.executeScheduled(); + task.cancel(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void cancelledCalledAfterHandler() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnCancelled(workerStateEvent -> handlerCalled.set(true)); + + // Transition to Cancelled state + service.start(); + executor.executeScheduled(); + task.cancel(); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().cancelledSemaphore.getQueueLength() == 0); + } + + @Test public void cancelledCalledAfterHandlerEvenIfConsumed() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnCancelled(workerStateEvent -> { + handlerCalled.set(true); + workerStateEvent.consume(); + }); + + // Transition to Cancelled state + service.start(); + executor.executeScheduled(); + task.cancel(); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().cancelledSemaphore.getQueueLength() == 0); + } + + @Test public void onCancelledHandlerCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> handlerCalled.set(true)); + + service.start(); + executor.executeScheduled(); + task.cancel(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void removed_onCancelledHandlerNotCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler handler = workerStateEvent -> handlerCalled.set(true); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, handler); + service.removeEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, handler); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + task.cancel(); + assertTrue(sanity.get()); + assertFalse(handlerCalled.get()); + } + + @Test public void removed_onCancelledFilterNotCalled() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler filter = workerStateEvent -> filterCalled.set(true); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, filter); + service.removeEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, filter); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + task.cancel(); + assertTrue(sanity.get()); + assertFalse(filterCalled.get()); + } + + @Test public void cancelCalledFromOnCancelled() { + final AtomicInteger cancelNotificationCount = new AtomicInteger(); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> { + service.cancel(); + }); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { + cancelNotificationCount.incrementAndGet(); + }); + + service.start(); + executor.executeScheduled(); + task.cancel(); + assertEquals(Worker.State.CANCELLED, service.getState()); + assertEquals(1, cancelNotificationCount.get()); + } + + @Test public void cancelCalledFromOnFailed() { + final AtomicInteger cancelNotificationCount = new AtomicInteger(); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> { + service.cancel(); + }); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { + cancelNotificationCount.incrementAndGet(); + }); + + service.start(); + executor.executeScheduled(); + task.fail(new Exception("Quit")); + assertEquals(Worker.State.FAILED, service.getState()); + assertEquals(0, cancelNotificationCount.get()); + } + + /*************************************************************************** + * * + * Tests for onFailed * + * * + **************************************************************************/ + + @Test public void onFailedPropertyNameShouldMatchMethodName() { + assertEquals("onFailed", service.onFailedProperty().getName()); + } + + @Test public void onFailedBeanShouldMatchService() { + assertSame(service, service.onFailedProperty().getBean()); + } + + @Test public void onFailedIsInitializedToNull() { + assertNull(service.getOnFailed()); + assertNull(service.onFailedProperty().get()); + } + + @Test public void onFailedFilterCalledBefore_onFailed() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> filterCalled.set(true)); + service.setOnFailed(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + // Transition to Succeeded state + service.start(); + executor.executeScheduled(); + task.fail(new Exception("The End")); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void failedCalledAfterHandler() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnFailed(workerStateEvent -> handlerCalled.set(true)); + + // Transition to Succeeded state + service.start(); + executor.executeScheduled(); + task.fail(new Exception("Quit Now")); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().failedSemaphore.getQueueLength() == 0); + } + + @Test public void failedCalledAfterHandlerEvenIfConsumed() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.setOnFailed(workerStateEvent -> handlerCalled.set(true)); + + // Transition to Succeeded state + service.start(); + executor.executeScheduled(); + task.fail(new Exception("Quit Now")); + // Events should have happened + assertTrue(handlerCalled.get() && factory.getCurrentTask().failedSemaphore.getQueueLength() == 0); + } + + @Test public void onFailedHandlerCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> handlerCalled.set(true)); + + service.start(); + executor.executeScheduled(); + task.fail(new Exception("Forget about it")); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void removed_onFailedHandlerNotCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler handler = workerStateEvent -> handlerCalled.set(true); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, handler); + service.removeEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, handler); + service.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + task.fail(new Exception("Quit")); + assertTrue(sanity.get()); + assertFalse(handlerCalled.get()); + } + + @Test public void removed_onFailedFilterNotCalled() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + EventHandler filter = workerStateEvent -> filterCalled.set(true); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, filter); + service.removeEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, filter); + service.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> sanity.set(true)); + + service.start(); + executor.executeScheduled(); + task.fail(new Exception("Quit")); + assertTrue(sanity.get()); + assertFalse(filterCalled.get()); + } + + /*************************************************************************** + * * + * Tests that invoking methods from the wrong thread leads to errors, and * + * that regardless of which thread starts the Service, all notification * + * (events, etc) happen on the FX thread only. * + * * + **************************************************************************/ + + @Test public void canCreateServiceOnRandomThread() { + RandomThread random = new RandomThread(() -> { + DoNothingService s = null; + try { + s = new DoNothingService(); + } finally { + if (s != null) s.shutdown(); + } + }); + random.test(); + } + + @Test public void canGetReferencesToPropertiesOnRandomThread() { + RandomThread random = new RandomThread(() -> { + DoNothingService s = null; + try { + s = new DoNothingService(); + s.exceptionProperty(); + s.executorProperty(); + s.messageProperty(); + s.progressProperty(); + s.onCancelledProperty(); + s.onFailedProperty(); + s.onReadyProperty(); + s.onRunningProperty(); + s.onScheduledProperty(); + s.onSucceededProperty(); + s.runningProperty(); + s.stateProperty(); + s.titleProperty(); + s.totalWorkProperty(); + s.valueProperty(); + s.workDoneProperty(); + } finally { + if (s != null) s.shutdown(); + } + }); + random.test(); + } + + @Test public void canInvokeGettersOnRandomThread() { + RandomThread random = new RandomThread(() -> { + DoNothingService s = null; + try { + s = new DoNothingService(); + s.getException(); + s.getExecutor(); + s.getMessage(); + s.getProgress(); + s.getOnCancelled(); + s.getOnFailed(); + s.getOnReady(); + s.getOnRunning(); + s.getOnScheduled(); + s.getOnSucceeded(); + s.isRunning(); + s.getState(); + s.getTitle(); + s.getTotalWork(); + s.getValue(); + s.getWorkDone(); + } finally { + if (s != null) s.shutdown(); + } + }); + random.test(); + } + + @Test public void canInvokeSettersOnRandomThread() { + RandomThread random = new RandomThread(() -> { + DoNothingService s = null; + try { + s = new DoNothingService(); + ServiceShim.setEventHandler(s, WorkerStateEvent.ANY, event -> { + }); + s.setOnCancelled(event -> { + }); + s.setOnFailed(event -> { + }); + s.setOnReady(event -> { + }); + s.setOnRunning(event -> { + }); + s.setOnScheduled(event -> { + }); + s.setOnSucceeded(event -> { + }); + } finally { + if (s != null) s.shutdown(); + } + }); + random.test(); + } + + @Test public void canInvokeStartOnRandomThread() { + RandomThread random = new RandomThread(() -> { + DoNothingService s = null; + try { + s = new DoNothingService(); + s.start(); + } finally { + if (s != null) s.shutdown(); + } + }); + random.test(); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeRestartOnRandomThreadAfterStart() throws Throwable { + assertThrowsException(s -> s.restart()); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeCancelOnRandomThreadAfterStart() throws Throwable { + assertThrowsException(s -> { + s.cancel(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeSettersOnRandomThreadAfterStart_1() throws Throwable { + assertThrowsException(s -> + ServiceShim.setEventHandler(s, WorkerStateEvent.ANY, event -> { + })); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeSettersOnRandomThreadAfterStart_2() throws Throwable { + assertThrowsException(s -> s.setOnCancelled(event -> { + })); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeSettersOnRandomThreadAfterStart_3() throws Throwable { + assertThrowsException(s -> s.setOnFailed(event -> { })); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeSettersOnRandomThreadAfterStart_4() throws Throwable { + assertThrowsException(s -> s.setOnReady(event -> { })); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeSettersOnRandomThreadAfterStart_5() throws Throwable { + assertThrowsException(s -> s.setOnRunning(event -> { })); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeSettersOnRandomThreadAfterStart_6() throws Throwable { + assertThrowsException(s -> s.setOnScheduled(event -> { + })); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeSettersOnRandomThreadAfterStart_7() throws Throwable { + assertThrowsException(s -> s.setOnSucceeded(event -> { })); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_1() throws Throwable { + assertThrowsException(s -> { + s.getException(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_2() throws Throwable { + assertThrowsException(s -> { + s.getExecutor(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_3() throws Throwable { + assertThrowsException(s -> { + s.getMessage(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_4() throws Throwable { + assertThrowsException(s -> { + s.getProgress(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_5() throws Throwable { + assertThrowsException(s -> { + s.getOnCancelled(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_6() throws Throwable { + assertThrowsException(s -> { + s.getOnFailed(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_7() throws Throwable { + assertThrowsException(s -> { + s.getOnReady(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_8() throws Throwable { + assertThrowsException(s -> { + s.getOnRunning(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_9() throws Throwable { + assertThrowsException(s -> { + s.getOnScheduled(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_10() throws Throwable { + assertThrowsException(s -> { + s.getOnSucceeded(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_11() throws Throwable { + assertThrowsException(s -> { + s.isRunning(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_12() throws Throwable { + assertThrowsException(s -> { + s.getState(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_13() throws Throwable { + assertThrowsException(s -> { + s.getTitle(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_14() throws Throwable { + assertThrowsException(s -> { + s.getTotalWork(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_15() throws Throwable { + assertThrowsException(s -> { + s.getValue(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokeGettersOnRandomThreadAfterStart_16() throws Throwable { + assertThrowsException(s -> { + s.getValue(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_1() throws Throwable { + assertThrowsException(s -> { + s.exceptionProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_2() throws Throwable { + assertThrowsException(s -> { + s.executorProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_3() throws Throwable { + assertThrowsException(s -> { + s.messageProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_4() throws Throwable { + assertThrowsException(s -> { + s.progressProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_5() throws Throwable { + assertThrowsException(s -> { + s.onCancelledProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_6() throws Throwable { + assertThrowsException(s -> { + s.onFailedProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_7() throws Throwable { + assertThrowsException(s -> { + s.onReadyProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_8() throws Throwable { + assertThrowsException(s -> { + s.onRunningProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_9() throws Throwable { + assertThrowsException(s -> { + s.onScheduledProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_10() throws Throwable { + assertThrowsException(s -> { + s.onSucceededProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_11() throws Throwable { + assertThrowsException(s -> { + s.runningProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_12() throws Throwable { + assertThrowsException(s -> { + s.stateProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_13() throws Throwable { + assertThrowsException(s -> { + s.titleProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_14() throws Throwable { + assertThrowsException(s -> { + s.totalWorkProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_15() throws Throwable { + assertThrowsException(s -> { + s.valueProperty(); + }); + } + + @Test (expected = IllegalStateException.class) + public void cannotInvokePropertyGettersOnRandomThreadAfterStart_16() throws Throwable { + assertThrowsException(s -> { + s.workDoneProperty(); + }); + } + + private void assertThrowsException(final ServiceTestExecution c) throws Throwable { + RandomThread random = new RandomThread(() -> { + DoNothingService s = null; + try { + s = new DoNothingService(); + s.start(); + c.test(s); + } finally { + if (s != null) s.shutdown(); + } + }); + + try { + random.test(); + } catch (AssertionError er) { + throw er.getCause(); + } + } + + private interface ServiceTestExecution { + public void test(DoNothingService s); + } + + /** + * Specialized thread used for checking access to various methods from a "random thread" other + * than the FX thread. This class has built into it all the supported needed for handling + * exceptions and so forth, such that assertion errors are raised if an exception occurs + * on the thread, and also handles blocking until the thread body concludes. + */ + private static final class RandomThread extends Thread { + private final CountDownLatch testCompleted = new CountDownLatch(1); + private Throwable error; + + public RandomThread(Runnable target) { + super(target); + } + + @Override public void run() { + try { + super.run(); + } catch (Throwable th) { + error = th; + } finally { + testCompleted.countDown(); + } + } + + public void test() throws AssertionError { + start(); + try { + testCompleted.await(); + } catch (InterruptedException e) { + throw new AssertionError("Test did not complete normally"); + } + if (error != null) { + throw new AssertionError(error); + } + } + } + + /** + * A service which does absolutely nothing and isn't hardwired to believe that + * the test thread is the FX thread (unlike the other services in these tests) + */ + private static final class DoNothingService extends ServiceShim { + private Thread pretendFXThread; + private ConcurrentLinkedQueue eventQueue = new ConcurrentLinkedQueue<>(); + private volatile boolean shutdown = false; + + public DoNothingService() { + setExecutor(command -> { + Thread backgroundThread = new Thread(command); + backgroundThread.start(); + }); + } + + void shutdown() { + shutdown = true; + } + + @Override protected Task createTask() { + return new TaskShim() { + @Override protected Object call() throws Exception { + return null; + } + + @Override public boolean isFxApplicationThread() { + return Thread.currentThread() == pretendFXThread; + } + + @Override + public void runLater(Runnable r) { + DoNothingService.this.runLater(r); + } + }; + } + + @Override public void runLater(Runnable r) { + eventQueue.add(r); + if (pretendFXThread == null) { + pretendFXThread = new Thread() { + @Override public void run() { + while (!shutdown) { + Runnable event = eventQueue.poll(); + if (event != null) { + event.run(); + } + } + } + }; + pretendFXThread.start(); + } + } + + @Override public boolean isFxApplicationThread() { + return Thread.currentThread() == pretendFXThread; + } + } + + /*************************************************************************** + * * + * A mythical subclass should be able to set an event handler and * + * have events fired on the Service work. * + * * + **************************************************************************/ + + @Test public void eventFiredOnSubclassWorks() { + final AtomicBoolean result = new AtomicBoolean(false); + TestServiceFactory factory = new TestServiceFactory() { + @Override public AbstractTask createTestTask() { + return new SimpleTask(); + } + + @Override public Service createService() { + MythicalService svc = new MythicalService(); + svc.setHandler(mythicalEvent -> result.set(true)); + ServiceShim.fireEvent(svc, new MythicalEvent()); + return svc; + } + }; + Service svc = factory.createService(); + svc.start(); + assertTrue(result.get()); + } + + private static final class MythicalService extends ServiceShim { + public void setHandler(EventHandler h) { + ServiceShim.setEventHandler(this, MythicalEvent.ANY, h); + } + + @Override protected Task createTask() { + return new SimpleTask(); + } + + @Override public void checkThread() { } + + @Override public void runLater(Runnable r) { + r.run(); + } + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/ServiceTest.java 2015-09-11 21:25:34.733286199 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import javafx.beans.property.ObjectProperty; -import javafx.beans.property.SimpleObjectProperty; -import javafx.concurrent.mocks.SimpleTask; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -/** - */ -public class ServiceTest { - private Service service; - - @Before public void setup() { - // I don't use the AbstractService here because I don't want to - // take advantage of the built in executor / threading stuff - service = new Service() { - @Override protected Task createTask() { - return new SimpleTask(); - } - - @Override void checkThread() { } - @Override void runLater(Runnable r) { - r.run(); - } - }; - } - - /****************************************************************** - * Executor Property * - *****************************************************************/ - - /** - * Tests that the executor property is null by default - */ - @Test public void executorDefaultsToNull() { - assertNull(service.getExecutor()); - assertNull(service.executorProperty().get()); - } - - /** - * Tests that you can set the executor. This will set the executor - * to some non-default setting and check that the same instance is - * then set on the service - */ - @Test public void executorCanBeSet() { - final Executor e = command -> { }; - service.setExecutor(e); - assertSame(e, service.getExecutor()); - assertSame(e, service.executorProperty().get()); - } - - /** - * Tests that you can bind the executor property of a Service - */ - @Test public void executorCanBeBound() { - final Executor e = command -> { }; - ObjectProperty other = new SimpleObjectProperty(e); - service.executorProperty().bind(other); - assertSame(e, service.getExecutor()); - assertSame(e, service.executorProperty().get()); - other.set(null); - assertNull(service.getExecutor()); - assertNull(service.executorProperty().get()); - } - - /** - * Tests that if you specify a custom executor, then it is used when - * you attempt to run a service - */ - @Test public void executorIsUsed() { - final AtomicBoolean results = new AtomicBoolean(false); - final Executor e = command -> results.set(true); - service.setExecutor(e); - service.start(); - assertTrue(results.get()); - } - - /****************************************************************** - * Test initial values for properties * - *****************************************************************/ - - @Test public void stateDefaultsTo_READY() { - assertSame(Worker.State.READY, service.getState()); - assertSame(Worker.State.READY, service.stateProperty().get()); - } - - @Test public void valueDefaultsToNull() { - assertNull(service.getValue()); - assertNull(service.valueProperty().get()); - } - - @Test public void exceptionDefaultsToNull() { - assertNull(service.getException()); - assertNull(service.exceptionProperty().get()); - } - - @Test public void workDoneDefaultsTo_NegativeOne() { - assertEquals(-1, service.getWorkDone(), 0); - assertEquals(-1, service.workDoneProperty().get(), 0); - } - - @Test public void totalWorkDefaultsTo_NegativeOne() { - assertEquals(-1, service.getTotalWork(), 0); - assertEquals(-1, service.totalWorkProperty().get(), 0); - } - - @Test public void progressDefaultsTo_NegativeOne() { - assertEquals(-1, service.getProgress(), 0); - assertEquals(-1, service.progressProperty().get(), 0); - } - - @Test public void runningDefaultsToFalse() { - assertFalse(service.isRunning()); - assertFalse(service.runningProperty().get()); - } - - @Test public void messageDefaultsToEmptyString() { - assertEquals("", service.getMessage()); - assertEquals("", service.messageProperty().get()); - } - - @Test public void titleDefaultsToEmptyString() { - assertEquals("", service.getTitle()); - assertEquals("", service.titleProperty().get()); - } - - /****************************************************************** - * Test that 32 simultaneous services will run concurrently * - *****************************************************************/ - - // This test should be reliable. Each of the concurrent tasks takes 1 second to complete - // and several micro / milliseconds to get setup and execute. So 2 seconds should be more - // than enough time. - @Test(timeout = 2000) public void testManyServicesRunConcurrently() throws Exception { - final CountDownLatch latch = new CountDownLatch(32); - for (int i=0; i<32; i++) { - Service s = new Service() { - @Override void checkThread() { } - @Override void runLater(Runnable r) { r.run(); } - - @Override protected Task createTask() { - return new Task() { - @Override protected Void call() throws Exception { - Thread.sleep(1000); - latch.countDown(); - return null; - } - - @Override void runLater(Runnable r) { - r.run(); - } - - @Override boolean isFxApplicationThread() { - return true; - } - }; - - } - }; - s.start(); - } - latch.await(); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/ServiceTest.java 2015-09-11 21:25:34.597286201 -0400 @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import javafx.beans.property.ObjectProperty; +import javafx.beans.property.SimpleObjectProperty; +import test.javafx.concurrent.mocks.SimpleTask; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; +import javafx.concurrent.Service; +import javafx.concurrent.Service; +import javafx.concurrent.ServiceShim; +import javafx.concurrent.Task; +import javafx.concurrent.Task; +import javafx.concurrent.TaskShim; +import javafx.concurrent.Worker; +import javafx.concurrent.Worker; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + */ +public class ServiceTest { + private Service service; + + @Before public void setup() { + // I don't use the AbstractService here because I don't want to + // take advantage of the built in executor / threading stuff + service = new ServiceShim() { + @Override public Task createTask() { + return new SimpleTask(); + } + + @Override public void checkThread() { } + @Override public void runLater(Runnable r) { + r.run(); + } + }; + } + + /****************************************************************** + * Executor Property * + *****************************************************************/ + + /** + * Tests that the executor property is null by default + */ + @Test public void executorDefaultsToNull() { + assertNull(service.getExecutor()); + assertNull(service.executorProperty().get()); + } + + /** + * Tests that you can set the executor. This will set the executor + * to some non-default setting and check that the same instance is + * then set on the service + */ + @Test public void executorCanBeSet() { + final Executor e = command -> { }; + service.setExecutor(e); + assertSame(e, service.getExecutor()); + assertSame(e, service.executorProperty().get()); + } + + /** + * Tests that you can bind the executor property of a Service + */ + @Test public void executorCanBeBound() { + final Executor e = command -> { }; + ObjectProperty other = new SimpleObjectProperty(e); + service.executorProperty().bind(other); + assertSame(e, service.getExecutor()); + assertSame(e, service.executorProperty().get()); + other.set(null); + assertNull(service.getExecutor()); + assertNull(service.executorProperty().get()); + } + + /** + * Tests that if you specify a custom executor, then it is used when + * you attempt to run a service + */ + @Test public void executorIsUsed() { + final AtomicBoolean results = new AtomicBoolean(false); + final Executor e = command -> results.set(true); + service.setExecutor(e); + service.start(); + assertTrue(results.get()); + } + + /****************************************************************** + * Test initial values for properties * + *****************************************************************/ + + @Test public void stateDefaultsTo_READY() { + assertSame(Worker.State.READY, service.getState()); + assertSame(Worker.State.READY, service.stateProperty().get()); + } + + @Test public void valueDefaultsToNull() { + assertNull(service.getValue()); + assertNull(service.valueProperty().get()); + } + + @Test public void exceptionDefaultsToNull() { + assertNull(service.getException()); + assertNull(service.exceptionProperty().get()); + } + + @Test public void workDoneDefaultsTo_NegativeOne() { + assertEquals(-1, service.getWorkDone(), 0); + assertEquals(-1, service.workDoneProperty().get(), 0); + } + + @Test public void totalWorkDefaultsTo_NegativeOne() { + assertEquals(-1, service.getTotalWork(), 0); + assertEquals(-1, service.totalWorkProperty().get(), 0); + } + + @Test public void progressDefaultsTo_NegativeOne() { + assertEquals(-1, service.getProgress(), 0); + assertEquals(-1, service.progressProperty().get(), 0); + } + + @Test public void runningDefaultsToFalse() { + assertFalse(service.isRunning()); + assertFalse(service.runningProperty().get()); + } + + @Test public void messageDefaultsToEmptyString() { + assertEquals("", service.getMessage()); + assertEquals("", service.messageProperty().get()); + } + + @Test public void titleDefaultsToEmptyString() { + assertEquals("", service.getTitle()); + assertEquals("", service.titleProperty().get()); + } + + /****************************************************************** + * Test that 32 simultaneous services will run concurrently * + *****************************************************************/ + + // This test should be reliable. Each of the concurrent tasks takes 1 second to complete + // and several micro / milliseconds to get setup and execute. So 2 seconds should be more + // than enough time. + @Test(timeout = 2000) public void testManyServicesRunConcurrently() throws Exception { + final CountDownLatch latch = new CountDownLatch(32); + for (int i=0; i<32; i++) { + Service s = new ServiceShim() { + @Override public void checkThread() { } + @Override public void runLater(Runnable r) { r.run(); } + + @Override protected Task createTask() { + return new TaskShim() { + @Override protected Void call() throws Exception { + Thread.sleep(1000); + latch.countDown(); + return null; + } + + @Override public void runLater(Runnable r) { + r.run(); + } + + @Override public boolean isFxApplicationThread() { + return true; + } + }; + + } + }; + s.start(); + } + latch.await(); + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/ServiceTestBase.java 2015-09-11 21:25:35.545286190 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.Executor; -import org.junit.Before; - -/** - * Base class for tests of the Service class. This class has built into it - * the notion of an event queue, and executing a Service on a background - * thread. It handles draining the EQ of events and so forth. - */ -public abstract class ServiceTestBase { - protected final ConcurrentLinkedQueue eventQueue = - new ConcurrentLinkedQueue(); - protected TestServiceFactory factory; - protected Service service; - - protected abstract TestServiceFactory setupServiceFactory(); - protected Executor createExecutor() { - return command -> { - if (command == null) Thread.dumpStack(); - Thread th = new Thread() { - @Override public void run() { - try { - command.run(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - eventQueue.add(new Sentinel()); - } - } - }; - th.setDaemon(true); - th.start(); - }; - } - - @Before public void setup() { - factory = setupServiceFactory(); - factory.test = this; - service = factory.createService(); - service.setExecutor(createExecutor()); - } - - public void handleEvents() { - Runnable r; - do { - r = eventQueue.poll(); - if (r != null) r.run(); - } while (r == null || !(r instanceof Sentinel)); - } - - // This is a sentinel class, indicating that the test is done (no more events in the event queue) - public static final class Sentinel implements Runnable { - @Override public void run() { } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/ServiceTestBase.java 2015-09-11 21:25:35.325286193 -0400 @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Executor; +import javafx.concurrent.Service; +import org.junit.Before; + +/** + * Base class for tests of the Service class. This class has built into it + * the notion of an event queue, and executing a Service on a background + * thread. It handles draining the EQ of events and so forth. + */ +public abstract class ServiceTestBase { + protected final ConcurrentLinkedQueue eventQueue = + new ConcurrentLinkedQueue(); + protected TestServiceFactory factory; + protected Service service; + + protected abstract TestServiceFactory setupServiceFactory(); + protected Executor createExecutor() { + return command -> { + if (command == null) Thread.dumpStack(); + Thread th = new Thread() { + @Override public void run() { + try { + command.run(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + eventQueue.add(new Sentinel()); + } + } + }; + th.setDaemon(true); + th.start(); + }; + } + + @Before public void setup() { + factory = setupServiceFactory(); + factory.test = this; + service = factory.createService(); + service.setExecutor(createExecutor()); + } + + public void handleEvents() { + Runnable r; + do { + r = eventQueue.poll(); + if (r != null) r.run(); + } while (r == null || !(r instanceof Sentinel)); + } + + // This is a sentinel class, indicating that the test is done (no more events in the event queue) + public static final class Sentinel implements Runnable { + @Override public void run() { } + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/ServiceWithSecurityManagerTest.java 2015-09-11 21:25:36.285286182 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import java.security.Permission; -import org.junit.Ignore; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.Statement; -import sun.awt.AWTSecurityManager; - -/** - * A test for the Service lifecycle methods with a security manager installed. - * The security manager installed lets privileged code run (most of the time) - * and otherwise lets the tests do what they need to but restricts the - * runtime from doing more or less anything else other than load library. - * It is ad-hoc, a more rigorous analysis on what the permissions should be - * would be great, and then we could add the ability to do security manager - * related tests on lots of different unit tests. - */ -@RunWith(ServiceWithSecurityManagerTest.ServiceTestRunner.class) -@Ignore("This class doesn't appear to run correctly, often s.evaluate isn't called. Likely bogus test at present.") -public class ServiceWithSecurityManagerTest extends ServiceLifecycleTest { - - public static final class ServiceTestRunner extends BlockJUnit4ClassRunner { - private ThreadGroup mainThreadGroup; - - public ServiceTestRunner(Class klass) throws InitializationError { - super(klass); - } - - @Override protected Statement methodBlock(FrameworkMethod method) { - final Statement s = super.methodBlock(method); - return new Statement() { - Throwable throwable; - @Override public void evaluate() throws Throwable { - SecurityManager original = System.getSecurityManager(); - try { - mainThreadGroup = new ThreadGroup(Thread.currentThread().getThreadGroup(), "FX Test Thread Group"); - Thread thread = new Thread(mainThreadGroup, () -> { - try { - s.evaluate(); - } catch (Throwable t) { - throwable = t; - } - }); - - System.setSecurityManager(new StrictSecurityManager()); - thread.start(); - thread.join(); - } finally { - System.setSecurityManager(original); - mainThreadGroup = null; - if (throwable != null) { - throw throwable; - } - } - } - }; - } - - /** - */ - private final class StrictSecurityManager extends AWTSecurityManager { - // If you create a Thread that is a child of mainThreadGroup, that is OK. - // If you create a ThreadGroup that is a child of mainThreadGroup, then that is bad. - private ThreadGroup securityThreadGroup = new ThreadGroup("Security Thread Group"); - - @Override public void checkPermission(Permission permission) { - if (isPrivileged()) return; // OK - if (permission instanceof RuntimePermission) { - if ("setSecurityManager".equals(permission.getName())) { - return; // OK - } - if ("accessClassInPackage.sun.util.logging".equals(permission.getName())) { - return; // OK - } - } - super.checkPermission(permission); - } - - @Override public void checkAccess(ThreadGroup g) { - if (g == securityThreadGroup) return; - if (!isPrivileged()) throw new SecurityException("ThreadGroup doesn't have permissions"); - super.checkAccess(g); - } - - @Override public ThreadGroup getThreadGroup() { - return securityThreadGroup; - } - - private boolean isPrivileged() { - StackTraceElement[] stack = Thread.currentThread().getStackTrace(); - for (StackTraceElement e : stack) { - if (e.getClassName().equals("java.security.AccessController") - && e.getMethodName().equals("doPrivileged")) { - return true; - } - } - return false; - } - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/ServiceWithSecurityManagerTest.java 2015-09-11 21:25:36.077286184 -0400 @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import java.security.Permission; +import org.junit.Ignore; +import org.junit.runner.RunWith; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.Statement; +import sun.awt.AWTSecurityManager; + +/** + * A test for the Service lifecycle methods with a security manager installed. + * The security manager installed lets privileged code run (most of the time) + * and otherwise lets the tests do what they need to but restricts the + * runtime from doing more or less anything else other than load library. + * It is ad-hoc, a more rigorous analysis on what the permissions should be + * would be great, and then we could add the ability to do security manager + * related tests on lots of different unit tests. + */ +@RunWith(ServiceWithSecurityManagerTest.ServiceTestRunner.class) +@Ignore("This class doesn't appear to run correctly, often s.evaluate isn't called. Likely bogus test at present.") +public class ServiceWithSecurityManagerTest extends ServiceLifecycleTest { + + public static final class ServiceTestRunner extends BlockJUnit4ClassRunner { + private ThreadGroup mainThreadGroup; + + public ServiceTestRunner(Class klass) throws InitializationError { + super(klass); + } + + @Override protected Statement methodBlock(FrameworkMethod method) { + final Statement s = super.methodBlock(method); + return new Statement() { + Throwable throwable; + @Override public void evaluate() throws Throwable { + SecurityManager original = System.getSecurityManager(); + try { + mainThreadGroup = new ThreadGroup(Thread.currentThread().getThreadGroup(), "FX Test Thread Group"); + Thread thread = new Thread(mainThreadGroup, () -> { + try { + s.evaluate(); + } catch (Throwable t) { + throwable = t; + } + }); + + System.setSecurityManager(new StrictSecurityManager()); + thread.start(); + thread.join(); + } finally { + System.setSecurityManager(original); + mainThreadGroup = null; + if (throwable != null) { + throw throwable; + } + } + } + }; + } + + /** + */ + private final class StrictSecurityManager extends AWTSecurityManager { + // If you create a Thread that is a child of mainThreadGroup, that is OK. + // If you create a ThreadGroup that is a child of mainThreadGroup, then that is bad. + private ThreadGroup securityThreadGroup = new ThreadGroup("Security Thread Group"); + + @Override public void checkPermission(Permission permission) { + if (isPrivileged()) return; // OK + if (permission instanceof RuntimePermission) { + if ("setSecurityManager".equals(permission.getName())) { + return; // OK + } + if ("accessClassInPackage.sun.util.logging".equals(permission.getName())) { + return; // OK + } + } + super.checkPermission(permission); + } + + @Override public void checkAccess(ThreadGroup g) { + if (g == securityThreadGroup) return; + if (!isPrivileged()) throw new SecurityException("ThreadGroup doesn't have permissions"); + super.checkAccess(g); + } + + @Override public ThreadGroup getThreadGroup() { + return securityThreadGroup; + } + + private boolean isPrivileged() { + StackTraceElement[] stack = Thread.currentThread().getStackTrace(); + for (StackTraceElement e : stack) { + if (e.getClassName().equals("java.security.AccessController") + && e.getMethodName().equals("doPrivileged")) { + return true; + } + } + return false; + } + } + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/TaskCancelTest.java 2015-09-11 21:25:36.989286174 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import javafx.concurrent.mocks.EpicFailTask; -import javafx.concurrent.mocks.InfiniteTask; -import javafx.concurrent.mocks.RunAwayTask; -import javafx.concurrent.mocks.SimpleTask; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * Tests what happens to a Task if it is canceled in each of the various - * states that a Task may be in. - */ -public class TaskCancelTest { - /** - * Since the InfiniteTask never ends (normally), I can test it from the - * ready, scheduled, running, cancelled, and failed states. I can't use - * it for testing what happens when the task succeeds though. - */ - private InfiniteTask task; - - @Before public void setup() { - task = new InfiniteTask(); - } - - /** - * Since the task begins in the ready state, I can just cancel it and - * see what happens. - */ - @Test public void cancellingA_READY_TaskShouldChangeStateTo_CANCELLED() { - assertTrue(task.cancel()); - assertEquals(Task.State.CANCELLED, task.getState()); - assertTrue(task.isDone()); - } - - /** - * I have some cheap mechanism for simulating the scheduling of a Task - * (it just changes the Task state correctly). So put it in the - * Scheduled state and then cancel it and see what happens. - */ - @Test public void cancellingA_SCHEDULED_TaskShouldChangeStateTo_CANCELLED() { - task.simulateSchedule(); - assertTrue(task.cancel()); - assertEquals(Task.State.CANCELLED, task.getState()); - assertTrue(task.isDone()); - } - - /** - * Since the task is an infinitely running task, and since there is a - * semaphore on the AbstractTask that tells me when certain state - * transitions have occurred, I can simply fire up another thread and - * run the infinite task, and then wait for that semaphore to trip. When - * it does, I know that we're running (and will never leave that state) - * so I can go ahead and then cancel it. - * - * @throws Exception shouldn't throw anything unless th.join fails - */ - @Test public void cancellingA_RUNNING_TaskShouldChangeStateTo_CANCELLED() throws Exception { - Thread th = new Thread(task); - th.start(); - task.runningSemaphore.acquire(); - assertTrue(task.cancel()); - th.join(); - - assertEquals(Task.State.CANCELLED, task.getState()); - // TODO why is this commented out? -// assertNull(task.getException()); - assertNull(task.getValue()); - assertTrue(task.isDone()); - } - - /** - * In this case I don't want to use the infinite task, so I'll just - * use a SimpleTask instead - */ - @Test public void cancellingA_SUCCEEDED_TaskShouldNotChangeTo_CANCELLED() { - Task t = new SimpleTask(); - t.run(); - assertFalse(t.cancel()); - assertEquals(Task.State.SUCCEEDED, t.getState()); - assertTrue(t.isDone()); - } - - /** - * Although I could end up using the infinite task for this one, I'm going - * to go ahead and reuse the epic fail task instead - */ - @Test public void cancellingA_FAILED_TaskShouldNotChangeTo_CANCELLED() { - Task t = new EpicFailTask(); - t.run(); - assertFalse(t.cancel()); - assertEquals(Task.State.FAILED, t.getState()); - assertTrue(t.isDone()); - } - - /** - * - */ - @Test public void aFreeRunningCancelledTaskReturnValueShouldBeIgnored() throws Exception { - RunAwayTask runAway = new RunAwayTask() { - protected void loop(int count) throws Exception { - } - }; - Thread th = new Thread(runAway); - th.start(); - runAway.runningSemaphore.acquire(); - assertTrue(runAway.cancel()); - runAway.stopLooping.set(true); - th.join(); - - assertEquals(Task.State.CANCELLED, runAway.getState()); - // TODO why is this commented out? -// assertNull(task.getException()); - assertNull(runAway.getValue()); - assertTrue(runAway.isDone()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/TaskCancelTest.java 2015-09-11 21:25:36.853286176 -0400 @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import javafx.concurrent.Task; +import test.javafx.concurrent.mocks.EpicFailTask; +import test.javafx.concurrent.mocks.InfiniteTask; +import test.javafx.concurrent.mocks.RunAwayTask; +import test.javafx.concurrent.mocks.SimpleTask; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Tests what happens to a Task if it is canceled in each of the various + * states that a Task may be in. + */ +public class TaskCancelTest { + /** + * Since the InfiniteTask never ends (normally), I can test it from the + * ready, scheduled, running, cancelled, and failed states. I can't use + * it for testing what happens when the task succeeds though. + */ + private InfiniteTask task; + + @Before public void setup() { + task = new InfiniteTask(); + } + + /** + * Since the task begins in the ready state, I can just cancel it and + * see what happens. + */ + @Test public void cancellingA_READY_TaskShouldChangeStateTo_CANCELLED() { + assertTrue(task.cancel()); + assertEquals(Task.State.CANCELLED, task.getState()); + assertTrue(task.isDone()); + } + + /** + * I have some cheap mechanism for simulating the scheduling of a Task + * (it just changes the Task state correctly). So put it in the + * Scheduled state and then cancel it and see what happens. + */ + @Test public void cancellingA_SCHEDULED_TaskShouldChangeStateTo_CANCELLED() { + task.simulateSchedule(); + assertTrue(task.cancel()); + assertEquals(Task.State.CANCELLED, task.getState()); + assertTrue(task.isDone()); + } + + /** + * Since the task is an infinitely running task, and since there is a + * semaphore on the AbstractTask that tells me when certain state + * transitions have occurred, I can simply fire up another thread and + * run the infinite task, and then wait for that semaphore to trip. When + * it does, I know that we're running (and will never leave that state) + * so I can go ahead and then cancel it. + * + * @throws Exception shouldn't throw anything unless th.join fails + */ + @Test public void cancellingA_RUNNING_TaskShouldChangeStateTo_CANCELLED() throws Exception { + Thread th = new Thread(task); + th.start(); + task.runningSemaphore.acquire(); + assertTrue(task.cancel()); + th.join(); + + assertEquals(Task.State.CANCELLED, task.getState()); + // TODO why is this commented out? +// assertNull(task.getException()); + assertNull(task.getValue()); + assertTrue(task.isDone()); + } + + /** + * In this case I don't want to use the infinite task, so I'll just + * use a SimpleTask instead + */ + @Test public void cancellingA_SUCCEEDED_TaskShouldNotChangeTo_CANCELLED() { + Task t = new SimpleTask(); + t.run(); + assertFalse(t.cancel()); + assertEquals(Task.State.SUCCEEDED, t.getState()); + assertTrue(t.isDone()); + } + + /** + * Although I could end up using the infinite task for this one, I'm going + * to go ahead and reuse the epic fail task instead + */ + @Test public void cancellingA_FAILED_TaskShouldNotChangeTo_CANCELLED() { + Task t = new EpicFailTask(); + t.run(); + assertFalse(t.cancel()); + assertEquals(Task.State.FAILED, t.getState()); + assertTrue(t.isDone()); + } + + /** + * + */ + @Test public void aFreeRunningCancelledTaskReturnValueShouldBeIgnored() throws Exception { + RunAwayTask runAway = new RunAwayTask() { + protected void loop(int count) throws Exception { + } + }; + Thread th = new Thread(runAway); + th.start(); + runAway.runningSemaphore.acquire(); + assertTrue(runAway.cancel()); + runAway.stopLooping.set(true); + th.join(); + + assertEquals(Task.State.CANCELLED, runAway.getState()); + // TODO why is this commented out? +// assertNull(task.getException()); + assertNull(runAway.getValue()); + assertTrue(runAway.isDone()); + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/TaskEventTest.java 2015-09-11 21:25:37.765286165 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,486 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import java.util.concurrent.atomic.AtomicBoolean; -import javafx.concurrent.mocks.EpicFailTask; -import javafx.concurrent.mocks.InfiniteTask; -import javafx.concurrent.mocks.MythicalEvent; -import javafx.concurrent.mocks.SimpleTask; -import javafx.event.EventHandler; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * Tests that the event notification machinery on Task works as expected. - * Event filters should be called before the onFoo methods, and the onFoo - * methods before the event handlers. The protected methods should be called - * in any case whether or not the event ends up consumed, and should always - * be called last. - */ -public class TaskEventTest { - - /*************************************************************************** - * - * Tests for onScheduled - * - **************************************************************************/ - - @Test public void onScheduledPropertyNameShouldMatchMethodName() { - Task task = new SimpleTask(); - assertEquals("onScheduled", task.onScheduledProperty().getName()); - } - - @Test public void onScheduledBeanShouldMatchTask() { - Task task = new SimpleTask(); - assertSame(task, task.onScheduledProperty().getBean()); - } - - @Test public void onScheduledIsInitializedToNull() { - Task task = new SimpleTask(); - assertNull(task.getOnScheduled()); - assertNull(task.onScheduledProperty().get()); - } - - @Test public void onScheduledCalledWhenSetViaProperty() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - SimpleTask task = new SimpleTask(); - task.onScheduledProperty().set(workerStateEvent -> handlerCalled.set(true)); - - task.simulateSchedule(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void onScheduledFilterCalledBefore_onScheduled() { - SimpleTask task = new SimpleTask(); - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - task.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> filterCalled.set(true)); - task.setOnScheduled(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - // Transition to Scheduled state - task.simulateSchedule(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void scheduledCalledAfterHandler() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean scheduledCalledLast = new AtomicBoolean(false); - SimpleTask task = new SimpleTask() { - @Override protected void scheduled() { - scheduledCalledLast.set(handlerCalled.get()); - } - }; - task.setOnScheduled(workerStateEvent -> handlerCalled.set(true)); - - // Transition to Scheduled state - task.simulateSchedule(); - // Events should have happened - assertTrue(scheduledCalledLast.get()); - } - - @Test public void scheduledCalledAfterHandlerEvenIfConsumed() { - final AtomicBoolean scheduledCalled = new AtomicBoolean(false); - SimpleTask task = new SimpleTask() { - @Override protected void scheduled() { - scheduledCalled.set(true); - } - }; - task.setOnScheduled(workerStateEvent -> workerStateEvent.consume()); - - // Transition to Scheduled state - task.simulateSchedule(); - // Events should have happened - assertTrue(scheduledCalled.get()); - } - - @Test public void onScheduledHandlerCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - SimpleTask task = new SimpleTask(); - task.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> handlerCalled.set(true)); - - task.simulateSchedule(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void removed_onScheduledHandlerNotCalled() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - SimpleTask task = new SimpleTask(); - EventHandler handler = workerStateEvent -> handlerCalled.set(true); - task.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, handler); - task.removeEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, handler); - task.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> sanity.set(true)); - - task.simulateSchedule(); - assertTrue(sanity.get()); - assertFalse(handlerCalled.get()); - } - - @Test public void removed_onScheduledFilterNotCalled() { - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean sanity = new AtomicBoolean(false); - SimpleTask task = new SimpleTask(); - EventHandler filter = workerStateEvent -> filterCalled.set(true); - task.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, filter); - task.removeEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, filter); - task.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> sanity.set(true)); - - task.simulateSchedule(); - assertTrue(sanity.get()); - assertFalse(filterCalled.get()); - } - - /*************************************************************************** - * - * Tests for onRunning - * - **************************************************************************/ - - @Test public void onRunningPropertyNameShouldMatchMethodName() { - Task task = new SimpleTask(); - assertEquals("onRunning", task.onRunningProperty().getName()); - } - - @Test public void onRunningBeanShouldMatchTask() { - Task task = new SimpleTask(); - assertSame(task, task.onRunningProperty().getBean()); - } - - @Test public void onRunningIsInitializedToNull() { - Task task = new SimpleTask(); - assertNull(task.getOnRunning()); - assertNull(task.onRunningProperty().get()); - } - - @Test public void onRunningCalledWhenSetViaProperty() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - SimpleTask task = new SimpleTask(); - task.onRunningProperty().set(workerStateEvent -> handlerCalled.set(true)); - - task.run(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void onRunningFilterCalledBefore_onRunning() { - SimpleTask task = new SimpleTask(); - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - task.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> filterCalled.set(true)); - task.setOnRunning(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - // Transition to Running state - task.run(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void runningCalledAfterHandler() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean runningCalledLast = new AtomicBoolean(false); - SimpleTask task = new SimpleTask() { - @Override protected void running() { - runningCalledLast.set(handlerCalled.get()); - } - }; - task.setOnRunning(workerStateEvent -> handlerCalled.set(true)); - - task.run(); - // Events should have happened - assertTrue(runningCalledLast.get()); - } - - @Test public void runningCalledAfterHandlerEvenIfConsumed() { - final AtomicBoolean runningCalled = new AtomicBoolean(false); - SimpleTask task = new SimpleTask() { - @Override protected void running() { - runningCalled.set(true); - } - }; - task.setOnRunning(workerStateEvent -> workerStateEvent.consume()); - - task.run(); - // Events should have happened - assertTrue(runningCalled.get()); - } - - /*************************************************************************** - * - * Tests for onSucceeded - * - **************************************************************************/ - - @Test public void onSucceededPropertyNameShouldMatchMethodName() { - Task task = new SimpleTask(); - assertEquals("onSucceeded", task.onSucceededProperty().getName()); - } - - @Test public void onSucceededBeanShouldMatchTask() { - Task task = new SimpleTask(); - assertSame(task, task.onSucceededProperty().getBean()); - } - - @Test public void onSucceededIsInitializedToNull() { - Task task = new SimpleTask(); - assertNull(task.getOnSucceeded()); - assertNull(task.onSucceededProperty().get()); - } - - @Test public void onSucceededCalledWhenSetViaProperty() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - SimpleTask task = new SimpleTask(); - task.onSucceededProperty().set(workerStateEvent -> handlerCalled.set(true)); - - task.run(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void onSucceededFilterCalledBefore_onSucceeded() { - SimpleTask task = new SimpleTask(); - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - task.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> filterCalled.set(true)); - task.setOnSucceeded(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - task.run(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void succeededCalledAfterHandler() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean succeededCalledLast = new AtomicBoolean(false); - SimpleTask task = new SimpleTask() { - @Override protected void succeeded() { - succeededCalledLast.set(handlerCalled.get()); - } - }; - task.setOnSucceeded(workerStateEvent -> handlerCalled.set(true)); - - task.run(); - // Events should have happened - assertTrue(succeededCalledLast.get()); - } - - @Test public void succeededCalledAfterHandlerEvenIfConsumed() { - final AtomicBoolean succeededCalled = new AtomicBoolean(false); - SimpleTask task = new SimpleTask() { - @Override protected void succeeded() { - succeededCalled.set(true); - } - }; - task.setOnSucceeded(workerStateEvent -> workerStateEvent.consume()); - - task.run(); - // Events should have happened - assertTrue(succeededCalled.get()); - } - - /*************************************************************************** - * - * Tests for onCancelled - * - **************************************************************************/ - - @Test public void onCancelledPropertyNameShouldMatchMethodName() { - Task task = new SimpleTask(); - assertEquals("onCancelled", task.onCancelledProperty().getName()); - } - - @Test public void onCancelledBeanShouldMatchTask() { - Task task = new SimpleTask(); - assertSame(task, task.onCancelledProperty().getBean()); - } - - @Test public void onCancelledIsInitializedToNull() { - Task task = new SimpleTask(); - assertNull(task.getOnCancelled()); - assertNull(task.onCancelledProperty().get()); - } - - @Test public void onCancelledCalledWhenSetViaProperty() throws Exception { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - InfiniteTask task = new InfiniteTask(); - task.onCancelledProperty().set(workerStateEvent -> handlerCalled.set(true)); - - Thread th = new Thread(task); - th.start(); - task.cancel(); - th.join(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void onCancelledFilterCalledBefore_onCancelled() throws Exception { - InfiniteTask task = new InfiniteTask(); - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - task.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> filterCalled.set(true)); - task.setOnCancelled(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - Thread th = new Thread(task); - th.start(); - task.cancel(); - th.join(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void cancelledCalledAfterHandler() throws Exception { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean cancelledCalledLast = new AtomicBoolean(false); - InfiniteTask task = new InfiniteTask() { - @Override protected void cancelled() { - cancelledCalledLast.set(handlerCalled.get()); - } - }; - task.setOnCancelled(workerStateEvent -> handlerCalled.set(true)); - - Thread th = new Thread(task); - th.start(); - task.cancel(); - th.join(); - // Events should have happened - assertTrue(cancelledCalledLast.get()); - } - - @Test public void cancelledCalledAfterHandlerEvenIfConsumed() throws Exception { - final AtomicBoolean cancelledCalled = new AtomicBoolean(false); - InfiniteTask task = new InfiniteTask() { - @Override protected void cancelled() { - cancelledCalled.set(true); - } - }; - task.setOnCancelled(workerStateEvent -> workerStateEvent.consume()); - - Thread th = new Thread(task); - th.start(); - task.cancel(); - th.join(); - // Events should have happened - assertTrue(cancelledCalled.get()); - } - - /*************************************************************************** - * - * Tests for onFailed - * - **************************************************************************/ - - @Test public void onFailedPropertyNameShouldMatchMethodName() { - Task task = new SimpleTask(); - assertEquals("onFailed", task.onFailedProperty().getName()); - } - - @Test public void onFailedBeanShouldMatchTask() { - Task task = new SimpleTask(); - assertSame(task, task.onFailedProperty().getBean()); - } - - @Test public void onFailedIsInitializedToNull() { - Task task = new SimpleTask(); - assertNull(task.getOnFailed()); - assertNull(task.onFailedProperty().get()); - } - - @Test public void onFailedCalledWhenSetViaProperty() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - Task task = new EpicFailTask(); - task.onFailedProperty().set(workerStateEvent -> handlerCalled.set(true)); - - task.run(); - // Events should have happened - assertTrue(handlerCalled.get()); - } - - @Test public void onFailedFilterCalledBefore_onFailed() { - Task task = new EpicFailTask(); - final AtomicBoolean filterCalled = new AtomicBoolean(false); - final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); - task.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> filterCalled.set(true)); - task.setOnFailed(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); - - task.run(); - // Events should have happened - assertTrue(filterCalledFirst.get()); - } - - @Test public void failedCalledAfterHandler() { - final AtomicBoolean handlerCalled = new AtomicBoolean(false); - final AtomicBoolean failedCalledLast = new AtomicBoolean(false); - EpicFailTask task = new EpicFailTask() { - @Override protected void failed() { - failedCalledLast.set(handlerCalled.get()); - } - }; - task.setOnFailed(workerStateEvent -> handlerCalled.set(true)); - - task.run(); - // Events should have happened - assertTrue(failedCalledLast.get()); - } - - @Test public void failedCalledAfterHandlerEvenIfConsumed() { - final AtomicBoolean failedCalled = new AtomicBoolean(false); - EpicFailTask task = new EpicFailTask() { - @Override protected void failed() { - failedCalled.set(true); - } - }; - task.setOnFailed(workerStateEvent -> workerStateEvent.consume()); - - task.run(); - // Events should have happened - assertTrue(failedCalled.get()); - } - - /*************************************************************************** - * - * A mythical subclass should be able to set an event handler and - * have events fired on the Service work. - * - **************************************************************************/ - - @Test public void eventFiredOnSubclassWorks() { - final AtomicBoolean result = new AtomicBoolean(false); - MythicalTask task = new MythicalTask(); - task.setHandler(mythicalEvent -> result.set(true)); - task.fireEvent(new MythicalEvent()); - assertTrue(result.get()); - } - - private static final class MythicalTask extends SimpleTask { - public void setHandler(EventHandler h) { - super.setEventHandler(MythicalEvent.ANY, h); - } - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/TaskEventTest.java 2015-09-11 21:25:37.565286168 -0400 @@ -0,0 +1,490 @@ +/* + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import java.util.concurrent.atomic.AtomicBoolean; +import javafx.concurrent.Task; +import javafx.concurrent.TaskShim; +import javafx.concurrent.WorkerStateEvent; +import test.javafx.concurrent.mocks.EpicFailTask; +import test.javafx.concurrent.mocks.InfiniteTask; +import test.javafx.concurrent.mocks.MythicalEvent; +import test.javafx.concurrent.mocks.SimpleTask; +import javafx.event.EventHandler; +import javafx.event.EventType; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Tests that the event notification machinery on Task works as expected. + * Event filters should be called before the onFoo methods, and the onFoo + * methods before the event handlers. The protected methods should be called + * in any case whether or not the event ends up consumed, and should always + * be called last. + */ +public class TaskEventTest { + + /*************************************************************************** + * + * Tests for onScheduled + * + **************************************************************************/ + + @Test public void onScheduledPropertyNameShouldMatchMethodName() { + Task task = new SimpleTask(); + assertEquals("onScheduled", task.onScheduledProperty().getName()); + } + + @Test public void onScheduledBeanShouldMatchTask() { + Task task = new SimpleTask(); + assertSame(task, task.onScheduledProperty().getBean()); + } + + @Test public void onScheduledIsInitializedToNull() { + Task task = new SimpleTask(); + assertNull(task.getOnScheduled()); + assertNull(task.onScheduledProperty().get()); + } + + @Test public void onScheduledCalledWhenSetViaProperty() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + SimpleTask task = new SimpleTask(); + task.onScheduledProperty().set(workerStateEvent -> handlerCalled.set(true)); + + task.simulateSchedule(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void onScheduledFilterCalledBefore_onScheduled() { + SimpleTask task = new SimpleTask(); + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + task.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> filterCalled.set(true)); + task.setOnScheduled(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + // Transition to Scheduled state + task.simulateSchedule(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void scheduledCalledAfterHandler() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean scheduledCalledLast = new AtomicBoolean(false); + SimpleTask task = new SimpleTask() { + @Override protected void scheduled() { + scheduledCalledLast.set(handlerCalled.get()); + } + }; + task.setOnScheduled(workerStateEvent -> handlerCalled.set(true)); + + // Transition to Scheduled state + task.simulateSchedule(); + // Events should have happened + assertTrue(scheduledCalledLast.get()); + } + + @Test public void scheduledCalledAfterHandlerEvenIfConsumed() { + final AtomicBoolean scheduledCalled = new AtomicBoolean(false); + SimpleTask task = new SimpleTask() { + @Override protected void scheduled() { + scheduledCalled.set(true); + } + }; + task.setOnScheduled(workerStateEvent -> workerStateEvent.consume()); + + // Transition to Scheduled state + task.simulateSchedule(); + // Events should have happened + assertTrue(scheduledCalled.get()); + } + + @Test public void onScheduledHandlerCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + SimpleTask task = new SimpleTask(); + task.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> handlerCalled.set(true)); + + task.simulateSchedule(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void removed_onScheduledHandlerNotCalled() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + SimpleTask task = new SimpleTask(); + EventHandler handler = workerStateEvent -> handlerCalled.set(true); + task.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, handler); + task.removeEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, handler); + task.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> sanity.set(true)); + + task.simulateSchedule(); + assertTrue(sanity.get()); + assertFalse(handlerCalled.get()); + } + + @Test public void removed_onScheduledFilterNotCalled() { + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean sanity = new AtomicBoolean(false); + SimpleTask task = new SimpleTask(); + EventHandler filter = workerStateEvent -> filterCalled.set(true); + task.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, filter); + task.removeEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, filter); + task.addEventFilter(WorkerStateEvent.WORKER_STATE_SCHEDULED, workerStateEvent -> sanity.set(true)); + + task.simulateSchedule(); + assertTrue(sanity.get()); + assertFalse(filterCalled.get()); + } + + /*************************************************************************** + * + * Tests for onRunning + * + **************************************************************************/ + + @Test public void onRunningPropertyNameShouldMatchMethodName() { + Task task = new SimpleTask(); + assertEquals("onRunning", task.onRunningProperty().getName()); + } + + @Test public void onRunningBeanShouldMatchTask() { + Task task = new SimpleTask(); + assertSame(task, task.onRunningProperty().getBean()); + } + + @Test public void onRunningIsInitializedToNull() { + Task task = new SimpleTask(); + assertNull(task.getOnRunning()); + assertNull(task.onRunningProperty().get()); + } + + @Test public void onRunningCalledWhenSetViaProperty() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + SimpleTask task = new SimpleTask(); + task.onRunningProperty().set(workerStateEvent -> handlerCalled.set(true)); + + task.run(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void onRunningFilterCalledBefore_onRunning() { + SimpleTask task = new SimpleTask(); + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + task.addEventFilter(WorkerStateEvent.WORKER_STATE_RUNNING, workerStateEvent -> filterCalled.set(true)); + task.setOnRunning(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + // Transition to Running state + task.run(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void runningCalledAfterHandler() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean runningCalledLast = new AtomicBoolean(false); + SimpleTask task = new SimpleTask() { + @Override protected void running() { + runningCalledLast.set(handlerCalled.get()); + } + }; + task.setOnRunning(workerStateEvent -> handlerCalled.set(true)); + + task.run(); + // Events should have happened + assertTrue(runningCalledLast.get()); + } + + @Test public void runningCalledAfterHandlerEvenIfConsumed() { + final AtomicBoolean runningCalled = new AtomicBoolean(false); + SimpleTask task = new SimpleTask() { + @Override protected void running() { + runningCalled.set(true); + } + }; + task.setOnRunning(workerStateEvent -> workerStateEvent.consume()); + + task.run(); + // Events should have happened + assertTrue(runningCalled.get()); + } + + /*************************************************************************** + * + * Tests for onSucceeded + * + **************************************************************************/ + + @Test public void onSucceededPropertyNameShouldMatchMethodName() { + Task task = new SimpleTask(); + assertEquals("onSucceeded", task.onSucceededProperty().getName()); + } + + @Test public void onSucceededBeanShouldMatchTask() { + Task task = new SimpleTask(); + assertSame(task, task.onSucceededProperty().getBean()); + } + + @Test public void onSucceededIsInitializedToNull() { + Task task = new SimpleTask(); + assertNull(task.getOnSucceeded()); + assertNull(task.onSucceededProperty().get()); + } + + @Test public void onSucceededCalledWhenSetViaProperty() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + SimpleTask task = new SimpleTask(); + task.onSucceededProperty().set(workerStateEvent -> handlerCalled.set(true)); + + task.run(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void onSucceededFilterCalledBefore_onSucceeded() { + SimpleTask task = new SimpleTask(); + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + task.addEventFilter(WorkerStateEvent.WORKER_STATE_SUCCEEDED, workerStateEvent -> filterCalled.set(true)); + task.setOnSucceeded(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + task.run(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void succeededCalledAfterHandler() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean succeededCalledLast = new AtomicBoolean(false); + SimpleTask task = new SimpleTask() { + @Override protected void succeeded() { + succeededCalledLast.set(handlerCalled.get()); + } + }; + task.setOnSucceeded(workerStateEvent -> handlerCalled.set(true)); + + task.run(); + // Events should have happened + assertTrue(succeededCalledLast.get()); + } + + @Test public void succeededCalledAfterHandlerEvenIfConsumed() { + final AtomicBoolean succeededCalled = new AtomicBoolean(false); + SimpleTask task = new SimpleTask() { + @Override protected void succeeded() { + succeededCalled.set(true); + } + }; + task.setOnSucceeded(workerStateEvent -> workerStateEvent.consume()); + + task.run(); + // Events should have happened + assertTrue(succeededCalled.get()); + } + + /*************************************************************************** + * + * Tests for onCancelled + * + **************************************************************************/ + + @Test public void onCancelledPropertyNameShouldMatchMethodName() { + Task task = new SimpleTask(); + assertEquals("onCancelled", task.onCancelledProperty().getName()); + } + + @Test public void onCancelledBeanShouldMatchTask() { + Task task = new SimpleTask(); + assertSame(task, task.onCancelledProperty().getBean()); + } + + @Test public void onCancelledIsInitializedToNull() { + Task task = new SimpleTask(); + assertNull(task.getOnCancelled()); + assertNull(task.onCancelledProperty().get()); + } + + @Test public void onCancelledCalledWhenSetViaProperty() throws Exception { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + InfiniteTask task = new InfiniteTask(); + task.onCancelledProperty().set(workerStateEvent -> handlerCalled.set(true)); + + Thread th = new Thread(task); + th.start(); + task.cancel(); + th.join(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void onCancelledFilterCalledBefore_onCancelled() throws Exception { + InfiniteTask task = new InfiniteTask(); + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + task.addEventFilter(WorkerStateEvent.WORKER_STATE_CANCELLED, workerStateEvent -> filterCalled.set(true)); + task.setOnCancelled(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + Thread th = new Thread(task); + th.start(); + task.cancel(); + th.join(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void cancelledCalledAfterHandler() throws Exception { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean cancelledCalledLast = new AtomicBoolean(false); + InfiniteTask task = new InfiniteTask() { + @Override protected void cancelled() { + cancelledCalledLast.set(handlerCalled.get()); + } + }; + task.setOnCancelled(workerStateEvent -> handlerCalled.set(true)); + + Thread th = new Thread(task); + th.start(); + task.cancel(); + th.join(); + // Events should have happened + assertTrue(cancelledCalledLast.get()); + } + + @Test public void cancelledCalledAfterHandlerEvenIfConsumed() throws Exception { + final AtomicBoolean cancelledCalled = new AtomicBoolean(false); + InfiniteTask task = new InfiniteTask() { + @Override protected void cancelled() { + cancelledCalled.set(true); + } + }; + task.setOnCancelled(workerStateEvent -> workerStateEvent.consume()); + + Thread th = new Thread(task); + th.start(); + task.cancel(); + th.join(); + // Events should have happened + assertTrue(cancelledCalled.get()); + } + + /*************************************************************************** + * + * Tests for onFailed + * + **************************************************************************/ + + @Test public void onFailedPropertyNameShouldMatchMethodName() { + Task task = new SimpleTask(); + assertEquals("onFailed", task.onFailedProperty().getName()); + } + + @Test public void onFailedBeanShouldMatchTask() { + Task task = new SimpleTask(); + assertSame(task, task.onFailedProperty().getBean()); + } + + @Test public void onFailedIsInitializedToNull() { + Task task = new SimpleTask(); + assertNull(task.getOnFailed()); + assertNull(task.onFailedProperty().get()); + } + + @Test public void onFailedCalledWhenSetViaProperty() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + Task task = new EpicFailTask(); + task.onFailedProperty().set(workerStateEvent -> handlerCalled.set(true)); + + task.run(); + // Events should have happened + assertTrue(handlerCalled.get()); + } + + @Test public void onFailedFilterCalledBefore_onFailed() { + Task task = new EpicFailTask(); + final AtomicBoolean filterCalled = new AtomicBoolean(false); + final AtomicBoolean filterCalledFirst = new AtomicBoolean(false); + task.addEventFilter(WorkerStateEvent.WORKER_STATE_FAILED, workerStateEvent -> filterCalled.set(true)); + task.setOnFailed(workerStateEvent -> filterCalledFirst.set(filterCalled.get())); + + task.run(); + // Events should have happened + assertTrue(filterCalledFirst.get()); + } + + @Test public void failedCalledAfterHandler() { + final AtomicBoolean handlerCalled = new AtomicBoolean(false); + final AtomicBoolean failedCalledLast = new AtomicBoolean(false); + EpicFailTask task = new EpicFailTask() { + @Override protected void failed() { + failedCalledLast.set(handlerCalled.get()); + } + }; + task.setOnFailed(workerStateEvent -> handlerCalled.set(true)); + + task.run(); + // Events should have happened + assertTrue(failedCalledLast.get()); + } + + @Test public void failedCalledAfterHandlerEvenIfConsumed() { + final AtomicBoolean failedCalled = new AtomicBoolean(false); + EpicFailTask task = new EpicFailTask() { + @Override protected void failed() { + failedCalled.set(true); + } + }; + task.setOnFailed(workerStateEvent -> workerStateEvent.consume()); + + task.run(); + // Events should have happened + assertTrue(failedCalled.get()); + } + + /*************************************************************************** + * + * A mythical subclass should be able to set an event handler and + * have events fired on the Service work. + * + **************************************************************************/ + + @Test public void eventFiredOnSubclassWorks() { + final AtomicBoolean result = new AtomicBoolean(false); + MythicalTask task = new MythicalTask(); + task.setHandler(mythicalEvent -> result.set(true)); + task.fireEvent(new MythicalEvent()); + assertTrue(result.get()); + } + + private static final class MythicalTask extends SimpleTask { + public void setHandler(EventHandler h) { + TaskShim.setEventHandler(this, MythicalEvent.ANY, h); + } + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/TaskExceptionTest.java 2015-09-11 21:25:38.505286157 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import java.util.Arrays; -import java.util.Collection; - -import javafx.concurrent.mocks.EpicFailTask; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import static org.junit.Assert.*; - -@RunWith(Parameterized.class) -public class TaskExceptionTest { - @Parameterized.Parameters public static Collection implementations() { - return Arrays.asList(new Object[][]{ - {new Exception("Exception")}, - {new IllegalArgumentException("IAE")}, - {new NullPointerException("NPE")}, - {new RuntimeException("RuntimeException")} - }); - } - - private Exception exception; - private Task task; - - public TaskExceptionTest(Exception th) { - this.exception = th; - } - - @Before public void setup() { - task = new EpicFailTask(exception); - } - - /************************************************************************ - * Run the task and check that the exception property is set, and that - * the value property is null. The progress fields may be in some - * arbitrary state. - ***********************************************************************/ - - @Test public void afterRunningExceptionShouldBeSet() { - task.run(); - assertNotNull(task.getException()); - } - - @Test public void afterRunningValueShouldBe_Null() { - task.run(); - assertNull(task.getValue()); - } - - @Test public void afterRunningWorkDoneShouldBe_10() { - task.run(); - assertEquals(10, task.getWorkDone(), 0); - } - - @Test public void afterRunningTotalWorkShouldBe_20() { - task.run(); - assertEquals(20, task.getTotalWork(), 0); - } - - @Test public void afterRunningProgressShouldBe_FiftyPercent() { - task.run(); - assertEquals(.5, task.getProgress(), 0); - } - - @Test public void afterRunningStateShouldBe_FAILED() { - task.run(); - assertEquals(Worker.State.FAILED, task.getState()); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/TaskExceptionTest.java 2015-09-11 21:25:38.325286159 -0400 @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import java.util.Arrays; +import java.util.Collection; +import javafx.concurrent.Task; +import javafx.concurrent.Worker; + +import test.javafx.concurrent.mocks.EpicFailTask; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import static org.junit.Assert.*; + +@RunWith(Parameterized.class) +public class TaskExceptionTest { + @Parameterized.Parameters public static Collection implementations() { + return Arrays.asList(new Object[][]{ + {new Exception("Exception")}, + {new IllegalArgumentException("IAE")}, + {new NullPointerException("NPE")}, + {new RuntimeException("RuntimeException")} + }); + } + + private Exception exception; + private Task task; + + public TaskExceptionTest(Exception th) { + this.exception = th; + } + + @Before public void setup() { + task = new EpicFailTask(exception); + } + + /************************************************************************ + * Run the task and check that the exception property is set, and that + * the value property is null. The progress fields may be in some + * arbitrary state. + ***********************************************************************/ + + @Test public void afterRunningExceptionShouldBeSet() { + task.run(); + assertNotNull(task.getException()); + } + + @Test public void afterRunningValueShouldBe_Null() { + task.run(); + assertNull(task.getValue()); + } + + @Test public void afterRunningWorkDoneShouldBe_10() { + task.run(); + assertEquals(10, task.getWorkDone(), 0); + } + + @Test public void afterRunningTotalWorkShouldBe_20() { + task.run(); + assertEquals(20, task.getTotalWork(), 0); + } + + @Test public void afterRunningProgressShouldBe_FiftyPercent() { + task.run(); + assertEquals(.5, task.getProgress(), 0); + } + + @Test public void afterRunningStateShouldBe_FAILED() { + task.run(); + assertEquals(Worker.State.FAILED, task.getState()); + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/TaskProgressTest.java 2015-09-11 21:25:39.265286148 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,268 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import javafx.concurrent.mocks.ProgressingTask; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * A Task which always completes normally, but which also progresses from - * 0 to 20 (inclusive). Initially the indeterminate state is used for - * progress and maxProgress, but during execution the progress and - * maxProgress are updated. - */ -public class TaskProgressTest { - private Task task; - - @Before public void setup() { - task = new ProgressingTask(); - } - - /************************************************************************ - * Run the task and check that the final progress and maxProgress and - * percentDone have correct values. - ***********************************************************************/ - - @Test public void afterRunningWorkDoneShouldBe_20() { - task.run(); - assertEquals(20, task.getWorkDone(), 0); - } - - @Test public void afterRunningTotalWorkShouldBe_20() { - task.run(); - assertEquals(20, task.getTotalWork(), 0); - } - - @Test public void afterRunningProgressShouldBe_1() { - task.run(); - assertEquals(1, task.getProgress(), 0); - } - - /************************************************************************ - * Test the updateProgress method on Task, that various inputs lead to - * expected outputs according to the specification - ***********************************************************************/ - - @Test public void updateProgress_Long_0_100() { - task.updateProgress(0, 100); - assertEquals(0, task.getProgress(), 0); - assertEquals(0, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_n1_100() { - task.updateProgress(-1, 100); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_n10_100() { - task.updateProgress(-10, 100); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_MIN_VALUE_100() { - task.updateProgress(Long.MIN_VALUE, 100); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_10_100() { - task.updateProgress(10, 100); - assertEquals(.1, task.getProgress(), 0); - assertEquals(10, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_100_100() { - task.updateProgress(100, 100); - assertEquals(1, task.getProgress(), 0); - assertEquals(100, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_110_100() { - task.updateProgress(110, 100); - assertEquals(1, task.getProgress(), 0); - assertEquals(100, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_MAX_VALUE_100() { - task.updateProgress(Long.MAX_VALUE, 100); - assertEquals(1, task.getProgress(), 0); - assertEquals(100, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_0_n1() { - task.updateProgress(0, -1); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_0_n10() { - task.updateProgress(0, -10); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_0_MIN_VALUE() { - task.updateProgress(0, Long.MIN_VALUE); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_100_10() { - task.updateProgress(100, 10); - assertEquals(1, task.getProgress(), 0); - assertEquals(10, task.getWorkDone(), 0); - assertEquals(10, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Long_100_MAX_VALUE() { - task.updateProgress(100, Long.MAX_VALUE); - assertEquals(100.0 / Long.MAX_VALUE, task.getProgress(), 0); - assertEquals(100, task.getWorkDone(), 0); - assertEquals(Long.MAX_VALUE, task.getTotalWork(), 0); - } - - /* Now test the Double variants (Infinity, NaN)*/ - @Test public void updateProgress_Double_Infinity_100() { - task.updateProgress(Double.POSITIVE_INFINITY, 100); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_NInfinity_100() { - task.updateProgress(Double.NEGATIVE_INFINITY, 100); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_NaN_100() { - task.updateProgress(Double.NaN, 100); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(100, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_0_Infinity() { - task.updateProgress(0, Double.POSITIVE_INFINITY); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_0_NInfinity() { - task.updateProgress(0, Double.NEGATIVE_INFINITY); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_0_NaN() { - task.updateProgress(0, Double.NaN); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_Infinity_Infinity() { - task.updateProgress(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_NInfinity_Infinity() { - task.updateProgress(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_Infinity_NInfinity() { - task.updateProgress(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_NInfinity_NInfinity() { - task.updateProgress(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_Infinity_NaN() { - task.updateProgress(Double.POSITIVE_INFINITY, Double.NaN); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_NInfinity_NaN() { - task.updateProgress(Double.NEGATIVE_INFINITY, Double.NaN); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_NaN_Infinity() { - task.updateProgress(Double.NaN, Double.POSITIVE_INFINITY); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_NaN_NInfinity() { - task.updateProgress(Double.NaN, Double.NEGATIVE_INFINITY); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void updateProgress_Double_NaN_NaN() { - task.updateProgress(Double.NaN, Double.NaN); - assertEquals(-1, task.getProgress(), 0); - assertEquals(-1, task.getWorkDone(), 0); - assertEquals(-1, task.getTotalWork(), 0); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/TaskProgressTest.java 2015-09-11 21:25:39.129286150 -0400 @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import javafx.concurrent.Task; +import javafx.concurrent.TaskShim; +import test.javafx.concurrent.mocks.ProgressingTask; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * A Task which always completes normally, but which also progresses from + * 0 to 20 (inclusive). Initially the indeterminate state is used for + * progress and maxProgress, but during execution the progress and + * maxProgress are updated. + */ +public class TaskProgressTest { + private Task task; + + @Before public void setup() { + task = new ProgressingTask(); + } + + /************************************************************************ + * Run the task and check that the final progress and maxProgress and + * percentDone have correct values. + ***********************************************************************/ + + @Test public void afterRunningWorkDoneShouldBe_20() { + task.run(); + assertEquals(20, task.getWorkDone(), 0); + } + + @Test public void afterRunningTotalWorkShouldBe_20() { + task.run(); + assertEquals(20, task.getTotalWork(), 0); + } + + @Test public void afterRunningProgressShouldBe_1() { + task.run(); + assertEquals(1, task.getProgress(), 0); + } + + /************************************************************************ + * Test the updateProgress method on Task, that various inputs lead to + * expected outputs according to the specification + ***********************************************************************/ + + @Test public void updateProgress_Long_0_100() { + TaskShim.updateProgress(task, 0, 100); + assertEquals(0, task.getProgress(), 0); + assertEquals(0, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_n1_100() { + TaskShim.updateProgress(task, -1, 100); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_n10_100() { + TaskShim.updateProgress(task, -10, 100); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_MIN_VALUE_100() { + TaskShim.updateProgress(task, Long.MIN_VALUE, 100); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_10_100() { + TaskShim.updateProgress(task, 10, 100); + assertEquals(.1, task.getProgress(), 0); + assertEquals(10, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_100_100() { + TaskShim.updateProgress(task, 100, 100); + assertEquals(1, task.getProgress(), 0); + assertEquals(100, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_110_100() { + TaskShim.updateProgress(task, 110, 100); + assertEquals(1, task.getProgress(), 0); + assertEquals(100, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_MAX_VALUE_100() { + TaskShim.updateProgress(task, Long.MAX_VALUE, 100); + assertEquals(1, task.getProgress(), 0); + assertEquals(100, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_0_n1() { + TaskShim.updateProgress(task, 0, -1); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_0_n10() { + TaskShim.updateProgress(task, 0, -10); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_0_MIN_VALUE() { + TaskShim.updateProgress(task, 0, Long.MIN_VALUE); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_100_10() { + TaskShim.updateProgress(task, 100, 10); + assertEquals(1, task.getProgress(), 0); + assertEquals(10, task.getWorkDone(), 0); + assertEquals(10, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Long_100_MAX_VALUE() { + TaskShim.updateProgress(task, 100, Long.MAX_VALUE); + assertEquals(100.0 / Long.MAX_VALUE, task.getProgress(), 0); + assertEquals(100, task.getWorkDone(), 0); + assertEquals(Long.MAX_VALUE, task.getTotalWork(), 0); + } + + /* Now test the Double variants (Infinity, NaN)*/ + @Test public void updateProgress_Double_Infinity_100() { + TaskShim.updateProgress(task, Double.POSITIVE_INFINITY, 100); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_NInfinity_100() { + TaskShim.updateProgress(task, Double.NEGATIVE_INFINITY, 100); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_NaN_100() { + TaskShim.updateProgress(task, Double.NaN, 100); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(100, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_0_Infinity() { + TaskShim.updateProgress(task, 0, Double.POSITIVE_INFINITY); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_0_NInfinity() { + TaskShim.updateProgress(task, 0, Double.NEGATIVE_INFINITY); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_0_NaN() { + TaskShim.updateProgress(task, 0, Double.NaN); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_Infinity_Infinity() { + TaskShim.updateProgress(task, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_NInfinity_Infinity() { + TaskShim.updateProgress(task, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_Infinity_NInfinity() { + TaskShim.updateProgress(task, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_NInfinity_NInfinity() { + TaskShim.updateProgress(task, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_Infinity_NaN() { + TaskShim.updateProgress(task, Double.POSITIVE_INFINITY, Double.NaN); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_NInfinity_NaN() { + TaskShim.updateProgress(task, Double.NEGATIVE_INFINITY, Double.NaN); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_NaN_Infinity() { + TaskShim.updateProgress(task, Double.NaN, Double.POSITIVE_INFINITY); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_NaN_NInfinity() { + TaskShim.updateProgress(task, Double.NaN, Double.NEGATIVE_INFINITY); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void updateProgress_Double_NaN_NaN() { + TaskShim.updateProgress(task, Double.NaN, Double.NaN); + assertEquals(-1, task.getProgress(), 0); + assertEquals(-1, task.getWorkDone(), 0); + assertEquals(-1, task.getTotalWork(), 0); + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/TaskSimpleTest.java 2015-09-11 21:25:39.949286141 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,185 +0,0 @@ -/* - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import javafx.beans.value.ChangeListener; -import javafx.beans.value.ObservableValue; -import java.util.ArrayList; -import java.util.List; - -import javafx.concurrent.mocks.SimpleTask; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * A Task which simply completes normally. It never throws an Exception. - * It also never increments the progress or touches messages or anything - * else. - */ -public class TaskSimpleTest { - private Task task; - - @Before public void setup() { - task = new SimpleTask(); - - // Checks that the running property is always correct. - task.runningProperty().addListener((o, oldValue, newValue) -> { - Worker.State s = task.getState(); - if (newValue) { - assertTrue(s == Worker.State.SCHEDULED || s == Worker.State.RUNNING); - } else { - assertTrue(s != Worker.State.SCHEDULED && s != Worker.State.RUNNING); - } - }); - } - - /************************************************************************ - * Test the initial values for the Task, - ***********************************************************************/ - - @Test public void stateShouldBe_READY_ByDefault() { - assertEquals(Task.State.READY, task.getState()); - } - - @Test public void workDoneShouldBe_Indeterminate_ByDefault() { - assertEquals(-1, task.getWorkDone(), 0); - } - - @Test public void totalWorkShouldBe_Indeterminate_ByDefault() { - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void progressShouldBe_Indeterminate_ByDefault() { - assertEquals(-1, task.getWorkDone(), 0); - } - - @Test public void valueShouldBe_Null_ByDefault() { - assertNull(task.getValue()); - } - - @Test public void exceptionShouldBe_Null_ByDefault() { - assertNull(task.getException()); - } - - @Test public void runningShouldBe_False_ByDefault() { - assertEquals(false, task.isRunning()); - } - - @Test public void messageShouldBe_EmptyString_ByDefault() { - assertEquals("", task.getMessage()); - } - - @Test public void titleShouldBe_EmptyString_ByDefault() { - assertEquals("", task.getTitle()); - } - - @Test public void isCancelledShouldBe_False_ByDefault() { - assertEquals(false, task.isCancelled()); - } - - @Test public void isDoneShouldBe_False_ByDefault() { - assertEquals(false, task.isDone()); - } - - /************************************************************************ - * Run the task and make sure that the states SCHEDULED, RUNNING, and - * SUCCEEDED were all encountered in order. Check the condition at the - * end of execution. Progress should equal maxProgress (-1 in this case), - * percentDone should still be -1. value should be "Sentinel" and - * exception should be null, running should be false. - ***********************************************************************/ - - @Test public void afterRunningStatesShouldHaveBeen_SCHEDULED_RUNNING_SUCCEEDED() { - final List states = new ArrayList(); - task.stateProperty().addListener((observable, oldValue, newValue) -> { - states.add(newValue); - }); - - task.run(); - - assertArrayEquals(states.toArray(), new Worker.State[]{ - Worker.State.SCHEDULED, - Worker.State.RUNNING, - Worker.State.SUCCEEDED - }); - } - - @Test public void afterRunningWorkDoneShouldBe_Indeterminate() { - task.run(); - assertEquals(-1, task.getWorkDone(), 0); - } - - @Test public void afterRunningTotalWorkShouldBe_Indeterminate() { - task.run(); - assertEquals(-1, task.getTotalWork(), 0); - } - - @Test public void afterRunningProgressShouldBe_Indeterminate() { - task.run(); - assertEquals(-1, task.getWorkDone(), 0); - } - - @Test public void afterRunningValueShouldBe_Finished() { - task.run(); - assertEquals("Sentinel", task.getValue()); - } - - @Test public void afterRunningExceptionShouldBe_Null() { - task.run(); - assertNull(task.getException()); - } - - @Test public void afterRunningMessageShouldBe_EmptyString() { - task.run(); - assertEquals("", task.getMessage()); - } - - @Test public void afterRunningTitleShouldBe_EmptyString() { - task.run(); - assertEquals("", task.getTitle()); - } - - @Test public void afterRunning_isCancelled_ShouldBe_False() { - task.run(); - assertEquals(false, task.isCancelled()); - } - - @Test public void afterRunning_isDone_ShouldBe_True() { - task.run(); - assertEquals(true, task.isDone()); - } - - /************************************************************************ - * TODO Need to resolve what should happen when get() is called - * The following few tests are setup so that we can test that - * invoking "get" instead of "run" still results in the state - * being set correctly for the Task. In theory, the exception, - * value, and other fields should be updated when get is called (?) - ***********************************************************************/ - -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/TaskSimpleTest.java 2015-09-11 21:25:39.809286142 -0400 @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import java.util.ArrayList; +import java.util.List; +import javafx.concurrent.Task; +import javafx.concurrent.Worker; + +import test.javafx.concurrent.mocks.SimpleTask; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * A Task which simply completes normally. It never throws an Exception. + * It also never increments the progress or touches messages or anything + * else. + */ +public class TaskSimpleTest { + private Task task; + + @Before public void setup() { + task = new SimpleTask(); + + // Checks that the running property is always correct. + task.runningProperty().addListener((o, oldValue, newValue) -> { + Worker.State s = task.getState(); + if (newValue) { + assertTrue(s == Worker.State.SCHEDULED || s == Worker.State.RUNNING); + } else { + assertTrue(s != Worker.State.SCHEDULED && s != Worker.State.RUNNING); + } + }); + } + + /************************************************************************ + * Test the initial values for the Task, + ***********************************************************************/ + + @Test public void stateShouldBe_READY_ByDefault() { + assertEquals(Task.State.READY, task.getState()); + } + + @Test public void workDoneShouldBe_Indeterminate_ByDefault() { + assertEquals(-1, task.getWorkDone(), 0); + } + + @Test public void totalWorkShouldBe_Indeterminate_ByDefault() { + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void progressShouldBe_Indeterminate_ByDefault() { + assertEquals(-1, task.getWorkDone(), 0); + } + + @Test public void valueShouldBe_Null_ByDefault() { + assertNull(task.getValue()); + } + + @Test public void exceptionShouldBe_Null_ByDefault() { + assertNull(task.getException()); + } + + @Test public void runningShouldBe_False_ByDefault() { + assertEquals(false, task.isRunning()); + } + + @Test public void messageShouldBe_EmptyString_ByDefault() { + assertEquals("", task.getMessage()); + } + + @Test public void titleShouldBe_EmptyString_ByDefault() { + assertEquals("", task.getTitle()); + } + + @Test public void isCancelledShouldBe_False_ByDefault() { + assertEquals(false, task.isCancelled()); + } + + @Test public void isDoneShouldBe_False_ByDefault() { + assertEquals(false, task.isDone()); + } + + /************************************************************************ + * Run the task and make sure that the states SCHEDULED, RUNNING, and + * SUCCEEDED were all encountered in order. Check the condition at the + * end of execution. Progress should equal maxProgress (-1 in this case), + * percentDone should still be -1. value should be "Sentinel" and + * exception should be null, running should be false. + ***********************************************************************/ + + @Test public void afterRunningStatesShouldHaveBeen_SCHEDULED_RUNNING_SUCCEEDED() { + final List states = new ArrayList(); + task.stateProperty().addListener((observable, oldValue, newValue) -> { + states.add(newValue); + }); + + task.run(); + + assertArrayEquals(states.toArray(), new Worker.State[]{ + Worker.State.SCHEDULED, + Worker.State.RUNNING, + Worker.State.SUCCEEDED + }); + } + + @Test public void afterRunningWorkDoneShouldBe_Indeterminate() { + task.run(); + assertEquals(-1, task.getWorkDone(), 0); + } + + @Test public void afterRunningTotalWorkShouldBe_Indeterminate() { + task.run(); + assertEquals(-1, task.getTotalWork(), 0); + } + + @Test public void afterRunningProgressShouldBe_Indeterminate() { + task.run(); + assertEquals(-1, task.getWorkDone(), 0); + } + + @Test public void afterRunningValueShouldBe_Finished() { + task.run(); + assertEquals("Sentinel", task.getValue()); + } + + @Test public void afterRunningExceptionShouldBe_Null() { + task.run(); + assertNull(task.getException()); + } + + @Test public void afterRunningMessageShouldBe_EmptyString() { + task.run(); + assertEquals("", task.getMessage()); + } + + @Test public void afterRunningTitleShouldBe_EmptyString() { + task.run(); + assertEquals("", task.getTitle()); + } + + @Test public void afterRunning_isCancelled_ShouldBe_False() { + task.run(); + assertEquals(false, task.isCancelled()); + } + + @Test public void afterRunning_isDone_ShouldBe_True() { + task.run(); + assertEquals(true, task.isDone()); + } + + /************************************************************************ + * TODO Need to resolve what should happen when get() is called + * The following few tests are setup so that we can test that + * invoking "get" instead of "run" still results in the state + * being set correctly for the Task. In theory, the exception, + * value, and other fields should be updated when get is called (?) + ***********************************************************************/ + +} --- old/modules/graphics/src/test/java/javafx/concurrent/TaskSwampEventQueueTest.java 2015-09-11 21:25:40.637286133 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CyclicBarrier; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * In this test, the Task is going to attempt to totally swamp the - * Event Queue by posting message updates very rapidly (that is, - * the background threaded code isn't going to worry about it, - * it is just going to send progress updates thousands of times - * each second, and it is up to the Task implementation to - * coalesce these down into a very sustainable number of entries - * on the event queue. Basically, there should only ever be one - * event on the event queue which gets the most recent value). - */ -public class TaskSwampEventQueueTest { - private CyclicBarrier barrier; - private List eventQueue; - private Task task; - private Thread th; - - @Before public void setup() { - barrier = new CyclicBarrier(2); - eventQueue = new ArrayList<>(); - task = new AbstractTask() { - @Override protected String call() throws Exception { - for (int i=0; i<1000; i++) { - updateProgress(i, 2000); - } - barrier.await(); // I will wait here until the test code is read - barrier.await(); // I will wait here until the test code tells me to continue - for (int i=1000; i<=2000; i++) { - updateProgress(i, 2000); - } - barrier.await(); // I'm done basically - return "Sentinel"; - } - - @Override boolean isFxApplicationThread() { - return Thread.currentThread() != th; - } - - @Override void runLater(Runnable r) { - eventQueue.add(r); - } - }; - } - - @Test public void numberOfEventsOnTheEventQueueShouldNeverBeLarge() throws Exception { - th = new Thread(task); - th.start(); - - barrier.await(); - // There may actually 2 runnables on the queue, the first is the one that updates - // the "state" of the Task, and the second is the progress update. - assertTrue(eventQueue.size() == 2 || eventQueue.size() == 1); - while (eventQueue.size() > 0) eventQueue.remove(0).run(); - assertEquals(1000 - 1, task.getWorkDone(), 0); - assertEquals(2000, task.getTotalWork(), 0); - barrier.await(); - barrier.await(); - // There may be another 2 runnables on the queue, the first is the progress update, - // the second sets the value & updates the state of the Task. - assertTrue(eventQueue.size() == 2 || eventQueue.size() == 1); - while (eventQueue.size() > 0) eventQueue.remove(0).run(); - assertEquals(2000, task.getWorkDone(), 0); - assertEquals(2000, task.getTotalWork(), 0); - } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/TaskSwampEventQueueTest.java 2015-09-11 21:25:40.425286135 -0400 @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CyclicBarrier; +import javafx.concurrent.Task; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * In this test, the Task is going to attempt to totally swamp the + * Event Queue by posting message updates very rapidly (that is, + * the background threaded code isn't going to worry about it, + * it is just going to send progress updates thousands of times + * each second, and it is up to the Task implementation to + * coalesce these down into a very sustainable number of entries + * on the event queue. Basically, there should only ever be one + * event on the event queue which gets the most recent value). + */ +public class TaskSwampEventQueueTest { + private CyclicBarrier barrier; + private List eventQueue; + private Task task; + private Thread th; + + @Before public void setup() { + barrier = new CyclicBarrier(2); + eventQueue = new ArrayList<>(); + task = new AbstractTask() { + @Override protected String call() throws Exception { + for (int i=0; i<1000; i++) { + updateProgress(i, 2000); + } + barrier.await(); // I will wait here until the test code is read + barrier.await(); // I will wait here until the test code tells me to continue + for (int i=1000; i<=2000; i++) { + updateProgress(i, 2000); + } + barrier.await(); // I'm done basically + return "Sentinel"; + } + + @Override public boolean isFxApplicationThread() { + return Thread.currentThread() != th; + } + + @Override public void runLater(Runnable r) { + eventQueue.add(r); + } + }; + } + + @Test public void numberOfEventsOnTheEventQueueShouldNeverBeLarge() throws Exception { + th = new Thread(task); + th.start(); + + barrier.await(); + // There may actually 2 runnables on the queue, the first is the one that updates + // the "state" of the Task, and the second is the progress update. + assertTrue(eventQueue.size() == 2 || eventQueue.size() == 1); + while (eventQueue.size() > 0) eventQueue.remove(0).run(); + assertEquals(1000 - 1, task.getWorkDone(), 0); + assertEquals(2000, task.getTotalWork(), 0); + barrier.await(); + barrier.await(); + // There may be another 2 runnables on the queue, the first is the progress update, + // the second sets the value & updates the state of the Task. + assertTrue(eventQueue.size() == 2 || eventQueue.size() == 1); + while (eventQueue.size() > 0) eventQueue.remove(0).run(); + assertEquals(2000, task.getWorkDone(), 0); + assertEquals(2000, task.getTotalWork(), 0); + } +} --- old/modules/graphics/src/test/java/javafx/concurrent/TestServiceFactory.java 2015-09-11 21:25:41.329286125 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.concurrent; - -/** - * The Task and Service tests need to do a little trickery due to threading. - * Although in practice they run on different threads (ie: the UI and - * background threads), while testing I want to be able to run predictably - * and quickly on just the test thread. This implementation of - * Service is used as the base implementation of all Services which are - * tested. It will simply run the given command immediately, and makes - * sure the checkThread does nothing. - */ -public abstract class TestServiceFactory { - public final Thread appThread = Thread.currentThread(); - public ServiceTestBase test; - protected AbstractTask currentTask; - - protected abstract AbstractTask createTestTask(); - protected Service createService() { - return new Service() { - @Override protected Task createTask() { - currentTask = createTestTask(); - currentTask.test = test; - currentTask.appThread = appThread; - return currentTask; - } - - @Override boolean isFxApplicationThread() { - return Thread.currentThread() == appThread; - } - - @Override void runLater(Runnable r) { - if (test != null) { - test.eventQueue.add(r); - } else { - r.run(); - } - } - }; - } - - public final AbstractTask getCurrentTask() { return currentTask; } -} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/TestServiceFactory.java 2015-09-11 21:25:41.141286127 -0400 @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent; + +import javafx.concurrent.Service; +import javafx.concurrent.ServiceShim; +import javafx.concurrent.Task; + +/** + * The Task and Service tests need to do a little trickery due to threading. + * Although in practice they run on different threads (ie: the UI and + * background threads), while testing I want to be able to run predictably + * and quickly on just the test thread. This implementation of + * Service is used as the base implementation of all Services which are + * tested. It will simply run the given command immediately, and makes + * sure the checkThread does nothing. + */ +public abstract class TestServiceFactory { + public final Thread appThread = Thread.currentThread(); + public ServiceTestBase test; + public AbstractTask currentTask; + + public abstract AbstractTask createTestTask(); + public Service createService() { + return new ServiceShim() { + @Override protected Task createTask() { + currentTask = createTestTask(); + currentTask.set_test(test); + currentTask.appThread = appThread; + return currentTask; + } + + @Override public boolean isFxApplicationThread() { + return Thread.currentThread() == appThread; + } + + @Override public void runLater(Runnable r) { + if (test != null) { + test.eventQueue.add(r); + } else { + r.run(); + } + } + }; + } + + public final AbstractTask getCurrentTask() { return currentTask; } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/mocks/EpicFailTask.java 2015-09-11 21:25:41.873286119 -0400 @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent.mocks; + +import test.javafx.concurrent.AbstractTask; +import javafx.concurrent.TaskShim; + +/** + * + */ +public class EpicFailTask extends AbstractTask { + private Exception exception; + + public EpicFailTask() { + this(new Exception("Failure")); + } + + public EpicFailTask(Exception exception) { + this.exception = exception; + } + + @Override protected String call() throws Exception { + updateProgress(10, 20); + updateMessage("About to fail"); + updateTitle("Epic Fail"); + throw exception; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/mocks/InfiniteTask.java 2015-09-11 21:25:42.709286110 -0400 @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent.mocks; + +import test.javafx.concurrent.AbstractTask; + +/** + * + */ +public class InfiniteTask extends AbstractTask { + @SuppressWarnings("InfiniteLoopStatement") + @Override protected String call() throws Exception { + while (true) { + Thread.sleep(1); // Cancel will eventually end up here? + } + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/mocks/MythicalEvent.java 2015-09-11 21:25:43.449286101 -0400 @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent.mocks; + +import javafx.event.Event; +import javafx.event.EventType; + +/** + * An event subclass that is used in several of the tests + */ +public class MythicalEvent extends Event { + public static final EventType ANY = new EventType<>(Event.ANY, "MYTHICAL"); + + public MythicalEvent() { + super(ANY); + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/mocks/ProgressingTask.java 2015-09-11 21:25:44.197286093 -0400 @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent.mocks; + +import test.javafx.concurrent.AbstractTask; + +/** + * + */ +public class ProgressingTask extends AbstractTask { + @Override protected String call() throws Exception { + for (int i=0; i<=20; i++) { + updateProgress(i, 20); + } + return "Sentinel"; + } +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/mocks/RunAwayTask.java 2015-09-11 21:25:44.941286085 -0400 @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent.mocks; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import test.javafx.concurrent.AbstractTask; + +/** + * A Task which will simply loop forever without end. This is used to simulate + * what happens when a task doesn't head the "isCancelled" flag or + * cancellation in any way. To make sure it finally does terminate (so the + * tests will work) there is a stopLooping atomic boolean that + * the test needs to set to true. + * + *

To make sure that a single loop has occurred before we quit, there is + * a loopHasHappened boolean. This way we always know that + * a single iteration has completed, at least, before the task was + * terminated.

+ * + *

Different tests want to use a RunAwayTask differently. Some want to + * call updateValue in the body of the loop, while others do not. For this + * reason, the RunAwayTask is abstract and an abstract loop + * method is defined that a subclass implements to implement the body + * of the loop.

+ */ +public abstract class RunAwayTask extends AbstractTask { + public AtomicBoolean stopLooping = new AtomicBoolean(false); + private boolean loopHasHappened = false; + + @Override protected String call() throws Exception { + int count = 0; + while (!loopHasHappened || !stopLooping.get()) { + count++; + loop(count); + loopHasHappened = true; + } + return "" + count; + } + + protected abstract void loop(int count) throws Exception; + +} --- /dev/null 2015-09-11 11:06:08.592686920 -0400 +++ new/modules/graphics/src/test/java/test/javafx/concurrent/mocks/SimpleTask.java 2015-09-11 21:25:45.689286076 -0400 @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package test.javafx.concurrent.mocks; + +import test.javafx.concurrent.AbstractTask; + +/** + * + */ +public class SimpleTask extends AbstractTask { + @Override protected String call() throws Exception { + return "Sentinel"; + } +} --- old/modules/graphics/src/test/java/javafx/css/CssLexerTest.java 2015-09-11 21:25:46.569286066 -0400 +++ /dev/null 2015-09-11 11:06:08.592686920 -0400 @@ -1,849 +0,0 @@ -/* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package javafx.css; - -import com.sun.javafx.css.parser.Token; - -import java.io.CharArrayReader; -import java.io.Reader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import static org.junit.Assert.*; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - - -public class CssLexerTest { - - public CssLexerTest() { - } - - private void checkTokens(List resultTokens, Token... expectedTokens) - throws org.junit.ComparisonFailure { - - if (expectedTokens.length != resultTokens.size()) { - throw new org.junit.ComparisonFailure( - "lengths do not match", - Arrays.toString(expectedTokens), - resultTokens.toString() - ); - } - - for (int n = 0; n getTokens(String string) { - - Reader reader = new CharArrayReader(string.toCharArray()); - final CssLexer lexer = new CssLexer(); - lexer.setReader(reader); - - final List tokens = new ArrayList(); - - Token token = null; - do { - token = lexer.nextToken(); - tokens.add(token); - } while (token.getType() != Token.EOF); - - return Collections.unmodifiableList(tokens); - } - - private void lexDigitsWithUnits(String units, int type) throws org.junit.ComparisonFailure { - - checkTokens(getTokens("123"+units), new Token(type, "123"+units), Token.EOF_TOKEN); - checkTokens(getTokens("123.45"+units), new Token(type, "123.45"+units), Token.EOF_TOKEN); - checkTokens(getTokens(".45"+units), new Token(type, ".45"+units), Token.EOF_TOKEN); - checkTokens(getTokens("-123"+units), new Token(type, "-123"+units), Token.EOF_TOKEN); - checkTokens(getTokens("-.45"+units), new Token(type, "-.45"+units), Token.EOF_TOKEN); - checkTokens(getTokens("+123"+units), new Token(type, "+123"+units), Token.EOF_TOKEN); - checkTokens(getTokens("+.45"+units), new Token(type, "+.45"+units), Token.EOF_TOKEN); - } - - @Test - public void testLexValidDigits() { - lexDigitsWithUnits("", CssLexer.NUMBER); - } - - @Test - public void testLexValidDigitsWithCM() { - lexDigitsWithUnits("cm", CssLexer.CM); - // case should be ignored - lexDigitsWithUnits("cM", CssLexer.CM); - } - @Test - public void testLexValidDigitsWithDEG() { - lexDigitsWithUnits("deg", CssLexer.DEG); - // case should be ignored - lexDigitsWithUnits("dEg", CssLexer.DEG); - } - @Test - public void testLexValidDigitsWithEM() { - lexDigitsWithUnits("em", CssLexer.EMS); - // case should be ignored - lexDigitsWithUnits("Em", CssLexer.EMS); - } - @Test - public void testLexValidDigitsWithEX() { - lexDigitsWithUnits("ex", CssLexer.EXS); - // case should be ignored - lexDigitsWithUnits("Ex", CssLexer.EXS); - } - @Test - public void testLexValidDigitsWithGRAD() { - lexDigitsWithUnits("grad", CssLexer.GRAD); - // case should be ignored - lexDigitsWithUnits("gRad", CssLexer.GRAD); - } - @Test - public void testLexValidDigitsWithIN() { - lexDigitsWithUnits("in", CssLexer.IN); - // case should be ignored - lexDigitsWithUnits("In", CssLexer.IN); - } - @Test - public void testLexValidDigitsWithMM() { - lexDigitsWithUnits("mm", CssLexer.MM); - // case should be ignored - lexDigitsWithUnits("mM", CssLexer.MM); - } - @Test - public void testLexValidDigitsWithPC() { - lexDigitsWithUnits("pc", CssLexer.PC); - // case should be ignored - lexDigitsWithUnits("Pc", CssLexer.PC); - } - @Test - public void testLexValidDigitsWithPT() { - lexDigitsWithUnits("pt", CssLexer.PT); - // case should be ignored - lexDigitsWithUnits("PT", CssLexer.PT); - } - @Test - public void testLexValidDigitsWithPX() { - lexDigitsWithUnits("px", CssLexer.PX); - // case should be ignored - lexDigitsWithUnits("Px", CssLexer.PX); - } - @Test - public void testLexValidDigitsWithRAD() { - lexDigitsWithUnits("rad", CssLexer.RAD); - // case should be ignored - lexDigitsWithUnits("RaD", CssLexer.RAD); - } - @Test - public void testLexValidDigitsWithTURN() { - lexDigitsWithUnits("turn", CssLexer.TURN); - // case should be ignored - lexDigitsWithUnits("TurN", CssLexer.TURN); - } - @Test - public void testLexValidDigitsWithS() { - lexDigitsWithUnits("s", CssLexer.SECONDS); - // case should be ignored - lexDigitsWithUnits("S", CssLexer.SECONDS); - } - @Test - public void testLexValidDigitsWithMS() { - lexDigitsWithUnits("ms", CssLexer.MS); - // case should be ignored - lexDigitsWithUnits("mS", CssLexer.MS); - } - @Test - public void testLexValidDigitsWithPCT() { - lexDigitsWithUnits("%", CssLexer.PERCENTAGE); - } - @Test - public void testLexValidDigitsWithBadUnits() { - lexDigitsWithUnits("xyzzy", Token.INVALID); - } - @Test - public void textLexValidDigitsValidDigits() { - checkTokens( - getTokens("foo: 10pt; bar: 20%;"), - new Token(CssLexer.IDENT, "foo"), - new Token(CssLexer.COLON, ":"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.PT, "10pt"), - new Token(CssLexer.SEMI, ";"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.IDENT, "bar"), - new Token(CssLexer.COLON, ":"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.PERCENTAGE, "20%"), - new Token(CssLexer.SEMI, ";"), - Token.EOF_TOKEN - ); - } - @Test - public void textLexInvalidDigitsValidDigits() { - checkTokens( - getTokens("foo: 10pz; bar: 20%;"), - new Token(CssLexer.IDENT, "foo"), - new Token(CssLexer.COLON, ":"), - new Token(CssLexer.WS, " "), - new Token(Token.INVALID, "10pz"), - new Token(CssLexer.SEMI, ";"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.IDENT, "bar"), - new Token(CssLexer.COLON, ":"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.PERCENTAGE, "20%"), - new Token(CssLexer.SEMI, ";"), - Token.EOF_TOKEN - ); - } - @Test - public void textLexValidDigitsBangImportant() { - checkTokens( - getTokens("foo: 10pt !important;"), - new Token(CssLexer.IDENT, "foo"), - new Token(CssLexer.COLON, ":"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.PT, "10pt"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.IMPORTANT_SYM, "!important"), - new Token(CssLexer.SEMI, ";"), - Token.EOF_TOKEN - ); - } - @Test - public void textLexInvalidDigitsBangImportant() { - checkTokens( - getTokens("foo: 10pz !important;"), - new Token(CssLexer.IDENT, "foo"), - new Token(CssLexer.COLON, ":"), - new Token(CssLexer.WS, " "), - new Token(Token.INVALID, "10pz"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.IMPORTANT_SYM, "!important"), - new Token(CssLexer.SEMI, ";"), - Token.EOF_TOKEN - ); - } - @Test - public void textLexValidDigitsInSequence() { - checkTokens( - getTokens("-1 0px 1pt .5em;"), - new Token(CssLexer.NUMBER, "-1"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.PX, "0px"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.PT, "1pt"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.EMS, ".5em"), - new Token(CssLexer.SEMI, ";"), - Token.EOF_TOKEN - ); - } - @Test - public void textLexInvalidDigitsInSequence() { - checkTokens( - getTokens("-1 0px 1pz .5em;"), - new Token(CssLexer.NUMBER, "-1"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.PX, "0px"), - new Token(CssLexer.WS, " "), - new Token(Token.INVALID, "1pz"), - new Token(CssLexer.WS, " "), - new Token(CssLexer.EMS, ".5em"), - new Token(CssLexer.SEMI, ";"), - Token.EOF_TOKEN - ); - } - - @Test - public void testTokenOffset() { - - String str = "a: b;"; - // [?][0] = line - // [?][1] = offset - Token[] expected = { - new Token(CssLexer.IDENT, "a", 1, 0), - new Token(CssLexer.COLON, ":", 1, 1), - new Token(CssLexer.WS, " ", 1, 2), - new Token(CssLexer.IDENT, "b", 1, 3), - new Token(CssLexer.SEMI, ";", 1, 4), - Token.EOF_TOKEN - }; - - List tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n tlist = getTokens(str); - checkTokens(tlist, expected); - - for(int n=0; n resultTokens, TokenShim... expectedTokens) + throws org.junit.ComparisonFailure { + + if (expectedTokens.length != resultTokens.size()) { + throw new org.junit.ComparisonFailure( + "lengths do not match", + Arrays.toString(expectedTokens), + resultTokens.toString() + ); + } + + for (int n = 0; n getTokens(String string) { + + Reader reader = new CharArrayReader(string.toCharArray()); + final CssLexerShim lexer = new CssLexerShim(); + lexer.setReader(reader); + + final List tokens = new ArrayList(); + + TokenShim token = null; + do { + token = lexer.nextToken(); + tokens.add(token); + } while (token.getType() != Token.EOF); + + return Collections.unmodifiableList(tokens); + } + + private void lexDigitsWithUnits(String units, int type) throws org.junit.ComparisonFailure { + + checkTokens(getTokens("123"+units), new TokenShim(type, "123"+units), TokenShim.EOF_TOKEN); + checkTokens(getTokens("123.45"+units), new TokenShim(type, "123.45"+units), TokenShim.EOF_TOKEN); + checkTokens(getTokens(".45"+units), new TokenShim(type, ".45"+units), TokenShim.EOF_TOKEN); + checkTokens(getTokens("-123"+units), new TokenShim(type, "-123"+units), TokenShim.EOF_TOKEN); + checkTokens(getTokens("-.45"+units), new TokenShim(type, "-.45"+units), TokenShim.EOF_TOKEN); + checkTokens(getTokens("+123"+units), new TokenShim(type, "+123"+units), TokenShim.EOF_TOKEN); + checkTokens(getTokens("+.45"+units), new TokenShim(type, "+.45"+units), TokenShim.EOF_TOKEN); + } + + @Test + public void testLexValidDigits() { + lexDigitsWithUnits("", CssLexerShim.NUMBER); + } + + @Test + public void testLexValidDigitsWithCM() { + lexDigitsWithUnits("cm", CssLexerShim.CM); + // case should be ignored + lexDigitsWithUnits("cM", CssLexerShim.CM); + } + @Test + public void testLexValidDigitsWithDEG() { + lexDigitsWithUnits("deg", CssLexerShim.DEG); + // case should be ignored + lexDigitsWithUnits("dEg", CssLexerShim.DEG); + } + @Test + public void testLexValidDigitsWithEM() { + lexDigitsWithUnits("em", CssLexerShim.EMS); + // case should be ignored + lexDigitsWithUnits("Em", CssLexerShim.EMS); + } + @Test + public void testLexValidDigitsWithEX() { + lexDigitsWithUnits("ex", CssLexerShim.EXS); + // case should be ignored + lexDigitsWithUnits("Ex", CssLexerShim.EXS); + } + @Test + public void testLexValidDigitsWithGRAD() { + lexDigitsWithUnits("grad", CssLexerShim.GRAD); + // case should be ignored + lexDigitsWithUnits("gRad", CssLexerShim.GRAD); + } + @Test + public void testLexValidDigitsWithIN() { + lexDigitsWithUnits("in", CssLexerShim.IN); + // case should be ignored + lexDigitsWithUnits("In", CssLexerShim.IN); + } + @Test + public void testLexValidDigitsWithMM() { + lexDigitsWithUnits("mm", CssLexerShim.MM); + // case should be ignored + lexDigitsWithUnits("mM", CssLexerShim.MM); + } + @Test + public void testLexValidDigitsWithPC() { + lexDigitsWithUnits("pc", CssLexerShim.PC); + // case should be ignored + lexDigitsWithUnits("Pc", CssLexerShim.PC); + } + @Test + public void testLexValidDigitsWithPT() { + lexDigitsWithUnits("pt", CssLexerShim.PT); + // case should be ignored + lexDigitsWithUnits("PT", CssLexerShim.PT); + } + @Test + public void testLexValidDigitsWithPX() { + lexDigitsWithUnits("px", CssLexerShim.PX); + // case should be ignored + lexDigitsWithUnits("Px", CssLexerShim.PX); + } + @Test + public void testLexValidDigitsWithRAD() { + lexDigitsWithUnits("rad", CssLexerShim.RAD); + // case should be ignored + lexDigitsWithUnits("RaD", CssLexerShim.RAD); + } + @Test + public void testLexValidDigitsWithTURN() { + lexDigitsWithUnits("turn", CssLexerShim.TURN); + // case should be ignored + lexDigitsWithUnits("TurN", CssLexerShim.TURN); + } + @Test + public void testLexValidDigitsWithS() { + lexDigitsWithUnits("s", CssLexerShim.SECONDS); + // case should be ignored + lexDigitsWithUnits("S", CssLexerShim.SECONDS); + } + @Test + public void testLexValidDigitsWithMS() { + lexDigitsWithUnits("ms", CssLexerShim.MS); + // case should be ignored + lexDigitsWithUnits("mS", CssLexerShim.MS); + } + @Test + public void testLexValidDigitsWithPCT() { + lexDigitsWithUnits("%", CssLexerShim.PERCENTAGE); + } + @Test + public void testLexValidDigitsWithBadUnits() { + lexDigitsWithUnits("xyzzy", Token.INVALID); + } + @Test + public void textLexValidDigitsValidDigits() { + checkTokens( + getTokens("foo: 10pt; bar: 20%;"), + new TokenShim(CssLexerShim.IDENT, "foo"), + new TokenShim(CssLexerShim.COLON, ":"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.PT, "10pt"), + new TokenShim(CssLexerShim.SEMI, ";"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.IDENT, "bar"), + new TokenShim(CssLexerShim.COLON, ":"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.PERCENTAGE, "20%"), + new TokenShim(CssLexerShim.SEMI, ";"), + TokenShim.EOF_TOKEN + ); + } + @Test + public void textLexInvalidDigitsValidDigits() { + checkTokens( + getTokens("foo: 10pz; bar: 20%;"), + new TokenShim(CssLexerShim.IDENT, "foo"), + new TokenShim(CssLexerShim.COLON, ":"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(Token.INVALID, "10pz"), + new TokenShim(CssLexerShim.SEMI, ";"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.IDENT, "bar"), + new TokenShim(CssLexerShim.COLON, ":"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.PERCENTAGE, "20%"), + new TokenShim(CssLexerShim.SEMI, ";"), + TokenShim.EOF_TOKEN + ); + } + @Test + public void textLexValidDigitsBangImportant() { + checkTokens( + getTokens("foo: 10pt !important;"), + new TokenShim(CssLexerShim.IDENT, "foo"), + new TokenShim(CssLexerShim.COLON, ":"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.PT, "10pt"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.IMPORTANT_SYM, "!important"), + new TokenShim(CssLexerShim.SEMI, ";"), + TokenShim.EOF_TOKEN + ); + } + @Test + public void textLexInvalidDigitsBangImportant() { + checkTokens( + getTokens("foo: 10pz !important;"), + new TokenShim(CssLexerShim.IDENT, "foo"), + new TokenShim(CssLexerShim.COLON, ":"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(Token.INVALID, "10pz"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.IMPORTANT_SYM, "!important"), + new TokenShim(CssLexerShim.SEMI, ";"), + TokenShim.EOF_TOKEN + ); + } + @Test + public void textLexValidDigitsInSequence() { + checkTokens( + getTokens("-1 0px 1pt .5em;"), + new TokenShim(CssLexerShim.NUMBER, "-1"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.PX, "0px"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.PT, "1pt"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.EMS, ".5em"), + new TokenShim(CssLexerShim.SEMI, ";"), + TokenShim.EOF_TOKEN + ); + } + @Test + public void textLexInvalidDigitsInSequence() { + checkTokens( + getTokens("-1 0px 1pz .5em;"), + new TokenShim(CssLexerShim.NUMBER, "-1"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.PX, "0px"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(Token.INVALID, "1pz"), + new TokenShim(CssLexerShim.WS, " "), + new TokenShim(CssLexerShim.EMS, ".5em"), + new TokenShim(CssLexerShim.SEMI, ";"), + TokenShim.EOF_TOKEN + ); + } + + @Test + public void testTokenOffset() { + + String str = "a: b;"; + // [?][0] = line + // [?][1] = offset + TokenShim[] expected = { + new TokenShim(CssLexerShim.IDENT, "a", 1, 0), + new TokenShim(CssLexerShim.COLON, ":", 1, 1), + new TokenShim(CssLexerShim.WS, " ", 1, 2), + new TokenShim(CssLexerShim.IDENT, "b", 1, 3), + new TokenShim(CssLexerShim.SEMI, ";", 1, 4), + TokenShim.EOF_TOKEN + }; + + List tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n tlist = getTokens(str); + checkTokens(tlist, expected); + + for(int n=0; n> list, String prop) { - for (CssMetaData styleable : list) { - if (prop.equals(styleable.getProperty())) return styleable; - } - return null; - } - - /** - * Test of getCssMetaData method of class Styleable. - */ - @Test - public void testGetCssMetaData_Styleable() { - Styleable styleable = new TestNode(); - List> expResult = TestNode.getClassCssMetaData(); - List result = styleable.getCssMetaData(); - assertEquals(expResult, result); - } - - @Test - public void testGetJavafxBeansProperty() { - TestNode testNode = new TestNode(); - WritableValue prop = TestNodeBase.StyleableProperties.TEST.getStyleableProperty(testNode); - assert(prop != null); - CssMetaData result = ((StyleableProperty)prop).getCssMetaData(); - assert(result == TestNodeBase.StyleableProperties.TEST); - } - - /** - * Test of getProperty method, of class CssMetaData. - */ - @Test - public void testGetProperty() { - - String expResult = "-fx-test"; - String result = TestNodeBase.StyleableProperties.TEST.getProperty(); - assertEquals(expResult, result); - } - - /** - * Test of getConverter method, of class CssMetaData. - */ - @Test - public void testGetConverter() { - - StyleConverter expResult = BooleanConverter.getInstance(); - StyleConverter result = TestNodeBase.StyleableProperties.TEST.getConverter(); - assertEquals(expResult, result); - } - - /** - * Test of getInitialValue method, of class CssMetaData. - */ - @Test - public void testGetInitialValue() { - - TestNode testNode = new TestNode(); - Double expResult = testNode.getXyzzy(); - Double result = (Double)TestNode.StyleableProperties.XYZZY.getInitialValue(testNode); - assertEquals(expResult, result); - - } - - /** - * Test of getSubProperties method, of class CssMetaData. - */ - @Test - public void testGetSubProperties() { - - CssMetaData fontProp = - new FontCssMetaData("-fx-font", Font.getDefault()) { - - @Override - public boolean isSettable(TestNode n) { - return true; - } - - @Override - public StyleableProperty getStyleableProperty(TestNode n) { - return null; - } - }; - - List> list = fontProp.getSubProperties(); - assertNotNull(list); - - } - - /** - * Test of isInherits method, of class CssMetaData. - */ - @Test - public void testIsInherits() { - - boolean expResult = false; - boolean result = TestNode.StyleableProperties.XYZZY.isInherits(); - assertEquals(expResult, result); - - } - - /** - * Test of toString method, of class CssMetaData. - */ - @Test - public void testToString() { - - CssMetaData fontProp = - new FontCssMetaData("-fx-font", Font.getDefault()) { - - @Override - public boolean isSettable(TestNode n) { - return true; - } - - @Override - public StyleableProperty getStyleableProperty(TestNode n) { - return null; - } - }; - - String string = fontProp.toString(); - assertNotNull(string); - - } - - /** - * Test of equals method, of class CssMetaData. - */ - @Test - public void testEquals() { - TestNode testNode = new TestNode(); - Node node = new Node() { - - @Override - protected NGNode impl_createPeer() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public BaseBounds impl_computeGeomBounds(BaseBounds bb, BaseTransform bt) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - protected boolean impl_computeContains(double d, double d1) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Object impl_processMXNode(MXNodeAlgorithm mxna, MXNodeAlgorithmContext mxnac) { - throw new UnsupportedOperationException("Not supported yet."); - } - }; - - CssMetaData testNodeOpacity = get(TestNode.getClassCssMetaData(), "-fx-opacity"); - CssMetaData nodeOpacity = get(Node.getClassCssMetaData(), "-fx-opacity"); - - assertTrue(testNodeOpacity.equals(nodeOpacity)); - } - - static int ord = 0; - static CascadingStyle createCascadingStyle(Selector selector, Declaration declaration) { - - Set pseudoClasses = null; - if (selector instanceof SimpleSelector) { - - pseudoClasses = ((SimpleSelector)selector).getPseudoClassStates(); - } else { - - pseudoClasses = new PseudoClassState(); - for (SimpleSelector sel : ((CompoundSelector)selector).getSelectors()) { - - Set selectorPseudoClasses = sel.getPseudoClassStates(); - pseudoClasses.addAll(selectorPseudoClasses); - } - } - - return new CascadingStyle( - new Style(selector, declaration), - pseudoClasses, - 0, - ord++ - ); - } - - @Test @org.junit.Ignore - public void testGetMatchingStyles() { - - - final Stylesheet stylesheet = new Stylesheet(); - stylesheet.setOrigin(StyleOrigin.USER_AGENT); - StyleManager.getInstance().getInstance().setDefaultUserAgentStylesheet(stylesheet); - - final List rules = stylesheet.getRules(); - - // - // .root { -fx-base: red; -fx-color: -fx-base; } - // - List rootStyleClass = new ArrayList(); - rootStyleClass.add("root"); - - Selector root = new SimpleSelector("*", rootStyleClass, null, null); - - ParsedValue fxBaseValue = new CssParser().parseExpr("-fx-base", "red"); - Declaration fxBase = new Declaration("-fx-base", fxBaseValue, false); - - ParsedValueImpl fxColorValue = new ParsedValueImpl(fxBase.getProperty(), null, true); - Declaration fxColor = new Declaration("-fx-color", fxColorValue, false); - - List selectors = new ArrayList(); - Collections.addAll(selectors, root); - - List declarations = new ArrayList(); - Collections.addAll(declarations, fxBase, fxColor); - - Rule baseRule = new Rule(selectors, declarations); - rules.add(baseRule); - - // - // .rect { -fx-fill: -fx-color; } - // - List rectStyleClass = new ArrayList(); - rectStyleClass.add("rect"); - - Selector rect = new SimpleSelector("*", rectStyleClass, null, null); - - ParsedValue fxFillValue = new CssParser().parseExpr("-fx-fill", "-fx-color"); - Declaration fxFill = new Declaration("-fx-fill", fxFillValue, false); - - selectors = new ArrayList(); - Collections.addAll(selectors, rect); - - declarations = new ArrayList(); - Collections.addAll(declarations, fxFill); - - Rule rectRule = new Rule(selectors, declarations); - rules.add(rectRule); - - // .rect:hover { -fx-fill: yellow; } - List pseudoclasses = new ArrayList(); - pseudoclasses.add("hover"); - - Selector rectHover = new SimpleSelector("*", rectStyleClass, pseudoclasses, null); - - ParsedValueImpl fxFillHoverValue = new ParsedValueImpl(Color.YELLOW, null); - Declaration fxFillHover = new Declaration("-fx-fill", fxFillHoverValue, false); - - selectors = new ArrayList(); - Collections.addAll(selectors, rectHover); - - declarations = new ArrayList(); - Collections.addAll(declarations, fxFillHover); - - Rule rectHoverRule = new Rule(selectors, declarations); - rules.add(rectHoverRule); - - List