diff options
author | mark <mark@138bc75d-0d04-0410-961f-82ee72b054a4> | 2006-08-14 23:12:35 +0000 |
---|---|---|
committer | mark <mark@138bc75d-0d04-0410-961f-82ee72b054a4> | 2006-08-14 23:12:35 +0000 |
commit | ffde862e033a0825e1e9972a89c0f1f80b261a8e (patch) | |
tree | 97037d2c09c8384d80531f67ec36a01205df6bdb /libjava/classpath/examples | |
parent | b415ff10527e977c3758234fd930e2c027bfa17d (diff) | |
download | gcc-ffde862e033a0825e1e9972a89c0f1f80b261a8e.tar.gz |
2006-08-14 Mark Wielaard <mark@klomp.org>
Imported GNU Classpath 0.92
* HACKING: Add more importing hints. Update automake version
requirement.
* configure.ac (gconf-peer): New enable AC argument.
Add --disable-gconf-peer and --enable-default-preferences-peer
to classpath configure when gconf is disabled.
* scripts/makemake.tcl: Set gnu/java/util/prefs/gconf and
gnu/java/awt/dnd/peer/gtk to bc. Classify
gnu/java/security/Configuration.java as generated source file.
* gnu/java/lang/management/VMGarbageCollectorMXBeanImpl.java,
gnu/java/lang/management/VMMemoryPoolMXBeanImpl.java,
gnu/java/lang/management/VMClassLoadingMXBeanImpl.java,
gnu/java/lang/management/VMRuntimeMXBeanImpl.java,
gnu/java/lang/management/VMMemoryManagerMXBeanImpl.java,
gnu/java/lang/management/VMThreadMXBeanImpl.java,
gnu/java/lang/management/VMMemoryMXBeanImpl.java,
gnu/java/lang/management/VMCompilationMXBeanImpl.java: New VM stub
classes.
* java/lang/management/VMManagementFactory.java: Likewise.
* java/net/VMURLConnection.java: Likewise.
* gnu/java/nio/VMChannel.java: Likewise.
* java/lang/Thread.java (getState): Add stub implementation.
* java/lang/Class.java (isEnum): Likewise.
* java/lang/Class.h (isEnum): Likewise.
* gnu/awt/xlib/XToolkit.java (getClasspathTextLayoutPeer): Removed.
* javax/naming/spi/NamingManager.java: New override for StackWalker
functionality.
* configure, sources.am, Makefile.in, gcj/Makefile.in,
include/Makefile.in, testsuite/Makefile.in: Regenerated.
git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/trunk@116139 138bc75d-0d04-0410-961f-82ee72b054a4
Diffstat (limited to 'libjava/classpath/examples')
30 files changed, 6056 insertions, 62 deletions
diff --git a/libjava/classpath/examples/Makefile.am b/libjava/classpath/examples/Makefile.am index 71909e8d64d..84e3ebe0fc9 100644 --- a/libjava/classpath/examples/Makefile.am +++ b/libjava/classpath/examples/Makefile.am @@ -23,8 +23,9 @@ endif # All our example java source files EXAMPLE_JAVA_FILES = $(srcdir)/gnu/classpath/examples/*/*.java $(srcdir)/gnu/classpath/examples/*/*/*.java $(srcdir)/gnu/classpath/examples/*/*/*/*.java -# The example C source files +# The example C source & header files EXAMPLE_C_FILES = $(srcdir)/gnu/classpath/examples/*/*.c +EXAMPLE_CH_FILES = $(srcdir)/gnu/classpath/examples/*/*.h # The zip files with classes we want to produce. EXAMPLE_ZIP = examples.zip @@ -39,7 +40,7 @@ EXAMPLE_ICONS = $(srcdir)/gnu/classpath/examples/icons/*.png READMES = $(srcdir)/gnu/classpath/examples/CORBA/swing/README.html # All the files we find "interesting" -ALL_EXAMPLE_FILES = $(EXAMPLE_JAVA_FILES) $(EXAMPLE_C_FILES) $(EXAMPLE_ICONS) $(READMES) +ALL_EXAMPLE_FILES = $(EXAMPLE_JAVA_FILES) $(EXAMPLE_C_FILES) $(EXAMPLE_CH_FILES) $(EXAMPLE_ICONS) $(READMES) # Some architecture independent data to be installed. example_DATA = $(EXAMPLE_ZIP) README @@ -62,7 +63,9 @@ install-data-local: $(INSTALL_DATA) $$file $(DESTDIR)$(pkgdatadir)/examples/$$f; \ done echo "$(INSTALL_DATA) Makefile.jawt $(DESTDIR)$(pkgdatadir)/examples/" + echo "$(INSTALL_DATA) Makefile.java2d $(DESTDIR)$(pkgdatadir)/examples/" $(INSTALL_DATA) Makefile.jawt $(DESTDIR)$(pkgdatadir)/examples/ + $(INSTALL_DATA) Makefile.java2d $(DESTDIR)$(pkgdatadir)/examples/ uninstall-local: srcdir_cnt=`echo $(srcdir) | wc -c`; \ @@ -72,10 +75,12 @@ uninstall-local: rm -f $(DESTDIR)$(pkgdatadir)/examples/$$f; \ done echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.jawt" + echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.java2d" rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.jawt + rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.java2d # Make sure everything is included in the distribution. -EXTRA_DIST = README Makefile.jawt.in +EXTRA_DIST = README Makefile.jawt.in Makefile.java2d.in dist-hook: srcdir_cnt=`echo $(srcdir) | wc -c`; \ for file in $(ALL_EXAMPLE_FILES); do \ diff --git a/libjava/classpath/examples/Makefile.in b/libjava/classpath/examples/Makefile.in index d8336a98bf3..47742688983 100644 --- a/libjava/classpath/examples/Makefile.in +++ b/libjava/classpath/examples/Makefile.in @@ -39,7 +39,7 @@ host_triplet = @host@ target_triplet = @target@ subdir = examples DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ - $(srcdir)/Makefile.jawt.in + $(srcdir)/Makefile.java2d.in $(srcdir)/Makefile.jawt.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/../../libtool.m4 \ $(top_srcdir)/m4/acattribute.m4 $(top_srcdir)/m4/accross.m4 \ @@ -52,7 +52,7 @@ am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs CONFIG_HEADER = $(top_builddir)/include/config.h -CONFIG_CLEAN_FILES = Makefile.jawt +CONFIG_CLEAN_FILES = Makefile.jawt Makefile.java2d SOURCES = DIST_SOURCES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; @@ -95,6 +95,8 @@ CREATE_CORE_JNI_LIBRARIES_FALSE = @CREATE_CORE_JNI_LIBRARIES_FALSE@ CREATE_CORE_JNI_LIBRARIES_TRUE = @CREATE_CORE_JNI_LIBRARIES_TRUE@ CREATE_DSSI_LIBRARIES_FALSE = @CREATE_DSSI_LIBRARIES_FALSE@ CREATE_DSSI_LIBRARIES_TRUE = @CREATE_DSSI_LIBRARIES_TRUE@ +CREATE_GCONF_PEER_LIBRARIES_FALSE = @CREATE_GCONF_PEER_LIBRARIES_FALSE@ +CREATE_GCONF_PEER_LIBRARIES_TRUE = @CREATE_GCONF_PEER_LIBRARIES_TRUE@ CREATE_GTK_PEER_LIBRARIES_FALSE = @CREATE_GTK_PEER_LIBRARIES_FALSE@ CREATE_GTK_PEER_LIBRARIES_TRUE = @CREATE_GTK_PEER_LIBRARIES_TRUE@ CREATE_JNI_HEADERS_FALSE = @CREATE_JNI_HEADERS_FALSE@ @@ -115,6 +117,7 @@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DATE = @DATE@ +DEFAULT_PREFS_PEER = @DEFAULT_PREFS_PEER@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ @@ -145,6 +148,10 @@ FREETYPE2_CFLAGS = @FREETYPE2_CFLAGS@ FREETYPE2_LIBS = @FREETYPE2_LIBS@ GCJ = @GCJ@ GCJX = @GCJX@ +GCONF_CFLAGS = @GCONF_CFLAGS@ +GCONF_LIBS = @GCONF_LIBS@ +GDK_CFLAGS = @GDK_CFLAGS@ +GDK_LIBS = @GDK_LIBS@ GJDOC = @GJDOC@ GLIB_CFLAGS = @GLIB_CFLAGS@ GLIB_LIBS = @GLIB_LIBS@ @@ -195,6 +202,7 @@ PACKAGE_VERSION = @PACKAGE_VERSION@ PANGOFT2_CFLAGS = @PANGOFT2_CFLAGS@ PANGOFT2_LIBS = @PANGOFT2_LIBS@ PATH_SEPARATOR = @PATH_SEPARATOR@ +PATH_TO_ESCHER = @PATH_TO_ESCHER@ PATH_TO_GLIBJ_ZIP = @PATH_TO_GLIBJ_ZIP@ PERL = @PERL@ PKG_CONFIG = @PKG_CONFIG@ @@ -215,6 +223,8 @@ USER_SPECIFIED_CLASSLIB_FALSE = @USER_SPECIFIED_CLASSLIB_FALSE@ USER_SPECIFIED_CLASSLIB_TRUE = @USER_SPECIFIED_CLASSLIB_TRUE@ USER_SPECIFIED_JAVAH_FALSE = @USER_SPECIFIED_JAVAH_FALSE@ USER_SPECIFIED_JAVAH_TRUE = @USER_SPECIFIED_JAVAH_TRUE@ +USE_ESCHER_FALSE = @USE_ESCHER_FALSE@ +USE_ESCHER_TRUE = @USE_ESCHER_TRUE@ USE_PREBUILT_GLIBJ_ZIP_FALSE = @USE_PREBUILT_GLIBJ_ZIP_FALSE@ USE_PREBUILT_GLIBJ_ZIP_TRUE = @USE_PREBUILT_GLIBJ_ZIP_TRUE@ VERSION = @VERSION@ @@ -290,8 +300,9 @@ GLIBJ_CLASSPATH = '$(top_builddir)/lib':'$(top_builddir)/lib/glibj.zip' # All our example java source files EXAMPLE_JAVA_FILES = $(srcdir)/gnu/classpath/examples/*/*.java $(srcdir)/gnu/classpath/examples/*/*/*.java $(srcdir)/gnu/classpath/examples/*/*/*/*.java -# The example C source files +# The example C source & header files EXAMPLE_C_FILES = $(srcdir)/gnu/classpath/examples/*/*.c +EXAMPLE_CH_FILES = $(srcdir)/gnu/classpath/examples/*/*.h # The zip files with classes we want to produce. EXAMPLE_ZIP = examples.zip @@ -306,7 +317,7 @@ EXAMPLE_ICONS = $(srcdir)/gnu/classpath/examples/icons/*.png READMES = $(srcdir)/gnu/classpath/examples/CORBA/swing/README.html # All the files we find "interesting" -ALL_EXAMPLE_FILES = $(EXAMPLE_JAVA_FILES) $(EXAMPLE_C_FILES) $(EXAMPLE_ICONS) $(READMES) +ALL_EXAMPLE_FILES = $(EXAMPLE_JAVA_FILES) $(EXAMPLE_C_FILES) $(EXAMPLE_CH_FILES) $(EXAMPLE_ICONS) $(READMES) # Some architecture independent data to be installed. example_DATA = $(EXAMPLE_ZIP) README @@ -315,7 +326,7 @@ example_DATA = $(EXAMPLE_ZIP) README exampledir = $(pkgdatadir)/examples # Make sure everything is included in the distribution. -EXTRA_DIST = README Makefile.jawt.in +EXTRA_DIST = README Makefile.jawt.in Makefile.java2d.in all: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) all-am @@ -351,6 +362,8 @@ $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh Makefile.jawt: $(top_builddir)/config.status $(srcdir)/Makefile.jawt.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +Makefile.java2d: $(top_builddir)/config.status $(srcdir)/Makefile.java2d.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo @@ -524,7 +537,9 @@ install-data-local: $(INSTALL_DATA) $$file $(DESTDIR)$(pkgdatadir)/examples/$$f; \ done echo "$(INSTALL_DATA) Makefile.jawt $(DESTDIR)$(pkgdatadir)/examples/" + echo "$(INSTALL_DATA) Makefile.java2d $(DESTDIR)$(pkgdatadir)/examples/" $(INSTALL_DATA) Makefile.jawt $(DESTDIR)$(pkgdatadir)/examples/ + $(INSTALL_DATA) Makefile.java2d $(DESTDIR)$(pkgdatadir)/examples/ uninstall-local: srcdir_cnt=`echo $(srcdir) | wc -c`; \ @@ -534,7 +549,9 @@ uninstall-local: rm -f $(DESTDIR)$(pkgdatadir)/examples/$$f; \ done echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.jawt" + echo "rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.java2d" rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.jawt + rm -f $(DESTDIR)$(pkgdatadir)/examples/Makefile.java2d dist-hook: srcdir_cnt=`echo $(srcdir) | wc -c`; \ for file in $(ALL_EXAMPLE_FILES); do \ diff --git a/libjava/classpath/examples/Makefile.java2d.in b/libjava/classpath/examples/Makefile.java2d.in new file mode 100644 index 00000000000..dac22068c4d --- /dev/null +++ b/libjava/classpath/examples/Makefile.java2d.in @@ -0,0 +1,17 @@ +# @configure_input@ + +srcdir = @srcdir@ +prefix = @prefix@ +exec_prefix = @exec_prefix@ +includedir = @includedir@ +libdir = @libdir@ +pkglibdir = $(libdir)/@PACKAGE@ +GTK_CFLAGS = @GTK_CFLAGS@ +GTK_LIBS = @GTK_LIBS@ + +all: $(srcdir)/gnu/classpath/examples/java2d/bench.c $(srcdir)/gnu/classpath/examples/java2d/bench.h + gcc -g -O0 -Wall -I$(srcdir)/gnu/classpath/examples/java2d $(GTK_CFLAGS) -L$(GTK_LIBS) \ + -o cairobench $(srcdir)/gnu/classpath/examples/java2d/bench.c + +clean: + rm -f gnu/classpath/examples/java2d/bench diff --git a/libjava/classpath/examples/README b/libjava/classpath/examples/README index 727677363c6..f7bf599624a 100644 --- a/libjava/classpath/examples/README +++ b/libjava/classpath/examples/README @@ -46,6 +46,23 @@ You can then run the example as follows: export LD_LIBRARY_PATH=.:/usr/local/classpath/lib/classpath jamvm gnu.classpath.examples.jawt.DemoJAWT +The java2d benchmarking demos include a GTK widget to measure the native +speed of some basic java2d options, without the JNI overhead. + +You can invoke it with: + + make -f Makefile.java2d + +Or you can compile by hand as follows: + + gcc -g -O0 -Wall -I./gnu/classpath/examples/java2d \ + -o cairobench gnu/classpath/examples/java2d/bench.c \ + `pkg-config --libs --cflags gtk+-2.0` + +You can then run the example as follows: + + ./cairobench + All example code is distributed under the GNU General Public License (GPL). The example icons used in some of the examples come from gnome-icon-theme diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHelper.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHelper.java index c41ebe237ea..652ee53ccee 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHelper.java +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToPassHelper.java @@ -38,6 +38,8 @@ exception statement from your version. */ package gnu.classpath.examples.CORBA.SimpleCommunication.communication; +import gnu.CORBA.OrbRestricted; + import org.omg.CORBA.ORB; import org.omg.CORBA.StructMember; import org.omg.CORBA.TypeCode; @@ -81,13 +83,14 @@ public abstract class StructureToPassHelper */ public static synchronized TypeCode type() { - StructMember[] members = new StructMember[ 2 ]; + StructMember[] members = new StructMember[2]; TypeCode member = null; - member = ORB.init().create_string_tc(0); - members [ 0 ] = new StructMember("a", member, null); - member = ORB.init().create_string_tc(0); - members [ 1 ] = new StructMember("b", member, null); - return ORB.init().create_struct_tc(StructureToPassHelper.id(), "StructureToPass", members); + member = OrbRestricted.Singleton.create_string_tc(0); + members[0] = new StructMember("a", member, null); + member = OrbRestricted.Singleton.create_string_tc(0); + members[1] = new StructMember("b", member, null); + return OrbRestricted.Singleton.create_struct_tc(StructureToPassHelper.id(), + "StructureToPass", members); } /** diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHelper.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHelper.java index 42fb7a574a7..2ac03a895ed 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHelper.java +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/StructureToReturnHelper.java @@ -37,6 +37,8 @@ exception statement from your version. */ package gnu.classpath.examples.CORBA.SimpleCommunication.communication; +import gnu.CORBA.OrbRestricted; + import org.omg.CORBA.ORB; import org.omg.CORBA.StructMember; import org.omg.CORBA.TCKind; @@ -86,17 +88,18 @@ public abstract class StructureToReturnHelper */ public static synchronized TypeCode type() { - StructMember[] members = new StructMember[ 3 ]; - TypeCode member = ORB.init().get_primitive_tc(TCKind.tk_long); - members [ 0 ] = new StructMember("n", member, null); - member = ORB.init().create_string_tc(0); - members [ 1 ] = new StructMember("c", member, null); - member = ORB.init().get_primitive_tc(TCKind.tk_long); - member = ORB.init().create_array_tc(3, member); - members [ 2 ] = new StructMember("arra", member, null); - return ORB.init().create_struct_tc(StructureToReturnHelper.id(), "StructureToReturn", - members - ); + StructMember[] members = new StructMember[3]; + TypeCode member = OrbRestricted.Singleton.get_primitive_tc(TCKind.tk_long); + members[0] = new StructMember("n", member, null); + member = OrbRestricted.Singleton.create_string_tc(0); + members[1] = new StructMember("c", member, null); + member = OrbRestricted.Singleton.get_primitive_tc(TCKind.tk_long); + member = OrbRestricted.Singleton.create_array_tc(3, member); + members[2] = new StructMember("arra", member, null); + return OrbRestricted.Singleton.create_struct_tc( + StructureToReturnHelper.id(), + "StructureToReturn", + members); } /** diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHelper.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHelper.java index f111d0eac93..ccf792da875 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHelper.java +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/TreeNodeHelper.java @@ -38,6 +38,9 @@ exception statement from your version. */ package gnu.classpath.examples.CORBA.SimpleCommunication.communication; + +import gnu.CORBA.OrbRestricted; + import org.omg.CORBA.Any; import org.omg.CORBA.ORB; import org.omg.CORBA.StructMember; @@ -128,18 +131,18 @@ public abstract class TreeNodeHelper // To avoid the infinite recursion loop, the // recursive reference is handled in specific way. if (active) - return ORB.init().create_recursive_tc(_id); + return OrbRestricted.Singleton.create_recursive_tc(_id); active = true; // List all memebers of the TreeNode structure. StructMember[] members = new StructMember[ 2 ]; TypeCode memberType; - memberType = ORB.init().create_string_tc(0); + memberType = OrbRestricted.Singleton.create_string_tc(0); members [ 0 ] = new StructMember("name", memberType, null); - memberType = ORB.init().create_recursive_tc(""); + memberType = OrbRestricted.Singleton.create_recursive_tc(""); members [ 1 ] = new StructMember("children", memberType, null); typeCode = - ORB.init().create_struct_tc(TreeNodeHelper.id(), "TreeNode", members); + OrbRestricted.Singleton.create_struct_tc(TreeNodeHelper.id(), "TreeNode", members); active = false; } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisExceptionHelper.java b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisExceptionHelper.java index 4d5eee74b4b..6ad13a9bbc7 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisExceptionHelper.java +++ b/libjava/classpath/examples/gnu/classpath/examples/CORBA/SimpleCommunication/communication/WeThrowThisExceptionHelper.java @@ -38,6 +38,8 @@ exception statement from your version. */ package gnu.classpath.examples.CORBA.SimpleCommunication.communication; +import gnu.CORBA.OrbRestricted; + import org.omg.CORBA.Any; import org.omg.CORBA.ORB; import org.omg.CORBA.StructMember; @@ -96,9 +98,9 @@ public abstract class WeThrowThisExceptionHelper { StructMember[] members = new StructMember[ 1 ]; TypeCode member = null; - member = ORB.init().get_primitive_tc(TCKind.tk_long); + member = OrbRestricted.Singleton.get_primitive_tc(TCKind.tk_long); members [ 0 ] = new StructMember("ourField", member, null); - return ORB.init().create_struct_tc(WeThrowThisExceptionHelper.id(), + return OrbRestricted.Singleton.create_struct_tc(WeThrowThisExceptionHelper.id(), "WeThrowThisException", members ); } diff --git a/libjava/classpath/examples/gnu/classpath/examples/awt/AicasGraphicsBenchmark.java b/libjava/classpath/examples/gnu/classpath/examples/awt/AicasGraphicsBenchmark.java new file mode 100644 index 00000000000..ed18fd4c2ee --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/awt/AicasGraphicsBenchmark.java @@ -0,0 +1,1018 @@ +/* AnimationApplet.java -- An example of an old-style AWT applet + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.awt; + +import java.awt.BorderLayout; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.Insets; +import java.awt.Label; +import java.awt.Panel; +import java.awt.Toolkit; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.net.URL; +import java.util.Iterator; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.TreeMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class AicasGraphicsBenchmark extends Panel +{ + /** + * Default number of test-iterations. + */ + private static final int DEFAULT_TEST_SIZE = 1000; + + /** + * Default screen size. + */ + private static final int DEFAULT_SCREEN_WIDTH = 320; + private static final int DEFAULT_SCREEN_HEIGHT = 240; + + /** + * AWT tests. + */ + private static final int AWTTEST_LINES = 1 << 0; + private static final int AWTTEST_RECT = 1 << 1; + private static final int AWTTEST_POLYLINE = 1 << 2; + private static final int AWTTEST_POLYGON = 1 << 3; + private static final int AWTTEST_ARC = 1 << 4; + private static final int AWTTEST_OVAL = 1 << 5; + private static final int AWTTEST_ROUNDRECT = 1 << 6; + private static final int AWTTEST_STRING = 1 << 7; + private static final int AWTTEST_TRANSPARENTIMAGE = 1 << 8; + private static final int AWTTEST_IMAGE = 1 << 9; + + private static final int AWTTEST_NONE = 0; + private static final int AWTTEST_ALL = AWTTEST_LINES + | AWTTEST_RECT + | AWTTEST_POLYLINE + | AWTTEST_POLYGON + | AWTTEST_ARC + | AWTTEST_OVAL + | AWTTEST_ROUNDRECT + | AWTTEST_STRING + | AWTTEST_TRANSPARENTIMAGE + | AWTTEST_IMAGE + ; + + int iterations = 1; + private int screenWidth = DEFAULT_SCREEN_WIDTH; + private int screenHeight = DEFAULT_SCREEN_HEIGHT; + boolean doubleBufferFlag = true; + private int awtTests = AWTTEST_ALL; + + private Label testLabel; + + private String testContext = ""; + + Logger logger = Logger.getLogger("AicasGraphicsBenchmark"); + + private Image pngTestImage; + private Image gifTestImage; + + private TestSet testSetMap = new TestSet(); + + public AicasGraphicsBenchmark() + { + pngTestImage = loadImage("aicas.png"); + gifTestImage = loadImage("palme.gif"); + + setLayout(new BorderLayout()); + testLabel = new Label(); + add(testLabel,BorderLayout.NORTH); + add(new GraphicsTest(),BorderLayout.CENTER); + } + + void setTestContext(String testName) + { + logger.logp(Level.INFO, "AicasGraphicsBenchmark", "recordTest", + "--- Starting new test context: " + testName); + testContext = testName; + testLabel.setText(testName); + } + + private void recordTest(String testName, long time) + { + logger.logp(Level.INFO, "AicasGraphicsBenchmark", "recordTest", + testContext + ": " + testName + " duration (ms): " + time); + TestRecorder recorder = testSetMap.getTest(testName); + if (recorder == null) + { + recorder = new TestRecorder(testName); + testSetMap.putTest(testName,recorder); + } + recorder.addRun(time); + } + + void printReport() + { + for (Iterator i = testSetMap.testIterator(); i.hasNext(); ) + { + TestRecorder recorder = testSetMap.getTest((String)i.next()); + System.out.println("TEST " + recorder.getTestName() + ": average " + + recorder.getAverage() + "ms [" + + recorder.getMinTime() + "-" + recorder.getMaxTime() + + "]"); + } + } + + public static void main(String[] args) + { + int awtTests; + int i; + boolean endOfOptionsFlag; + AicasGraphicsBenchmark speed= new AicasGraphicsBenchmark(); + + // Parse arguments. + i = 0; + endOfOptionsFlag = false; + awtTests = AWTTEST_NONE; + while (i < args.length) + { + if (!endOfOptionsFlag) + { + if (args[i].equals("--help") || args[i].equals("-help") + || args[i].equals("-h")) + { + System.out.println("Usage: AicasGraphicsBenchmark [<options>] [<test> ...]"); + System.out.println(""); + System.out.println("Options: -i|--iterations=<n|-1> - number of iterations (-1 is infinite)"); + System.out.println(" -w|--width=<n> - screen width; default "+DEFAULT_SCREEN_WIDTH); + System.out.println(" -h|--height=<n> - screen height; default "+DEFAULT_SCREEN_HEIGHT); + System.out.println(" -n|--noDoubleBuffer - disable double-buffering test"); + System.out.println(""); + System.out.println("Tests: line"); + System.out.println(" rect"); + System.out.println(" polyline"); + System.out.println(" polygon"); + System.out.println(" arc"); + System.out.println(" oval"); + System.out.println(" roundrect"); + System.out.println(" string"); + System.out.println(" transparentimage"); + System.out.println(" image"); + System.exit(1); + } + else if ((args[i].startsWith("-i=") + || args[i].startsWith("--iterations="))) + { + speed.iterations = + Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-i") || args[i].equals("--iterations"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.iterations = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].startsWith("-w=") + || args[i].startsWith("--width="))) + { + speed.screenWidth = + Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-w") || args[i].equals("--width"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.screenWidth = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].startsWith("-h=") + || args[i].startsWith("--height="))) + { + speed.screenHeight = + Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i+=1; + continue; + } + else if ((args[i].equals("-h") || args[i].equals("--height"))) + { + if ((i+1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.screenHeight = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].equals("-n") + || args[i].equals("--noDoubleBuffer"))) + { + speed.doubleBufferFlag = false; + i += 1; + continue; + } + else if (args[i].equals("--")) + { + endOfOptionsFlag = true; + i += 1; + continue; + } + else if (args[i].startsWith("-")) + { + System.err.println("ERROR: Unknown option '" + args[i] + "'!"); + System.exit(2); + } + } + StringTokenizer tokenizer = new StringTokenizer(args[i], " +,"); + while (tokenizer.hasMoreTokens()) + { + String s = tokenizer.nextToken().toLowerCase(); + if (s.equals("line")) + awtTests |= AWTTEST_LINES; + else if (s.equals("rect")) + awtTests |= AWTTEST_RECT; + else if (s.equals("polyline")) + awtTests |= AWTTEST_POLYLINE; + else if (s.equals("polygon")) + awtTests |= AWTTEST_POLYGON; + else if (s.equals("arc")) + awtTests |= AWTTEST_ARC; + else if (s.equals("oval")) + awtTests |= AWTTEST_OVAL; + else if (s.equals("roundrect")) + awtTests |= AWTTEST_ROUNDRECT; + else if (s.equals("string")) + awtTests |= AWTTEST_STRING; + else if (s.equals("transparentimage")) + awtTests |= AWTTEST_TRANSPARENTIMAGE; + else if (s.equals("image")) + awtTests |= AWTTEST_IMAGE; + else + { + System.err.println("Unknown AWT test '" + s + "'!"); + System.exit(2); + } + } + i += 1; + } + if (awtTests != AWTTEST_NONE) + speed.awtTests = awtTests; + + // Create graphics. + final Frame frame = new Frame("AicasGraphicsBenchmark"); + + frame.addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + frame.setVisible(false); + System.exit(0); + } + }); + + frame.add(speed,BorderLayout.CENTER); + frame.setSize(speed.screenWidth,speed.screenHeight); + frame.setVisible(true); + + // Insets are correctly set only after the native peer was created. + Insets insets = frame.getInsets(); + // The internal size of the frame should be 320x240. + frame.setSize(320 + insets.right + insets.left, + 240 + insets.top + insets.bottom); + } + + private Image loadImage(String imageName) + { + Image result = null; + logger.logp(Level.INFO, "AicasGraphicsBenchmark", "loadImage", + "Loading image: " + imageName); + URL url = getClass().getResource(imageName); + if (url != null) + { + result = Toolkit.getDefaultToolkit().getImage(url); + prepareImage(result, this); + } + else + { + logger.logp(Level.WARNING, "AicasGraphicsBenchmark", "loadImage", + "Could not locate image resource in class path: " + + imageName); + } + return result; + } + + /** + * Executes the test methods. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + void runTestSet(Graphics g, Dimension size) + { + if ((awtTests & AWTTEST_LINES) != 0) + test_drawLine(g, size); + if ((awtTests & AWTTEST_RECT) != 0) + test_drawRect(g, size); + if ((awtTests & AWTTEST_RECT) != 0) + test_fillRect(g, size); + if ((awtTests & AWTTEST_POLYLINE) != 0) + test_drawPolyline(g, size); + if ((awtTests & AWTTEST_POLYGON) != 0) + test_drawPolygon(g, size); + if ((awtTests & AWTTEST_POLYGON) != 0) + test_fillPolygon(g,size); + if ((awtTests & AWTTEST_ARC) != 0) + test_drawArc(g,size); + if ((awtTests & AWTTEST_ARC) != 0) + test_fillArc(g,size); + if ((awtTests & AWTTEST_OVAL) != 0) + test_drawOval(g, size); + if ((awtTests & AWTTEST_OVAL) != 0) + test_fillOval(g, size); + if ((awtTests & AWTTEST_ROUNDRECT) != 0) + test_fillRoundRect(g, size); + if ((awtTests & AWTTEST_STRING) != 0) + test_drawString(g, size); + if ((awtTests & AWTTEST_TRANSPARENTIMAGE) != 0) + test_drawTransparentImage(g,size); + if ((awtTests & AWTTEST_IMAGE) != 0) + test_drawImage(g,size); + } + + /** + * Gets a new random Color. + * + * @returna new random Color + */ + private Color getNextColor() + { + return new Color((int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1); + } + + /** + * Draws random lines within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawLine(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x1 = (int) (Math.random() * (size.width-minSize)); + int y1 = (int) (Math.random() * (size.height-minSize)); + int x2 = (int) (Math.random() * (size.width-minSize)); + int y2 = (int) (Math.random() * (size.height-minSize)); + g.drawLine(x1, y1, x2, y2); + } + long endTime = System.currentTimeMillis(); + recordTest("drawLine " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random rectangles within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawRect(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x1 = (int) (Math.random() * (size.width-minSize)); + int y1 = (int) (Math.random() * (size.height-minSize)); + int x2 = (int) (Math.random() * (size.width-minSize)); + int y2 = (int) (Math.random() * (size.height-minSize)); + g.drawRect(x1, y1, x2, y2); + } + long endTime = System.currentTimeMillis(); + recordTest("drawRect " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random rectangles within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillRect(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x1 = (int) (Math.random() * (size.width-minSize)); + int y1 = (int) (Math.random() * (size.height-minSize)); + int x2 = (int) (Math.random() * (size.width-minSize)); + int y2 = (int) (Math.random() * (size.height-minSize)); + g.fillRect(x1, y1, x2, y2); + } + long endTime = System.currentTimeMillis(); + recordTest("fillRect " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random polylines within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawPolyline(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int points = (int)(Math.random() * 6) + 3; + int[] x_coords = new int[points]; + int[] y_coords = new int[points]; + for (int j = 0; j < points; j+=1) + { + x_coords[j] = (int)(Math.random() * (size.width)); + y_coords[j] = (int)(Math.random() * (size.height)); + } + g.drawPolyline(x_coords,y_coords, points); + } + long endTime = System.currentTimeMillis(); + recordTest("drawPolyline " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random polygons within the given dimensions. + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawPolygon(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int points = (int) (Math.random() * 6) + 3; + int[] xcoords = new int[points]; + int[] ycoords = new int[points]; + for(int j = 0; j < points; j+=1) + { + xcoords[j] = (int) (Math.random() * (size.width)); + ycoords[j] = (int) (Math.random() * (size.height)); + } + g.drawPolygon(xcoords, ycoords, points); + } + long endTime = System.currentTimeMillis(); + recordTest("drawPolygon " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random filled polygons within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillPolygon(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + long startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int points = (int) (Math.random() * 6) + 3; + int[] xcoords = new int[points]; + int[] ycoords = new int[points]; + for (int j = 0; j < points; j+=1) + { + xcoords[j] = (int) (Math.random() * (size.width)); + ycoords[j] = (int) (Math.random() * (size.height)); + } + g.fillPolygon(xcoords, ycoords, points); + } + long endTime = System.currentTimeMillis(); + recordTest("fillPolygon " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random arcs within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawArc(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int startAngle = (int) (Math.random() * 360); + int arcAngle = (int) (Math.random() * 360 - startAngle); + g.drawArc(x, y, width, height, startAngle, arcAngle); + } + endTime = System.currentTimeMillis(); + recordTest("drawArc " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random filled arcs within the given dimensions. + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillArc(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int)(Math.random() * (size.width - x - minSize) + minSize); + int height = (int)(Math.random() * (size.height - y - minSize) + minSize); + int startAngle = (int)(Math.random() * 360); + int arcAngle = (int)(Math.random() * 360); + g.fillArc(x, y, width, height, startAngle, arcAngle); + + } + endTime = System.currentTimeMillis(); + recordTest("fillArc " + maxTests + " times", (endTime - startTime)); + } + + /** + * Draws random ovals within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawOval(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int)(Math.random() * (size.width - minSize + 1)); + int y = (int)(Math.random() * (size.height - minSize + 1)); + int width = (int)(Math.random() * (size.width - x - minSize) + minSize); + int height = (int)(Math.random() * (size.height - y - minSize) + minSize); + g.drawOval(x, y, Math.min(width, height), Math.min(width, height)); + } + endTime = System.currentTimeMillis(); + recordTest("drawOval " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random filled ovals within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillOval(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + g.fillOval(x, y, width,height); + } + endTime = System.currentTimeMillis(); + recordTest("fillOval " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random filled rounded rectangles within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillRoundRect(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i=0; i < maxTests; i+=1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int arcWidth = (int) (Math.random() * (width - 1) + 1); + int arcHeight = (int) (Math.random() * (height - 1) + 5); + g.fillRoundRect(x, y, width, height, arcWidth, arcHeight); + } + endTime = System.currentTimeMillis(); + recordTest("fillRoundRect " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random images within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawImage(Graphics g, Dimension size) + { + if (gifTestImage == null) + { + logger.logp(Level.WARNING, "AicasGraphicsBenchmark", "runTestSet", + "Skipping 'test_drawImage' due to missing resource."); + return; + } + + int maxTests = DEFAULT_TEST_SIZE / 2; + if(maxTests == 0) + maxTests = 1; + int imageWidth = gifTestImage.getWidth(this); + int imageHeight = gifTestImage.getHeight(this); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - imageWidth + 1)); + int y = (int) (Math.random() * (size.height - imageHeight + 1)); + g.drawImage(gifTestImage, x, y, this); + } + long endTime = System.currentTimeMillis(); + recordTest("drawImage " + maxTests + " times", (endTime-startTime)); + } + + /** + * Draws random transparent images within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawTransparentImage(Graphics g, Dimension size) + { + if (pngTestImage == null) + { + logger.logp(Level.WARNING, "AicasGraphicsBenchmark", "runTestSet", + "Skipping 'test_drawTransparentImage' due to missing resource."); + return; + } + + + int maxTests = DEFAULT_TEST_SIZE / 5; + if(maxTests == 0) + maxTests = 1; + int imageWidth = pngTestImage.getWidth(this); + int imageHeight = pngTestImage.getHeight(this); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + int x = (int) (Math.random() * (size.width - imageWidth + 1)); + int y = (int) (Math.random() * (size.height - imageHeight + 1)); + g.drawImage(pngTestImage, x, y, this); + } + long endTime = System.currentTimeMillis(); + recordTest("draw transparent image " + maxTests + " times", + (endTime-startTime)); + } + + /** + * Draws random strings within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawString(Graphics g, Dimension size) + { + int maxTests = DEFAULT_TEST_SIZE; + String testString = "HelloWorld"; + int stringWidth = g.getFontMetrics().stringWidth(testString); + int stringHeight = g.getFontMetrics().getHeight(); + + long startTime = System.currentTimeMillis(); + for(int i = 0; i < maxTests; i += 1) + { + g.setColor(getNextColor()); + g.drawString(testString, (int) (Math.random() * (size.width - stringWidth + 1)),(int)(Math.random() * (size.height - stringHeight + 1)) + stringHeight); + } + long endTime = System.currentTimeMillis(); + recordTest("drawString " + maxTests + " times", (endTime-startTime)); + } + + private class GraphicsTest extends Canvas implements Runnable + { + Thread paintThread; + boolean done = false; + boolean doPaint = false; + boolean withClipping = false; + + public GraphicsTest() + { + paintThread = new Thread(this); + paintThread.start(); + } + + public void run() + { + int runCount = 0; + while (!done) + { + runCount++; + + try + { + synchronized (this) + { + while (!doPaint) + { + try + { + wait(200); + } + catch (InterruptedException exception) + { + return; + } + } + } + + if (iterations != 0) + System.out.println("--- run...(" + runCount + "/" + iterations + + ") ------------------------------------------------------"); + + Graphics g = getGraphics(); + Dimension size = getSize(); + logger.logp(Level.INFO, "AicasGraphicsBenchmark.GraphicsTest", "run", + "Start testing non-double-buffered drawing"); + runSet_noClipping(g,size); + runSet_zeroClipping(g, size); + runSet_withClipping(g, size); + g.dispose(); + + if (doubleBufferFlag) + { + logger.logp(Level.INFO, "AicasGraphicsBenchmark.GraphicsTest", + "run", "Start testing double-buffered drawing"); + Graphics canvas = getGraphics(); + Image doublebuffer = createImage(size.width,size.height); + g = doublebuffer.getGraphics(); + runSet_noClipping(g,size); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + + g = doublebuffer.getGraphics(); + runSet_withClipping(g, size); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + + g = doublebuffer.getGraphics(); + runSet_zeroClipping(g, size); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + canvas.dispose(); + } + + printReport(); + + if (iterations != 0) + { + if (iterations != -1) + iterations--; + } + else + { + System.out.println("--- done --------------------------------------------------------"); + synchronized (this) + { + doPaint = false; + } + done = true; + } + } + catch (Error error) + { + System.err.println("Error: " + error); + System.exit(129); + } + } + System.exit(0); + } + + private void runSet_zeroClipping(Graphics g, Dimension size) + { + int clipped_width; + int clipped_height; + int clipped_x; + int clipped_y; + + clipped_width = 0; + clipped_height = 0; + clipped_x = (size.width) / 2; + clipped_y = (size.height) / 2; + g.setClip(0, 0, size.width, size.height); + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + g.setColor(Color.WHITE); + g.drawRect(0, 0, size.width - 1, size.height - 1); + g.fillRect(clipped_x - 1, clipped_y - 1, clipped_width + 2, clipped_height + 2); + + g.clipRect(clipped_x, clipped_y, clipped_width, clipped_height); + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + + setTestContext("clipping to zero"); + + runTestSet(g, size); + } + + private void runSet_withClipping(Graphics g, Dimension size) + { + int clipped_width = 2 * size.width / 3; + int clipped_height = 2 * size.height / 3; + int clipped_x = (size.width - clipped_width) / 2; + int clipped_y = (size.height - clipped_height) / 2; + + g.setClip(0,0,size.width,size.height); + + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + g.setColor(Color.GREEN); + g.drawRect(0, 0, size.width - 1, size.height - 1); + g.setColor(Color.WHITE); + g.fillRect(clipped_x - 1, clipped_y - 1, clipped_width + 2, clipped_height + 2); + + g.clipRect(clipped_x, clipped_y, clipped_width, clipped_height); + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + + setTestContext("with clipping"); + + runTestSet(g, size); + } + + public void runSet_noClipping(Graphics g, Dimension size) + { + g.setColor(Color.BLACK); + g.fillRect(0, 0, size.width, size.height); + + setTestContext("without clipping"); + + runTestSet(g, size); + } + + public void paint(Graphics g) + { + synchronized(this) + { + doPaint=true; + notify(); + } + } + } +} + +class TestContext +{ +} + +class TestSet +{ + private Map testsMap = new TreeMap(); + + public void putTest(String testName, TestRecorder recoder) + { + testsMap.put(testName,recoder); + } + + public TestRecorder getTest(String testName) + { + return (TestRecorder)testsMap.get(testName); + } + + public Iterator testIterator() + { + return testsMap.keySet().iterator(); + } +} + +class TestRecorder +{ + String test; + long totalTime = 0; + long minTime = Long.MAX_VALUE; + long maxTime = Long.MIN_VALUE; + int runCount = 0; + + /** + * @return Returns the maxTime. + */ + public final long getMaxTime() + { + return maxTime; + } + + /** + * @return Returns the minTime. + */ + public final long getMinTime() + { + return minTime; + } + + /** + * @return Returns the test name. + */ + public final String getTestName() + { + return test; + } + + public final double getAverage() + { + return ((double)totalTime) / ((double)runCount); + } + + public TestRecorder(String testName) + { + test = testName; + } + + public void addRun(long time) + { + totalTime += time; + if(minTime > time) + minTime = time; + if(maxTime < time) + maxTime = time; + runCount += 1; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java index 64594e47b10..bd5e755cbb5 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java @@ -20,11 +20,70 @@ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA package gnu.classpath.examples.awt; -import java.awt.*; +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Canvas; +import java.awt.Checkbox; +import java.awt.CheckboxGroup; +import java.awt.CheckboxMenuItem; +import java.awt.Choice; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.DisplayMode; +import java.awt.FileDialog; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.GridLayout; +import java.awt.Image; +import java.awt.Insets; +import java.awt.Label; import java.awt.List; -import java.awt.event.*; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.MenuShortcut; +import java.awt.Panel; +import java.awt.ScrollPane; +import java.awt.TextField; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.DragSourceContext; +import java.awt.dnd.DragSourceDragEvent; +import java.awt.dnd.DragSourceDropEvent; +import java.awt.dnd.DragSourceEvent; +import java.awt.dnd.DragSourceListener; +import java.awt.dnd.DropTarget; +import java.awt.dnd.DropTargetDragEvent; +import java.awt.dnd.DropTargetDropEvent; +import java.awt.dnd.DropTargetEvent; +import java.awt.dnd.DropTargetListener; +import java.awt.dnd.InvalidDnDOperationException; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; import java.net.URL; -import java.util.*; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; class Demo { @@ -154,6 +213,9 @@ class Demo addSubWindow ("RandomTests", new TestWindow (this)); addSubWindow ("RoundRect", new RoundRectWindow ()); addSubWindow ("Animation", new AnimationWindow ()); + addSubWindow ("Resolution", new ResolutionWindow ()); + addSubWindow ("Fullscreen", new FullscreenWindow ()); + addSubWindow ("Drag n' Drop", new DragDropWindow ()); Panel sp = new Panel(); PrettyPanel p = new PrettyPanel(); @@ -744,6 +806,234 @@ class Demo t.beep(); } } + + static class ResolutionWindow extends SubFrame + { + GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); + + public void init () + { + initted = true; + + setTitle("Change Screen Resolution"); + final List list = new List(); + DisplayMode[] modes = gd.getDisplayModes(); + + for (int i=0;i<modes.length;i++ ) + list.add(modes[i].getWidth() + "x" + + modes[i].getHeight() + + ((modes[i].getBitDepth() != DisplayMode.BIT_DEPTH_MULTI) + ? "x" + modes[i].getBitDepth() + "bpp" + : "") + + ((modes[i].getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN) + ? "@" + modes[i].getRefreshRate() + "Hz" + : "")); + + ActionListener al = new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + int i = list.getSelectedIndex(); + gd.setDisplayMode(gd.getDisplayModes()[i]); + } + }; + + Button b = new Button("Switch"); + Button c = new Button("Close"); + + list.addActionListener(al); + b.addActionListener(al); + + c.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) { + dispose(); + } + }); + + setLayout(new GridLayout(3, 1, 5, 5)); + add(list); + add(b); + add(c); + + pack(); + } + } + + static class DragDropWindow + extends SubFrame + implements ActionListener, DropTargetListener + { + DragLabel source = new DragLabel("Drag and drop me to the following Button", + Label.CENTER); + + Button target = new Button(); + + public void init() + { + source.setForeground(Color.red); + add(source, BorderLayout.NORTH); + + target.addActionListener(this); + add(target, BorderLayout.SOUTH); + + new DropTarget(target, DnDConstants.ACTION_COPY_OR_MOVE, this); + + setSize(205, 100); + + pack(); + } + + public void actionPerformed(ActionEvent e) + { + Button b = (Button) e.getSource(); + b.setLabel(""); + } + + public void dragEnter(DropTargetDragEvent e) + { + } + + public void dragExit(DropTargetEvent e) + { + } + + public void dragOver(DropTargetDragEvent e) + { + } + + public void drop(DropTargetDropEvent e) + { + try + { + Transferable t = e.getTransferable(); + + if (e.isDataFlavorSupported(DataFlavor.stringFlavor)) + { + e.acceptDrop(e.getDropAction()); + + String s; + s = (String) t.getTransferData(DataFlavor.stringFlavor); + + target.setLabel(s); + + e.dropComplete(true); + } + else + e.rejectDrop(); + } + catch (java.io.IOException e2) + { + } + catch (UnsupportedFlavorException e2) + { + } + } + + public void dropActionChanged(DropTargetDragEvent e) + { + } + + class DragLabel + extends Label + implements DragGestureListener, DragSourceListener + { + private DragSource ds = DragSource.getDefaultDragSource(); + + public DragLabel(String s, int alignment) + { + super(s, alignment); + int action = DnDConstants.ACTION_COPY_OR_MOVE; + ds.createDefaultDragGestureRecognizer(this, action, this); + } + + public void dragGestureRecognized(DragGestureEvent e) + { + try + { + Transferable t = new StringSelection(getText()); + e.startDrag(DragSource.DefaultCopyNoDrop, t, this); + } + catch (InvalidDnDOperationException e2) + { + System.out.println(e2); + } + } + + public void dragDropEnd(DragSourceDropEvent e) + { + if (e.getDropSuccess() == false) + return; + + int action = e.getDropAction(); + if ((action & DnDConstants.ACTION_MOVE) != 0) + setText(""); + } + + public void dragEnter(DragSourceDragEvent e) + { + DragSourceContext ctx = e.getDragSourceContext(); + + int action = e.getDropAction(); + if ((action & DnDConstants.ACTION_COPY) != 0) + ctx.setCursor(DragSource.DefaultCopyDrop); + else + ctx.setCursor(DragSource.DefaultCopyNoDrop); + } + + public void dragExit(DragSourceEvent e) + { + } + + public void dragOver(DragSourceDragEvent e) + { + } + + public void dropActionChanged(DragSourceDragEvent e) + { + } + } + } + + static class FullscreenWindow extends SubFrame + { + GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); + + public void init () + { + initted = true; + + setTitle("Fullscreen Exclusive Mode"); + + ActionListener al = new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + if (gd.getFullScreenWindow() == FullscreenWindow.this) + gd.setFullScreenWindow(null); + else + gd.setFullScreenWindow(FullscreenWindow.this); + } + }; + + Button b = new Button("Toggle Fullscreen"); + Button c = new Button("Close"); + + b.addActionListener(al); + + c.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) { + gd.setFullScreenWindow(null); + dispose(); + } + }); + + setLayout(new GridLayout(3, 1, 5, 5)); + add(b); + add(c); + + pack(); + } + } static class RoundRectWindow extends SubFrame { diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmark.java b/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmark.java new file mode 100644 index 00000000000..118ae2463b8 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmark.java @@ -0,0 +1,1571 @@ +/* J2dBenchmark.java -- Benchmarking utility for java2d, + based on the Aicas AWT benchmarker + Copyright (C) 2006 Free Software Foundation, Inc. + + This file is part of GNU Classpath examples. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ + +package gnu.classpath.examples.java2d; + +import java.awt.AlphaComposite; +import java.awt.BasicStroke; +import java.awt.BorderLayout; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Insets; +import java.awt.Label; +import java.awt.MediaTracker; +import java.awt.Panel; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.TexturePaint; +import java.awt.Toolkit; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.geom.AffineTransform; +import java.awt.geom.Arc2D; +import java.awt.geom.CubicCurve2D; +import java.awt.geom.Ellipse2D; +import java.awt.geom.GeneralPath; +import java.awt.geom.Line2D; +import java.awt.geom.QuadCurve2D; +import java.awt.geom.Rectangle2D; +import java.awt.geom.RoundRectangle2D; +import java.awt.image.BufferedImage; +import java.net.URL; +import java.util.Iterator; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.TreeMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class J2dBenchmark + extends Panel +{ + /** + * Default number of test-iterations. + */ + protected static final int DEFAULT_TEST_SIZE = 1000; + + /** + * Default screen size. + */ + protected static final int DEFAULT_SCREEN_WIDTH = 320; + + protected static final int DEFAULT_SCREEN_HEIGHT = 240; + + /** + * Java2D tests. + */ + protected static final int J2DTEST_ARC = 1 << 0; + + protected static final int J2DTEST_CUBICCURVE = 1 << 1; + + protected static final int J2DTEST_ELLIPSE = 1 << 2; + + protected static final int J2DTEST_GENERALPATH = 1 << 3; + + protected static final int J2DTEST_LINE = 1 << 4; + + protected static final int J2DTEST_QUADCURVE = 1 << 5; + + protected static final int J2DTEST_RECTANGLE = 1 << 6; + + protected static final int J2DTEST_ROUNDRECTANGLE = 1 << 7; + + protected static final int J2DTEST_IMAGE = 1 << 8; + + protected static final int J2DTEST_NONE = 0; + + /* + private static final int J2DTEST_ALL = J2DTEST_ARC | J2DTEST_CUBICCURVE + | J2DTEST_ELLIPSE + | J2DTEST_GENERALPATH | J2DTEST_LINE + | J2DTEST_QUADCURVE + | J2DTEST_RECTANGLE + | J2DTEST_ROUNDRECTANGLE + | J2DTEST_IMAGE; + */ + private static final int J2DTEST_ALL = J2DTEST_ARC | J2DTEST_CUBICCURVE + | J2DTEST_ELLIPSE + | J2DTEST_LINE + | J2DTEST_QUADCURVE + | J2DTEST_RECTANGLE + | J2DTEST_ROUNDRECTANGLE + | J2DTEST_IMAGE; + + int iterations = 1; + + protected int screenWidth = DEFAULT_SCREEN_WIDTH; + + protected int screenHeight = DEFAULT_SCREEN_HEIGHT; + + protected boolean noClippingFlag = true; + + protected boolean withClippingFlag = true; + + protected boolean zeroClippingFlag = true; + + protected boolean singleBufferFlag = true; + + protected boolean doubleBufferFlag = true; + + protected boolean gradientFlag = false; + + protected String texture = null; + + protected boolean strokeFlag = false; + + protected float composite = 1; + + protected int xtranslate = 0; + + protected int ytranslate = 0; + + protected double xshear = 0; + + protected double yshear = 0; + + protected double rotate = 0; + + protected boolean antialiasFlag = false; + + protected AffineTransform affineTransform = null; + + protected int awtTests = J2DTEST_ALL; + + protected int testSize = DEFAULT_TEST_SIZE; + + private Label testLabel; + + private String testContext = ""; + + Logger logger = Logger.getLogger("J2dGraphicsBenchmark"); + + private Image pngTestImage; + + private Image gifTestImage; + + protected BufferedImage textureImage; + + protected TestSet testSetMap = new TestSet(); + + public String init() + { + boolean loadError = false; + pngTestImage = loadImage("aicas.png"); + gifTestImage = loadImage("palme.gif"); + + if (texture != null) + { + textureImage = loadBufferedImage(texture); + + if (textureImage == null) + { + logger.logp(Level.WARNING, "J2dGraphicsBenchmark", "init", + "Unable to load texture - defaulting " + + "to solid colours"); + texture = null; + loadError = true; + } + } + + setLayout(new BorderLayout()); + testLabel = new Label(); + add(testLabel, BorderLayout.NORTH); + add(new GraphicsTest(), BorderLayout.CENTER); + + if (loadError) + return "Unable to load image"; + else + return null; + } + + void setTestContext(String testName) + { + logger.logp(Level.INFO, "J2dGraphicsBenchmark", "recordTest", + "--- Starting new test context: " + testName); + testContext = testName; + testLabel.setText(testName); + } + + private void recordTest(String testName, long time) + { + logger.logp(Level.INFO, "J2dGraphicsBenchmark", "recordTest", + testContext + ": " + testName + " duration (ms): " + time); + TestRecorder recorder = testSetMap.getTest(testName); + if (recorder == null) + { + recorder = new TestRecorder(testName); + testSetMap.putTest(testName, recorder); + } + recorder.addRun(time); + } + + void printReport() + { + for (Iterator i = testSetMap.testIterator(); i.hasNext();) + { + TestRecorder recorder = testSetMap.getTest((String) i.next()); + System.out.println("TEST " + recorder.getTestName() + ": average " + + recorder.getAverage() + "ms [" + + recorder.getMinTime() + "-" + + recorder.getMaxTime() + "]"); + } + } + + void testComplete() + { + System.exit(0); + } + + public static void main(String[] args) + { + int awtTests; + int i; + boolean endOfOptionsFlag; + J2dBenchmark speed = new J2dBenchmark(); + + // Parse arguments. + i = 0; + endOfOptionsFlag = false; + awtTests = J2DTEST_NONE; + while (i < args.length) + { + if (! endOfOptionsFlag) + { + if (args[i].equals("--help") || args[i].equals("-help") + || args[i].equals("-h")) + { + System.out.println("Usage: J2dBenchmark [<options>] [<test> ...]"); + System.out.println(""); + System.out.println("Options: -i|--iterations=<n|-1> - number of iterations (-1 is infinite; default " + + speed.iterations + ")"); + System.out.println(" -w|--width=<n> - screen width; default " + + DEFAULT_SCREEN_WIDTH); + System.out.println(" -h|--height=<n> - screen height; default " + + DEFAULT_SCREEN_HEIGHT); + System.out.println(" -d|--noDoubleBuffer - disable double-buffering test"); + System.out.println(" -s|--testsize=<n> - size of each test; default " + + DEFAULT_TEST_SIZE); + System.out.println(" -c|--noClipping - disable clipping test"); + System.out.println(" -z|--noZeroClipping - disable clipping to zero test"); + System.out.println(""); + System.out.println("Additional options:"); + System.out.println(" --with-gradients - enable gradients (not compatible with --texture)"); + System.out.println(" --with-stroking - enable random stroking"); + System.out.println(" --texture=<file> - enable texturing with this file (not compatible with --with-gradients)"); + System.out.println(" --composite=<n|-1> - set alpha composite level; -1 for random; default 1.0 (no transparency)"); + System.out.println(" --anti-alias=<on|off> - set anti-aliasing hint (not all implementations respect this); default off"); + System.out.println(" --x-translate=<n> - set x-axis translation; default 0"); + System.out.println(" --y-translate=<n> - set y-axis translation; default 0"); + System.out.println(" --x-shear=<n> - set x-axis shear; default 0"); + System.out.println(" --y-shear=<n> - set y-axis shear; default 0"); + System.out.println(" --rotate=<n|-1> - set rotation (radians); -1 for random; default: 0 (none)"); + System.out.println(""); + System.out.println("Tests: arc"); + System.out.println(" cubiccurve"); + System.out.println(" ellipse"); + // System.out.println(" generalpath"); + System.out.println(" line"); + System.out.println(" quadcurve"); + System.out.println(" rectangle"); + System.out.println(" roundrectangle"); + System.out.println(" image"); + System.exit(1); + } + else if ((args[i].startsWith("-i=") || args[i].startsWith("--iterations="))) + { + speed.iterations = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-i") || args[i].equals("--iterations"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.iterations = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].startsWith("-w=") || args[i].startsWith("--width="))) + { + speed.screenWidth = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-w") || args[i].equals("--width"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.screenWidth = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].startsWith("-h=") || args[i].startsWith("--height="))) + { + speed.screenHeight = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-h") || args[i].equals("--height"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.screenHeight = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].equals("-d") || args[i].equals("--noDoubleBuffer"))) + { + speed.doubleBufferFlag = false; + i += 1; + continue; + } + else if ((args[i].startsWith("-s=") || args[i].startsWith("--testsize="))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.testSize = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if ((args[i].equals("-s") || args[i].equals("--testsize"))) + { + if ((i + 1) >= args.length) + { + System.err.println("ERROR: No argument given for option '" + + args[i] + "'!"); + System.exit(2); + } + speed.testSize = Integer.parseInt(args[i + 1]); + i += 2; + continue; + } + else if ((args[i].equals("-c") || args[i].equals("--noClipping"))) + { + speed.noClippingFlag = false; + i += 1; + continue; + } + else if ((args[i].equals("-z") || args[i].equals("--noZeroClipping"))) + { + speed.zeroClippingFlag = false; + i += 1; + continue; + } + else if (args[i].equals("--with-gradients")) + { + speed.gradientFlag = true; + i += 1; + continue; + } + else if (args[i].equals("--with-stroking")) + { + speed.strokeFlag = true; + i += 1; + continue; + } + else if (args[i].startsWith("--texture=")) + { + speed.texture = args[i].substring(args[i].indexOf('=') + 1); + i += 1; + continue; + } + else if (args[i].startsWith("--composite=")) + { + speed.composite = Float.parseFloat(args[i].substring(args[i].indexOf('=') + 1)); + if (speed.composite != - 1 + && (speed.composite < 0 || speed.composite > 1)) + { + System.err.println("ERROR: Invalid value for composite (must be between 0 and 1, or -1 for random)"); + System.exit(2); + } + i += 1; + continue; + } + else if (args[i].startsWith("--anti-alias=")) + { + speed.antialiasFlag = (args[i].substring(args[i].indexOf('=') + 1).equals("on")); + i += 1; + continue; + } + else if (args[i].startsWith("--x-translate=")) + { + speed.xtranslate = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if (args[i].startsWith("--y-translate=")) + { + speed.ytranslate = Integer.parseInt(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if (args[i].startsWith("--x-shear=")) + { + speed.xshear = Double.parseDouble(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if (args[i].startsWith("--y-shear=")) + { + speed.yshear = Double.parseDouble(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + else if (args[i].startsWith("--rotate=")) + { + speed.rotate = Double.parseDouble(args[i].substring(args[i].indexOf('=') + 1)); + i += 1; + continue; + } + + else if (args[i].equals("--")) + { + endOfOptionsFlag = true; + i += 1; + continue; + } + else if (args[i].startsWith("-")) + { + System.err.println("ERROR: Unknown option '" + args[i] + "'!"); + System.exit(2); + } + } + StringTokenizer tokenizer = new StringTokenizer(args[i], " +,"); + while (tokenizer.hasMoreTokens()) + { + String s = tokenizer.nextToken().toLowerCase(); + if (s.equals("arc")) + awtTests |= J2DTEST_ARC; + else if (s.equals("cubiccurve")) + awtTests |= J2DTEST_CUBICCURVE; + else if (s.equals("ellipse")) + awtTests |= J2DTEST_ELLIPSE; + else if (s.equals("generalpath")) + awtTests |= J2DTEST_GENERALPATH; + else if (s.equals("line")) + awtTests |= J2DTEST_LINE; + else if (s.equals("quadcurve")) + awtTests |= J2DTEST_QUADCURVE; + else if (s.equals("rectangle")) + awtTests |= J2DTEST_RECTANGLE; + else if (s.equals("roundrectangle")) + awtTests |= J2DTEST_ROUNDRECTANGLE; + else if (s.equals("image")) + awtTests |= J2DTEST_IMAGE; + else + { + System.err.println("Unknown AWT test '" + s + "'!"); + System.exit(2); + } + } + i += 1; + } + if (awtTests != J2DTEST_NONE) + speed.awtTests = awtTests; + + // Create graphics. + speed.init(); + final Frame frame = new Frame("J2dGraphicsBenchmark"); + + frame.addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + frame.setVisible(false); + System.exit(0); + } + }); + + frame.add(speed, BorderLayout.CENTER); + frame.setSize(speed.screenWidth, speed.screenHeight); + frame.setVisible(true); + + // Insets are correctly set only after the native peer was created. + Insets insets = frame.getInsets(); + // The internal size of the frame should be 320x240. + frame.setSize(320 + insets.right + insets.left, 240 + insets.top + + insets.bottom); + } + + private Image loadImage(String imageName) + { + Image result = null; + logger.logp(Level.INFO, "J2dGraphicsBenchmark", "loadImage", + "Loading image: " + imageName); + URL url = getClass().getResource(imageName); + if (url != null) + { + result = Toolkit.getDefaultToolkit().getImage(url); + prepareImage(result, this); + } + else + { + logger.logp(Level.WARNING, "J2dGraphicsBenchmark", "loadImage", + "Could not locate image resource in class path: " + + imageName); + } + return result; + } + + private BufferedImage loadBufferedImage(String imageName) + { + BufferedImage result = null; + logger.logp(Level.INFO, "J2dGraphicsBenchmark", "loadImage", + "Loading image: " + imageName); + + // Try to load image out of classpath before trying an absolute filename + URL url = getClass().getResource(imageName); + Image img; + if (url != null) + img = Toolkit.getDefaultToolkit().getImage(url); + else + img = Toolkit.getDefaultToolkit().getImage(imageName); + + if (img != null) + { + // Wait for image to load + try + { + MediaTracker tracker = new MediaTracker(this); + tracker.addImage(img, 1); + tracker.waitForAll(); + + prepareImage(img, this); + result = new BufferedImage(img.getWidth(this), img.getHeight(this), + BufferedImage.TYPE_INT_RGB); + result.createGraphics().drawImage(img, 0, 0, this); + } + catch (InterruptedException e) + { + } + catch (IllegalArgumentException e) + { + } + } + + if (result == null) + { + logger.logp(Level.WARNING, "J2dGraphicsBenchmark", "loadBufferedImage", + "Could not locate image resource in class path: " + + imageName); + } + return result; + } + + /** + * Executes the test methods. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + void runTestSet(Graphics2D g, Dimension size) + { + // Any user-specified options (ie set transforms, rendering hints) + prepareGraphics((Graphics2D) g); + + if ((awtTests & J2DTEST_ARC) != 0) + { + test_drawArc(g, size); + test_fillArc(g, size); + } + + if ((awtTests & J2DTEST_CUBICCURVE) != 0) + { + test_drawCubicCurve(g, size); + } + + if ((awtTests & J2DTEST_ELLIPSE) != 0) + { + test_drawEllipse(g, size); + test_fillEllipse(g, size); + } + + if ((awtTests & J2DTEST_GENERALPATH) != 0) + { + // Current implementation doesn't work + test_drawGeneralPath(g, size); + test_fillGeneralPath(g, size); + } + + if ((awtTests & J2DTEST_LINE) != 0) + { + test_drawLine(g, size); + } + + if ((awtTests & J2DTEST_QUADCURVE) != 0) + { + test_drawQuadCurve(g, size); + } + + if ((awtTests & J2DTEST_RECTANGLE) != 0) + { + test_drawRectangle(g, size); + test_fillRectangle(g, size); + } + + if ((awtTests & J2DTEST_ROUNDRECTANGLE) != 0) + { + test_drawRoundRectangle(g, size); + test_fillRoundRectangle(g, size); + } + + if ((awtTests & J2DTEST_IMAGE) != 0) + { + test_drawImage(g, size); + test_drawTransparentImage(g, size); + } + } + + /** + * Reset all graphics settings to the standard, default values + * + * @param g the object to apply settings to + */ + private void resetGraphics(Graphics2D g) + { + g.setTransform(new AffineTransform()); + g.setStroke(new BasicStroke()); + g.setComposite(AlphaComposite.SrcOut); + } + + /** + * Sets initial user graphics options + * + * @param g the object to apply settings to + */ + private void prepareGraphics(Graphics2D g) + { + // Transforms + if (affineTransform != null) + g.setTransform(affineTransform); + + else if (xtranslate != 0 || ytranslate != 0 || xshear != 0 || yshear != 0) + { + g.translate(xtranslate, ytranslate); + g.shear(xshear, yshear); + } + + if (rotate > 0) + g.rotate(rotate * Math.PI, screenWidth / 2, screenHeight / 2); + + // Composite (transparency) + if (composite > 0) + { + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, + composite)); + } + + // Textures + if (texture != null) + g.setPaint(new TexturePaint(textureImage, + new Rectangle(0, 0, textureImage.getWidth(), + textureImage.getHeight()))); + + // Anti-alias setting + if (antialiasFlag) + g.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + else + g.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_OFF)); + } + + /** + * Gets new random settings + * + * @param g the object to set parameters for + * @param size the screen size + */ + private void setRandom(Graphics2D g, Dimension size) + { + // Set colour / paint + if (gradientFlag) + { + Color c1 = new Color((int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1); + + Color c2 = new Color((int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1); + + g.setPaint(new GradientPaint(0, 0, c1, screenWidth / 5, + screenHeight / 5, c2, true)); + } + + else if (texture == null) + g.setPaint(new Color((int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1, + (int) (Math.random() * 254) + 1)); + + // Set stroke width and options + if (strokeFlag) + { + int cap = (int) (Math.random() * 3 + 1); + if (cap == 1) + cap = BasicStroke.CAP_SQUARE; + else if (cap == 2) + cap = BasicStroke.CAP_BUTT; + else + cap = BasicStroke.CAP_ROUND; + + int join = (int) (Math.random() * 3 + 1); + if (join == 1) + join = BasicStroke.JOIN_MITER; + else if (join == 2) + join = BasicStroke.JOIN_BEVEL; + else + join = BasicStroke.JOIN_ROUND; + + float[] dashes = { 10, 10 }; + g.setStroke(new BasicStroke((int) (Math.random() * 10), cap, join, 10f, + dashes, 0)); + } + + // Composite / transparency + if (composite == - 1) + { + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, + (float) Math.random())); + } + + // Transformations + if (rotate == - 1) + g.rotate(Math.random() * Math.PI * 2); + } + + /** + * Draws random arcs within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawArc(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int startAngle = (int) (Math.random() * 360); + int arcAngle = (int) (Math.random() * 360 - startAngle); + + Arc2D arc = new Arc2D.Double(x, y, width, height, startAngle, arcAngle, + Arc2D.OPEN); + g.draw(arc); + } + endTime = System.currentTimeMillis(); + recordTest("draw(Arc2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random filled arcs within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillArc(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int startAngle = (int) (Math.random() * 360); + int arcAngle = (int) (Math.random() * 360); + + Arc2D arc = new Arc2D.Double(x, y, width, height, startAngle, arcAngle, + Arc2D.OPEN); + g.fill(arc); + } + endTime = System.currentTimeMillis(); + recordTest("fill(Arc2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random cubic curves within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawCubicCurve(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int xc1 = (int) (Math.random() * (size.width - minSize)); + int yc1 = (int) (Math.random() * (size.height - minSize)); + int xc2 = (int) (Math.random() * (size.width - minSize)); + int yc2 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + + CubicCurve2D curve = new CubicCurve2D.Double(x1, y1, xc1, yc1, xc2, + yc2, x2, y2); + g.draw(curve); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(CubicCurve2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random ellipses within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawEllipse(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Ellipse2D ellipse = new Ellipse2D.Double(x1, y1, x2, y2); + g.draw(ellipse); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(Ellipse.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random ellipses within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillEllipse(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Ellipse2D ellipse = new Ellipse2D.Double(x1, y1, x2, y2); + g.fill(ellipse); + } + long endTime = System.currentTimeMillis(); + recordTest("fill(Ellipse.Double) " + maxTests + " times", + (endTime - startTime)); + } + + // TODO: fix the GeneralPath methods. + /** + * Draws random polygons within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawGeneralPath(Graphics2D g, Dimension size) + { + int maxTests = testSize; + long startTime = System.currentTimeMillis(); + + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int points = (int) (Math.random() * 6) + 2; + GeneralPath shape = new GeneralPath(); + shape.moveTo((float) Math.random() * (size.width), + (float) Math.random() * (size.height)); + for (int j = 0; j < points; j += 1) + { + shape.lineTo((float) (Math.random() * (size.width)), + (float) (Math.random() * (size.height))); + } + g.draw(shape); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(GeneralPath) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random filled polygons within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillGeneralPath(Graphics2D g, Dimension size) + { + int maxTests = testSize; + long startTime = System.currentTimeMillis(); + + GeneralPath shape = new GeneralPath(); + shape.moveTo((float) Math.random() * (size.width), (float) Math.random() + * (size.height)); + + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int points = (int) (Math.random() * 6) + 2; + for (int j = 0; j < points; j += 1) + { + shape.lineTo((float) (Math.random() * (size.width)), + (float) (Math.random() * (size.height))); + } + g.fill(shape); + } + long endTime = System.currentTimeMillis(); + recordTest("fill(GeneralPath) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random lines within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawLine(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Line2D line = new Line2D.Double(x1, y1, x2, y2); + g.draw(line); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(Line2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random quadratic curves within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawQuadCurve(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int xc = (int) (Math.random() * (size.width - minSize)); + int yc = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + + QuadCurve2D curve = new QuadCurve2D.Double(x1, y1, xc, yc, x2, y2); + g.draw(curve); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(QuadCurve2D.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random rectangles within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawRectangle(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Rectangle2D rect = new Rectangle2D.Double(x1, y1, x2, y2); + g.draw(rect); + } + long endTime = System.currentTimeMillis(); + recordTest("draw(Rectangle.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random rectangles within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillRectangle(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize = 10; + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x1 = (int) (Math.random() * (size.width - minSize)); + int y1 = (int) (Math.random() * (size.height - minSize)); + int x2 = (int) (Math.random() * (size.width - minSize)); + int y2 = (int) (Math.random() * (size.height - minSize)); + Rectangle2D rect = new Rectangle2D.Double(x1, y1, x2, y2); + g.fill(rect); + } + long endTime = System.currentTimeMillis(); + recordTest("fill(Rectangle.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random rounded rectangles within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawRoundRectangle(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int arcWidth = (int) (Math.random() * (width - 1) + 1); + int arcHeight = (int) (Math.random() * (height - 1) + 5); + RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, + height, arcWidth, + arcHeight); + g.draw(rect); + } + endTime = System.currentTimeMillis(); + recordTest("draw(RoundRectangle.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random filled rounded rectangles within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_fillRoundRectangle(Graphics2D g, Dimension size) + { + int maxTests = testSize; + int minSize; + long startTime; + long endTime; + minSize = 10; + startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - minSize + 1)); + int y = (int) (Math.random() * (size.height - minSize + 1)); + int width = (int) (Math.random() * (size.width - x - minSize) + minSize); + int height = (int) (Math.random() * (size.height - y - minSize) + minSize); + int arcWidth = (int) (Math.random() * (width - 1) + 1); + int arcHeight = (int) (Math.random() * (height - 1) + 5); + RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, + height, arcWidth, + arcHeight); + g.fill(rect); + } + endTime = System.currentTimeMillis(); + recordTest("fill(RoundRectangle.Double) " + maxTests + " times", + (endTime - startTime)); + } + + /** + * Draws random images within the given dimensions. + * + * @param g The Graphics2D object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawImage(Graphics2D g, Dimension size) + { + if (gifTestImage == null) + { + logger.logp(Level.WARNING, "J2dGraphicsBenchmark", "runTestSet", + "Skipping 'test_drawImage' due to missing resource."); + return; + } + + int maxTests = testSize / 2; + if (maxTests == 0) + maxTests = 1; + int imageWidth = gifTestImage.getWidth(this); + int imageHeight = gifTestImage.getHeight(this); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - imageWidth + 1)); + int y = (int) (Math.random() * (size.height - imageHeight + 1)); + g.drawImage(gifTestImage, x, y, this); + } + long endTime = System.currentTimeMillis(); + recordTest("drawImage " + maxTests + " times", (endTime - startTime)); + } + + /** + * Draws random transparent images within the given dimensions. + * + * @param g The Graphics object that is used to paint. + * @param size The size of the canvas. + */ + private void test_drawTransparentImage(Graphics2D g, Dimension size) + { + if (pngTestImage == null) + { + logger.logp(Level.WARNING, "AicasGraphicsBenchmark", "runTestSet", + "Skipping 'drawTransparentImage' due to missing resource."); + return; + } + + int maxTests = testSize / 5; + if (maxTests == 0) + maxTests = 1; + int imageWidth = pngTestImage.getWidth(this); + int imageHeight = pngTestImage.getHeight(this); + long startTime = System.currentTimeMillis(); + for (int i = 0; i < maxTests; i += 1) + { + setRandom(g, size); + int x = (int) (Math.random() * (size.width - imageWidth + 1)); + int y = (int) (Math.random() * (size.height - imageHeight + 1)); + g.drawImage(pngTestImage, x, y, this); + } + long endTime = System.currentTimeMillis(); + recordTest("draw transparent image " + maxTests + " times", + (endTime - startTime)); + } + + private class GraphicsTest + extends Canvas + implements Runnable + { + Thread paintThread; + + boolean done = false; + + boolean doPaint = false; + + boolean withClipping = false; + + public GraphicsTest() + { + paintThread = new Thread(this); + paintThread.start(); + } + + public void run() + { + int runCount = 0; + while (! done) + { + runCount++; + + try + { + synchronized (this) + { + while (! doPaint) + { + try + { + wait(200); + } + catch (InterruptedException exception) + { + return; + } + } + } + + // if (iterations != 0) + // System.out.println("--- run...(" + // + runCount + // + "/" + // + iterations + // + ") ------------------------------------------------------"); + + Graphics g = getGraphics(); + Dimension size = getSize(); + + if (singleBufferFlag) + { + logger.logp(Level.INFO, "J2dGraphicsBenchmark.GraphicsTest", + "run", + "Start testing non-double-buffered drawing"); + + if (noClippingFlag) + runSet_noClipping((Graphics2D) g, size, runCount); + + if (withClippingFlag) + runSet_withClipping((Graphics2D) g, size, runCount); + + if (zeroClippingFlag) + runSet_zeroClipping((Graphics2D) g, size, runCount); + + g.dispose(); + } + + if (doubleBufferFlag) + { + logger.logp(Level.INFO, "J2dGraphicsBenchmark.GraphicsTest", + "run", "Start testing double-buffered drawing"); + Graphics canvas = getGraphics(); + Image doublebuffer = createImage(size.width, size.height); + + if (noClippingFlag) + { + g = doublebuffer.getGraphics(); + runSet_noClipping((Graphics2D) g, size, + "double buffering", runCount); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + } + + if (withClippingFlag) + { + g = doublebuffer.getGraphics(); + runSet_withClipping((Graphics2D) g, size, + "double buffering", runCount); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + } + + if (zeroClippingFlag) + { + g = doublebuffer.getGraphics(); + runSet_zeroClipping((Graphics2D) g, size, + "double buffering", runCount); + g.dispose(); + canvas.drawImage(doublebuffer, 0, 0, this); + canvas.dispose(); + } + } + + printReport(); + + if (iterations != 1) + { + if (iterations != - 1) + iterations--; + } + else + { + // System.out.println("--- done + // --------------------------------------------------------"); + synchronized (this) + { + doPaint = false; + } + done = true; + } + } + catch (Error error) + { + System.err.println("Error: " + error); + System.exit(129); + } + } + testComplete(); + } + + private void runSet_zeroClipping(Graphics2D g, Dimension size, int runCount) + { + runSet_zeroClipping(g, size, "", runCount); + } + + private void runSet_zeroClipping(Graphics2D g, Dimension size, + String context, int runCount) + { + int clipped_width; + int clipped_height; + int clipped_x; + int clipped_y; + + clipped_width = 0; + clipped_height = 0; + clipped_x = (size.width) / 2; + clipped_y = (size.height) / 2; + + // Reset any transforms from past tests + resetGraphics(g); + + Rectangle fullWindow = new Rectangle(0, 0, size.width, size.height); + g.setClip(fullWindow); + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + Rectangle windowBorder = new Rectangle(0, 0, size.width - 1, + size.width - 1); + g.setPaint(Color.WHITE); + g.draw(windowBorder); + + Rectangle innerBorder = new Rectangle(clipped_x - 1, clipped_y - 1, + clipped_width + 2, + clipped_height + 2); + g.fill(innerBorder); + + Rectangle innerBox = new Rectangle(clipped_x, clipped_y, clipped_width, + clipped_height); + g.clip(innerBox); + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + if (context.equals("")) + setTestContext("(" + runCount + ") clipping to zero"); + else + setTestContext("(" + runCount + ") clipping to zero (" + context + ")"); + + runTestSet(g, size); + } + + private void runSet_withClipping(Graphics2D g, Dimension size, int runCount) + { + runSet_withClipping(g, size, "", runCount); + } + + private void runSet_withClipping(Graphics2D g, Dimension size, + String context, int runCount) + { + int clipped_width = 2 * size.width / 3; + int clipped_height = 2 * size.height / 3; + int clipped_x = (size.width - clipped_width) / 2; + int clipped_y = (size.height - clipped_height) / 2; + + // Reset any transforms from past tests + resetGraphics(g); + + Rectangle fullWindow = new Rectangle(0, 0, size.width, size.height); + g.setClip(fullWindow); + + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + Rectangle windowBorder = new Rectangle(0, 0, size.width - 1, + size.height - 1); + g.setPaint(Color.GREEN); + g.draw(windowBorder); + + Rectangle innerBorder = new Rectangle(clipped_x - 1, clipped_y - 1, + clipped_width + 2, + clipped_height + 2); + g.setPaint(Color.WHITE); + g.fill(innerBorder); + + Rectangle innerBox = new Rectangle(clipped_x, clipped_y, clipped_width, + clipped_height); + g.clip(innerBox); + + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + if (context.equals("")) + setTestContext("(" + runCount + ") with clipping "); + else + setTestContext("(" + runCount + ") with clipping (" + context + ")"); + + runTestSet(g, size); + } + + private void runSet_noClipping(Graphics2D g, Dimension size, int runCount) + { + runSet_noClipping(g, size, "", runCount); + } + + private void runSet_noClipping(Graphics2D g, Dimension size, + String context, int runCount) + { + // Reset any transforms from past tests + resetGraphics(g); + + Rectangle fullWindow = new Rectangle(0, 0, size.width, size.height); + g.setPaint(Color.BLACK); + g.fill(fullWindow); + + if (context.equals("")) + setTestContext("(" + runCount + ") without clipping"); + else + setTestContext("(" + runCount + ") without clipping (" + context + ")"); + + runTestSet(g, size); + } + + public void paint(Graphics g) + { + synchronized (this) + { + doPaint = true; + notify(); + } + } + } +} + +class TestContext +{ +} + +class TestSet +{ + private Map testsMap = new TreeMap(); + + public void putTest(String testName, TestRecorder recoder) + { + testsMap.put(testName, recoder); + } + + public TestRecorder getTest(String testName) + { + return (TestRecorder) testsMap.get(testName); + } + + public Iterator testIterator() + { + return testsMap.keySet().iterator(); + } +} + +class TestRecorder +{ + String test; + + long totalTime = 0; + + long minTime = Long.MAX_VALUE; + + long maxTime = Long.MIN_VALUE; + + int runCount = 0; + + /** + * @return Returns the maxTime. + */ + public final long getMaxTime() + { + return maxTime; + } + + /** + * @return Returns the minTime. + */ + public final long getMinTime() + { + return minTime; + } + + /** + * @return Returns the test name. + */ + public final String getTestName() + { + return test; + } + + public final long getAverage() + { + return (totalTime / runCount); + } + + public TestRecorder(String testName) + { + test = testName; + } + + public void addRun(long time) + { + totalTime += time; + if (minTime > time) + minTime = time; + if (maxTime < time) + maxTime = time; + runCount += 1; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmarkGUI.java b/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmarkGUI.java new file mode 100644 index 00000000000..bb583cbdcd2 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/J2dBenchmarkGUI.java @@ -0,0 +1,891 @@ +/* J2dBenchmarkGUI.java -- GUI for java2d benchmarker + Copyright (C) 2006 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + +package gnu.classpath.examples.java2d; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Container; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.GridLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.border.BevelBorder; + +/** + * Extends the J2dBenchmark to provide a GUI for selecting options and tests. + */ +public class J2dBenchmarkGUI + implements ActionListener +{ + + JLabel errorLabel; + + JCheckBox noClipping; + + JCheckBox withClipping; + + JCheckBox zeroClipping; + + JCheckBox singleBuffer; + + JCheckBox doubleBuffer; + + public J2dBenchmarkGUI() + { + super(); + } + + public static void main(String[] args) + { + new J2dBenchmarkGUI().run(); + } + + /** + * Sets up the initial GUI + */ + public void run() + { + // Store all elements in a hashtable so that they can be passed into the + // harness easily. + Hashtable elements = new Hashtable(); + + // Set up frame + final JFrame frame = new JFrame("Java2D benchmark"); + errorLabel = new JLabel(" "); + + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); + Container content = frame.getContentPane(); + + // Display options for dimensions, iterations, test size, etc + JPanel options = new JPanel(new GridLayout(0, 2)); + + options.add(new JLabel("Height: ")); + JTextField heightField = new JTextField(Integer.toString(J2dBenchmark.DEFAULT_SCREEN_HEIGHT)); + heightField.setColumns(5); + options.add(heightField); + elements.put("height", heightField); + + options.add(new JLabel("Width: ")); + JTextField widthField = new JTextField(Integer.toString(J2dBenchmark.DEFAULT_SCREEN_WIDTH)); + widthField.setColumns(5); + options.add(widthField); + elements.put("width", widthField); + + options.add(new JLabel("Iterations: ")); + JTextField iterField = new JTextField("1"); + iterField.setColumns(5); + options.add(iterField); + elements.put("iterations", iterField); + + options.add(new JLabel("Test size: ")); + JTextField testSizeField = new JTextField(Integer.toString(J2dBenchmark.DEFAULT_TEST_SIZE)); + testSizeField.setColumns(5); + options.add(testSizeField); + elements.put("size", testSizeField); + + options.add(new JLabel("Test without clipping: ")); + noClipping = new JCheckBox("", true); + noClipping.addActionListener(this); + options.add(noClipping); + elements.put("noclip", noClipping); + + options.add(new JLabel("Test with clipping: ")); + withClipping = new JCheckBox("", true); + withClipping.addActionListener(this); + options.add(withClipping); + elements.put("withclip", withClipping); + + options.add(new JLabel("Test with clipping to zero: ")); + zeroClipping = new JCheckBox("", true); + zeroClipping.addActionListener(this); + options.add(zeroClipping); + elements.put("zeroclip", zeroClipping); + + options.add(new JLabel("Run single-buffer test: ")); + singleBuffer = new JCheckBox("", true); + singleBuffer.addActionListener(this); + options.add(singleBuffer); + elements.put("singlebuffer", singleBuffer); + + options.add(new JLabel("Run double-buffer test: ")); + doubleBuffer = new JCheckBox("", true); + doubleBuffer.addActionListener(this); + options.add(doubleBuffer); + elements.put("doublebuffer", doubleBuffer); + + // Allow user to select tests to run + JPanel tests = new JPanel(); + tests.setLayout(new BoxLayout(tests, BoxLayout.PAGE_AXIS)); + tests.setBorder(new BevelBorder(BevelBorder.RAISED)); + tests.add(new JLabel("Shapes to test:")); + + JCheckBox test_arcDraw = new JCheckBox("Arc", true); + tests.add(test_arcDraw); + elements.put("test_arcDraw", test_arcDraw); + + JCheckBox test_ccurveDraw = new JCheckBox("Cubic Curve", true); + tests.add(test_ccurveDraw); + elements.put("test_ccurveDraw", test_ccurveDraw); + + JCheckBox test_ellipseDraw = new JCheckBox("Ellipse", true); + tests.add(test_ellipseDraw); + elements.put("test_ellipseDraw", test_ellipseDraw); + + /* + JCheckBox test_pathDraw = new JCheckBox("General Path", true); + tests.add(test_pathDraw); + elements.put("test_pathDraw", test_pathDraw); + */ + + JCheckBox test_lineDraw = new JCheckBox("Line", true); + tests.add(test_lineDraw); + elements.put("test_lineDraw", test_lineDraw); + + JCheckBox test_qcurveDraw = new JCheckBox("Quadratic Curve", true); + tests.add(test_qcurveDraw); + elements.put("test_qcurveDraw", test_qcurveDraw); + + JCheckBox test_rectDraw = new JCheckBox("Rectangle", true); + tests.add(test_rectDraw); + elements.put("test_rectDraw", test_rectDraw); + + JCheckBox test_rrectDraw = new JCheckBox("Round Rectangle", true); + tests.add(test_rrectDraw); + elements.put("test_rrectDraw", test_rrectDraw); + + JCheckBox test_image = new JCheckBox("Images", true); + tests.add(test_image); + elements.put("test_image", test_image); + + // Additional image-processing options + JPanel extras = new JPanel(); + extras.setBorder(new BevelBorder(BevelBorder.LOWERED)); + GridBagLayout layout = new GridBagLayout(); + GridBagConstraints gbc = new GridBagConstraints(); + gbc.anchor = GridBagConstraints.NORTHWEST; + gbc.insets = new Insets(5, 2, 15, 15); + extras.setLayout(layout); + + // Filling (solid, gradient, or texture) + JPanel opt_Fill = new JPanel(); + opt_Fill.setLayout(new BoxLayout(opt_Fill, BoxLayout.PAGE_AXIS)); + JLabel opt_FillLabel = new JLabel("Filling:"); + opt_FillLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + opt_Fill.add(opt_FillLabel); + + ButtonGroup opt_FillGroup = new ButtonGroup(); + JRadioButton opt_FillSolid = new JRadioButton("Solid colour", true); + opt_FillSolid.setActionCommand("solid"); + opt_Fill.add(opt_FillSolid); + opt_FillGroup.add(opt_FillSolid); + JRadioButton opt_FillGradient = new JRadioButton("Gradient", false); + opt_FillGradient.setActionCommand("gradient"); + opt_Fill.add(opt_FillGradient); + opt_FillGroup.add(opt_FillGradient); + JRadioButton opt_FillTexture = new JRadioButton("Texture", false); + opt_FillTexture.setActionCommand("texture"); + opt_Fill.add(opt_FillTexture); + opt_FillGroup.add(opt_FillTexture); + JTextField opt_FillTextureFile = new JTextField("texture file"); + opt_FillTextureFile.setAlignmentX(JComponent.LEFT_ALIGNMENT); + opt_Fill.add(opt_FillTextureFile); + elements.put("opt_FillGroup", opt_FillGroup); + elements.put("opt_FillTextureFile", opt_FillTextureFile); + layout.setConstraints(opt_Fill, gbc); + extras.add(opt_Fill); + + // Stroke + JPanel opt_Stroke = new JPanel(); + opt_Stroke.setLayout(new BoxLayout(opt_Stroke, BoxLayout.PAGE_AXIS)); + JLabel opt_StrokeLabel = new JLabel("Stroke:"); + opt_StrokeLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + opt_Stroke.add(opt_StrokeLabel); + JCheckBox opt_StrokeRandom = new JCheckBox("random", false); + elements.put("opt_StrokeRandom", opt_StrokeRandom); + opt_Stroke.add(opt_StrokeRandom); + gbc.gridwidth = GridBagConstraints.REMAINDER; + layout.setConstraints(opt_Stroke, gbc); + extras.add(opt_Stroke); + + // Anti-Alias + JPanel opt_Alias = new JPanel(); + opt_Alias.setLayout(new BoxLayout(opt_Alias, BoxLayout.PAGE_AXIS)); + JLabel opt_AliasLabel = new JLabel("Anti-Aliasing:"); + opt_AliasLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + opt_Alias.add(opt_AliasLabel); + JCheckBox opt_AliasOn = new JCheckBox("on", false); + elements.put("opt_AliasOn", opt_AliasOn); + opt_Alias.add(opt_AliasOn); + gbc.gridwidth = 1; + layout.setConstraints(opt_Alias, gbc); + extras.add(opt_Alias); + + // Alpha composite + JPanel opt_Composite = new JPanel(); + opt_Composite.setLayout(new BoxLayout(opt_Composite, BoxLayout.PAGE_AXIS)); + JLabel opt_CompositeLabel = new JLabel("Alpha Composite:"); + opt_CompositeLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + opt_Composite.add(opt_CompositeLabel); + JTextField opt_CompositeValue = new JTextField("1.0"); + opt_CompositeValue.setAlignmentX(JComponent.LEFT_ALIGNMENT); + elements.put("opt_CompositeValue", opt_CompositeValue); + opt_Composite.add(opt_CompositeValue); + gbc.gridwidth = GridBagConstraints.REMAINDER; + layout.setConstraints(opt_Composite, gbc); + extras.add(opt_Composite); + + // Transformations + // TODO: allow user-defined matrices for AffineTransform + // (backend already has hooks for it, need to create gui) + JLabel opt_TransformLabel = new JLabel("Transformations:"); + opt_TransformLabel.setBorder(new BevelBorder(BevelBorder.RAISED)); + gbc.insets = new Insets(5, 2, 0, 15); + layout.setConstraints(opt_TransformLabel, gbc); + extras.add(opt_TransformLabel); + + JPanel opt_Transform_Translate = new JPanel(new GridLayout(0, 2, 5, 5)); + opt_Transform_Translate.add(new JLabel("x-axis translation ")); + JTextField opt_TransformTranslateX = new JTextField("0"); + opt_TransformTranslateX.setAlignmentX(JComponent.LEFT_ALIGNMENT); + opt_Transform_Translate.add(opt_TransformTranslateX); + elements.put("opt_TransformTranslateX", opt_TransformTranslateX); + opt_Transform_Translate.add(new JLabel("y-axis translation ")); + JTextField opt_TransformTranslateY = new JTextField("0"); + opt_TransformTranslateY.setAlignmentX(JComponent.LEFT_ALIGNMENT); + opt_Transform_Translate.add(opt_TransformTranslateY); + elements.put("opt_TransformTranslateY", opt_TransformTranslateY); + gbc.gridwidth = 1; + gbc.insets = new Insets(0, 2, 5, 15); + layout.setConstraints(opt_Transform_Translate, gbc); + extras.add(opt_Transform_Translate); + + JPanel opt_Transform_Shear = new JPanel(new GridLayout(0, 2, 5, 5)); + opt_Transform_Shear.add(new JLabel("x-axis shear ")); + JTextField opt_TransformShearX = new JTextField("0"); + opt_TransformShearX.setAlignmentX(JComponent.LEFT_ALIGNMENT); + opt_Transform_Shear.add(opt_TransformShearX); + elements.put("opt_TransformShearX", opt_TransformShearX); + opt_Transform_Shear.add(new JLabel("y-axis shear ")); + JTextField opt_TransformShearY = new JTextField("0"); + opt_Transform_Shear.add(opt_TransformShearY); + elements.put("opt_TransformShearY", opt_TransformShearY); + gbc.gridwidth = GridBagConstraints.REMAINDER; + layout.setConstraints(opt_Transform_Shear, gbc); + extras.add(opt_Transform_Shear); + + JPanel opt_Transform_Rotate = new JPanel(new GridLayout(0, 2, 5, 5)); + opt_Transform_Rotate.add(new JLabel("rotation (radians) ")); + JTextField opt_TransformRotate = new JTextField("0"); + opt_Transform_Rotate.add(opt_TransformRotate); + elements.put("opt_TransformRotate", opt_TransformRotate); + layout.setConstraints(opt_Transform_Rotate, gbc); + extras.add(opt_Transform_Rotate); + + // Final submit button + JPanel submit = new JPanel(); + submit.setLayout(new BoxLayout(submit, BoxLayout.PAGE_AXIS)); + + JButton rectButton = new JButton("Run benchmark"); + rectButton.setAlignmentX(JComponent.CENTER_ALIGNMENT); + submit.add(rectButton, BorderLayout.CENTER); + + errorLabel.setAlignmentX(JComponent.CENTER_ALIGNMENT); + errorLabel.setForeground(Color.RED); + submit.add(errorLabel); + + rectButton.addActionListener(new Harness(elements, errorLabel)); + + // Lay it all out + JPanel body = new JPanel(); + body.setLayout(new BoxLayout(body, BoxLayout.LINE_AXIS)); + options.setAlignmentX(JComponent.LEFT_ALIGNMENT); + body.add(options); + body.add(Box.createHorizontalStrut(50)); + tests.setAlignmentX(JComponent.RIGHT_ALIGNMENT); + body.add(tests); + + body.setAlignmentX(JComponent.CENTER_ALIGNMENT); + panel.add(body); + extras.setAlignmentX(JComponent.CENTER_ALIGNMENT); + panel.add(extras); + submit.setAlignmentX(JComponent.CENTER_ALIGNMENT); + panel.add(submit); + + content.add(panel, BorderLayout.CENTER); + + // Leave some breathing space in the frame + frame.pack(); + + frame.addWindowListener(new WindowAdapter() + { + public void windowClosing(WindowEvent e) + { + frame.setVisible(false); + System.exit(0); + } + }); + + frame.show(); + } + + /** + * Handles user events on the options GUI, ensuring that user input is valid + */ + public void actionPerformed(ActionEvent ev) + { + if (! noClipping.isSelected() && ! withClipping.isSelected() + && ! zeroClipping.isSelected()) + errorLabel.setText("You must select at least one clipping option"); + + else if (! singleBuffer.isSelected() && ! doubleBuffer.isSelected()) + errorLabel.setText("You must select at least one buffering option"); + + else + errorLabel.setText(" "); + } + + /** + * Parses GUI input and sets options in the benchmarker + */ + private class Harness + implements ActionListener + { + Hashtable elements; + + JLabel errorLabel; + + /** + * Creates a new Harness object + * + * @param elements Hashtable containing the swing elements from the GUI + * @param errorLabel JLabel on which to display any error messages + */ + public Harness(Hashtable elements, JLabel errorLabel) + { + super(); + + this.elements = elements; + this.errorLabel = errorLabel; + } + + /** + * Handles user button-clicks, parsing the form, setting options, and + * starting the J2dBenchmark + * + * @param ae event that triggered this action + */ + public void actionPerformed(ActionEvent ae) + { + try + { + // Create benchmarker object + final JFrame frame = new JFrame("Java2D benchmark"); + J2dBenchmarkWrapper speed = new J2dBenchmarkWrapper(frame); + + // Set options + speed.setDimensions(Integer.parseInt(((JTextField) elements.get("width")).getText()), + Integer.parseInt(((JTextField) elements.get("height")).getText())); + + speed.setIterations(Integer.parseInt(((JTextField) elements.get("iterations")).getText())); + speed.setTestSize(Integer.parseInt(((JTextField) elements.get("size")).getText())); + + speed.setClipping(((JCheckBox) elements.get("noclip")).isSelected(), + ((JCheckBox) elements.get("withclip")).isSelected(), + ((JCheckBox) elements.get("zeroclip")).isSelected()); + + speed.setBuffers(((JCheckBox) elements.get("singlebuffer")).isSelected(), + ((JCheckBox) elements.get("doublebuffer")).isSelected()); + + // Set additional processing options + speed.setFill(((ButtonGroup) elements.get("opt_FillGroup")).getSelection().getActionCommand(), + ((JTextField) elements.get("opt_FillTextureFile")).getText()); + + speed.setStroke(((JCheckBox) elements.get("opt_StrokeRandom")).isSelected()); + + speed.setAlias(((JCheckBox) elements.get("opt_AliasOn")).isSelected()); + + speed.setComposite(Float.parseFloat(((JTextField) elements.get("opt_CompositeValue")).getText())); + + speed.setTranslation(Integer.parseInt(((JTextField) elements.get("opt_TransformTranslateX")).getText()), + Integer.parseInt(((JTextField) elements.get("opt_TransformTranslateY")).getText())); + + speed.setRotation(Double.parseDouble(((JTextField) elements.get("opt_TransformRotate")).getText())); + + speed.setShear(Double.parseDouble(((JTextField) elements.get("opt_TransformShearX")).getText()), + Double.parseDouble(((JTextField) elements.get("opt_TransformShearY")).getText())); + + // Set tests + int testSuite = 0; + if (((JCheckBox) elements.get("test_arcDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_ARC; + if (((JCheckBox) elements.get("test_ccurveDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_CUBICCURVE; + if (((JCheckBox) elements.get("test_ellipseDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_ELLIPSE; + //if (((JCheckBox)elements.get("test_pathDraw")).isSelected()) + // testSuite |= J2dBenchmarkWrapper.J2DTEST_GENERALPATH; + if (((JCheckBox) elements.get("test_lineDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_LINE; + if (((JCheckBox) elements.get("test_qcurveDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_QUADCURVE; + if (((JCheckBox) elements.get("test_rectDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_RECTANGLE; + if (((JCheckBox) elements.get("test_rrectDraw")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_ROUNDRECTANGLE; + if (((JCheckBox) elements.get("test_image")).isSelected()) + testSuite |= J2dBenchmarkWrapper.J2DTEST_IMAGE; + + if (testSuite != 0) + { + speed.setTests(testSuite); + + String initResult = speed.init(); + + if (initResult == null) + { + // Create graphics. + frame.add(speed, BorderLayout.CENTER); + frame.setSize( + Integer.parseInt(((JTextField) elements.get("width")).getText()), + Integer.parseInt(((JTextField) elements.get("height")).getText())); + frame.setVisible(true); + + // Insets are correctly set only after the native peer was + // created. + Insets insets = frame.getInsets(); + frame.setSize(frame.getWidth() + insets.right + insets.left, + frame.getHeight() + insets.top + insets.bottom); + + // Clear any old error messages + errorLabel.setText(" "); + } + else + errorLabel.setText(initResult); + } + else + errorLabel.setText("Please select at least one test."); + } + catch (NumberFormatException e) + { + errorLabel.setText("Please enter valid integers"); + } + } + } + + /** + * Wrapper for the J2dBenchmark, which outputs the results to a GUI + * instead of the command-line + */ + private class J2dBenchmarkWrapper + extends J2dBenchmark + { + JFrame myFrame; + + ResultsDisplay display; + + /** + * Create new J2dBenchmarkWrapper object + * + * @param frame parent frame + */ + public J2dBenchmarkWrapper(JFrame frame) + { + // Redirect log messages to the custom handler + logger.setUseParentHandlers(false); + display = new ResultsDisplay(); + display.setLevel(Level.INFO); + logger.addHandler(display); + + myFrame = frame; + } + + /** + * Set dimensions of benchmarking canvas + * + * @param width width of canvas + * @param height height of canvas + */ + public void setDimensions(int width, int height) + { + screenHeight = height; + screenWidth = width; + setSize(width, height); + } + + /** + * Set number of iterations + * + * @param it number of iterations + */ + public void setIterations(int it) + { + iterations = it; + } + + /** + * Set size of each test + * + * @param size size of test + */ + public void setTestSize(int size) + { + testSize = size; + } + + /** + * Set clipping options + * + * @param no run test with no clipping + * @param with run test with clipping + * @param zero run test with clipping to zero + */ + public void setClipping(boolean no, boolean with, boolean zero) + { + this.noClippingFlag = no; + this.withClippingFlag = with; + this.zeroClippingFlag = zero; + } + + /** + * Set buffering options + * + * @param single run test without double-buffering + * @param doubleb run test with double-buffering + */ + public void setBuffers(boolean single, boolean doubleb) + { + this.singleBufferFlag = single; + this.doubleBufferFlag = doubleb; + } + + /** + * Set fill options + * + * @param type fill type: "solid", "gradient", or "texture" + * @param file filename to use if texturing + */ + public void setFill(String type, String file) + { + if (type.equals("gradient")) + this.gradientFlag = true; + else if (type.equals("texture")) + { + this.texture = file; + } + } + + /** + * Set stroke options + * + * @param stroke boolean flag to use random stroking or not + */ + public void setStroke(boolean stroke) + { + this.strokeFlag = stroke; + } + + /** + * Set anti-aliasing options + * + * @param alias boolean flag to use anti-aliasing or not + */ + public void setAlias(boolean alias) + { + this.antialiasFlag = alias; + } + + /** + * Set alpha composite + * + * @param alpha alpha composite + */ + public void setComposite(float alpha) + { + this.composite = alpha; + } + + /** + * Set translation values + * + * @param x x-axis translation + * @param y y-axis translation + */ + public void setTranslation(int x, int y) + { + this.xtranslate = x; + this.ytranslate = y; + } + + /** + * Set rotation + * + * @param theta angle to rotate by (radians) + */ + public void setRotation(double theta) + { + this.rotate = theta; + } + + /** + * Set shear values + * + * @param x x-axis shear value + * @param y-axis shear value + */ + public void setShear(double x, double y) + { + this.xshear = x; + this.yshear = y; + } + + /** + * Set tests to run + * + * @param tests bit-shifted list of tests (see J2dBenchmark constants) + */ + public void setTests(int tests) + { + awtTests = tests; + } + + /** + * Saves test report after each iteration + */ + void printReport() + { + // Report test results to the GUI display + ArrayList results = new ArrayList(); + for (Iterator i = testSetMap.testIterator(); i.hasNext();) + { + TestRecorder recorder = testSetMap.getTest((String) i.next()); + + results.add("TEST " + recorder.getTestName() + ": average " + + recorder.getAverage() + "ms [" + recorder.getMinTime() + + "-" + recorder.getMaxTime() + "]"); + } + + display.report(results); + } + + /** + * Disables current frame and displays test results + */ + void testComplete() + { + // Clear benchmarking canvas and display results instead + myFrame.setVisible(false); + + display.show(); + } + } + + /** + * GUI to display results of benchmarking + */ + private class ResultsDisplay + extends Handler + implements ActionListener + { + /** + * Allow user to select results from each iteration + */ + JComboBox iterations; + + /** + * Area to print results in + */ + JTextArea results; + + /** + * Allow user to view summary or full details of test report + */ + JCheckBox details; + + /** + * Store all test results + */ + ArrayList testResults; + + /** + * Store all test details + */ + ArrayList testDetails; + + /** + * Initialize variables + */ + public ResultsDisplay() + { + testResults = new ArrayList(); + testDetails = new ArrayList(); + testDetails.add(new ArrayList()); + } + + /** + * Parse all results and display on a GUI + */ + public void show() + { + // Set up panel + JFrame frame = new JFrame("Java2D benchmark results"); + Container cp = frame.getContentPane(); + + // Non-editable text area for the results + results = new JTextArea(); + results.setEditable(false); + results.setRows(15); + results.setColumns(60); + + // Checkbox to optionally display details (ie log messages) + details = new JCheckBox("Details", false); + details.addActionListener(this); + + // Combo box to allow selection of iteration number + iterations = new JComboBox(); + iterations.addActionListener(this); + for (int i = 0; i < testResults.size(); i++) + iterations.addItem("Iteration #" + (i + 1)); + + // Lay it all out + JPanel topleft = new JPanel(); + topleft.add(new JLabel("View results from: ")); + topleft.add(iterations); + topleft.setAlignmentX(JComponent.LEFT_ALIGNMENT); + details.setAlignmentX(JComponent.RIGHT_ALIGNMENT); + JPanel top = new JPanel(); + top.setLayout(new BoxLayout(top, BoxLayout.LINE_AXIS)); + top.add(topleft); + top.add(details); + + cp.add(top, BorderLayout.NORTH); + cp.add(new JScrollPane(results), BorderLayout.SOUTH); + + frame.pack(); + frame.show(); + } + + /** + * This overrides the logger publish method, which accepts log messages and + * saves them for later display + * + * @param record information about the log event + */ + public void publish(LogRecord record) + { + ((ArrayList) testDetails.get(testDetails.size() - 1)).add(record.getMessage()); + } + + /** + * Accepts a test summary report, generated after each iteration of a test + * + * @param results test results + */ + public void report(ArrayList results) + { + testResults.add(results); + testDetails.add(new ArrayList()); + } + + /** + * Provided as part of the Handler interface; not used + */ + public void flush() + { + } + + /** + * Provided as part of the Handler interface; not used + */ + public void close() + { + } + + /** + * Handle user-generated events on the results GUI + */ + public void actionPerformed(ActionEvent ev) + { + // Display information about the requested iteration + int iteration = iterations.getSelectedIndex(); + String message = ""; + + // Display summary or details, as requested + Iterator it; + if (details.isSelected()) + it = ((ArrayList) testDetails.get(iteration)).iterator(); + else + it = ((ArrayList) testResults.get(iteration)).iterator(); + + // Parse the ArrayList's + while (it.hasNext()) + { + message = message + ((String) it.next() + "\n"); + } + + // Output to screen + results.setText(message); + } + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/JNIOverhead.java b/libjava/classpath/examples/gnu/classpath/examples/java2d/JNIOverhead.java new file mode 100644 index 00000000000..efa57d2a36f --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/JNIOverhead.java @@ -0,0 +1,390 @@ +/* JNIOverhead.java - demonstrator for classpath/gcj fillrect performance issue + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.java2d; + +import gnu.classpath.examples.swing.DemoFactory; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +/** + * @author Norman Hendrich + */ +public class JNIOverhead + extends JPanel + implements ActionListener +{ + + static JNIOverhead fillRectDemo; + + LCDCanvas lcd; + Worker worker; + JLabel label; + JCheckBox translate; + JCheckBox lines; + + int nx = 128; + int ny = 64; + int matrix[][], future[][]; + int generation = 0; + + // 20 msec, or 50 repaints per sec (theoretically) + int sleepMillis = 20; + long lastMillis = System.currentTimeMillis(); + + boolean enableRepaints = true; + + /** + * If true, test translation. + */ + boolean testTranslation = false; + + /** + * If true, paint lines rather than rectangles + */ + boolean paintLines; + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + public JNIOverhead() + { + setSize(nx, ny); + createContent(); + } + + public void createContent() + { + setLayout(new BorderLayout()); + + JPanel p = new JPanel(new BorderLayout()); + lcd = new LCDCanvas(); + label = new JLabel(); + label.setText("not running"); + + translate = new JCheckBox("translate"); + translate.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + testTranslation = translate.isSelected(); + } + }); + + lines = new JCheckBox("lines"); + lines.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + paintLines = lines.isSelected(); + } + }); + + JPanel bottom = new JPanel(); + bottom.add(lines); + bottom.add(translate); + + p.add(lcd, BorderLayout.CENTER); + p.add(bottom, BorderLayout.SOUTH); + p.add(label, BorderLayout.NORTH); + add(p); + } + + public void setSize(int _nx,int _ny ) + { + nx = _nx; + ny = _ny; + matrix = new int[nx][ny]; + future = new int[nx][ny]; + } + + public void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + public void setSleepMillis(int millis) + { + sleepMillis = millis; + } + + public class LCDCanvas extends JPanel + { + private int sx, sy; + private Color activePixel = new Color(30, 30, 40); + private Color passivePixel = new Color(200, 180, 240); + private Color gridPixel = new Color(255, 240, 240); + + public LCDCanvas() + { + super(); + sx = 4 * nx; + sy = 4 * ny; + } + + public void paintComponent(Graphics g) + { + // for buffered drawing - not used atm + // g.drawImage( buffer, 0, 0, null ); + long t1 = System.currentTimeMillis(); + + g.setColor(gridPixel); + g.fillRect(0, 0, sx, sy); + + Color pixelColor = null; + + int dx, dy; + + if (paintLines) + { + for (int ix = 0; ix < nx; ix++) + for (int iy = 0; iy < ny; iy++) + { + if (matrix[ix][iy] != 0) + pixelColor = activePixel; + else + pixelColor = passivePixel; + + dx = 4 * ix; + dy = 4 * iy; + g.setColor(pixelColor); + + if (testTranslation) + { + g.translate(dx, dy); + g.drawLine(0, 0, 5, 5); + g.translate(- dx, - dy); + } + else + g.drawLine(dx, dy, dx + 5, dy + 5); + } + } + else + for (int ix = 0; ix < nx; ix++) + { + for (int iy = 0; iy < ny; iy++) + { + if (matrix[ix][iy] != 0) + pixelColor = activePixel; + else + pixelColor = passivePixel; + + dx = 4 * ix; + dy = 4 * iy; + g.setColor(pixelColor); + + if (testTranslation) + { + g.translate(dx, dy); + g.fillRect(0, 0, 3, 3); + g.translate(- dx, - dy); + } + else + g.fillRect(dx, dy, 3, 3); + } + } + + long t2 = System.currentTimeMillis(); + + label.setText("paintComponent took " + (t2 - t1) + " msec. " + "(" + + (nx * ny + 1) + " " + + (paintLines ? "drawLine" : "fillRect") + " calls)"); + + } + + public Dimension getPreferredSize() + { + return new Dimension(sx,sy); + } + + public Dimension getMinimumSize() + { + return new Dimension(sx,sy); + } + } + + public class Worker extends Thread + { + public void run() + { + boolean running = true; + while(running) + { + iteration(); + + if (enableRepaints) + display(); + + if (sleepMillis > 0) + { + try + { + Thread.sleep( sleepMillis ); + } + catch(InterruptedException ie) + { + running = false; + } + } + } + } + } + + /** + * stupid animation algorithm: show binary representation of current + * iteration. + */ + public void iteration() + { + generation++; + + for (int i = 0; i < nx; i++) + { + long tmp1 = 1L << i; + for (int j = 0; j < ny; j++) + { + // count neighbors + long tmp2 = (1L << j); + + + long tmp3 = generation & tmp1 & tmp2; + if (tmp3 != 0) + matrix[i][j] = 1; + else + matrix[i][j] = 0; + } + } + + if ((generation % 100) == 0) + { + long t = System.currentTimeMillis(); + // System.out.println( + // " generation= " + generation + + // " iterations/sec= " + 100.0*1000/(t-lastMillis) ); + lastMillis = t; + } + } + + public void display() + { + lcd.repaint(); + } + + public static void usage() + { + System.out.println( + "Usage: <java> FillRect2 [-sleep <millis>] [-size <int>] [-nopaint]\n" + + "Example: jamvm FillRect2 -sleep 10 -size 100\n" + ); + System.exit(0); + } + + public static void main(String args[]) + throws Exception + { + fillRectDemo = new JNIOverhead(); + for (int i = 0; i < args.length; i++) + { + if ("-help".equals(args[i])) + { + usage(); + } + if ("-sleep".equals(args[i])) + { + fillRectDemo.setSleepMillis( Integer.parseInt(args[i + 1])); + i++; + } + if ("-size".equals(args[i])) + { + int size = Integer.parseInt(args[i + 1]); + fillRectDemo.setSize(size, size); + i++; + } + if ("-nopaint".equals(args[i])) + { + fillRectDemo.enableRepaints = false; + } + } + + SwingUtilities.invokeLater (new Runnable() + { + public void run() + { + + fillRectDemo.initFrameContent(); + JFrame frame = new JFrame("FillRect performance test"); + frame.getContentPane().add(fillRectDemo); + frame.pack(); + frame.show(); + fillRectDemo.worker = fillRectDemo.new Worker(); + fillRectDemo.worker.start(); + } + }); + } + + /** + * Returns a DemoFactory that creates a SliderDemo. + * + * @return a DemoFactory that creates a SliderDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + fillRectDemo = new JNIOverhead(); + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + fillRectDemo.worker = fillRectDemo.new Worker(); + fillRectDemo.worker.start(); + } + }); + return fillRectDemo; + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.c b/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.c new file mode 100644 index 00000000000..e5b45aa1c15 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.c @@ -0,0 +1,606 @@ +/* bench.c -- native benchmark for Cairo library (meant to test java2d) + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +#include "bench.h" +#include <math.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <gtk/gtk.h> +#include <sys/timeb.h> + +G_DEFINE_TYPE (Benchmark, benchmark, GTK_TYPE_DRAWING_AREA); + +// Needed for the gtk widget, but not used: +static void +benchmark_class_init (BenchmarkClass *klass) +{ +} + +static void +benchmark_init (Benchmark *obj) +{ +} + +// The Arc2D's PathIterator uses some transforms, so we condense the required +// functionality of AffineTransform +static void +doTransform (double rx, double ry, double theta, double *cvec) +{ + // Define identity matrix (corresponds to new AffineTransform()) + double m00 = 1; + double m10 = 0; + double m01 = 0; + double m11 = 1; + double m02 = 0; + double m12 = 0; + + // AffineTransform.scale(rx, ry) + m00 = m00 * rx; + m01 = m01 * ry; + m10 = m10 * rx; + m11 = m11 * ry; + + // AffineTransform.rotate(theta) + double c = cos(theta); + double s = sin(theta); + double n00 = m00 * c + m01 * s; + double n01 = m00 * -s + m01 * c; + double n10 = m10 * c + m11 * s; + double n11 = m10 * -s + m11 * c; + + m00 = n00; + m01 = n01; + m10 = n10; + m11 = n11; + + // AffineTransform.transform(cvec, 0, cvec, 0, 1) + double dstPts[2]; + dstPts[0] = (float) (m00 * cvec[0] + m01 * cvec[1] + m02); + dstPts[1] = (float) (m10 * cvec[0] + m11 * cvec[1] + m12); + cvec[0] = dstPts[0]; + cvec[1] = dstPts[1]; +} + +// Place an arc on the cairo path, simulating java2d's Arc2D +static void +setupArc(cairo_t *cr, GtkWidget *bench, int shift) +{ + double x, y; + + // Normally passed into the Arc2D constructor + x = bench->allocation.x + (rand() % (bench->allocation.width - minSize + 1)); + y = bench->allocation.y + (rand() % (bench->allocation.height - minSize + 1)); + + int angle = rand() % 360; + int length = (rand() % 360) - angle; + int width = rand() % (int)((bench->allocation.width - x - 10) + 10); + int height = rand() % (int)((bench->allocation.height - y - 10) + 10); + + // This is from the ArcPath iterator + double start = angle * (M_PI / 180); + double extent = length * (M_PI / 180); + + if (extent < 0) + { + extent = -extent; + start = 2 * M_PI - extent + start; + } + + int limit; + if (width < 0 || height < 0) // We assume type == 0; ie, Arc2D.OPEN + limit = -1; + else if (extent == 0) + limit = 0; + else if (extent <= M_PI / 2.0) + limit = 1; + else if (extent <= M_PI) + limit = 2; + else if (extent <= 3.0 * (M_PI / 2.0)) + limit = 3; + else + limit = 4; + + // This is from CairoGraphics2D.walkPath + double xnew = 0; + double ynew = 0; + double coords[6]; + + cairo_fill_rule_t cfillrule = CAIRO_FILL_RULE_WINDING; + cairo_set_fill_rule(cr, cfillrule); + + // First iteration will move to the starting point + double rx = width / 2; + double ry = height / 2; + double xmid = x + rx; + double ymid = y + ry; + coords[0] = xmid + rx * cos(start); + coords[1] = ymid - ry * sin(start); + + if (shift == 1) + { + xnew = floor(coords[0]) + 0.5; + ynew = floor(coords[1]) + 0.5; + } + else + { + xnew = coords[0]; + ynew = coords[1]; + } + + cairo_move_to(cr, xnew, ynew); + + // Iterate through segments of the arc + int current; + for (current = 1; current <= limit; current++) + { + // Back to the ArcPath iterator's getCurrent + double kappa = (sqrt(2.0) - 1.0) * (4.0 / 3.0); + double quad = (M_PI / 2.0); + + double curr_begin = start + (current - 1) * quad; + double curr_extent; + + if (start + extent - curr_begin < quad) + curr_extent = (start + extent) - curr_begin; + else + curr_extent = quad; + + double portion_of_a_quadrant = curr_extent / quad; + + double x0 = xmid + rx * cos(curr_begin); + double y0 = ymid - ry * sin(curr_begin); + + double x1 = xmid + rx * cos(curr_begin + curr_extent); + double y1 = ymid - ry * sin(curr_begin + curr_extent); + + double cvec[2]; + double len = kappa * portion_of_a_quadrant; + double angle = curr_begin; + + cvec[0] = 0; + cvec[1] = len; + doTransform(rx, ry, angle, cvec); + coords[0] = x0 + cvec[0]; + coords[1] = y0 - cvec[1]; + + cvec[0] = 0; + cvec[1] = -len; + doTransform(rx, ry, angle, cvec); + doTransform(1, 1, curr_extent, cvec); + coords[2] = x1 + cvec[0]; + coords[3] = y1 - cvec[1]; + + coords[4] = x1; + coords[5] = y1; + + // draw it, from CairoGraphics2D.walkPath + if (shift == 1) + { + xnew = floor(coords[4]) + 0.5; + ynew = floor(coords[5]) + 0.5; + cairo_curve_to(cr, floor(coords[0]) + 0.5, floor(coords[1]) + 0.5, + floor(coords[2]) + 0.5, floor(coords[3]) + 0.5, + xnew, ynew); + } + else + { + xnew = coords[4]; + ynew = coords[5]; + cairo_curve_to(cr, coords[0], coords[1], coords[2], + coords[3], xnew, ynew); + } + } + + // Randomize the colour, just for asthetics =) + cairo_set_source_rgb(cr, (rand() % 100 / (float)100), + (rand() % 100 / (float)100), + (rand() % 100 / (float)100)); + +} + +// Place a beizer curve on the cairo path, simulating java2d's CubicCurve2D +static void +setupCurve(cairo_t *cr, GtkWidget *bench, int shift) +{ + // These are options when creating a new curve + int x1 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y1 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int xc1 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int yc1 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int xc2 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int yc2 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int x2 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y2 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + + // From CairoGraphics2D.walkPath + double xnew = 0; + double ynew = 0; + double coords[6]; + + cairo_fill_rule_t cfillrule = CAIRO_FILL_RULE_WINDING; + cairo_set_fill_rule(cr, cfillrule); + + // And into CubicCurve's PathIterator... + // start by moving to the starting coordinate + coords[0] = (float) x1; + coords[1] = (float) y1; + + if (shift == 1) + { + xnew = floor(coords[0]) + 0.5; + ynew = floor(coords[1]) + 0.5; + } + else + { + xnew = coords[0]; + ynew = coords[1]; + } + + cairo_move_to(cr, xnew, ynew); + + // Now the curve itself + coords[0] = (float) xc1; + coords[1] = (float) yc1; + coords[2] = (float) xc2; + coords[3] = (float) yc2; + coords[4] = (float) x2; + coords[5] = (float) y2; + + if (shift == 1) + { + xnew = floor(coords[4]) + 0.5; + ynew = floor(coords[5]) + 0.5; + cairo_curve_to(cr, floor(coords[0]) + 0.5, floor(coords[1]) + 0.5, + floor(coords[2]) + 0.5, floor(coords[3]) + 0.5, + xnew, ynew); + } + else + { + xnew = coords[4]; + ynew = coords[5]; + cairo_curve_to(cr, coords[0], coords[1], coords[2], + coords[3], xnew, ynew); + } + + // Randomize colour for asthetics + cairo_set_source_rgb(cr, (rand() % 100 / (float)100), + (rand() % 100 / (float)100), + (rand() % 100 / (float)100)); +} + +// Place a line on the cairo path, simulating java2d's Line2D +static void +setupLine(cairo_t *cr, GtkWidget *bench, int shift) +{ + // These are set when you create a line + int x1 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y1 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int x2 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y2 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + + // This is from CairoGraphics2D.walkPath + double xnew = 0; + double ynew = 0; + double coords[6]; + + cairo_fill_rule_t cfillrule = CAIRO_FILL_RULE_WINDING; + cairo_set_fill_rule(cr, cfillrule); + + // And into Line2D's PathIterator + coords[0] = (float) x1; + coords[1] = (float) y1; + + if (shift == 1) + { + xnew = floor(coords[0]) + 0.5; + ynew = floor(coords[1]) + 0.5; + } + else + { + xnew = coords[0]; + ynew = coords[1]; + } + + cairo_move_to(cr, xnew, ynew); + + coords[0] = (float) x2; + coords[1] = (float) y2; + + if (shift == 1) + { + xnew = floor(coords[0]) + 0.5; + ynew = floor(coords[1]) + 0.5; + } + else + { + xnew = coords[0]; + ynew = coords[1]; + } + + cairo_line_to(cr, xnew, ynew); + + // Randomize colour for asthetics + cairo_set_source_rgb(cr, (rand() % 100 / (float)100), + (rand() % 100 / (float)100), + (rand() % 100 / (float)100)); +} + +// Place a rectangle on the cairo path, simulating java2d's Rectangle2D +static void +setupRect(cairo_t *cr, GtkWidget *bench, int shift) +{ + // These are set when you create a rectangle + int x1 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y1 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + int x2 = bench->allocation.x + (rand() % (bench->allocation.width - minSize)); + int y2 = bench->allocation.y + (rand() % (bench->allocation.height - minSize)); + + // draw() and fill() have been optimized to ignore the PathIterator. + // We do the same here. + double xnew = 0; + double ynew = 0; + + if (shift == 1) + { + xnew = floor(x1) + 0.5; + ynew = floor(y1) + 0.5; + } + else + { + xnew = x1; + ynew = y1; + } + + cairo_rectangle(cr, x1, y1, x2, y2); + + // Randomize colour for asthetics + cairo_set_source_rgb(cr, (rand() % 100 / (float)100), + (rand() % 100 / (float)100), + (rand() % 100 / (float)100)); +} + +// The real work gets done here: this function is called when the widget +// is drawn on screen. +static void +draw (GtkWidget *bench, cairo_t *cr) +{ + // Setup + struct timeb t1, t2; + int i, timeElapsed; + + cairo_set_line_width(cr, lineWidth); + + if (antialias == 0) + cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE); + else + cairo_set_antialias(cr, CAIRO_ANTIALIAS_GRAY); + + // Tell the user what's going on + printf("Testing native cairo drawing..\n"); + printf(" Screen size is %d x %d \n", screenWidth, screenHeight); + printf(" Line width is %d\n", lineWidth); + printf(" Test size: %d\n", testSize); + + if (antialias == 0) + printf(" Anti-alias is off\n"); + else + printf(" Anti-alias is on\n"); + + printf("\n"); + fflush(stdout); + + // Draw & fill Arc + if (arcTest == 1) + { + // Draw + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupArc(cr, bench, 1); + cairo_stroke (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Draw arc: %d ms\n", timeElapsed); + fflush(stdout); + + // Fill + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupArc(cr, bench, 0); + cairo_fill (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Fill arc: %d ms\n", timeElapsed); + } + + // Draw cubic curve + if (curveTest == 1) + { + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupCurve(cr, bench, 1); + cairo_stroke (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Draw cubic curve: %d ms\n", timeElapsed); + } + + // Ellipse: skip; this is just a special case of arc + // General path: skip; this doesn't even work in java2d + + // Draw Line + if (lineTest == 1) + { + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupLine(cr, bench, 1); + cairo_stroke (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Draw line: %d ms\n", timeElapsed); + } + + // Draw & fill Rectangle + if (rectTest == 1) + { + // Draw + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupRect(cr, bench, 1); + cairo_stroke (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Draw rectangle: %d ms\n", timeElapsed); + + // Fill + ftime(&t1); + for (i = 0; i < testSize; i++) + { + setupRect(cr, bench, 0); + cairo_fill (cr); + } + + ftime(&t2); + timeElapsed = 1000 * (t2.time - t1.time) + (t2.millitm - t1.millitm); + printf("Fill rectangle: %d ms\n", timeElapsed); + } + + // Round rectangle: skip, it's just a combination of lines and curves + // Image: skip? + + printf("\n"); +} + +GtkWidget * +benchmark_new (void) +{ + return g_object_new (BENCHMARK_TYPE, NULL); +} + +int +main (int argc, char **argv) +{ + // Set defaults + minSize = 10; + arcTest = 0; + curveTest = 0; + lineTest = 0; + rectTest = 0; + screenWidth = 320; + screenHeight = 240; + testSize = 1000; + antialias = 0; + lineWidth = 1; + + // Process any command-line user options + int i; + for (i = 1; i < argc; i++) + { + // Process options first + if (!strcmp(argv[i], "-a")) + antialias = 1; + else if (!strcmp(argv[i], "-h")) + screenHeight = atoi(argv[++i]); + else if (!strcmp(argv[i], "-l")) + lineWidth = atoi(argv[++i]); + else if (!strcmp(argv[i], "-t")) + testSize = atoi(argv[++i]); + else if (!strcmp(argv[i], "-w")) + screenWidth = atoi(argv[++i]); + else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--h") + || !strcmp(argv[i], "-help") || !strcmp(argv[i], "--help")) + { + printf("Cairo benchmarker, meant to measure JNI overhead\n"); + printf("Usage: bench [-a] [-h height] [-t test size] [-w width] [tests...]\n"); + printf("\n"); + printf(" Valid options: -a turn on anti-aliasing (default off)\n"); + printf(" -h set screen height (default 240)\n"); + printf(" -l set stroke line width (default 1)\n"); + printf(" -t set test size (default 1000)\n"); + printf(" -w set screen width (default 320)\n"); + printf(" -h | --help\n"); + printf(" Valid tests: arc\n"); + printf(" curve\n"); + printf(" line\n"); + printf(" rect\n"); + printf(" (default: run all)\n"); + exit (0); + } + + // Process tests + else if (!strcmp(argv[i], "arc")) + arcTest = 1; + else if (!strcmp(argv[i], "curve")) + curveTest = 1; + else if (!strcmp(argv[i], "line")) + lineTest = 1; + else if (!strcmp(argv[i], "rect")) + rectTest = 1; + } + + // If no tests were specified, we default to running all of them + if (arcTest == 0 && curveTest == 0 && lineTest == 0 && rectTest == 0) + { + arcTest = 1; + curveTest = 1; + lineTest = 1; + rectTest = 1; + } + + // Set up gtk widget + GtkWidget *window, *bench; + gtk_init (&argc, &argv); + + window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_window_resize(GTK_WINDOW(window), screenWidth, screenHeight); + gtk_window_set_title(GTK_WINDOW(window), "cairo benchmark"); + + // Set up benchmkar and cairo surface + bench = benchmark_new (); + gtk_container_add (GTK_CONTAINER (window), bench); + gtk_widget_show_all (window); + + cairo_t *cr; + cr = gdk_cairo_create (bench->window); + + // Run tests + draw (bench, cr); + + // Hold output on screen until user exits. + printf("Press any key to exit.\n"); + getchar(); + exit(0); +gtk_main(); +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.h b/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.h new file mode 100644 index 00000000000..aebd50a6785 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/java2d/bench.h @@ -0,0 +1,64 @@ +/* bench.h -- native benchmark for Cairo library (meant to test java2d) + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +#ifndef __BENCH_H__ +#define __BENCH_H__ + +#include <gtk/gtk.h> + +G_BEGIN_DECLS + +#define BENCHMARK_TYPE (benchmark_get_type()) +#define BENCHMARK(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj, BENCHMARK_TYPE, Benchmark) +#define BENCHMARK_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), BENCHMARK_TYPE, BenchmarkClass); +#define IS_BENCHMARK(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), BENCHMARK_TYPE)) +#define IS_BENCHMARK_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), BENCHMARK_TYPE)) +#define BENCHMARK_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), BENCHMARK_TYPE, BenchmarkClass)) + +typedef struct _Benchmark Benchmark; +typedef struct _BenchmarkClass BenchmarkClass; + +struct _Benchmark { + GtkDrawingArea parent; + +}; + +struct _BenchmarkClass { + GtkDrawingAreaClass parent_class; +}; + +GType benchmark_get_type (void); +GtkWidget *benchmark_new (void); + +static int minSize; +static int antialias; +static int arcTest; +static int curveTest; +static int lineTest; +static int rectTest; + +static int screenHeight; +static int screenWidth; +static int testSize; +static int lineWidth; + +G_END_DECLS + +#endif diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestBeans.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestBeans.java new file mode 100644 index 00000000000..ad8234555e5 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestBeans.java @@ -0,0 +1,55 @@ +/* TestBeans.java -- Tests the dynamic interface of the beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.management.DynamicMBean; + +public class TestBeans +{ + public static void main(String[] args) + throws Exception + { + List beans = new ArrayList(); + /* FIXME: When there's a server, this will be easier... :) */ + beans.add(ManagementFactory.getOperatingSystemMXBean()); + beans.add(ManagementFactory.getRuntimeMXBean()); + beans.add(ManagementFactory.getThreadMXBean()); + beans.add(ManagementFactory.getCompilationMXBean()); + beans.add(ManagementFactory.getClassLoadingMXBean()); + beans.add(ManagementFactory.getMemoryMXBean()); + beans.addAll(ManagementFactory.getMemoryPoolMXBeans()); + beans.addAll(ManagementFactory.getMemoryManagerMXBeans()); + beans.addAll(ManagementFactory.getGarbageCollectorMXBeans()); + Iterator it = beans.iterator(); + while (it.hasNext()) + { + DynamicMBean bean = (DynamicMBean) it.next(); + if (bean != null) + System.out.println(bean.getMBeanInfo()); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestClassLoading.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestClassLoading.java new file mode 100644 index 00000000000..113a4f2582c --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestClassLoading.java @@ -0,0 +1,41 @@ +/* TestClassLoading.java -- Tests the class loading bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ClassLoadingMXBean; +import java.lang.management.ManagementFactory; + +public class TestClassLoading +{ + public static void main(String[] args) + { + ClassLoadingMXBean bean = ManagementFactory.getClassLoadingMXBean(); + System.out.println("Bean: " + bean); + System.out.println("Loaded classes: " + bean.getLoadedClassCount()); + System.out.println("Unloaded classes: " + bean.getUnloadedClassCount()); + System.out.println("Total loaded classes: " + bean.getTotalLoadedClassCount()); + boolean verbosity = bean.isVerbose(); + System.out.println("Verbose class output: " + (verbosity ? "yes" : "no")); + System.out.println("Changing verbose setting..."); + bean.setVerbose(!verbosity); + System.out.println("Verbose class output: " + (bean.isVerbose() ? "yes" : "no")); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestCompilation.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestCompilation.java new file mode 100644 index 00000000000..ea8f45f6d1e --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestCompilation.java @@ -0,0 +1,48 @@ +/* TestCompilation.java -- Tests the compilation bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.CompilationMXBean; + +public class TestCompilation +{ + + public static void main(String[] args) + { + CompilationMXBean bean = ManagementFactory.getCompilationMXBean(); + if (bean == null) + { + System.out.println("The compilation bean is not supported by this VM."); + System.exit(-1); + } + System.out.println("Bean: " + bean); + System.out.println("JIT compiler name: " + bean.getName()); + boolean timeMonitoring = bean.isCompilationTimeMonitoringSupported(); + System.out.println("Compilation time monitoring supported: " + timeMonitoring); + if (timeMonitoring) + { + System.out.println("Compilation time: " + + bean.getTotalCompilationTime() + "ms"); + } + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestGarbageCollector.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestGarbageCollector.java new file mode 100644 index 00000000000..5d6d56797c4 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestGarbageCollector.java @@ -0,0 +1,53 @@ +/* TestGarbageCollector.java -- Tests the garbage collector beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; + +import java.util.Arrays; +import java.util.Iterator; + +public class TestGarbageCollector +{ + + public static void main(String[] args) + { + Iterator beans = ManagementFactory.getGarbageCollectorMXBeans().iterator(); + while (beans.hasNext()) + { + GarbageCollectorMXBean bean = (GarbageCollectorMXBean) beans.next(); + System.out.println("Bean: " + bean); + System.out.println("Name: " + bean.getName()); + System.out.println("Memory pool names: " + + Arrays.toString(bean.getMemoryPoolNames())); + System.out.println("Is valid: " + + (bean.isValid() ? "yes" : "no")); + System.out.println("Collection count: " + + bean.getCollectionCount()); + System.out.println("Collection time: " + + bean.getCollectionTime() + "ms"); + } + } +} + + + diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestMemory.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemory.java new file mode 100644 index 00000000000..ca25d62119b --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemory.java @@ -0,0 +1,52 @@ +/* TestMemory.java -- Tests the memory bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.MemoryMXBean; +import java.lang.management.ManagementFactory; + +public class TestMemory +{ + public static void main(String[] args) + { + MemoryMXBean bean = ManagementFactory.getMemoryMXBean(); + System.out.println("Bean: " + bean); + System.out.println("Heap memory usage: " + + bean.getHeapMemoryUsage()); + System.out.println("Non-heap memory usage: " + + bean.getNonHeapMemoryUsage()); + System.out.println("Objects pending finalization: " + + bean.getObjectPendingFinalizationCount()); + System.out.println("Running garbage collector via bean..."); + bean.gc(); + System.out.println("Heap memory usage: " + + bean.getHeapMemoryUsage()); + System.out.println("Non-heap memory usage: " + + bean.getNonHeapMemoryUsage()); + System.out.println("Objects pending finalization: " + + bean.getObjectPendingFinalizationCount()); + boolean verbosity = bean.isVerbose(); + System.out.println("Verbose memory output: " + (verbosity ? "yes" : "no")); + System.out.println("Changing verbose setting..."); + bean.setVerbose(!verbosity); + System.out.println("Verbose memory output: " + (bean.isVerbose() ? "yes" : "no")); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryManager.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryManager.java new file mode 100644 index 00000000000..30a0c985b9f --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryManager.java @@ -0,0 +1,49 @@ +/* TestMemoryManager.java -- Tests the memory manager beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryManagerMXBean; + +import java.util.Arrays; +import java.util.Iterator; + +public class TestMemoryManager +{ + + public static void main(String[] args) + { + Iterator beans = ManagementFactory.getMemoryManagerMXBeans().iterator(); + while (beans.hasNext()) + { + MemoryManagerMXBean bean = (MemoryManagerMXBean) beans.next(); + System.out.println("Bean: " + bean); + System.out.println("Name: " + bean.getName()); + System.out.println("Memory pool names: " + + Arrays.toString(bean.getMemoryPoolNames())); + System.out.println("Is valid: " + + (bean.isValid() ? "yes" : "no")); + } + } +} + + + diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryPool.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryPool.java new file mode 100644 index 00000000000..2476ed76fe0 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestMemoryPool.java @@ -0,0 +1,93 @@ +/* TestMemoryPool.java -- Tests the memory pool beans. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryPoolMXBean; +import java.lang.management.MemoryUsage; + +import java.util.Arrays; +import java.util.Iterator; + +public class TestMemoryPool +{ + + /** + * 1mb in bytes + */ + private static final int MB = 1 << 20; + + public static void main(String[] args) + { + Iterator beans = ManagementFactory.getMemoryPoolMXBeans().iterator(); + while (beans.hasNext()) + { + MemoryPoolMXBean bean = (MemoryPoolMXBean) beans.next(); + System.out.println("Bean: " + bean); + System.out.println("Name: " + bean.getName()); + System.out.println("Collection usage: " + bean.getCollectionUsage()); + boolean collectionUsage = bean.isCollectionUsageThresholdSupported(); + System.out.println("Collection usage threshold supported: " + + collectionUsage); + if (collectionUsage) + { + System.out.println("Collection usage threshold: " + + bean.getCollectionUsageThreshold()); + System.out.println("Setting collection usage threshold to 1MB (" + + MB + " bytes)"); + bean.setCollectionUsageThreshold(MB); + System.out.println("Collection usage threshold: " + + bean.getCollectionUsageThreshold()); + System.out.println("Collection usage threshold count: " + + bean.getCollectionUsageThresholdCount()); + System.out.println("Collection usage threshold exceeded: " + + (bean.isCollectionUsageThresholdExceeded() + ? "yes" : "no")); + } + System.out.println("Memory manager names: " + + Arrays.toString(bean.getMemoryManagerNames())); + System.out.println("Peak usage: " + bean.getPeakUsage()); + System.out.println("Current usage: " + bean.getUsage()); + System.out.println("Resetting peak usage..."); + bean.resetPeakUsage(); + System.out.println("Peak usage: " + bean.getPeakUsage()); + System.out.println("Current usage: " + bean.getUsage()); + boolean usage = bean.isUsageThresholdSupported(); + System.out.println("Usage threshold supported: " + usage); + if (usage) + { + System.out.println("Usage threshold: " + + bean.getUsageThreshold()); + System.out.println("Setting usage threshold to 1MB (" + + MB + " bytes)"); + bean.setUsageThreshold(MB); + System.out.println("Usage threshold: " + + bean.getUsageThreshold()); + System.out.println("Usage threshold count: " + + bean.getUsageThresholdCount()); + System.out.println("Usage threshold exceeded: " + + (bean.isUsageThresholdExceeded() + ? "yes" : "no")); + } + System.out.println("Valid: " + (bean.isValid() ? "yes" : "no")); + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestOS.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestOS.java new file mode 100644 index 00000000000..a13e514f8e1 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestOS.java @@ -0,0 +1,37 @@ +/* TestOS.java -- Tests the OS bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.OperatingSystemMXBean; + +public class TestOS +{ + public static void main(String[] args) + { + OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); + System.out.println("Bean: " + osBean); + System.out.println("OS Name: " + osBean.getName()); + System.out.println("OS Version: " + osBean.getVersion()); + System.out.println("Architecture: " + osBean.getArch()); + System.out.println("Processors: " + osBean.getAvailableProcessors()); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestRuntime.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestRuntime.java new file mode 100644 index 00000000000..2a629ca83c6 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestRuntime.java @@ -0,0 +1,54 @@ +/* TestRuntime.java -- Tests the runtime bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; + +import java.util.Date; + +public class TestRuntime +{ + + public static void main(String[] args) + { + RuntimeMXBean vmBean = ManagementFactory.getRuntimeMXBean(); + System.out.println("Bean: " + vmBean); + boolean bootClassPath = vmBean.isBootClassPathSupported(); + System.out.println("Boot Class Path Supported: " + bootClassPath); + if (bootClassPath) + System.out.println("Boot Class Path: " + vmBean.getBootClassPath()); + System.out.println("Class Path: " + vmBean.getClassPath()); + System.out.println("Input Arguments: " + vmBean.getInputArguments()); + System.out.println("Library Path: " + vmBean.getLibraryPath()); + System.out.println("Management Spec. Version: " + vmBean.getManagementSpecVersion()); + System.out.println("Name: " + vmBean.getName()); + System.out.println("Spec Name: " + vmBean.getSpecName()); + System.out.println("Spec Vendor: " + vmBean.getSpecVendor()); + System.out.println("Spec Version: " + vmBean.getSpecVersion()); + System.out.println("Start Time: " + new Date(vmBean.getStartTime())); + System.out.println("System Properties: " + vmBean.getSystemProperties()); + System.out.println("Uptime: " + vmBean.getUptime() + "ms"); + System.out.println("VM Name: " + vmBean.getVmName()); + System.out.println("VM Vendor: " + vmBean.getVmVendor()); + System.out.println("VM Version: " + vmBean.getVmVersion()); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/management/TestThread.java b/libjava/classpath/examples/gnu/classpath/examples/management/TestThread.java new file mode 100644 index 00000000000..e49776ce227 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/management/TestThread.java @@ -0,0 +1,118 @@ +/* TestThread.java -- Tests the thread bean. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.management; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; + +import java.util.Arrays; + +public class TestThread +{ + + public static void main(String[] args) + { + ThreadMXBean bean = ManagementFactory.getThreadMXBean(); + System.out.println("Bean: " + bean); + System.out.println("Monitor deadlocked threads: " + bean.findMonitorDeadlockedThreads()); + long[] ids = bean.getAllThreadIds(); + System.out.println("Live thread ids: " + Arrays.toString(ids)); + boolean currentTimeMonitoring = bean.isCurrentThreadCpuTimeSupported(); + System.out.println("Current thread CPU time monitoring supported: " + currentTimeMonitoring); + if (currentTimeMonitoring) + { + boolean timeEnabled = bean.isThreadCpuTimeEnabled(); + System.out.println("Is time monitoring enabled... " + + (timeEnabled ? "yes" : "no")); + if (!timeEnabled) + { + System.out.println("Enabling..."); + bean.setThreadCpuTimeEnabled(true); + timeEnabled = bean.isThreadCpuTimeEnabled(); + System.out.println("Should now be enabled... " + + (timeEnabled ? "yes" : "no")); + } + if (timeEnabled) + { + System.out.println("Current thread CPU time: " + + bean.getCurrentThreadCpuTime() + + "ns"); + System.out.println("Current thread user time: " + + bean.getCurrentThreadUserTime() + + "ns"); + } + } + System.out.println("Daemon thread count: " + bean.getDaemonThreadCount()); + System.out.println("Peak thread count: " + bean.getPeakThreadCount()); + System.out.println("Resetting..."); + bean.resetPeakThreadCount(); + System.out.println("Peak thread count: " + bean.getPeakThreadCount()); + System.out.println("Thread count: " + bean.getThreadCount()); + boolean timeMonitoring = bean.isThreadCpuTimeSupported(); + System.out.println("Thread CPU time monitoring supported: " + timeMonitoring); + if (timeMonitoring) + { + for (int a = 0; a < ids.length; ++a) + { + System.out.println("Thread " + a + + " CPU time: " + + bean.getThreadCpuTime(ids[a]) + "ns"); + System.out.println("Thread " + + a + " user time: " + + bean.getThreadUserTime(ids[a]) + "ns"); + } + } + System.out.println("Current thread info: " + + bean.getThreadInfo(Thread.currentThread().getId())); + System.out.println("All thread info: " + Arrays.toString(bean.getThreadInfo(ids))); + System.out.println("Total started threads: " + bean.getTotalStartedThreadCount()); + boolean contentionMonitoring = bean.isThreadContentionMonitoringSupported(); + System.out.println("Thread contention monitoring supported: " + contentionMonitoring); + if (contentionMonitoring) + { + boolean contentionEnabled = bean.isThreadContentionMonitoringEnabled(); + System.out.println("Thread contention monitoring shouldn't be enabled... " + + (contentionEnabled ? "but it is" : "true")); + if (!contentionEnabled) + { + System.out.println("Enabling..."); + bean.setThreadContentionMonitoringEnabled(true); + contentionEnabled = bean.isThreadContentionMonitoringEnabled(); + System.out.println("Should now be enabled... " + + (contentionEnabled ? "it is" : "nope")); + } + if (contentionEnabled) + { + ThreadInfo[] info = bean.getThreadInfo(ids); + for (int a = 0; a < info.length; ++a) + { + System.out.println("Blocked time for thread " + + info[a].getThreadId() + ": " + + info[a].getBlockedTime() + "ms"); + System.out.println("Waited time for thread " + + info[a].getThreadId() + ": " + + info[a].getWaitedTime() + "ms"); + } + } + } + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java index 0f0b3555ea0..19bc27c1de8 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java @@ -22,12 +22,15 @@ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA package gnu.classpath.examples.swing; +import gnu.classpath.examples.java2d.JNIOverhead; + import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; +import javax.swing.plaf.basic.BasicLookAndFeel; import javax.swing.plaf.metal.DefaultMetalTheme; import javax.swing.plaf.metal.MetalLookAndFeel; import javax.swing.plaf.metal.MetalTheme; @@ -156,7 +159,10 @@ public class Demo examples.add(new JMenuItem(new PopupAction("NavigationFilter", NavigationFilterDemo.createDemoFactory()))); - + examples.add(new JMenuItem(new PopupAction("JNI Overhead", + JNIOverhead.createDemoFactory()))); + + final JMenuItem vmMenu; help.add(new JMenuItem("just play with the widgets")); @@ -187,6 +193,10 @@ public class Demo } }); + // Installs the BasicLookAndFeel. + UIManager.installLookAndFeel("(Basic Look And Feel)", + InstantiableBasicLookAndFeel.class.getName()); + // Create L&F menu. JMenu lafMenu = new JMenu("Look and Feel"); ButtonGroup lafGroup = new ButtonGroup(); @@ -200,6 +210,8 @@ public class Demo boolean selected = laf.getClassName().equals(currentLaf); lafItem.setSelected(selected); lafMenu.add(lafItem); + + lafGroup.add(lafItem); } // Create themes menu. @@ -543,7 +555,10 @@ public class Demo panel.add(new JButton(new PopupAction("Tree", TreeDemo.createDemoFactory()))); panel.add(new JButton(new PopupAction("Theme Editor", - MetalThemeEditor.createDemoFactory()))); + MetalThemeEditor.createDemoFactory()))); + panel.add(new JButton(new PopupAction("JNI Overhead", + JNIOverhead.createDemoFactory()))); + JButton exitDisposer = mkDisposerButton(frame); panel.add(exitDisposer); @@ -652,10 +667,45 @@ public class Demo { ex.printStackTrace(); } + SwingUtilities.updateComponentTreeUI(frame); themesMenu.setEnabled(laf.getClassName() .equals("javax.swing.plaf.metal.MetalLookAndFeel")); } + } + /** + * An implementation of BasicLookAndFeel which can be instantiated. + * + * @author Robert Schuster (robertschuster@fsfe.org) + * + */ + public static class InstantiableBasicLookAndFeel extends BasicLookAndFeel + { + public String getDescription() + { + return "An instantiable implementation of BasicLookAndFeel"; + } + + public String getID() + { + return "instantiableBasicLookAndFeel"; + } + + public String getName() + { + return "Instantiable Basic Look And Feel"; + } + + public boolean isNativeLookAndFeel() + { + return false; + } + + public boolean isSupportedLookAndFeel() + { + return true; + } } + } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/HtmlDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/HtmlDemo.java new file mode 100644 index 00000000000..223ee07cd4a --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/HtmlDemo.java @@ -0,0 +1,298 @@ +/* HtmlDemo.java -- HTML viewer demo + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextPane; +import javax.swing.SwingUtilities; +import javax.swing.text.Element; +import javax.swing.text.html.HTMLDocument; + +/** + * Parses and displays HTML content. + * + * @author Audrius Meskauskas (audriusa@bioinformatics.org) + */ +public class HtmlDemo extends JPanel +{ + + JTextPane html = new JTextPane(); + + JTextArea text = new JTextArea("<html><body>" + + "123456789HR!<hr>987654321"+ + "123456789BR!<br>987654321"+ + "<p id='insertHere'>Insertion target</p><p>"+ + "<font color=red>ma</font>"+ + "<sup>sup</sup>normal<sub>sub</sub>normal</p><p>Table:"+ + "<table><tr>a<td>b<td>c<tr>x<td>y<td>z</table></body></html>"); + + JPanel buttons; + + int n; + + public HtmlDemo() + { + super(); + html.setContentType("text/html"); // not now. + createContent(); + } + + /** + * Returns a panel with the demo content. The panel uses a BorderLayout(), and + * the BorderLayout.SOUTH area is empty, to allow callers to add controls to + * the bottom of the panel if they want to (a close button is added if this + * demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + + JPanel center = new JPanel(); + GridLayout layout = new GridLayout(); + layout.setRows(2); + center.setLayout(layout); + center.add(new JScrollPane(text)); + center.add(new JScrollPane(html)); + + buttons = new JPanel(); + + JButton parse = new JButton("parse"); + parse.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + String t = text.getText(); + System.out.println("HtmlDemo.java.createContent:Parsing started"); + html.setText(t); + System.out.println("HtmlDemo.java.createContent:Parsing completed"); + } + }); + + buttons.add(parse); + + JButton insertBeforeEnd = new JButton("before end"); + insertBeforeEnd.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + HTMLDocument doc = (HTMLDocument) html.getDocument(); + Element el = doc.getElement("insertHere"); + System.out.println("Element found:"+el); + try + { + doc.insertBeforeEnd(el,"before end "+(n++)); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }); + + JButton insertBeforeStart = new JButton("before start"); + insertBeforeStart.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + HTMLDocument doc = (HTMLDocument) html.getDocument(); + Element el = doc.getElement("insertHere"); + System.out.println("Element found:"+el); + try + { + doc.insertBeforeStart(el,"before start "+(n++)); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }); + + JButton insertAfterEnd = new JButton("after end"); + insertAfterEnd.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + HTMLDocument doc = (HTMLDocument) html.getDocument(); + Element el = doc.getElement("insertHere"); + System.out.println("Element found:"+el); + try + { + doc.insertAfterEnd(el,"after end "+(n++)); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }); + + JButton insertAfterStart = new JButton("after start"); + insertAfterStart.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + HTMLDocument doc = (HTMLDocument) html.getDocument(); + Element el = doc.getElement("insertHere"); + System.out.println("Element found:"+el); + try + { + doc.insertAfterStart(el,"after start "+(n++)); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }); + + + JButton setInner = new JButton("inner"); + setInner.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + HTMLDocument doc = (HTMLDocument) html.getDocument(); + Element el = doc.getElement("insertHere"); + System.out.println("Element found:"+el); + try + { + doc.setInnerHTML(el,"inner "+(n++)); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }); + + JButton setOuter = new JButton("outer"); + setOuter.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + HTMLDocument doc = (HTMLDocument) html.getDocument(); + Element el = doc.getElement("insertHere"); + System.out.println("Element found:"+el); + try + { + doc.setOuterHTML(el,"outer "+(n++)); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }); + + + buttons.add(insertBeforeStart); + buttons.add(insertAfterStart); + buttons.add(insertBeforeEnd); + buttons.add(insertAfterEnd); + + buttons.add(setInner); + buttons.add(setOuter); + + add(center, BorderLayout.CENTER); + add(buttons, BorderLayout.SOUTH); + } + + /** + * The executable method to display the editable table. + * + * @param args + * unused. + */ + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + HtmlDemo demo = new HtmlDemo(); + + JButton exit = new JButton("exit"); + exit.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent event) + { + System.exit(0); + } + }); + + demo.buttons.add(exit); + + JFrame frame = new JFrame(); + frame.getContentPane().add(demo); + frame.setSize(new Dimension(700, 480)); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a HtmlDemo. + * + * @return a DemoFactory that creates a HtmlDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new HtmlDemo(); + } + }; + } +} + diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java index 6c1be74cc2e..5184e5ba0f6 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java @@ -160,7 +160,7 @@ public class NavigationFilterDemo pt = text.getCaret().getMagicCaretPosition(); // Calculate its position above. - newpos = Utilities.getPositionAbove(text, pos, pt.x); + newpos = Utilities.getPositionAbove(text, pos, (pt != null) ? pt.x : 0); // If we have a valid position, then calculate the next word start // from there. @@ -173,7 +173,7 @@ public class NavigationFilterDemo pt = text.getCaret().getMagicCaretPosition(); // Calculate its position below. - newpos = Utilities.getPositionBelow(text, pos, pt.x); + newpos = Utilities.getPositionBelow(text, pos, (pt != null) ? pt.x : 0); // If we have a valid position, then calculate the next word start // from there. @@ -192,7 +192,6 @@ public class NavigationFilterDemo else return Utilities.getPreviousWord(text, newpos); case SwingConstants.EAST: - // Simply calculate the next word's start offset. return Utilities.getNextWord(text, newpos); default: // Do whatever the super implementation did. diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java index 9d797d20317..527fe455e4b 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java @@ -66,17 +66,17 @@ public class TabbedPaneDemo JPanel p = new JPanel(); p.setLayout(new GridLayout(2, 2)); JTabbedPane tabs1 = new JTabbedPane(SwingConstants.TOP); - tabs1.add("Top Item 1", new JButton("Button")); - tabs1.add("Top Item 2", new JButton("Button")); + tabs1.add("Top Item 1", new JButton("Content: Top Item 1")); + tabs1.add("Top Item 2", new JButton("Content: Top Item 2")); JTabbedPane tabs2 = new JTabbedPane(SwingConstants.LEFT); - tabs2.add("Left Item 1", new JButton("Button")); - tabs2.add("Left Item 2", new JButton("Button")); + tabs2.add("Left Item 1", new JButton("Content: Left Item 1")); + tabs2.add("Left Item 2", new JButton("Content: Left Item 2")); JTabbedPane tabs3 = new JTabbedPane(SwingConstants.BOTTOM); - tabs3.add("Bottom Item 1", new JButton("Button")); - tabs3.add("Bottom Item 2", new JButton("Button")); + tabs3.add("Bottom Item 1", new JButton("Content: Bottom Item 1")); + tabs3.add("Bottom Item 2", new JButton("Content: Bottom Item 2")); JTabbedPane tabs4 = new JTabbedPane(SwingConstants.RIGHT); - tabs4.add("Right Item 1", new JButton("Button")); - tabs4.add("Right Item 2", new JButton("Button")); + tabs4.add("Right Item 1", new JButton("Content: Right Item 1")); + tabs4.add("Right Item 2", new JButton("Content: Right Item 2")); p.add(tabs1); p.add(tabs2); p.add(tabs3); diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java index e661ee3adc6..d4a97b3ef45 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java @@ -39,19 +39,36 @@ exception statement from your version. */ package gnu.classpath.examples.swing; import java.awt.BorderLayout; +import java.awt.Component; import java.awt.Dimension; +import java.awt.Rectangle; +import java.text.DateFormat; +import java.util.Date; +import javax.swing.AbstractCellEditor; +import javax.swing.BorderFactory; +import javax.swing.DefaultCellEditor; +import javax.swing.DefaultListCellRenderer; import javax.swing.Icon; +import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; +import javax.swing.JList; import javax.swing.JPanel; +import javax.swing.JScrollBar; import javax.swing.JScrollPane; +import javax.swing.JSlider; import javax.swing.JTable; +import javax.swing.JTextField; import javax.swing.SwingUtilities; +import javax.swing.border.Border; import javax.swing.plaf.metal.MetalIconFactory; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; /** * Displays the editable table. The first column consists of check boxes. @@ -78,12 +95,11 @@ public class TableDemo extends JPanel { /** - * Return true if the cell is editable. - * Icons are not editable, other cells are editable. + * All cells are editable in our table. */ public boolean isCellEditable(int row, int column) { - return column!=1; + return true; } /** @@ -144,6 +160,77 @@ public class TableDemo extends JPanel } /** + * The scroll bar renderer. + */ + class SliderCell + extends AbstractCellEditor + implements TableCellEditor, TableCellRenderer + { + /** + * The editor bar. + */ + JSlider bar; + + /** + * The renderer bar. + */ + JSlider rendererBar; + + /** + * The border around the bar, if required. + */ + Border border = BorderFactory.createLineBorder(table.getGridColor()); + + SliderCell() + { + bar = new JSlider(); + bar.setOrientation(JScrollBar.HORIZONTAL); + bar.setMinimum(0); + bar.setMaximum(rows); + bar.setBorder(border); + + rendererBar = new JSlider(); + rendererBar.setMinimum(0); + rendererBar.setMaximum(rows); + rendererBar.setEnabled(false); + } + + /** + * Get the editor. + */ + public Component getTableCellEditorComponent(JTable table, Object value, + boolean isSelected, int row, + int column) + { + if (value instanceof Integer) + bar.setValue(((Integer) value).intValue()); + return bar; + } + + /** + * Get the renderer. + */ + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, + boolean hasFocus, int row, + int column) + { + rendererBar.setValue(((Integer) value).intValue()); + if (hasFocus) + rendererBar.setBorder(border); + else + rendererBar.setBorder(null); + return rendererBar; + } + + public Object getCellEditorValue() + { + return new Integer(bar.getValue()); + } + + } + + /** * The table being displayed. */ JTable table = new JTable(); @@ -159,6 +246,25 @@ public class TableDemo extends JPanel Object[][] values; /** + * The icons that appear in the icon column. + */ + Icon[] icons = new Icon[] + { + MetalIconFactory.getTreeComputerIcon(), + MetalIconFactory.getTreeHardDriveIcon(), + MetalIconFactory.getTreeFolderIcon(), + }; + + /** + * The choices in the combo boxes + */ + String [] sides = new String[] + { + "north", "south", "east", "west" + }; + + + /** * Create the table demo with the given titel. */ public TableDemo() @@ -178,29 +284,25 @@ public class TableDemo extends JPanel setLayout(new BorderLayout()); values = new Object[rows][]; - // The icons that appear in the icon column. - Icon[] icons = new Icon[] - { - MetalIconFactory.getTreeComputerIcon(), - MetalIconFactory.getTreeHardDriveIcon(), - MetalIconFactory.getTreeFolderIcon(), - }; - for (int i = 0; i < values.length; i++) { values[i] = new Object[cols]; - for (int j = 2; j < cols; j++) + for (int j = 3; j < cols; j++) { values[i][j] = "" + ((char) ('a' + j)) + i; } values [i][0] = i % 2 == 0? Boolean.TRUE : Boolean.FALSE; - values [i][1] = icons [ i % icons.length ]; + values [i][1] = icons [ i % icons.length ]; + values [i][2] = sides [ i % sides.length ]; + values [i][4] = new Integer(i); } table.setModel(model); // Make the columns with gradually increasing width: DefaultTableColumnModel cm = new DefaultTableColumnModel(); + table.setColumnModel(cm); + for (int i = 0; i < cols; i++) { TableColumn column = new TableColumn(i); @@ -215,8 +317,9 @@ public class TableDemo extends JPanel cm.addColumn(column); } - - table.setColumnModel(cm); + + setCustomEditors(); + setInformativeHeaders(); // Create the table, place it into scroll pane and place // the pane into this frame. @@ -226,6 +329,52 @@ public class TableDemo extends JPanel scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.getViewport().add(table); add(scroll, BorderLayout.CENTER); + + // Increase the row height to make the icons and sliders look better. + table.setRowHeight(table.getRowHeight()+2); + } + + /** + * Set the more informative column headers for specific columns. + */ + void setInformativeHeaders() + { + TableColumnModel cm = table.getColumnModel(); + + cm.getColumn(0).setHeaderValue("check"); + cm.getColumn(1).setHeaderValue("icon"); + cm.getColumn(2).setHeaderValue("combo"); + cm.getColumn(3).setHeaderValue("edit combo"); + cm.getColumn(4).setHeaderValue("slider"); + } + + /** + * Set the custom editors for combo boxes. This method also sets one + * custom renderer. + */ + void setCustomEditors() + { + TableColumnModel cm = table.getColumnModel(); + + // Set combo-box based editor for icons (note that no custom + // renderer is needed for JComboBox to work with icons. + JComboBox combo0 = new JComboBox(icons); + cm.getColumn(1).setCellEditor(new DefaultCellEditor(combo0)); + + // Set the simple combo box editor for the third column: + JComboBox combo1 = new JComboBox(sides); + cm.getColumn(2).setCellEditor(new DefaultCellEditor(combo1)); + + // Set the editable combo box for the forth column: + JComboBox combo2 = new JComboBox(sides); + combo2.setEditable(true); + cm.getColumn(3).setCellEditor(new DefaultCellEditor(combo2)); + + SliderCell scrollView = new SliderCell(); + cm.getColumn(4).setCellEditor(scrollView); + cm.getColumn(4).setCellRenderer(scrollView); + + table.setColumnModel(cm); } /** @@ -266,3 +415,4 @@ public class TableDemo extends JPanel }; } } + |