undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

6
src/demo/share/README Normal file
View file

@ -0,0 +1,6 @@
The source code provided with demos for the JDK is meant
to illustrate the usage of a given feature or technique and has been
deliberately simplified. Additional steps required for a
production-quality application, such as security checks, input
validation, and proper error handling, might not be present in the
sample code.

View file

@ -0,0 +1,144 @@
#
# Copyright (c) 2002, 2025, Oracle and/or its affiliates. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# - Neither the name of Oracle nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
ifndef SOURCE
export SOURCE := 8
endif
ifndef TARGET
export TARGET := 8
endif
ifndef JAVAC
export JAVAC := javac
endif
ifndef JAVA
export JAVA := java
endif
ifndef JAR
export JAR := jar
endif
SOURCEPATH=src
CLASSES=build
DIST=dist
RESOURCES=resources
J2DBENCH_CLASSES = \
$(CLASSES)/j2dbench/J2DBench.class \
$(CLASSES)/j2dbench/Destinations.class \
$(CLASSES)/j2dbench/Group.class \
$(CLASSES)/j2dbench/Result.class \
$(CLASSES)/j2dbench/Modifier.class \
$(CLASSES)/j2dbench/Node.class \
$(CLASSES)/j2dbench/Option.class \
$(CLASSES)/j2dbench/ResultSet.class \
$(CLASSES)/j2dbench/TestEnvironment.class \
$(CLASSES)/j2dbench/Test.class \
$(CLASSES)/j2dbench/ui/EnableButton.class \
$(CLASSES)/j2dbench/ui/CompactLayout.class \
$(CLASSES)/j2dbench/tests/ImageTests.class \
$(CLASSES)/j2dbench/tests/RenderTests.class \
$(CLASSES)/j2dbench/tests/PixelTests.class \
$(CLASSES)/j2dbench/tests/MiscTests.class \
$(CLASSES)/j2dbench/tests/iio/IIOTests.class \
$(CLASSES)/j2dbench/tests/iio/InputTests.class \
$(CLASSES)/j2dbench/tests/iio/InputImageTests.class \
$(CLASSES)/j2dbench/tests/iio/InputStreamTests.class \
$(CLASSES)/j2dbench/tests/iio/OutputTests.class \
$(CLASSES)/j2dbench/tests/iio/OutputImageTests.class \
$(CLASSES)/j2dbench/tests/iio/OutputStreamTests.class \
$(CLASSES)/j2dbench/tests/text/TextConstructionTests.class \
$(CLASSES)/j2dbench/tests/text/TextMeasureTests.class \
$(CLASSES)/j2dbench/tests/text/TextRenderTests.class \
$(CLASSES)/j2dbench/tests/text/TextTests.class \
$(CLASSES)/j2dbench/tests/GraphicsTests.class
J2DANALYZER_CLASSES = \
$(CLASSES)/j2dbench/report/IIOComparator.class \
$(CLASSES)/j2dbench/report/HTMLSeriesReporter.class \
$(CLASSES)/j2dbench/report/J2DAnalyzer.class \
$(CLASSES)/j2dbench/report/XMLHTMLReporter.class
J2DBENCH_RESOURCES = \
$(CLASSES)/j2dbench/tests/iio/images \
$(CLASSES)/j2dbench/tests/cmm/images \
$(CLASSES)/j2dbench/tests/text/textdata
SCM_DIRs = .hg .svn CVS RCS SCCS Codemgr_wsdata deleted_files
all: mkdirs J2DBench.jar J2DAnalyzer.jar
run: mkdirs J2DBench.jar
$(JAVA) -jar $(DIST)/J2DBench.jar
analyze: mkdirs J2DAnalyzer.jar
$(JAVA) -jar $(DIST)/J2DAnalyzer.jar
J2DBench.jar: \
$(J2DBENCH_CLASSES) $(J2DBENCH_RESOURCES) \
$(CLASSES)/j2dbench.manifest
$(JAR) cvmf $(CLASSES)/j2dbench.manifest $(DIST)/J2DBench.jar -C $(CLASSES) j2dbench
J2DAnalyzer.jar: $(J2DANALYZER_CLASSES) $(CLASSES)/j2danalyzer.manifest
$(JAR) cvmf $(CLASSES)/j2danalyzer.manifest \
$(DIST)/J2DAnalyzer.jar -C $(CLASSES) j2dbench/report
$(CLASSES)/j2dbench/tests/iio/images: $(RESOURCES)/images
cp -r $< $@
cd $@ && rm -rf $(SCM_DIRs)
$(CLASSES)/j2dbench/tests/text/textdata: $(RESOURCES)/textdata
cp -r $< $@
cd $@ && rm -rf $(SCM_DIRs)
$(CLASSES)/j2dbench/tests/cmm/images: $(RESOURCES)/cmm_images
cp -r $< $@
cd $@ && rm -rf $(SCM_DIRs)
$(CLASSES)/j2dbench.manifest:
echo "Main-Class: j2dbench.J2DBench" > $@
$(CLASSES)/j2danalyzer.manifest:
echo "Main-Class: j2dbench.report.J2DAnalyzer" > $@
$(DIST):
mkdir $(DIST)
$(CLASSES):
mkdir $(CLASSES)
mkdirs: $(DIST) $(CLASSES)
$(CLASSES)/j2dbench/%.class: $(SOURCEPATH)/j2dbench/%.java
$(JAVAC) -g:none -source $(SOURCE) -target $(TARGET) -d $(CLASSES) -sourcepath $(SOURCEPATH) $<
clean:
rm -rf $(CLASSES)
rm -rf $(DIST)

View file

@ -0,0 +1,166 @@
-----------------------------------------------------------------------
Introduction
-----------------------------------------------------------------------
J2DBench is a suite of benchmarks with a GUI front end that lets you
analyze the performance of many Java2D graphical operations. You can
easily modify the test options, and save them for later runs using
GUI, or load them in batch mode to allow quick testing on different
builds. It also provides logging of the result, to make the
comparison of the collected data easier.
J2DAnalyzer is J2DBench a results analyzer/comparator which can
compare the results generated by the J2DBench runs.
XMLHTMLReporter is an additional tool which can create an html report
from the results files generated by the J2DBench runs.
-----------------------------------------------------------------------
Minimum requirements
-----------------------------------------------------------------------
The benchmark requires at least jdk1.4 to compile and run. Note that
source/target is set to 1.7 in the makefile and build.xml, because of
support in jdk 14 compiler. To check compatibility with jdk1.4 you can
use "-source 1.4 -target 1.4" options and jdk1.7.
Yo can use TARGET/SOURCE of makefile and -Dtarget/surce to set them up for your convinience.
Similarly you can set JAVA/JAVAC/JAR and -Djava/javac to select diffferent java/javac then is on yoru PATH
Unluckily in ant, you can not set jar, but ant should honor JAVA_HOME
-----------------------------------------------------------------------
How To Compile
-----------------------------------------------------------------------
#> cd J2DBench
The benchmark can be compiled by using either ant:
#> ant
or gnumake (assuming there's 'javac' in the path):
#> gnumake
The jar files will be generated into J2DBench/dist directory.
Note that the workspace also contains Netbeans 4.0 project file:
J2DBench/nbproject/project.xml
allowing it to be easily imported into Netbeans.
-----------------------------------------------------------------------
How To Run J2DBench, J2DAnalyzer, XMLHTMLReporter
-----------------------------------------------------------------------
#> ant run
or
#> java -jar dist/J2DBench.jar
To get help page for each of the tools, run:
#> java -jar dist/J2DBench.jar -help
#> java -jar dist/J2DAnalyzer.jar -help
#> java -cp dist/J2DAnalyzer.jar j2dbench.report.XMLHTMLReporter -help
-----------------------------------------------------------------------
Using J2DBench GUI to Create Options File
-----------------------------------------------------------------------
There are global options, options specific to a group of benchmarks,
and benchmark-specific options.
Global options affect all groups of benchmarks, group options only
affect benchmarks in particular group, and benchmark-specific ones are
relevant to a single benchmark.
Examples of important global options:
Calibration:
if the "Fixed Number of reps" is set to 0, J2DBench will calibrate
each individual benchmark, meaning that it will determine how many
repetitions each benchmark can perform in "Target Test Time", and
use this number of repetitions for each Test Run.
If "Fixed Number of reps" is non-0, each benchmark will be run for
specified number of repetitions. The use of Calibration mode is
preferable because the time per operation can vary widely among
the various tests.
Output Destinations:
where the benchmarks will render to.
All selected benchmarks will be repeated for each selected
destination.
Example of benchmark group options:
TextBenchmarks/TextOptions/Graphics
Text AntiAlias:
whether to use text antialiasing for text benchmarks
Example of a benchmark option:
Graphics Benchmarks/Imaging Benchmarks:
Image Rendering Sources (for Imaging Benchmarks only):
the source image types used for testing
Example of a benchmark:
Graphics Benchmarks/Imaging Benchmarks/Image Rendering Tests:
drawImage(img, tx, obs):
test the Graphics2D's
drawImage(Image image, AffineTransform tx, ImageObserver obs)
operation.
General note: you can chose multiple options in some cases by holding
Shift or Ctrl key.
-----------------------------------------------------------------------
Use Scenario
-----------------------------------------------------------------------
Suppose you want to compare rendering performance of the default
and opengl pipelines.
Start J2DBench (assuming the current dir is J2DBench's top dir)
#> java -jar dist/J2DBench.jar
You can either create and save the option file by selecting desired
tests and their attributes, or use one of the provided option files in
options/ directory (for example, default.opt, which is used below).
Note that it's very easy to create an option file which would take an
extremely long time to execute the tests, so be be careful when
choosing the options and benchmarks to run.
After the options file is created, start J2DBench in batch mode to run
the benchmarks for the default pipeline:
#> java -jar dist/J2DBench.jar -batch -loadopts options/default.opt \
-saveres default.res -title "Rendering - Default ppl" \
-desc "Rendering tests with the default pipeline"
This command will run the benchmarks defined in options/default.opt
file and save the result in default.res file.
(You can also run selected tests directly from the GUI mode by hitting
"Run Tests" in the J2DBench dialog)
Now run the benchmark with opengl pipeline:
#> java -Dsun.java2d.opengl=True -jar dist/J2DBench.jar -batch \
-loadopts options/default.opt \
-saveres opengl.res -title "Rendering - OpenGL" \
-desc "Rendering tests with OpenGL pipeline"
Now let's analyze the results using J2DAnalyzer:
#> java -jar dist/J2DAnalyzer.jar default.res opengl.res
Note that you can compare more than two sets of results, see
J2DAnalyzer's help page.
You can also generate html pages from the results files using
j2dbench.report.XMLHTMLReporter class in J2DAnalyzer.jar. Suppose
generated pages are to be stored in html_results directory.
First, make sure html_results/testcases directory exists:
#> mkdir -p html_results/testcases
Then generate the report:
#> java -cp J2DAnalyzer.jar j2dbench.report.XMLHTMLReporter \
-r html_results -b default.res -t opengl.res
The html report will be generated in html_results/ directory.
The index page:
html_results/Summary_Report.html

View file

@ -0,0 +1,135 @@
<!--
Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Oracle nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<project name="J2DBench" default="dist" basedir=".">
<description>
simple example build file
</description>
<!-- set global properties for this build -->
<property name="src" location="src"/>
<property name="build" location="build"/>
<property name="dist" location="dist"/>
<property name="resources" location="resources"/>
<condition property="source" value="8">
<not>
<isset property="source"/>
</not>
</condition>
<condition property="target" value="8">
<not>
<isset property="target"/>
</not>
</condition>
<condition property="java" value="java">
<not>
<isset property="java"/>
</not>
</condition>
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>
<target name="compile" depends="init"
description="compile the source " >
<!-- Compile the java code from ${src} into ${build} -->
<javac debug="off" source="${source}" target="${target}" srcdir="${src}" destdir="${build}"/>
</target>
<target name="run" depends="dist"
description="run J2DBench" >
<java jar="${dist}/J2DBench.jar"
fork="true"
jvm="${java}"
>
</java>
</target>
<target name="analyze" depends="dist"
description="run J2DAnalyzer" >
<java jar="${dist}/J2DAnalyzer.jar"
fork="true"
jvm="${java}"
>
</java>
</target>
<target name="resources" depends="init"
description="copy resources into build dir" >
<!-- Copy the resource files from ${resources} into ${build}/ -->
<mkdir dir="${dist}"/>
<mkdir dir="${build}/j2dbench/tests/text/textdata"/>
<copy todir="${build}/j2dbench/tests/text/textdata">
<fileset dir="${resources}/textdata" />
</copy>
<mkdir dir="${build}/j2dbench/tests/iio/images"/>
<copy todir="${build}/j2dbench/tests/iio/images">
<fileset dir="${resources}/images" />
</copy>
<mkdir dir="${build}/j2dbench/tests/cmm/images"/>
<copy todir="${build}/j2dbench/tests/cmm/images">
<fileset dir="${resources}/cmm_images" />
</copy>
</target>
<target name="dist" depends="compile, resources"
description="generate the distribution" >
<!-- Create the distribution directory -->
<mkdir dir="${dist}"/>
<!-- Put everything in ${build} into the J2DBench.jar file -->
<jar jarfile="${dist}/J2DBench.jar" basedir="${build}"
excludes="j2dbench/report/**" >
<manifest>
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Main-Class" value="j2dbench.J2DBench"/>
</manifest>
</jar>
<jar jarfile="${dist}/J2DAnalyzer.jar" basedir="${build}"
includes="j2dbench/report/**" >
<manifest>
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Main-Class" value="j2dbench.report.J2DAnalyzer"/>
</manifest>
</jar>
</target>
<target name="clean"
description="clean up" >
<!-- Delete the ${build} and ${dist} directory trees -->
<delete dir="${build}"/>
<delete dir="${dist}"/>
</target>
</project>

View file

@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Oracle nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.ant.freeform</type>
<configuration>
<general-data xmlns="http://www.netbeans.org/ns/freeform-project/1">
<!--Do not use Project Properties customizer when editing this file manually.-->
<name>J2DBench</name>
<folders>
<source-folder>
<label>src</label>
<type>java</type>
<location>src</location>
</source-folder>
<source-folder>
<label>src</label>
<location>src</location>
</source-folder>
</folders>
<ide-actions>
<action name="build">
<target>compile</target>
</action>
<action name="clean">
<target>clean</target>
</action>
<action name="run">
<target>run</target>
</action>
<action name="rebuild">
<target>clean</target>
<target>compile</target>
</action>
</ide-actions>
<view>
<items>
<source-folder style="packages">
<label>src</label>
<location>src</location>
</source-folder>
<source-file>
<location>build.xml</location>
</source-file>
</items>
<context-menu>
<ide-action name="build"/>
<ide-action name="clean"/>
<ide-action name="run"/>
<ide-action name="rebuild"/>
</context-menu>
</view>
</general-data>
<java-data xmlns="http://www.netbeans.org/ns/freeform-project-java/1">
<compilation-unit>
<package-root>src</package-root>
<source-level>1.5</source-level>
</compilation-unit>
</java-data>
</configuration>
</project>

View file

@ -0,0 +1,267 @@
prog.verbose=disabled
prog.printresults=enabled
global.env.outputwidth=640
global.env.outputheight=480
global.env.runcount=5
global.env.repcount=0
global.env.testtime=2500
global.results.workunits=units
global.results.timeunits=sec
global.results.ratio=unitspersec
global.dest.offscreen=disabled
global.dest.frame.defaultframe=disabled
global.dest.frame.transframe=disabled
global.dest.frame.shapedframe=disabled
global.dest.frame.shapedtransframe=disabled
global.dest.compatimg.compatimg=disabled
global.dest.compatimg.opqcompatimg=disabled
global.dest.compatimg.bmcompatimg=disabled
global.dest.compatimg.transcompatimg=disabled
global.dest.volimg.volimg=enabled
global.dest.volimg.opqvolimg=disabled
global.dest.volimg.bmvolimg=disabled
global.dest.volimg.transvolimg=disabled
global.dest.bufimg.IntXrgb=disabled
global.dest.bufimg.IntArgb=disabled
global.dest.bufimg.IntArgbPre=disabled
global.dest.bufimg.3ByteBgr=disabled
global.dest.bufimg.ByteIndexed=disabled
global.dest.bufimg.ByteGray=disabled
global.dest.bufimg.4ByteAbgr=disabled
global.dest.bufimg.4ByteAbgrPre=disabled
global.dest.bufimg.custom=disabled
graphics.opts.anim=2
graphics.opts.sizes=20,250
graphics.opts.alpharule=SrcOver
graphics.opts.transform=ident
graphics.opts.extraalpha=Both
graphics.opts.xormode=Off
graphics.opts.clip=Both
graphics.opts.renderhint=Default
graphics.render.opts.paint=single,random
graphics.render.opts.alphacolor=Off
graphics.render.opts.antialias=Both
graphics.render.opts.stroke=width1
graphics.render.tests.drawLine=enabled
graphics.render.tests.drawLineHoriz=disabled
graphics.render.tests.drawLineVert=disabled
graphics.render.tests.fillRect=enabled
graphics.render.tests.drawRect=disabled
graphics.render.tests.fillOval=enabled
graphics.render.tests.drawOval=disabled
graphics.render.tests.fillPoly=disabled
graphics.render.tests.drawPoly=disabled
graphics.render.tests.shape.fillCubic=enabled
graphics.render.tests.shape.drawCubic=disabled
graphics.render.tests.shape.fillEllipse2D=disabled
graphics.render.tests.shape.drawEllipse2D=disabled
graphics.imaging.src.offscr.opaque=disabled
graphics.imaging.src.offscr.bitmask=disabled
graphics.imaging.src.offscr.translucent=disabled
graphics.imaging.src.opqcompatimg.opaque=enabled
graphics.imaging.src.opqcompatimg.bitmask=disabled
graphics.imaging.src.opqcompatimg.translucent=disabled
graphics.imaging.src.bmcompatimg.opaque=disabled
graphics.imaging.src.bmcompatimg.bitmask=disabled
graphics.imaging.src.bmcompatimg.translucent=disabled
graphics.imaging.src.transcompatimg.opaque=disabled
graphics.imaging.src.transcompatimg.bitmask=disabled
graphics.imaging.src.transcompatimg.translucent=enabled
graphics.imaging.src.opqvolimg.opaque=disabled
graphics.imaging.src.opqvolimg.bitmask=disabled
graphics.imaging.src.opqvolimg.translucent=disabled
graphics.imaging.src.bmvolimg.opaque=disabled
graphics.imaging.src.bmvolimg.bitmask=disabled
graphics.imaging.src.bmvolimg.translucent=disabled
graphics.imaging.src.transvolimg.opaque=disabled
graphics.imaging.src.transvolimg.bitmask=disabled
graphics.imaging.src.transvolimg.translucent=disabled
graphics.imaging.src.bufimg.IntXrgb.opaque=enabled
graphics.imaging.src.bufimg.IntXrgb.bitmask=disabled
graphics.imaging.src.bufimg.IntXrgb.translucent=disabled
graphics.imaging.src.bufimg.IntArgb.opaque=disabled
graphics.imaging.src.bufimg.IntArgb.bitmask=disabled
graphics.imaging.src.bufimg.IntArgb.translucent=enabled
graphics.imaging.src.bufimg.IntArgbPre.opaque=disabled
graphics.imaging.src.bufimg.IntArgbPre.bitmask=disabled
graphics.imaging.src.bufimg.IntArgbPre.translucent=disabled
graphics.imaging.src.bufimg.ByteGray.opaque=disabled
graphics.imaging.src.bufimg.ByteGray.bitmask=disabled
graphics.imaging.src.bufimg.ByteGray.translucent=disabled
graphics.imaging.src.bufimg.3ByteBgr.opaque=disabled
graphics.imaging.src.bufimg.3ByteBgr.bitmask=disabled
graphics.imaging.src.bufimg.3ByteBgr.translucent=disabled
graphics.imaging.src.bufimg.4ByteAbgr.opaque=disabled
graphics.imaging.src.bufimg.4ByteAbgr.bitmask=disabled
graphics.imaging.src.bufimg.4ByteAbgr.translucent=disabled
graphics.imaging.src.bufimg.4ByteAbgrPre.opaque=disabled
graphics.imaging.src.bufimg.4ByteAbgrPre.bitmask=disabled
graphics.imaging.src.bufimg.4ByteAbgrPre.translucent=disabled
graphics.imaging.src.bufimg.ByteIndexedBm.opaque=disabled
graphics.imaging.src.bufimg.ByteIndexedBm.bitmask=disabled
graphics.imaging.src.bufimg.ByteIndexedBm.translucent=disabled
graphics.imaging.src.bufimg.unmanagedIntXrgb.opaque=disabled
graphics.imaging.src.bufimg.unmanagedIntXrgb.bitmask=disabled
graphics.imaging.src.bufimg.unmanagedIntXrgb.translucent=disabled
graphics.imaging.src.bufimg.unmanagedIntArgb.opaque=disabled
graphics.imaging.src.bufimg.unmanagedIntArgb.bitmask=disabled
graphics.imaging.src.bufimg.unmanagedIntArgb.translucent=disabled
graphics.imaging.src.bufimg.unmanagedIntArgbPre.opaque=disabled
graphics.imaging.src.bufimg.unmanagedIntArgbPre.bitmask=disabled
graphics.imaging.src.bufimg.unmanagedIntArgbPre.translucent=disabled
graphics.imaging.src.bufimg.unmanaged3ByteBgr.opaque=disabled
graphics.imaging.src.bufimg.unmanaged3ByteBgr.bitmask=disabled
graphics.imaging.src.bufimg.unmanaged3ByteBgr.translucent=disabled
graphics.imaging.benchmarks.opts.interpolation=Nearest neighbor
graphics.imaging.benchmarks.opts.touchsrc=Off
graphics.imaging.benchmarks.tests.drawimage=enabled
graphics.imaging.benchmarks.tests.drawimagebg=disabled
graphics.imaging.benchmarks.tests.drawimagescaleup=enabled
graphics.imaging.benchmarks.tests.drawimagescaledown=disabled
graphics.imaging.benchmarks.tests.drawimagescalesplit=disabled
graphics.imaging.benchmarks.tests.drawimagetxform=enabled
graphics.imaging.imageops.opts.op=convolve3x3zero
graphics.imaging.imageops.tests.graphics2d.drawimageop=disabled
graphics.imaging.imageops.tests.bufimgop.filternull=disabled
graphics.imaging.imageops.tests.bufimgop.filtercached=disabled
graphics.imaging.imageops.tests.rasterop.filternull=disabled
graphics.imaging.imageops.tests.rasterop.filtercached=disabled
graphics.misc.copytests.copyAreaVert=disabled
graphics.misc.copytests.copyAreaHoriz=disabled
graphics.misc.copytests.copyAreaDiag=disabled
pixel.opts.renderto=Off
pixel.opts.renderfrom=Off
pixel.src.1BitBinary=disabled
pixel.src.2BitBinary=disabled
pixel.src.4BitBinary=disabled
pixel.src.ByteIndexed=disabled
pixel.src.ByteGray=disabled
pixel.src.Short555=disabled
pixel.src.Short565=disabled
pixel.src.ShortGray=disabled
pixel.src.3ByteBgr=disabled
pixel.src.4ByteAbgr=disabled
pixel.src.IntXrgb=disabled
pixel.src.IntXbgr=disabled
pixel.src.IntArgb=disabled
pixel.bimgtests.getrgb=disabled
pixel.bimgtests.setrgb=disabled
pixel.rastests.getdataelem=disabled
pixel.rastests.setdataelem=disabled
pixel.rastests.getpixel=disabled
pixel.rastests.setpixel=disabled
pixel.dbtests.getelem=disabled
pixel.dbtests.setelem=disabled
text.opts.data.tlength=32
text.opts.data.tscript=english
text.opts.font.fname=dialog
text.opts.font.fstyle=0
text.opts.font.fsize=13.0
text.opts.font.ftx=Identity
text.opts.graphics.textaa=Off,On
text.opts.graphics.tfm=Off
text.opts.graphics.gaa=Off
text.opts.graphics.gtx=Identity
text.opts.advopts.gvstyle=0
text.opts.advopts.tlruns=1
text.opts.advopts.maptype=FONT
text.Rendering.tests.drawString=enabled
text.Rendering.tests.drawChars=disabled
text.Rendering.tests.drawBytes=disabled
text.Rendering.tests.drawGlyphVectors=disabled
text.Rendering.tests.drawTextLayout=disabled
text.Measuring.tests.stringWidth=disabled
text.Measuring.tests.stringBounds=disabled
text.Measuring.tests.charsWidth=disabled
text.Measuring.tests.charsBounds=disabled
text.Measuring.tests.fontcandisplay=disabled
text.Measuring.tests.gvWidth=disabled
text.Measuring.tests.gvLogicalBounds=disabled
text.Measuring.tests.gvVisualBounds=disabled
text.Measuring.tests.gvPixelBounds=disabled
text.Measuring.tests.gvOutline=disabled
text.Measuring.tests.gvGlyphLogicalBounds=disabled
text.Measuring.tests.gvGlyphVisualBounds=disabled
text.Measuring.tests.gvGlyphPixelBounds=disabled
text.Measuring.tests.gvGlyphOutline=disabled
text.Measuring.tests.gvGlyphTransform=disabled
text.Measuring.tests.gvGlyphMetrics=disabled
text.Measuring.tests.tlAdvance=disabled
text.Measuring.tests.tlAscent=disabled
text.Measuring.tests.tlBounds=disabled
text.Measuring.tests.tlGetCaretInfo=disabled
text.Measuring.tests.tlGetNextHit=disabled
text.Measuring.tests.tlGetCaretShape=disabled
text.Measuring.tests.tlGetLogicalHighlightShape=disabled
text.Measuring.tests.tlHitTest=disabled
text.Measuring.tests.tlOutline=disabled
text.construction.tests.gvfromfontstring=disabled
text.construction.tests.gvfromfontchars=disabled
text.construction.tests.gvfromfontci=disabled
text.construction.tests.gvfromfontglyphs=disabled
text.construction.tests.gvfromfontlayout=disabled
text.construction.tests.tlfromfont=disabled
text.construction.tests.tlfrommap=disabled
imageio.opts.size=250
imageio.opts.content=photo
imageio.input.opts.general.source.file=disabled
imageio.input.opts.general.source.url=disabled
imageio.input.opts.general.source.byteArray=disabled
imageio.input.opts.imageio.useCache=Off
imageio.input.image.toolkit.opts.format=
imageio.input.image.toolkit.tests.createImage=disabled
imageio.input.image.imageio.opts.format=
imageio.input.image.imageio.tests.imageioRead=disabled
imageio.input.image.imageio.reader.opts.seekForwardOnly=On
imageio.input.image.imageio.reader.opts.ignoreMetadata=On
imageio.input.image.imageio.reader.opts.installListener=Off
imageio.input.image.imageio.reader.tests.read=disabled
imageio.input.image.imageio.reader.tests.getImageMetadata=disabled
imageio.input.stream.tests.construct=disabled
imageio.input.stream.tests.read=disabled
imageio.input.stream.tests.readByteArray=disabled
imageio.input.stream.tests.readFullyByteArray=disabled
imageio.input.stream.tests.readBit=disabled
imageio.input.stream.tests.readByte=disabled
imageio.input.stream.tests.readUnsignedByte=disabled
imageio.input.stream.tests.readShort=disabled
imageio.input.stream.tests.readUnsignedShort=disabled
imageio.input.stream.tests.readInt=disabled
imageio.input.stream.tests.readUnsignedInt=disabled
imageio.input.stream.tests.readFloat=disabled
imageio.input.stream.tests.readLong=disabled
imageio.input.stream.tests.readDouble=disabled
imageio.input.stream.tests.skipBytes=disabled
imageio.output.opts.general.dest.file=disabled
imageio.output.opts.general.dest.byteArray=disabled
imageio.output.opts.imageio.useCache=Off
imageio.output.image.imageio.opts.format=
imageio.output.image.imageio.tests.imageioWrite=disabled
imageio.output.image.imageio.writer.opts.installListener=Off
imageio.output.image.imageio.writer.tests.write=disabled
imageio.output.stream.tests.construct=disabled
imageio.output.stream.tests.write=disabled
imageio.output.stream.tests.writeByteArray=disabled
imageio.output.stream.tests.writeBit=disabled
imageio.output.stream.tests.writeByte=disabled
imageio.output.stream.tests.writeShort=disabled
imageio.output.stream.tests.writeInt=disabled
imageio.output.stream.tests.writeFloat=disabled
imageio.output.stream.tests.writeLong=disabled
imageio.output.stream.tests.writeDouble=disabled
cmm.opts.profiles=1001
cmm.colorconv.data.fromRGB=disabled
cmm.colorconv.data.toRGB=disabled
cmm.colorconv.data.fromCIEXYZ=disabled
cmm.colorconv.data.toCIEXYZ=disabled
cmm.colorconv.ccop.ccopOptions.size=250
cmm.colorconv.ccop.ccopOptions.content=photo
cmm.colorconv.ccop.ccopOptions.srcType=INT_ARGB
cmm.colorconv.ccop.ccopOptions.dstType=INT_ARGB
cmm.colorconv.ccop.op_img=disabled
cmm.colorconv.ccop.op_rst=disabled
cmm.colorconv.ccop.op_draw=disabled
cmm.colorconv.embed.embedOptions.Images=512x512
cmm.colorconv.embed.embd_img_read=disabled
cmm.profiles.getHeader=disabled
cmm.profiles.getNumComponents=disabled

Binary file not shown.

After

Width:  |  Height:  |  Size: 420 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View file

@ -0,0 +1,11 @@
ما هي الشفرة الموحدة "يونِكود" ؟
أساسًا، تتعامل الحواسيب فقط مع الأرقام، وتقوم بتخزين الأحرف والمحارف الأخرى بعد أن تُعطي رقما معينا لكل واحد منها. وقبل اختراع "يونِكود"، كان هناك مئات الأنظمة للتشفير وتخصيص هذه الأرقام للمحارف، ولم يوجد نظام تشفير واحد يحتوي على جميع المحارف الضرورية. وعلى سبيل المثال، فإن الاتحاد الأوروبي لوحده، احتوى العديد من الشفرات المختلفة ليغطي جميع اللغات المستخدمة في الاتحاد. وحتى لو اعتبرنا لغة واحدة، كاللغة الإنجليزية، فإن جدول شفرة واحد لم يكف لاستيعاب جميع الأحرف وعلامات الترقيم والرموز الفنية والعلمية الشائعة الاستعمال.
وتجدر الملاحظة أن أنظمة التشفير المختلفة تتعارض مع بعضها البعض. وبعبارة أخرى، يمكن أن يستخدِم جدولي شفرة نفس الرقم لتمثيل محرفين مختلفين، أو رقمين مختلفين لتمثيل نفس المحرف. ولو أخذنا أي جهاز حاسوب، وبخاصة جهاز النادل (server)، فيجب أن تكون لديه القدرة على التعامل مع عدد كبير من الشفرات المختلفة، ويتم تصميمه على هذا الأساس. ومع ذلك، فعندما تمر البيانات عبر أنظمة مختلفة، توجد هناك خطورة لضياع أو تحريف بعض هذه البيانات.
"يونِكود" تغير هذا كليـا !
تخصص الشفرة الموحدة "يونِكود" رقما وحيدا لكل محرف في جميع اللغات العالمية، وذلك بغض النظر عن نوع الحاسوب أو البرامج المستخدمة. وقد تـم تبني مواصفة "يونِكود" مــن قبـل قادة الصانعين لأنظمة الحواسيب فـي العالم، مثل شركات آي.بي.إم. (IBM)، أبـل (APPLE)، هِيـْولِـت بـاكـرد (Hewlett-Packard) ، مايكروسوفت (Microsoft)، أوراكِـل (Oracle) ، صن (Sun) وغيرها. كما أن المواصفات والمقاييس الحديثة (مثل لغة البرمجة "جافا" "JAVA" ولغة "إكس إم إل" "XML" التي تستخدم لبرمجة الانترنيت) تتطلب استخدام "يونِكود". علاوة على ذلك ، فإن "يونِكود" هي الطـريـقـة الرسـمية لتطبيق المقيـاس الـعـالـمي إيزو ١٠٦٤٦ (ISO 10646) .
إن بزوغ مواصفة "يونِكود" وتوفُّر الأنظمة التي تستخدمه وتدعمه، يعتبر من أهم الاختراعات الحديثة في عولمة البرمجيات لجميع اللغات في العالم. وإن استخدام "يونِكود" في عالم الانترنيت سيؤدي إلى توفير كبير مقارنة مع استخدام المجموعات التقليدية للمحارف المشفرة. كما أن استخدام "يونِكود" سيُمكِّن المبرمج من كتابة البرنامج مرة واحدة، واستخدامه على أي نوع من الأجهزة أو الأنظمة، ولأي لغة أو دولة في العالم أينما كانت، دون الحاجة لإعادة البرمجة أو إجراء أي تعديل. وأخيرا، فإن استخدام "يونِكود" سيمكن البيانات من الانتقال عبر الأنظمة والأجهزة المختلفة دون أي خطورة لتحريفها، مهما تعددت الشركات الصانعة للأنظمة واللغات، والدول التي تمر من خلالها هذه البيانات.

View file

@ -0,0 +1,19 @@
What is Unicode?
Unicode provides a unique number for every character,
no matter what the platform,
no matter what the program,
no matter what the language.
Fundamentally, computers just deal with numbers. They store letters and other characters by assigning a number for each one. Before Unicode was invented, there were hundreds of different encoding systems for assigning these numbers. No single encoding could contain enough characters: for example, the European Union alone requires several different encodings to cover all its languages. Even for a single language like English no single encoding was adequate for all the letters, punctuation, and technical symbols in common use.
These encoding systems also conflict with one another. That is, two encodings can use the same number for two different characters, or use different numbers for the same character. Any given computer (especially servers) needs to support many different encodings; yet whenever data is passed between different encodings or platforms, that data always runs the risk of corruption.
Unicode is changing all that!
Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language. The Unicode Standard has been adopted by such industry leaders as Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys and many others. Unicode is required by modern standards such as XML, Java, ECMAScript (JavaScript), LDAP, CORBA 3.0, WML, etc., and is the official way to implement ISO/IEC 10646. It is supported in many operating systems, all modern browsers, and many other products. The emergence of the Unicode Standard, and the availability of tools supporting it, are among the most significant recent global software technology trends.
Incorporating Unicode into client-server or multi-tiered applications and websites offers significant cost savings over the use of legacy character sets. Unicode enables a single software product or a single website to be targeted across multiple platforms, languages and countries without re-engineering. It allows data to be transported through many different systems without corruption.
About the Unicode Consortium
The Unicode Consortium is a non-profit organization founded to develop, extend and promote use of the Unicode Standard, which specifies the representation of text in modern software products and standards. The membership of the consortium represents a broad spectrum of corporations and organizations in the computer and information processing industry. The consortium is supported financially solely through membership dues. Membership in the Unicode Consortium is open to organizations and individuals anywhere in the world who support the Unicode Standard and wish to assist in its extension and implementation.
For more information, see the Glossary, Unicode Enabled Products, Technical Introduction and Useful Resources.

View file

@ -0,0 +1,20 @@
Τι είναι το Unicode?
Η κωδικοσελίδα Unicode προτείνει έναν και μοναδικό αριθμό για κάθε χαρακτήρα,
ανεξάρτητα από το λειτουργικό σύστημα,
ανεξάρτητα από το λογισμικό,
ανεξάρτητα από την γλώσσα.
Οι ηλεκτρονικοί υπολογιστές, σε τελική ανάλυση, χειρίζονται απλώς αριθμούς. Αποθηκεύουν γράμματα και άλλους χαρακτήρες αντιστοιχώντας στο καθένα τους από έναν αριθμό (ονομάζουμε μία τέτοια αντιστοιχία κωδικοσελίδα). Πριν την εφεύρεση του Unicode, υπήρχαν εκατοντάδες διαφορετικές κωδικοσελίδες. Λόγω περιορισμών μεγέθους όμως, σε καμία κωδικοσελίδα δεν χωρούσαν αρκετοί χαρακτήρες: λόγου χάριν, η Ευρωπαϊκή Ένωση χρειαζόταν πλήθος διαφορετικών κωδικοσελίδων για να καλύψει όλες τις γλώσσες των χωρών-μελών της. Ακόμα και για μία και μόνη γλώσσα, όπως π.χ. τα Αγγλικά, μία κωδικοσελίδα δεν επαρκούσε για να καλύψει όλα τα γράμματα, σημεία στίξης και τεχνικά σύμβολα ευρείας χρήσης.
Εκτός αυτού, οι κωδικοσελίδες αυτές διαφωνούσαν μεταξύ τους. Έτσι, δύο κωδικοσελίδες μπορούσαν κάλλιστα να χρησιμοποιούν τον ίδιο αριθμό για δύο διαφορετικούς χαρακτήρες, ή να χρησιμοποιούν διαφορετικούς αριθμούς για τον ίδιο χαρακτήρα. Κάθε υπολογιστής (και ιδίως εάν ήταν διακομιστής) έπρεπε να υποστηρίζει πλήθος διαφορετικών κωδικοσελίδων· ταυτόχρονα κάθε φορά που δεδομένα μεταφέρονταν μεταξύ διαφορετικών κωδικοσελίδων ή λειτουργικών συστημάτων, τα δεδομένα αυτά κινδύνευαν να αλλοιωθούν.
Το Unicode αλλάζει αυτή την κατάσταση!
Το Unicode προτείνει έναν μοναδικό αριθμό για κάθε χαρακτήρα, ανεξάρτητα από το λειτουργικό σύστημα, ανεξάρτητα από το λογισμικό, ανεξάρτητα από την γλώσσα. Την κωδικοσελίδα Unicode έχουν ασπασθεί κορυφαίοι παράγοντες του χώρου των λογισμικών όπως οι: Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys και πολλοί άλλοι. Το Unicode απαιτούν πολλές σύγχρονες τυποποιήσεις όπως οι: XML, Java, ECMAScript (JavaScript), LDAP, CORBA 3.0, WML, κ.λπ., και είναι η επίσημη μέθοδος εφαρμογής της τυποποίησης ISO/IEC 10646. Υποστηρίζεται από πολλά λειτουργικά συστήματα, όλους τους σύχρονους περιηγητές Διαδικτύου, και πολλά άλλα προϊόντα. Η εμφάνιση της κωδικοσελίδας Unicode, και η διαθεσιμότητα εργαλείων που να την υποστηρίζουν είναι από τις σημαντικότερες εξελίξεις της πρόσφατης τεχνολογίας λογισμικών.
Η ενσωμάτωση του Unicode σε εφαρμογές πελάτη-διακομιστή ή "multi-tiered" προσφέρει σημαντικές οικονομίες σε σχέση με τις ως τώρα υπάρχουσες κωδικοσελίδες. Χάρις στο Unicode ένα και μόνο προϊόν ή μία και μόνη τοποθεσία Διαδικτύου μπορεί να επικοινωνεί με διάφορα λειτουργικά συστήματα, σε διάφορες γλώσσες και χώρες, χωρίς την ανάγκη επαναπρογραμματισμού. Γίνεται έτσι δυνατή η μεταφορά δεδομένων ανάμεσα σε πλήθος διαφορετικών συστημάτων δίχως κίνδυνο αλλοίωσης.
Σχετικά με το Κονσόρτιουμ Unicode
Tο Κονσόρτιουμ Unicode είναι ένας κοινωφελής οργανισμός· ιδρύθηκε για να αναπτύξει, να επεκτείνει και να μεταδώσει την χρήση της κωδικοσελίδας Unicode που καθορίζει την αναπαράσταση κειμένου σε σύγχρονα λογισμικά προϊόντα και τυποποιήσεις. Μεγάλος αριθμός εταιρειών και οργανισμών της διεθνούς βιομηχανίας υπολογιστών και λογισμικών είναι μέλη του Κονσόρτιουμ Unicode. Το Κονσόρτιουμ χρηματοδοτείται μόνο από τις συνδρομές των μελών του. Μέλος του κονσόρτιουμ Unicode μπορεί να γίνει οιοσδήποτε (οργανισμός, εταιρεία ή ιδιώτης, οπουδήποτε στον κόσμο) που να υποστηρίζει την κωδικοσελίδα Unicode και να επιθυμεί να συνδράμει στην επέκταση και στην εφαρμογή της.
Για περαιτέρω πληροφορίες, βλέπε τις εξής ιστοσελίδες: Γλωσσάρι, Δείγματα προϊόντων συμβατών με το Unicode, Τεχνική Εισαγωγή και Χρήσιμες πηγές πληροφοριών.

View file

@ -0,0 +1,19 @@
יוניקוד מקצה מספר ייחודי לכל תו,
לא משנה על איזו פלטפורמה,
לא משנה באיזו תוכנית,
ולא משנה באיזו שפה.
באופן בסיסי, מחשבים עוסקים רק במספרים. הם מאחסנים אותיות ותווים אחרים על-ידי הקצאת מספר לכל אחד מהם. בטרם הומצא היוניקוד, היו מאות מערכות קידוד שונות להקצאת המספרים הללו. אף לא אחת מהן יכלה להכיל כמות תווים מספקת. לדוגמא: רק לאיחוד האירופאי נדרשים כמה סוגי קידודים שונים על מנת לכסות את כל השפות המדוברות בו. יתירה מזאת אף לשפה בודדת, כמו אנגלית למשל, לא היה די במערכת קידוד אחת בעבור כל האותיות, סימני הפיסוק והסמלים הטכניים שבשימוש שוטף.
מערכות קידוד אלו אף סותרות זו את זו. כלומר, שני קידודים יכולים להשתמש באותו מספר לשני תוים נבדלים, או להשתמש במספרים שונים לאותו תו. על כל מחשב (ובמיוחד שרתים) לתמוך במספר רב של מערכות קידוד שונות; אולם כל אימת שנתונים עוברים בין מערכות קידוד או פלטפורמות שונות קיים הסיכון שייפגמו.
יוניקוד משנה את כל זה!
יוניקוד מקצה מספר ייחודי לכל תו, ללא תלות בפלטפורמה, בתוכנית, או בשפה. תקן היוניקוד אומץ על-ידי המובילים בתעשייה כמו Apple‏, HP‏, IBM‏, JustSystem‏, Microsoft‏, Oracle‏, SAP‏, Sun‏, Sybase‏, Unisys‏ ורבים אחרים. יוניקוד נדרש על-ידי תקנים מודרניים כמו XML‏, Java‏, ECMAScript (JavaScript)‎‏, LDAP‏, CORBA 3.0‎‏, WML‏ וכדומה, ומהווה למעשה את היישום הרשמי של תקן ISO/IEC 10646. הוא נתמך על ידי מערכות הפעלה רבות, כל הדפדפנים החדישים, ומוצרים רבים אחרים. הופעת תקן היוניקוד וזמינות הכלים התומכים בו נמנות עם המגמות הכלל-עולמיות החשובות ביותר, אשר מסתמנות לאחרונה בטכנולוגיית התוכנה.
שילוב יוניקוד ביישומי שרת-לקוח או ביישומים רבי-שכבות ובאתרי אינטרנט מאפשר חיסכון ניכר בעלויות לעומת השימוש בסדרות התווים המסורתיות. הודות ליוניקוד, מוצר תוכנה אחד או אתר יחיד ברשת יכול להרחיב את יעדיו למגוון פלטפורמות, ארצות ושפות ללא צורך בשינויים מרחיקים. יוניקוד מאפשר מעבר נתונים דרך מערכות רבות ושונות מבלי שייפגמו.
פרטים אודות הקונסורציום של יוניקוד (Unicode Consortium)
הקונסורציום של יוניקוד הוא ארגון ללא מטרת רווח שנוסד כדי לפתח, להרחיב ולקדם את השימוש בתקן יוניקוד, אשר מגדיר את ייצוג הטקסט במוצרי תוכנה ותקנים מודרניים. חברים בקונסורציום מגוון רחב של תאגידים וארגונים בתעשיית המחשבים ועיבוד המידע. הקונסורציום ממומן על-ידי דמי-חבר בלבד. החברות בקונסורציום יוניקוד פתוחה לארגונים ולאנשים פרטיים, בכל רחבי העולם, אשר תומכים בתקן יוניקוד ומעוניינים לסייע בהתפתחותו והטמעתו.
למידע נוסף, ראה מילון מונחים, רשימה חלקית של מוצרים מותאמים ליוניקוד, מבוא טכני ו- חומרי עזר [קישורים באנגלית].

View file

@ -0,0 +1,19 @@
यूनिकोड क्या है?
यूनिकोड प्रत्येक अक्षर के लिए एक विशेष नम्बर प्रदान करता है,
चाहे कोई भी प्लैटफॉर्म हो,
चाहे कोई भी प्रोग्राम हो,
चाहे कोई भी भाषा हो।
कम्प्यूटर, मूल रूप से, नंबरों से सम्बंध रखते हैं। ये प्रत्येक अक्षर और वर्ण के लिए एक नंबर निर्धारित करके अक्षर और वर्ण संग्रहित करते हैं। यूनिकोड का आविष्कार होने से पहले, ऐसे नंबर देने के लिए सैंकडों विभिन्न संकेत लिपि प्रणालियां थीं। किसी एक संकेत लिपि में पर्याप्त अक्षर नहीं हो सकते हैं : उदाहरण के लिए, यूरोपिय संघ को अकेले ही, अपनी सभी भाषाऒं को कवर करने के लिए अनेक विभिन्न संकेत लिपियों की आवश्यकता होती है। अंग्रेजी जैसी भाषा के लिए भी, सभी अक्षरों, विरामचिन्हों और सामान्य प्रयोग के तकनीकी प्रतीकों हेतु एक ही संकेत लिपि पर्याप्त नहीं थी।
ये संकेत लिपि प्रणालियां परस्पर विरोधी भी हैं। इसीलिए, दो संकेत लिपियां दो विभिन्न अक्षरों के लिए, एक ही नंबर प्रयोग कर सकती हैं, अथवा समान अक्षर के लिए विभिन्न नम्बरों का प्रयोग कर सकती हैं। किसी भी कम्प्यूटर (विशेष रूप से सर्वर) को विभिन्न संकेत लिपियां संभालनी पड़ती है; फिर भी जब दो विभिन्न संकेत लिपियों अथवा प्लैटफॉर्मों के बीच डाटा भेजा जाता है तो उस डाटा के हमेशा खराब होने का जोखिम रहता है।
यूनिकोड से यह सब कुछ बदल रहा है!
यूनिकोड, प्रत्येक अक्षर के लिए एक विशेष नंबर प्रदान करता है, चाहे कोई भी प्लैटफॉर्म हो, चाहे कोई भी प्रोग्राम हो, चाहे कोई भी भाषा हो। यूनिकोड स्टैंडर्ड को ऐपल, एच.पी., आई.बी.एम., जस्ट सिस्टम, माईक्रोसॉफ्ट, औरेकल, सैप, सन, साईबेस, यूनिसिस जैसी उद्योग की प्रमुख कम्पनियों और कई अन्य ने अपनाया है। यूनिकोड की आवश्यकता आधुनिक मानदंडों, जैसे एक्स.एम.एल., जावा, एकमा स्क्रिप्ट (जावा स्क्रिप्ट), एल.डी.ए.पी., कोर्बा 3.0, डब्ल्यू.एम.एल. के लिए होती है और यह आई.एस.ओ./आई.ई.सी. 10646 को लागू करने का अधिकारिक तरीका है। यह कई संचालन प्रणालियों, सभी आधुनिक ब्राउजरों और कई अन्य उत्पादों में होता है। यूनिकोड स्टैंडर्ड की उत्पति और इसके सहायक उपकरणों की उपलब्धता, हाल ही के अति महत्वपूर्ण विश्वव्यापी सॉफ्टवेयर टेक्नोलॉजी रुझानों में से हैं।
यूनिकोड को ग्राहक-सर्वर अथवा बहु-आयामी उपकरणों और वेबसाइटों में शामिल करने से, परंपरागत उपकरणों के प्रयोग की अपेक्षा खर्च में अत्यधिक बचत होती है। यूनिकोड से एक ऐसा अकेला सॉफ्टवेयर उत्पाद अथवा अकेला वेबसाइट मिल जाता है, जिसे री-इंजीनियरिंग के बिना विभिन्न प्लैटफॉर्मों, भाषाओं और देशों में उपयोग किया जा सकता है। इससे डाटा को बिना किसी बाधा के विभिन्न प्रणालियों से होकर ले जाया जा सकता है।
यूनिकोड कन्सॉर्शियम के बारे में
यूनिकोड कन्सॉर्शियम, लाभ न कमाने वाला एक संगठन है जिसकी स्थापना यूनिकोड स्टैंडर्ड, जो आधुनिक सॉफ्टवेयर उत्पादों और मानकों में पाठ की प्रस्तुति को निर्दिष्ट करता है, के विकास, विस्तार और इसके प्रयोग को बढ़ावा देने के लिए की गई थी। इस कन्सॉर्शियम के सदस्यों में, कम्प्यूटर और सूचना उद्योग में विभिन्न निगम और संगठन शामिल हैं। इस कन्सॉर्शियम का वित्तपोषण पूर्णतः सदस्यों के शुल्क से किया जाता है। यूनिकोड कन्सॉर्शियम में सदस्यता, विश्व में कहीं भी स्थित उन संगठनों और व्यक्तियों के लिए खुली है जो यूनिकोड का समर्थन करते हैं और जो इसके विस्तार और कार्यान्वयन में सहायता करना चाहते हैं।
अधिक जानकारी के लिए, शब्दावली, सैम्पल यूनिकोड-सक्षम उत्पाद, तकनीकी परिचय और उपयोगी स्रोत देखिए।

View file

@ -0,0 +1,19 @@
ユニコードとは何か?
ユニコードは、すべての文字に固有の番号を付与します
プラットフォームには依存しません
プログラムにも依存しません
言語にも依存しません
コンピューターは、本質的には数字しか扱うことができません。コンピューターは、文字や記号などのそれぞれに番号を割り振ることによって扱えるようにします。ユニコードが出来るまでは、これらの番号を割り振る仕組みが何百種類も存在しました。どの一つをとっても、十分な文字を含んではいませんでした。例えば、欧州連合一つを見ても、そのすべての言語をカバーするためには、いくつかの異なる符号化の仕組みが必要でした。英語のような一つの言語に限っても、一つだけの符号化の仕組みでは、一般的に使われるすべての文字、句読点、技術的な記号などを扱うには不十分でした。
これらの符号化の仕組みは、相互に矛盾するものでもありました。二つの異なる符号化の仕組みが、二つの異なる文字に同一の番号を付けることもできるし、同じ文字に異なる番号を付けることもできるのです。どのようなコンピューターも(特にサーバーは)多くの異なった符号化の仕組みをサポートする必要があります。たとえデータが異なる符号化の仕組みやプラットフォームを通過しても、いつどこでデータが乱れるか分からない危険を冒すことのなるのです。
ユニコードはすべてを変えます
ユニコードは、プラットフォームに係わらず、プログラムに係わらず、言語に係わらず、すべての文字に独立した番号を与えます。ユニコード標準は、アップル、ヒューレットパッカード、IBM、ジャストシステム、マイクロソフト、オラクル、SAP、サン、サイベースなどの産業界の主導的企業と他の多くの企業に採用されています。ユニコードは、XML、Java、ECMAScript(JavaScript)、LDAP、CORBA 3.0などの最先端の標準の前提となっており、ユニコードを実装すれば、ISO/IEC 10646に適合することになります。ユニコードは、多くのオペレーティングシステムとすべての最新のブラウザーと他の多くの製品でサポートされています。ユニコード標準の出現とユニコードをサポートするツール類は、昨今顕著になっているソフトウエア技術のグローバル化の流れに対して、特に役に立っています。
ユニコードをクライアントサーバー型のアプリケーションや、多層構造を持つアプリケーション、ウェブサイトなどにに組み込むことで、従来の文字コードセットを用いるよりも明らかなコスト削減が可能です。ユニコードは、単一のソフトウエア製品、単一のウェブサイトに、何ら手を加えることなく、複数のプラットフォーム、複数の言語、複数の国をカバーすることが出来るのです。ユニコードは、データが多くの異なるシステムの間を、何の乱れもなしに転送することを可能とするのです。
ユニコードコンソーシアムについて
ユニコードコンソーシアムは、最新のソフトウエア製品と標準においてテキストを表現することを意味する“ユニコード標準”の構築、発展、普及、利用促進を目的として設立された非営利組織です。同コンソーシアムの会員は、コンピューターと情報処理に係わる広汎な企業や組織から構成されています。同コンソーシアムは、財政的には、純粋に会費のみによって運営されています。ユニコード標準を支持し、その拡張と実装を支援する世界中の組織や個人は、だれもがユニコードコンソーシアムの会員なることができます。
より詳しいことをお知りになりたい方は、Glossary, Unicode-Enabled Products, Technical Introduction および Useful Resourcesをご参照ください。

View file

@ -0,0 +1,19 @@
유니코드에 대해 ?
어떤 플랫폼,
어떤 프로그램,
어떤 언어에도 상관없이
유니코드는 모든 문자에 대해 고유 번호를 제공합니다.
기본적으로 컴퓨터는 숫자만 처리합니다. 글자나 다른 문자에도 숫자를 지정하여 저장합니다. 유니코드가 개발되기 전에는 이러한 숫자를 지정하기 위해 수백 가지의 다른 기호화 시스템을 사용했습니다. 단일 기호화 방법으로는 모든 문자를 포함할 수 없었습니다. 예를 들어 유럽 연합에서만 보더라도 모든 각 나라별 언어를 처리하려면 여러 개의 다른 기호화 방법이 필요합니다. 영어와 같은 단일 언어의 경우도 공통적으로 사용되는 모든 글자, 문장 부호 및 테크니컬 기호에 맞는 단일 기호화 방법을 갖고 있지 못하였습니다.
이러한 기호화 시스템은 또한 다른 기호화 시스템과 충돌합니다. 즉 두 가지 기호화 방법이 두 개의 다른 문자에 대해 같은 번호를 사용하거나 같은 문자에 대해 다른 번호를 사용할 수 있습니다. 주어진 모든 컴퓨터(특히 서버)는 서로 다른 여러 가지 기호화 방법을 지원해야 합니다. 그러나, 데이터를 서로 다른 기호화 방법이나 플랫폼 간에 전달할 때마다 그 데이터는 항상 손상의 위험을 겪게 됩니다.
유니코드로 모든 것을 해결할 수 있습니다!
유니코드는 사용 중인 플랫폼, 프로그램, 언어에 관계없이 문자마다 고유한 숫자를 제공합니다. 유니코드 표준은 Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys 및 기타 여러 회사와 같은 업계 선두주자에 의해 채택되었습니다. 유니코드는 XML, Java, ECMAScript(JavaScript), LDAP, CORBA 3.0, WML 등과 같이 현재 널리 사용되는 표준에서 필요하며 이는 ISO/IEC 10646을 구현하는 공식적인 방법입니다. 이는 많은 운영 체제, 요즘 사용되는 모든 브라우저 및 기타 많은 제품에서 지원됩니다. 유니코드 표준의 부상과 이를 지원하는 도구의 가용성은 최근 전 세계에 불고 있는 기술 경향에서 가장 중요한 부분을 차지하고 있습니다.
유니코드를 클라이언트-서버 또는 다중-연결 응용 프로그램과 웹 사이트에 통합하면 레거시 문자 세트 사용에 있어서 상당한 비용 절감 효과가 나타납니다. 유니코드를 통해 리엔지니어링 없이 다중 플랫폼, 언어 및 국가 간에 단일 소프트웨어 플랫폼 또는 단일 웹 사이트를 목표로 삼을 수 있습니다. 이를 사용하면 데이터를 손상 없이 여러 시스템을 통해 전송할 수 있습니다.
유니코드 콘소시엄에 대해
유니코드 콘소시엄은 비영리 조직으로서 현대 소프트웨어 제품과 표준에서 텍스트의 표현을 지정하는 유니코드 표준의 사용을 개발하고 확장하며 장려하기 위해 세워졌습니다. 콘소시엄 멤버쉽은 컴퓨터와 정보 처리 산업에 종사하고 있는 광범위한 회사 및 조직의 범위를 나타냅니다. 콘소시엄의 재정은 전적으로 회비에 의해 충당됩니다. 유니코드 컨소시엄에서의 멤버쉽은 전 세계 어느 곳에서나 유니코드 표준을 지원하고 그 확장과 구현을 지원하고자하는 조직과 개인에게 개방되어 있습니다.
더 자세한 내용은 용어집, 예제 유니코드 사용 가능 제품, 기술 정보 및 기타 유용한 정보를 참조하십시오.

View file

@ -0,0 +1,19 @@
Unicode คืออะไร?
Unicode กำหนดหมายเลขเฉพาะสำหรับทุกอักขระ
โดยไม่สนใจว่าเป็นแพล็ตฟอร์มใด
ไม่ขึ้นกับว่าจะเป็นโปรแกรมใด
และไม่ว่าจะเป็นภาษาใด
โดยพื้นฐานแล้ว, คอมพิวเตอร์จะเกี่ยวข้องกับเรื่องของตัวเลข. คอมพิวเตอร์จัดเก็บตัวอักษรและอักขระอื่นๆ โดยการกำหนดหมายเลขให้สำหรับแต่ละตัว. ก่อนหน้าที่๊ Unicode จะถูกสร้างขึ้น, ได้มีระบบ encoding อยู่หลายร้อยระบบสำหรับการกำหนดหมายเลขเหล่านี้. ไม่มี encoding ใดที่มีจำนวนตัวอักขระมากเพียงพอ: ยกตัวอย่างเช่น, เฉพาะในกลุ่มสหภาพยุโรปเพียงแห่งเดียว ก็ต้องการหลาย encoding ในการครอบคลุมทุกภาษาในกลุ่ม. หรือแม้แต่ในภาษาเดี่ยว เช่น ภาษาอังกฤษ ก็ไม่มี encoding ใดที่เพียงพอสำหรับทุกตัวอักษร, เครื่องหมายวรรคตอน และสัญลักษณ์ทางเทคนิคที่ใช้กันอยู่ทั่วไป.
ระบบ encoding เหล่านี้ยังขัดแย้งซึ่งกันและกัน. นั่นก็คือ, ในสอง encoding สามารถใช้หมายเลขเดียวกันสำหรับตัวอักขระสองตัวที่แตกต่างกัน,หรือใช้หมายเลขต่างกันสำหรับอักขระตัวเดียวกัน. ในระบบคอมพิวเตอร์ (โดยเฉพาะเซิร์ฟเวอร์) ต้องมีการสนับสนุนหลาย encoding; และเมื่อข้อมูลที่ผ่านไปมาระหว่างการเข้ารหัสหรือแพล็ตฟอร์มที่ต่างกัน, ข้อมูลนั้นจะเสี่ยงต่อการผิดพลาดเสียหาย.
Unicode จะเปลี่ยนแปลงสิ่งเหล่านั้นทั้งหมด!
Unicode กำหนดหมายเลขเฉพาะสำหรับแต่ละอักขระ, โดยไม่สนใจว่าเป็นแพล็ตฟอร์มใด, ไม่ขึ้นกับว่าจะเป็นโปรแกรมใดและไม่ว่าจะเป็นภาษาใด. มาตรฐาน Unicode ได้ถูกนำไปใช้โดยผู้นำในอุตสาหกรรม เช่น Apple, HP, IBM, JustSystem, Microsoft, Oracle, SAP, Sun, Sybase, Unisys และอื่นๆ อีกมาก. Unicode เป็นสิ่งที่จำเป็นสำหรับมาตรฐานใหม่ๆ เช่น XML, Java, ECMAScript (JavaScript), LDAP, CORBA 3.0, WML ฯลฯ., และเป็นแนวทางอย่างเป็นทางการในการทำ ISO/IEC 10646. Unicode ได้รับการสนับสนุนในระบบปฏิบัติการจำนวนมาก, บราวเซอร์ใหม่ๆ ทกตัว, และผลิตภัณฑ์อื่นๆ อีกมาก. การเกิดขึ้นของ Unicode Standard และทูลส์ต่างๆ ที่มีในการสนับสนุน Unicode, เป็นหนึ่งในแนวโน้มทางเทคโนโลยีซอฟต์แวร์ระดับโลกที่มีความสำคัญที่สุด.
การรวม Unicode เข้าไปในระบบไคลเอ็นต์-เซิร์ฟเวอร์ หรือแอ็พพลิเคชันแบบ multi-tiered และเว็บไซต์ จะทำให้เกิดการประหยัดค่าใช้จ่ายมากกว่าการใช้ชุดอักขระแบบเดิม. Unicode ทำให้ผลิตภัณฑ์ซอฟต์แวร์หนึ่งเดียว หรือเว็บไซต์แห่งเดียว รองรับได้หลายแพล็ตฟอร์ม, หลายภาษาและหลายประเทศโดยไม่ต้องทำการรื้อปรับระบบ. Unicode ยังทำให้ข้อมูลสามารถเคลื่อนย้ายไปมาในหลายๆ ระบบโดยไม่เกิดความผิดพลาดเสียหาย.
เกี่ยวกับ Unicode Consortium
Unicode Consortium เป็นองค์กรไม่แสวงหากำไรที่ก่อตั้งขึ้นเพื่อพัฒนา, ขยายและส่งเสริมการใช้ Unicode Standard, ซึ่งกำหนดรูปแบบการแทนค่าของข้อความในผลิตภัณฑ์ซอฟต์แวร์และมาตรฐานใหม่ๆ. สมาชิกของสมาคมเป็นตัวแทนจากบริษัทและองค์กรในอุตสาหกรรมคอมพิวเตอร์และการประมวลผลสารสนเทศ. สมาคมได้รับการสนับสนุนทางการเงินผ่านทางค่าธรรมเนียมของการเป็นสมาชิกเท่านั้น. สมาชิกภาพของ Unicode Consortium เปิดกว้างสำหรับองค์กรหรือบุคคลใดๆ ในโลกที่ต้องการสนับสนุน Unicode Standard และช่วยเหลือการขยายตัวและการนำ Unicode ไปใช้งาน.
สำหรับข้อมูลเพิ่มเติม, ให้ดูที่ Glossary, Sample Unicode-Enabled Products, Technical Introduction และ Useful Resources.

View file

@ -0,0 +1,461 @@
/*
* Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Polygon;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.WritableRaster;
import javax.swing.SwingUtilities;
import j2dbench.tests.GraphicsTests;
import j2dbench.tests.ImageTests;
public abstract class Destinations extends Option.Enable {
public static Group.EnableSet destroot;
public static Group frameroot;
public static Group bufimgdestroot;
public static Group compatimgdestroot;
public static Group volimgdestroot;
public static void init() {
destroot = new Group.EnableSet(TestEnvironment.globaloptroot,
"dest", "Output Destination Options");
new OffScreen();
frameroot = new Group.EnableSet(destroot, "frame", "Output to Frame");
frameroot.setHorizontal();
new Screen(false, false);
if (ImageTests.hasOpacityWindow) {
new Screen(true, false);
}
if (ImageTests.hasShapedWindow) {
new Screen(false, true);
}
if (ImageTests.hasShapedWindow && ImageTests.hasOpacityWindow) {
new Screen(true, true);
}
if (GraphicsTests.hasGraphics2D) {
if (ImageTests.hasCompatImage) {
compatimgdestroot =
new Group.EnableSet(destroot, "compatimg",
"Compatible Image Destinations");
compatimgdestroot.setHorizontal();
new CompatImg();
new CompatImg(Transparency.OPAQUE);
new CompatImg(Transparency.BITMASK);
new CompatImg(Transparency.TRANSLUCENT);
}
if (ImageTests.hasVolatileImage) {
volimgdestroot = new Group.EnableSet(destroot, "volimg",
"Output to Volatile Image");
volimgdestroot.setHorizontal();
new VolatileImg();
if (ImageTests.hasTransparentVolatileImage) {
new VolatileImg(Transparency.OPAQUE);
new VolatileImg(Transparency.BITMASK);
new VolatileImg(Transparency.TRANSLUCENT);
}
}
bufimgdestroot = new Group.EnableSet(destroot, "bufimg",
"BufferedImage Destinations");
new BufImg(BufferedImage.TYPE_INT_RGB);
new BufImg(BufferedImage.TYPE_INT_ARGB);
new BufImg(BufferedImage.TYPE_INT_ARGB_PRE);
new BufImg(BufferedImage.TYPE_3BYTE_BGR);
new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
new BufImg(BufferedImage.TYPE_BYTE_GRAY);
new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
new BufImg(BufferedImage.TYPE_4BYTE_ABGR_PRE);
new CustomImg();
}
}
public Destinations(Group parent,
String nodename, String description,
boolean defenabled)
{
super(parent, nodename, description, defenabled);
}
public void modifyTest(TestEnvironment env) {
setDestination(env);
}
public void restoreTest(TestEnvironment env) {
env.setTestImage(null);
}
public String getAbbreviatedModifierDescription(Object val) {
return "to "+getModifierValueName(val);
}
public abstract void setDestination(TestEnvironment env);
public static class Screen extends Destinations {
private boolean opacity;
private boolean shaped;
public Screen(boolean opacity, boolean shaped) {
super(frameroot, getDescription(opacity,shaped),
getLongDescription(opacity,shaped), false);
this.opacity = opacity;
this.shaped = shaped;
}
private static String getDescription(boolean opacity, boolean shaped){
if (opacity && shaped) {
return "shapedtransframe";
}
if (shaped) {
return "shapedframe";
}
if (opacity) {
return "transframe";
}
return "defaultframe";
}
private static String getLongDescription(boolean opacity, boolean shaped){
if (opacity && shaped) {
return "Translucent and Shaped";
}
if (shaped) {
return "Shaped";
}
if (opacity) {
return "Translucent";
}
return "Default";
}
public String getModifierValueName(Object val) {
if (opacity && shaped) {
return "Translucent and Shaped Frame";
}
if (shaped) {
return "Shaped Frame";
}
if (opacity) {
return "Translucent Frame";
}
return "Default Frame";
}
public void setDestination(TestEnvironment env) {
env.setTestImage(null);
}
public void modifyTest(TestEnvironment env) {
setDestination(env);
Frame frame = (Frame) SwingUtilities.getWindowAncestor(env.comp);
if (frame != null && (opacity || shaped)) {
frame.dispose();
frame.setUndecorated(true);
int w = frame.getWidth();
int h = frame.getHeight();
if (shaped) {
Polygon p = new Polygon();
p.addPoint(0, 0);
p.addPoint(w, 0);
p.addPoint(0, h);
p.addPoint(w, h);
p.addPoint(0, 0);
frame.setShape(p);
}
if (opacity) {
frame.setOpacity(0.5f);
}
frame.setVisible(true);
}
}
public void restoreTest(TestEnvironment env) {
env.setTestImage(null);
Frame frame = (Frame) SwingUtilities.getWindowAncestor(env.comp);
if (frame != null && (opacity || shaped)) {
frame.dispose();
frame.setShape(null);
frame.setOpacity(1);
frame.setUndecorated(false);
frame.setVisible(true);
}
}
}
public static class OffScreen extends Destinations {
public OffScreen() {
super(destroot, "offscreen", "Output to OffScreen Image", false);
}
public String getModifierValueName(Object val) {
return "OffScreen";
}
public void setDestination(TestEnvironment env) {
Component c = env.getCanvas();
env.setTestImage(c.createImage(env.getWidth(), env.getHeight()));
}
}
public static class CompatImg extends Destinations {
int transparency;
public static String[] ShortNames = {
"compatimg",
"opqcompatimg",
"bmcompatimg",
"transcompatimg",
};
public static String[] ShortDescriptions = {
"Default",
"Opaque",
"Bitmask",
"Translucent",
};
public static String[] LongDescriptions = {
"Default Compatible Image",
"Opaque Compatible Image",
"Bitmask Compatible Image",
"Translucent Compatible Image",
};
public static String[] ModifierNames = {
"CompatImage()",
"CompatImage(Opaque)",
"CompatImage(Bitmask)",
"CompatImage(Translucent)",
};
public CompatImg() {
this(0);
}
public CompatImg(int transparency) {
super(compatimgdestroot,
ShortNames[transparency],
ShortDescriptions[transparency],
false);
this.transparency = transparency;
}
public String getModifierValueName(Object val) {
return ModifierNames[transparency];
}
public void setDestination(TestEnvironment env) {
Component c = env.getCanvas();
GraphicsConfiguration gc = c.getGraphicsConfiguration();
int w = env.getWidth();
int h = env.getHeight();
if (transparency == 0) {
env.setTestImage(gc.createCompatibleImage(w, h));
} else {
env.setTestImage(gc.createCompatibleImage(w, h, transparency));
}
}
}
public static class VolatileImg extends Destinations {
private final int transparency;
public static final String[] ShortNames = {
"volimg",
"opqvolimg",
"bmvolimg",
"transvolimg",
};
public static final String[] ShortDescriptions = {
"Default",
"Opaque",
"Bitmask",
"Translucent",
};
public static final String[] LongDescriptions = {
"Default VolatileImg Image",
"Opaque VolatileImg Image",
"Bitmask VolatileImg Image",
"Translucent VolatileImg Image",
};
public static final String[] ModifierNames = {
"VolatileImg()",
"VolatileImg(Opaque)",
"VolatileImg(Bitmask)",
"VolatileImg(Translucent)",
};
public VolatileImg() {
this(0);
}
public VolatileImg(final int transparency) {
super(volimgdestroot,
ShortNames[transparency],
ShortDescriptions[transparency],
false);
this.transparency = transparency;
}
public String getModifierValueName(final Object val) {
return ModifierNames[transparency];
}
public void setDestination(final TestEnvironment env) {
Component c = env.getCanvas();
GraphicsConfiguration gc = c.getGraphicsConfiguration();
int w = env.getWidth();
int h = env.getHeight();
if (transparency == 0) {
env.setTestImage(gc.createCompatibleVolatileImage(w, h));
} else {
env.setTestImage(gc.createCompatibleVolatileImage(w, h, transparency));
}
}
}
public static class BufImg extends Destinations {
int type;
Image img;
public static String[] ShortNames = {
"custom",
"IntXrgb",
"IntArgb",
"IntArgbPre",
"IntXbgr",
"3ByteBgr",
"4ByteAbgr",
"4ByteAbgrPre",
"Short565",
"Short555",
"ByteGray",
"ShortGray",
"ByteBinary",
"ByteIndexed",
};
public static String[] Descriptions = {
"Custom Image",
"32-bit XRGB Packed Image",
"32-bit ARGB Packed Image",
"32-bit ARGB Alpha Premultiplied Packed Image",
"32-bit XBGR Packed Image",
"3-byte BGR Component Image",
"4-byte ABGR Component Image",
"4-byte ABGR Alpha Premultiplied Component Image",
"16-bit 565 RGB Packed Image",
"15-bit 555 RGB Packed Image",
"8-bit Grayscale Image",
"16-bit Grayscale Image",
"1-bit Binary Image",
"8-bit Indexed Image",
};
public BufImg(int type) {
super(bufimgdestroot, ShortNames[type], Descriptions[type], false);
this.type = type;
}
public String getModifierValueName(Object val) {
return "BufImg("+getNodeName()+")";
}
public void setDestination(TestEnvironment env) {
if (img == null) {
img = new BufferedImage(env.getWidth(), env.getHeight(), type);
}
env.setTestImage(img);
}
}
public static class CustomImg extends Destinations {
private Image img;
public CustomImg() {
super(bufimgdestroot,
"custom",
"Custom (3-float RGB) Image",
false);
}
public String getModifierValueName(Object val) {
return "CustomImg";
}
public void setDestination(TestEnvironment env) {
if (img == null) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
ComponentColorModel cm =
new ComponentColorModel(cs, false, false,
Transparency.OPAQUE,
DataBuffer.TYPE_FLOAT);
WritableRaster raster =
cm.createCompatibleWritableRaster(env.getWidth(),
env.getHeight());
img = new BufferedImage(cm, raster, false, null);
}
env.setTestImage(img);
}
}
}

View file

@ -0,0 +1,355 @@
/*
* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
import java.io.PrintWriter;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.border.TitledBorder;
import java.util.NoSuchElementException;
import j2dbench.ui.CompactLayout;
import j2dbench.ui.EnableButton;
public class Group extends Node {
public static Group root = new Group();
private Node children;
private boolean tabbed;
private boolean hidden;
private boolean horizontal;
private Boolean bordered;
private int tabPlacement;
private Group() {
setTabbed(JTabbedPane.LEFT);
}
public Group(String nodeName, String description) {
this(root, nodeName, description);
}
public Group(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
public void addChild(Node child) {
Node prev = null;
for (Node node = children; node != null; node = node.getNext()) {
if (node.getNodeName().equalsIgnoreCase(child.getNodeName())) {
throw new RuntimeException("duplicate child added");
}
prev = node;
}
if (prev == null) {
children = child;
} else {
prev.setNext(child);
}
}
public Node.Iterator getChildIterator() {
return new ChildIterator();
}
public Node.Iterator getRecursiveChildIterator() {
return new RecursiveChildIterator();
}
public Node getFirstChild() {
return children;
}
public boolean isBordered() {
if (bordered == null) {
return (getParent() == null || !getParent().isTabbed());
}
return bordered.booleanValue();
}
public boolean isTabbed() {
return tabbed;
}
public boolean isHidden() {
return hidden;
}
public boolean isHorizontal() {
return horizontal;
}
public void setBordered(boolean b) {
bordered = b ? Boolean.TRUE : Boolean.FALSE;
}
public void setTabbed() {
setTabbed(JTabbedPane.TOP);
}
public void setTabbed(int tabPlacement) {
this.tabbed = true;
this.tabPlacement = tabPlacement;
}
public void setHidden() {
hidden = true;
}
public void setHorizontal() {
horizontal = true;
}
public void traverse(Visitor v) {
super.traverse(v);
for (Node node = children; node != null; node = node.getNext()) {
node.traverse(v);
}
}
public void restoreDefault() {
}
public String setOption(String key, String value) {
int index = key.indexOf('.');
String subkey;
if (index < 0) {
subkey = "";
} else {
subkey = key.substring(index+1);
key = key.substring(0, index);
}
for (Node node = children; node != null; node = node.getNext()) {
if (node.getNodeName().equalsIgnoreCase(key)) {
return node.setOption(subkey, value);
}
}
return "Key failed to match an existing option";
}
public void write(PrintWriter pw) {
}
public JComponent getJComponent() {
if (isHidden()) {
return null;
} else if (isTabbed()) {
JTabbedPane jtp = new JTabbedPane(tabPlacement);
for (Node node = children; node != null; node = node.getNext()) {
JComponent comp = node.getJComponent();
if (comp != null) {
jtp.addTab(node.getDescription(), comp);
}
}
return jtp;
} else {
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p,
horizontal
? BoxLayout.X_AXIS
: BoxLayout.Y_AXIS));
p.setLayout(new CompactLayout(horizontal));
if (getDescription() != null && isBordered()) {
p.setBorder(new TitledBorder(getDescription()));
addEnableButtons(p);
}
for (Node node = children; node != null; node = node.getNext()) {
JComponent comp = node.getJComponent();
if (comp != null) {
p.add(comp);
}
}
return new JScrollPane(p);
}
}
public void addEnableButtons(JPanel p) {
p.add(new EnableButton(this, EnableButton.DEFAULT));
p.add(new EnableButton(this, EnableButton.CLEAR));
p.add(new EnableButton(this, EnableButton.INVERT));
p.add(new EnableButton(this, EnableButton.SET));
}
public static void restoreAllDefaults() {
root.traverse(new Visitor() {
public void visit(Node node) {
node.restoreDefault();
}
});
}
public static void writeAll(final PrintWriter pw) {
root.traverse(new Visitor() {
public void visit(Node node) {
node.write(pw);
}
});
pw.flush();
}
public static String setOption(String s) {
int index = s.indexOf('=');
if (index < 0) {
return "No value specified";
}
String key = s.substring(0, index);
String value = s.substring(index+1);
return root.setOption(key, value);
}
public String toString() {
return "Group("+getTreeName()+")";
}
public class ChildIterator implements Node.Iterator {
protected Node cur = getFirstChild();
public boolean hasNext() {
return (cur != null);
}
public Node next() {
Node ret = cur;
if (ret == null) {
throw new NoSuchElementException();
}
cur = cur.getNext();
return ret;
}
}
public class RecursiveChildIterator extends ChildIterator {
Node.Iterator subiterator;
public boolean hasNext() {
while (true) {
if (subiterator != null && subiterator.hasNext()) {
return true;
}
if (cur instanceof Group) {
subiterator = ((Group) cur).getRecursiveChildIterator();
cur = cur.getNext();
} else {
subiterator = null;
return super.hasNext();
}
}
}
public Node next() {
if (subiterator != null) {
return subiterator.next();
} else {
return super.next();
}
}
}
public static class EnableSet extends Group implements Modifier {
public EnableSet() {
super();
}
public EnableSet(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
public Modifier.Iterator getIterator(TestEnvironment env) {
return new EnableIterator();
}
public void modifyTest(TestEnvironment env, Object val) {
((Option.Enable) val).modifyTest(env);
env.setModifier(this, val);
}
public void restoreTest(TestEnvironment env, Object val) {
((Option.Enable) val).restoreTest(env);
env.removeModifier(this);
}
public String getAbbreviatedModifierDescription(Object val) {
Option.Enable oe = (Option.Enable) val;
return oe.getAbbreviatedModifierDescription(Boolean.TRUE);
}
public String getModifierValueName(Object val) {
Option.Enable oe = (Option.Enable) val;
return oe.getModifierValueName(Boolean.TRUE);
}
public class EnableIterator implements Modifier.Iterator {
Node.Iterator childiterator = getRecursiveChildIterator();
Option.Enable curval;
public boolean hasNext() {
if (curval != null) {
return true;
}
while (childiterator.hasNext()) {
Node node = childiterator.next();
if (node instanceof Option.Enable) {
curval = (Option.Enable) node;
if (curval.isEnabled()) {
return true;
}
curval = null;
}
}
return false;
}
public Object next() {
if (curval == null) {
if (!hasNext()) {
throw new NoSuchElementException();
}
}
Object ret = curval;
curval = null;
return ret;
}
}
}
}

View file

@ -0,0 +1,821 @@
/*
* Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.awt.Frame;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.text.SimpleDateFormat;
import java.util.Date;
import j2dbench.tests.GraphicsTests;
import j2dbench.tests.ImageTests;
import j2dbench.tests.MiscTests;
import j2dbench.tests.RenderTests;
import j2dbench.tests.PixelTests;
import j2dbench.tests.iio.IIOTests;
import j2dbench.tests.cmm.CMMTests;
import j2dbench.tests.text.TextConstructionTests;
import j2dbench.tests.text.TextMeasureTests;
import j2dbench.tests.text.TextRenderTests;
import j2dbench.tests.text.TextTests;
public class J2DBench {
static Group progoptroot;
static Option.Enable verbose;
static Option.Enable printresults;
static boolean looping = false;
static JFrame guiFrame;
static final SimpleDateFormat sdf =
new SimpleDateFormat("MM.dd.yyyy 'at' HH:mm aaa z");
public static void init() {
progoptroot = new Group("prog", "Program Options");
progoptroot.setHidden();
verbose =
new Option.Enable(progoptroot,
"verbose", "Verbose print statements",
false);
printresults =
new Option.Enable(progoptroot,
"printresults", "Print results after each run",
true);
}
public static void usage(int exitcode) {
System.out.println("usage: java -jar J2DBench.jar "+
"[<optionname>=<value>]");
System.out.println(" "+
"[-list] "+
"[-gui | -interactive] "+
"[-batch] "+
"[-noshow] "+
"[-nosave] "+
"[-report:[NMKAUOsmuna/]] "+
"[-usage | -help] "+
"\n "+
"\n "+
"[-loadopts | -loadoptions] <optfile> "+
"[-saveopts | -saveoptions] <optfile> "+
"\n "+
"[-saveres | -saveresults] <resfile> "+
"[-appres | -appendresults] <resfile> "+
"\n "+
"[-title] <title> "+
"[-desc | -description] <description> "+
"\n "+
"[-loop] <duration> [-loopdef | -loopdefault] "+
"");
System.out.println(" -list "+
"List the option settings on stdout");
System.out.println(" -gui "+
"Run the program in interactive mode (launch GUI)");
System.out.println(" -batch "+
"Run the program in batch mode (do not launch GUI)");
System.out.println(" -noshow "+
"Do not show output on the screen (batch mode)");
System.out.println(" -nosave "+
"Do not show save results to a file (batch mode)");
System.out.println(" -report "+
"Rate format to report 'X per Y' (default u/s)");
System.out.println(" "+
" N = report in single units or ops");
System.out.println(" "+
" M = report in millions of units or ops");
System.out.println(" "+
" K = report in thousands of units or ops");
System.out.println(" "+
" A = (auto) M or K as needed");
System.out.println(" "+
" U = units as defined by the operation");
System.out.println(" "+
" O = operations");
System.out.println(" "+
" s = report by whole seconds");
System.out.println(" "+
" m = report by milliseconds");
System.out.println(" "+
" u = report by microseconds");
System.out.println(" "+
" n = report by nanoseconds");
System.out.println(" "+
" a = (auto) milli/micro/nanoseconds as needed");
System.out.println(" "+
" / = invert (N/sec or secs/N)");
System.out.println(" -usage "+
"Print out this usage message");
System.out.println(" -saveres "+
"Save the results to the indicated file");
System.out.println(" -appres "+
"Append the results to the indicated file");
System.out.println(" -title "+
"Use the title for the saved results");
System.out.println(" -desc "+
"Use the description for the saved results");
System.out.println(" -loop "+
"Loop for the specified duration"+
"\n "+
"Duration specified as :"+
"\n "+
"<days>d / <hours>h / <minutes>m / dd:hh:mm");
System.out.println(" -loopdef "+
"Loop for a default duration of 72 hours");
System.exit(exitcode);
}
public static void main(String[] argv) {
init();
TestEnvironment.init();
Result.init();
Destinations.init();
GraphicsTests.init();
RenderTests.init();
PixelTests.init();
ImageTests.init();
MiscTests.init();
TextTests.init();
TextRenderTests.init();
TextMeasureTests.init();
TextConstructionTests.init();
IIOTests.init();
CMMTests.init();
boolean gui = true;
boolean showresults = true;
boolean saveresults = true;
String resfilename = null;
String title = null;
String desc = null;
boolean appendres = false;
long requiredLoopTime = 259200000; // 72 hrs * 60 * 60 * 1000
for (int i = 0; i < argv.length; i++) {
String arg = argv[i];
if (arg.equalsIgnoreCase("-list")) {
PrintWriter pw = new PrintWriter(System.out);
Node.Iterator iter = Group.root.getRecursiveChildIterator();
while (iter.hasNext()) {
Node n = iter.next();
n.write(pw);
}
pw.flush();
} else if (arg.equalsIgnoreCase("-gui") ||
arg.equalsIgnoreCase("-interactive"))
{
gui = true;
} else if (arg.equalsIgnoreCase("-batch")) {
gui = false;
} else if (arg.equalsIgnoreCase("-noshow")) {
showresults = false;
} else if (arg.equalsIgnoreCase("-nosave")) {
saveresults = false;
} else if (arg.equalsIgnoreCase("-usage") ||
arg.equalsIgnoreCase("-help"))
{
usage(0);
} else if (arg.equalsIgnoreCase("-loadoptions") ||
arg.equalsIgnoreCase("-loadopts"))
{
if (++i < argv.length) {
String file = argv[i];
String reason = loadOptions(file);
if (reason != null) {
System.err.println(reason);
System.exit(1);
}
} else {
usage(1);
}
} else if (arg.equalsIgnoreCase("-saveoptions") ||
arg.equalsIgnoreCase("-saveopts"))
{
if (++i < argv.length) {
String file = argv[i];
String reason = saveOptions(file);
if (reason != null) {
System.err.println(reason);
System.exit(1);
}
} else {
usage(1);
}
} else if (arg.equalsIgnoreCase("-saveresults") ||
arg.equalsIgnoreCase("-saveres") ||
arg.equalsIgnoreCase("-appendresults") ||
arg.equalsIgnoreCase("-appres"))
{
if (++i < argv.length) {
resfilename = argv[i];
appendres = arg.substring(0, 4).equalsIgnoreCase("-app");
} else {
usage(1);
}
} else if (arg.equalsIgnoreCase("-title")) {
if (++i < argv.length) {
title = argv[i];
} else {
usage(1);
}
} else if (arg.equalsIgnoreCase("-desc") ||
arg.equalsIgnoreCase("-description"))
{
if (++i < argv.length) {
desc = argv[i];
} else {
usage(1);
}
} else if (arg.equalsIgnoreCase("-loopdef") ||
arg.equalsIgnoreCase("-loopdefault"))
{
requiredLoopTime = 259200000; // 72 hrs * 60 * 60 * 1000
J2DBench.looping = true;
} else if (arg.equalsIgnoreCase("-loop")) {
if (++i >= argv.length) {
usage(1);
}
J2DBench.looping = true;
/*
* d or D -> Days
* h or H -> Hours
* m or M -> Minutes
* dd:hh:mm -> Days:Hours:Minutes
*/
if (argv[i].indexOf(":") >= 0) {
String[] values = argv[i].split(":");
int[] intVals = new int[3];
for(int j=0; j<values.length; j++) {
try {
intVals[j] = Integer.parseInt(values[j]);
} catch(Exception e) {}
}
System.out.println("\nLoop for " + intVals[0] +
" days " + intVals[1] +
" hours and " + intVals[2] + " minutes.\n");
requiredLoopTime = ((intVals[0] * 24 * 60 * 60) +
(intVals[1] * 60 * 60) +
(intVals[2] * 60)) * 1000;
} else {
String type = argv[i].substring(argv[i].length() - 1);
int multiplyWith = 1;
if (type.equalsIgnoreCase("d")) {
multiplyWith = 24 * 60 * 60;
} else if (type.equalsIgnoreCase("h")) {
multiplyWith = 60 * 60;
} else if (type.equalsIgnoreCase("m")) {
multiplyWith = 60;
} else {
System.err.println("Invalid \"-loop\" option specified.");
usage(1);
}
int val = 1;
try {
val = Integer.parseInt(argv[i].substring(0, argv[i].length() - 1));
} catch(Exception e) {
System.err.println("Invalid \"-loop\" option specified.");
usage(1);
}
requiredLoopTime = val * multiplyWith * 1000;
}
} else if (arg.length() > 8 &&
arg.substring(0, 8).equalsIgnoreCase("-report:"))
{
String error = Result.parseRateOpt(arg.substring(8));
if (error != null) {
System.err.println("Invalid rate: "+error);
usage(1);
}
} else {
String reason = Group.root.setOption(arg);
if (reason != null) {
System.err.println("Option "+arg+" ignored: "+reason);
}
}
}
if (verbose.isEnabled()) {
Group.root.traverse(new Node.Visitor() {
public void visit(Node node) {
System.out.println(node);
}
});
}
if (gui) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
startGUI();
}
});
} else {
long start = System.currentTimeMillis();
int nLoopCount = 1;
if (saveresults) {
if (title == null) {
title = inputUserStr("title");
}
if (desc == null) {
desc = inputUserStr("description");
}
}
PrintWriter writer = null;
if (J2DBench.looping) {
System.out.println("\nAbout to run tests for : " +
(requiredLoopTime/1000) + " seconds.\n");
if(resfilename != null) {
try {
String loopReportFileName =
resfilename.substring(0, resfilename.lastIndexOf(".xml"));
writer = new PrintWriter(
new FileWriter(loopReportFileName + "_Loop.html"));
writer.println("<html><head><title>" + title + "</title></head>");
writer.println("<body bgcolor=\"#ffffff\"><hr size=\"1\">");
writer.println("<center><h2>" + title + "</h2>");
writer.println("</center><hr size=\"1\"><br>");
writer.flush();
} catch(IOException ioe) {
ioe.printStackTrace();
System.err.println("\nERROR : Could not create Loop-Report. Exit");
System.exit(1);
}
}
}
do {
Date loopStart = new Date();
if (J2DBench.looping) {
writer.println("<b>Loop # " + nLoopCount + "</b><br>");
writer.println("<b>Start : </b>" + sdf.format(loopStart) + "<br>");
writer.flush();
}
runTests(showresults);
if (saveresults) {
if (resfilename != null) {
lastResults.setTitle(title);
lastResults.setDescription(desc);
String reason = saveResults(resfilename, appendres);
if (reason != null) {
System.err.println(reason);
}
} else {
saveResults(title, desc);
}
}
if (J2DBench.looping) {
Date loopEnd = new Date();
System.out.println("\n================================================================");
System.out.println("-- Completed Loop " + nLoopCount + " at " + sdf.format(loopEnd) + " --");
System.out.println("================================================================\n");
writer.println("<b>End : </b>" + sdf.format(loopEnd) + "<br>");
writer.println("<b>Duration </b>: " + (loopEnd.getTime() - loopStart.getTime())/1000 + " Seconds<br>");
writer.println("<b>Total : " + (loopEnd.getTime() - start)/1000 + " Seconds</b><br>");
writer.println("</center><hr size=\"1\">");
writer.flush();
if ((loopEnd.getTime() - start) > requiredLoopTime) {
break;
}
//Append results for looping - mode
appendres = true;
nLoopCount++;
}
} while(J2DBench.looping);
if (J2DBench.looping) {
writer.println("</html>");
writer.flush();
writer.close();
}
}
}
public static String loadOptions(String filename) {
FileReader fr;
try {
fr = new FileReader(filename);
} catch (FileNotFoundException e) {
return "file "+filename+" not found";
}
return loadOptions(fr, filename);
}
public static String loadOptions(File file) {
FileReader fr;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
return "file "+file.getPath()+" not found";
}
return loadOptions(fr, file.getPath());
}
public static String loadOptions(FileReader fr, String filename) {
LineNumberReader lnr = new LineNumberReader(fr);
Group.restoreAllDefaults();
String line;
try {
while ((line = lnr.readLine()) != null) {
String reason = Group.root.setOption(line);
if (reason != null) {
System.err.println("Option "+line+
" at line "+lnr.getLineNumber()+
" ignored: "+reason);
}
}
} catch (IOException e) {
Group.restoreAllDefaults();
return ("IO Error reading "+filename+
" at line "+lnr.getLineNumber());
}
return null;
}
public static String saveOptions(String filename) {
return saveOptions(new File(filename));
}
public static String saveOptions(File file) {
if (file.exists()) {
if (!file.isFile()) {
return "Cannot save options to a directory!";
}
int ret = JOptionPane.showOptionDialog
(guiFrame,
new String[] {
"The file '"+file.getName()+"' already exists!",
"",
"Do you wish to overwrite this file?",
},
"File exists!",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, new String[] {
"Overwrite",
"Cancel",
}, "Cancel");
if (ret == 1) {
return null;
}
}
FileWriter fw;
try {
fw = new FileWriter(file);
} catch (IOException e) {
return "Error opening option file "+file.getPath();
}
return saveOptions(fw, file.getPath());
}
public static String saveOptions(FileWriter fw, String filename) {
PrintWriter pw = new PrintWriter(fw);
Group.writeAll(pw);
return null;
}
public static JFileChooser theFC;
public static JFileChooser getFileChooser() {
if (theFC == null) {
theFC = new JFileChooser(System.getProperty("user.dir"));
}
theFC.rescanCurrentDirectory();
return theFC;
}
public static ResultSet lastResults;
public static boolean saveOrDiscardLastResults() {
if (lastResults != null) {
int ret = JOptionPane.showConfirmDialog
(guiFrame,
"The results of the last test will be "+
"discarded if you continue! Do you want "+
"to save them?",
"Discard last results?",
JOptionPane.YES_NO_CANCEL_OPTION);
if (ret == JOptionPane.CANCEL_OPTION) {
return false;
} else if (ret == JOptionPane.YES_OPTION) {
if (saveResults()) {
lastResults = null;
} else {
return false;
}
}
}
return true;
}
public static String inputUserStr(String type) {
return JOptionPane.showInputDialog("Enter a "+
type+
" for this result set:");
}
public static boolean saveResults() {
return saveResults(inputUserStr("title"), inputUserStr("description"));
}
public static boolean saveResults(String title, String desc) {
lastResults.setTitle(title);
lastResults.setDescription(desc);
JFileChooser fc = getFileChooser();
int ret = fc.showSaveDialog(guiFrame);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
boolean append = false;
if (file.exists()) {
if (!file.isFile()) {
System.err.println("Cannot save results to a directory!");
return false;
}
ret = JOptionPane.showOptionDialog
(guiFrame,
new String[] {
"The file '"+file.getName()+"' already exists!",
"",
"Do you wish to overwrite or append to this file?",
},
"File exists!",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, new String[] {
"Overwrite",
"Append",
"Cancel",
}, "Cancel");
if (ret == 0) {
append = false;
} else if (ret == 1) {
append = true;
} else {
return false;
}
}
String reason = saveResults(file, append);
if (reason == null) {
return true;
} else {
System.err.println(reason);
}
}
return false;
}
public static String saveResults(String filename, boolean append) {
FileWriter fw;
try {
fw = new FileWriter(filename, append);
} catch (IOException e) {
return "Error opening results file "+filename;
}
return saveResults(fw, filename, append);
}
public static String saveResults(File file, boolean append) {
FileWriter fw;
try {
fw = new FileWriter(file, append);
} catch (IOException e) {
return "Error opening results file "+file.getName();
}
return saveResults(fw, file.getName(), append);
}
public static String saveResults(FileWriter fw, String filename,
boolean append)
{
PrintWriter pw = new PrintWriter(fw);
if (!append) {
pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
pw.println("<!--For Entertainment Purposes Only-->");
}
pw.println();
lastResults.write(pw);
pw.flush();
pw.close();
return null;
}
public static void startGUI() {
final JFrame f = new JFrame("J2DBench") {
public Dimension getPreferredSize() {
Dimension pref = super.getPreferredSize();
pref.width = Math.max(pref.width, 800);
pref.height = Math.max(pref.height, 600);
return pref;
}
};
guiFrame = f;
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(Group.root.getJComponent(), BorderLayout.CENTER);
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
JButton b = new JButton("Run Tests...");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!saveOrDiscardLastResults()) {
return;
}
if (verbose.isEnabled()) {
System.out.println(e);
System.out.println("running tests...");
}
new Thread(new Runnable() {
public void run() {
runTests(true);
}
}).start();
if (verbose.isEnabled()) {
System.out.println("done");
}
}
});
p.add(b);
b = new JButton("Load Options");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = getFileChooser();
int ret = fc.showOpenDialog(f);
if (ret == JFileChooser.APPROVE_OPTION) {
String reason = loadOptions(fc.getSelectedFile());
if (reason != null) {
System.err.println(reason);
}
}
}
});
p.add(b);
b = new JButton("Save Options");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = getFileChooser();
int ret = fc.showSaveDialog(f);
if (ret == JFileChooser.APPROVE_OPTION) {
String reason = saveOptions(fc.getSelectedFile());
if (reason != null) {
System.err.println(reason);
}
}
}
});
p.add(b);
b = new JButton("Save Results");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (saveResults()) {
lastResults = null;
}
}
});
p.add(b);
b = new JButton("Quit");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!saveOrDiscardLastResults()) {
return;
}
System.exit(0);
}
});
p.add(b);
f.getContentPane().add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
Rectangle usable = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getMaximumWindowBounds().intersection(f.getBounds());
f.setBounds(usable);
f.setVisible(true);
}
public static void runTests(boolean showresults) {
final TestEnvironment env = new TestEnvironment();
Frame f = null;
if (showresults) {
f = new Frame("J2DBench test run");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
env.stop();
}
});
f.add(env.getCanvas());
f.pack();
f.show();
}
for (int i = 0; i < 5; i++) {
env.idle();
}
env.runAllTests();
if (showresults) {
f.hide();
f.dispose();
}
lastResults = env.results;
if (J2DBench.printresults.isEnabled()) {
System.out.println();
}
System.out.println("All test results:");
env.summarize();
System.out.println();
}
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
public interface Modifier {
public Modifier.Iterator getIterator(TestEnvironment env);
public void modifyTest(TestEnvironment env, Object val);
public void restoreTest(TestEnvironment env, Object val);
public String getTreeName();
public String getAbbreviatedModifierDescription(Object val);
public String getModifierValueName(Object val);
public static interface Iterator {
public boolean hasNext();
public Object next();
}
public static interface Filter {
public boolean isCompatible(Object val);
}
}

View file

@ -0,0 +1,116 @@
/*
* Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
import java.io.PrintWriter;
import javax.swing.JLabel;
import javax.swing.JComponent;
public abstract class Node {
private String nodeName;
private String description;
private Group parent;
private Node next;
protected Node() {
}
public Node(Group parent, String nodeName, String description) {
this.parent = parent;
this.nodeName = nodeName;
this.description = description;
parent.addChild(this);
}
public Group getParent() {
return parent;
}
public String getNodeName() {
return nodeName;
}
public String getTreeName() {
String name = nodeName;
if (parent != null) {
String pname = parent.getTreeName();
if (pname != null) {
name = pname + "." + name;
}
}
return name;
}
public String getDescription() {
return description;
}
public JComponent getJComponent() {
return (nodeName != null) ? new JLabel(description) : null;
}
public Node getNext() {
return next;
}
public void setNext(Node node) {
this.next = node;
}
public void traverse(Visitor v) {
v.visit(this);
}
public abstract void restoreDefault();
public abstract void write(PrintWriter pw);
public abstract String setOption(String key, String value);
public static interface Visitor {
public void visit(Node node);
}
public static interface Iterator {
public boolean hasNext();
public Node next();
}
}

View file

@ -0,0 +1,864 @@
/*
* Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComponent;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.border.LineBorder;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
public abstract class Option extends Node implements Modifier {
public Option(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
public abstract boolean isDefault();
public void modifyTest(TestEnvironment env, Object val) {
env.setModifier(this, val);
}
public void restoreTest(TestEnvironment env, Object val) {
env.removeModifier(this);
}
public abstract String getValString();
public String getValString(Object v) {
return v.toString();
}
public String getOptionString() {
return getTreeName()+"="+getValString();
}
public String getOptionString(Object value) {
return getTreeName()+"="+getValString(value);
}
public String getAbbreviatedModifierDescription(Object value) {
return getNodeName()+"="+getValString(value);
}
public String getModifierValueName(Object val) {
return getValString(val);
}
public String setOption(String key, String value) {
if (key.length() != 0) {
return "Option name too specific";
}
return setValueFromString(value);
}
public abstract String setValueFromString(String value);
public void write(PrintWriter pw) {
//if (!isDefault()) {
pw.println(getOptionString());
//}
}
public String toString() {
return "Option("+getOptionString()+")";
}
public static class Toggle extends Option {
public static final int Off = 0;
public static final int On = 1;
public static final int Both = 2;
private static final String[] valnames = {"Off", "On", "Both"};
private static final Boolean[][] valuelist = {
BooleanIterator.FalseList,
BooleanIterator.TrueList,
BooleanIterator.FalseTrueList,
};
int defaultvalue;
int value;
JPanel jp;
JComboBox jcb;
public Toggle(Group parent, String nodeName, String description,
int defaultvalue)
{
super(parent, nodeName, description);
if (defaultvalue != Off &&
defaultvalue != On &&
defaultvalue != Both)
{
throw new IllegalArgumentException("bad default");
}
this.defaultvalue = this.value = defaultvalue;
}
public void restoreDefault() {
if (value != defaultvalue) {
value = defaultvalue;
updateGUI();
}
}
public void updateGUI() {
if (jcb != null) {
jcb.setSelectedIndex(value);
}
}
public boolean isDefault() {
return (value == defaultvalue);
}
public Modifier.Iterator getIterator(TestEnvironment env) {
return new BooleanIterator(valuelist[value]);
}
public JComponent getJComponent() {
if (jp == null) {
jp = new JPanel();
jp.setLayout(new BorderLayout());
JLabel jl = new JLabel(getDescription());
jp.add(jl, BorderLayout.WEST);
jcb = new JComboBox(valnames);
updateGUI();
jcb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox jcb = (JComboBox) e.getItemSelectable();
value = jcb.getSelectedIndex();
if (J2DBench.verbose.isEnabled()) {
System.out.println(getOptionString());
}
}
}
});
jp.add(jcb, BorderLayout.EAST);
}
return jp;
}
public String getAbbreviatedModifierDescription(Object value) {
String ret = getNodeName();
if (value.equals(Boolean.FALSE)) {
ret = "!"+ret;
}
return ret;
}
public String getValString() {
return valnames[value];
}
public String setValueFromString(String value) {
for (int i = 0; i < valnames.length; i++) {
if (valnames[i].equalsIgnoreCase(value)) {
if (this.value != i) {
this.value = i;
updateGUI();
}
return null;
}
}
return "Bad value";
}
}
public static class Enable extends Option {
boolean defaultvalue;
boolean value;
JCheckBox jcb;
public Enable(Group parent, String nodeName, String description,
boolean defaultvalue)
{
super(parent, nodeName, description);
this.defaultvalue = this.value = defaultvalue;
}
public boolean isEnabled() {
return value;
}
public void modifyTest(TestEnvironment env) {
// Used from within a Group.EnableSet group.
}
public void restoreTest(TestEnvironment env) {
// Used from within a Group.EnableSet group.
}
public void restoreDefault() {
if (value != defaultvalue) {
value = defaultvalue;
updateGUI();
}
}
public void updateGUI() {
if (jcb != null) {
jcb.setSelected(value);
}
}
public boolean isDefault() {
return (value == defaultvalue);
}
public Modifier.Iterator getIterator(TestEnvironment env) {
return new BooleanIterator(value);
}
public JComponent getJComponent() {
if (jcb == null) {
jcb = new JCheckBox(getDescription());
updateGUI();
jcb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
value = (e.getStateChange() == ItemEvent.SELECTED);
if (J2DBench.verbose.isEnabled()) {
System.out.println(getOptionString());
}
}
});
}
return jcb;
}
public String getAbbreviatedModifierDescription(Object value) {
String ret = getNodeName();
if (value.equals(Boolean.FALSE)) {
ret = "!"+ret;
}
return ret;
}
public String getValString() {
return (value ? "enabled" : "disabled");
}
public String setValueFromString(String value) {
boolean newval;
if (value.equalsIgnoreCase("enabled")) {
newval = true;
} else if (value.equalsIgnoreCase("disabled")) {
newval = false;
} else {
return "Bad Value";
}
if (this.value != newval) {
this.value = newval;
updateGUI();
}
return null;
}
}
public static class Int extends Option {
int minvalue;
int maxvalue;
int defaultvalue;
int value;
JPanel jp;
JTextField jtf;
public Int(Group parent, String nodeName, String description,
int minvalue, int maxvalue, int defaultvalue)
{
super(parent, nodeName, description);
this.minvalue = minvalue;
this.maxvalue = maxvalue;
if (defaultvalue < minvalue || defaultvalue > maxvalue) {
throw new RuntimeException("bad value string: "+value);
}
this.defaultvalue = this.value = defaultvalue;
}
public int getIntValue() {
return value;
}
public void restoreDefault() {
if (value != defaultvalue) {
value = defaultvalue;
updateGUI();
}
}
public void updateGUI() {
if (jtf != null) {
jtf.setText(getValString());
}
}
public boolean isDefault() {
return (value == defaultvalue);
}
public Modifier.Iterator getIterator(TestEnvironment env) {
return new SwitchIterator(new Object[] { new Integer(value) }, 1);
}
public JComponent getJComponent() {
if (jp == null) {
jp = new JPanel();
jp.setLayout(new BorderLayout());
jp.add(new JLabel(getDescription()), BorderLayout.WEST);
jtf = new JTextField(10);
updateGUI();
jtf.setDocument(new PlainDocument() {
public void insertString(int offs, String str,
AttributeSet a)
throws BadLocationException
{
if (str == null) {
return;
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
Toolkit.getDefaultToolkit().beep();
return;
}
}
String oldstr = jtf.getText();
super.insertString(offs, str, a);
str = jtf.getText();
if (setValueFromString(str) == null) {
if (J2DBench.verbose.isEnabled()) {
System.out.println(getOptionString());
}
} else {
super.remove(0, super.getLength());
super.insertString(0, oldstr, null);
Toolkit.getDefaultToolkit().beep();
}
}
});
jtf.setText(getValString());
jp.add(jtf, BorderLayout.EAST);
}
return jp;
}
public String getValString() {
return Integer.toString(value);
}
public String setValueFromString(String value) {
int val;
try {
val = Integer.parseInt(value);
} catch (NumberFormatException e) {
return "Value not an integer ("+value+")";
}
if (val < minvalue || val > maxvalue) {
return "Value out of range";
}
if (this.value != val) {
this.value = val;
updateGUI();
}
return null;
}
}
public static class ObjectList extends Option {
int size;
String[] optionnames;
Object[] optionvalues;
String[] abbrevnames;
String[] descnames;
int defaultenabled;
int enabled;
JPanel jp;
JList jlist;
int numrows;
public ObjectList(Group parent, String nodeName, String description,
String[] optionnames,
Object[] optionvalues,
String[] abbrevnames,
String[] descnames,
int defaultenabled)
{
this(parent, nodeName, description,
Math.min(Math.min(optionnames.length,
optionvalues.length),
Math.min(abbrevnames.length,
descnames.length)),
optionnames, optionvalues,
abbrevnames, descnames, defaultenabled);
}
public ObjectList(Group parent, String nodeName, String description,
int size,
String[] optionnames,
Object[] optionvalues,
String[] abbrevnames,
String[] descnames,
int defaultenabled)
{
super(parent, nodeName, description);
this.size = size;
this.optionnames = trim(optionnames, size);
this.optionvalues = trim(optionvalues, size);
this.abbrevnames = trim(abbrevnames, size);
this.descnames = trim(descnames, size);
this.enabled = this.defaultenabled = defaultenabled;
}
private static String[] trim(String[] list, int size) {
if (list.length == size) {
return list;
}
String[] newlist = new String[size];
System.arraycopy(list, 0, newlist, 0, size);
return newlist;
}
private static Object[] trim(Object[] list, int size) {
if (list.length == size) {
return list;
}
Object[] newlist = new Object[size];
System.arraycopy(list, 0, newlist, 0, size);
return newlist;
}
public void restoreDefault() {
if (enabled != defaultenabled) {
enabled = defaultenabled;
updateGUI();
}
}
public void updateGUI() {
if (jlist != null) {
int enabled = this.enabled;
jlist.clearSelection();
for (int curindex = 0; curindex < size; curindex++) {
if ((enabled & (1 << curindex)) != 0) {
jlist.addSelectionInterval(curindex, curindex);
}
}
}
}
public boolean isDefault() {
return (enabled == defaultenabled);
}
public Modifier.Iterator getIterator(TestEnvironment env) {
return new SwitchIterator(optionvalues, enabled);
}
public void setNumRows(int numrows) {
this.numrows = numrows;
}
public JComponent getJComponent() {
if (jp == null) {
jp = new JPanel();
jp.setLayout(new BorderLayout());
jp.add(new JLabel(getDescription()), BorderLayout.WEST);
jlist = new JList(descnames);
if (numrows > 0) {
try {
jlist.setLayoutOrientation(JList.VERTICAL_WRAP);
} catch (NoSuchMethodError e) {
}
jlist.setVisibleRowCount(numrows);
}
jlist.setBorder(new LineBorder(Color.black, 2));
updateGUI();
jlist.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int flags = 0;
for (int curindex = 0; curindex < size; curindex++) {
JList list = (JList) e.getSource();
if (list.isSelectedIndex(curindex)) {
flags |= (1 << curindex);
}
}
enabled = flags;
if (J2DBench.verbose.isEnabled()) {
System.out.println(getOptionString());
}
}
});
jp.add(jlist, BorderLayout.EAST);
}
return jp;
}
public String getValString() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < size; i++) {
if ((enabled & (1 << i)) != 0) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(optionnames[i]);
}
}
return sb.toString();
}
int findValueIndex(Object value) {
for (int i = 0; i < size; i++) {
if (optionvalues[i] == value) {
return i;
}
}
return -1;
}
public String getValString(Object value) {
return optionnames[findValueIndex(value)];
}
public String getAbbreviatedModifierDescription(Object value) {
return abbrevnames[findValueIndex(value)];
}
public String setValueFromString(String value) {
int enabled = 0;
StringTokenizer st = new StringTokenizer(value, ",");
while (st.hasMoreTokens()) {
String s = st.nextToken();
try {
for (int i = 0; i < size; i++) {
if (optionnames[i].equals(s)) {
enabled |= (1 << i);
s = null;
break;
}
}
} catch (NumberFormatException e) {
}
if (s != null) {
return "Bad value in list ("+s+")";
}
}
this.enabled = enabled;
updateGUI();
return null;
}
}
public static class IntList extends ObjectList {
public IntList(Group parent, String nodeName, String description,
int[] values, String[] abbrevnames, String[] descnames,
int defaultenabled)
{
super(parent, nodeName, description,
makeNames(values), makeValues(values),
abbrevnames, descnames, defaultenabled);
}
private static String[] makeNames(int[] intvalues) {
String[] names = new String[intvalues.length];
for (int i = 0; i < intvalues.length; i++) {
names[i] = Integer.toString(intvalues[i]);
}
return names;
}
private static Object[] makeValues(int[] intvalues) {
Object[] values = new Object[intvalues.length];
for (int i = 0; i < intvalues.length; i++) {
values[i] = new Integer(intvalues[i]);
}
return values;
}
}
public static class ObjectChoice extends Option {
int size;
String[] optionnames;
Object[] optionvalues;
String[] abbrevnames;
String[] descnames;
int defaultselected;
int selected;
JPanel jp;
JComboBox jcombo;
public ObjectChoice(Group parent, String nodeName, String description,
String[] optionnames,
Object[] optionvalues,
String[] abbrevnames,
String[] descnames,
int defaultselected)
{
this(parent, nodeName, description,
Math.min(Math.min(optionnames.length,
optionvalues.length),
Math.min(abbrevnames.length,
descnames.length)),
optionnames, optionvalues,
abbrevnames, descnames, defaultselected);
}
public ObjectChoice(Group parent, String nodeName, String description,
int size,
String[] optionnames,
Object[] optionvalues,
String[] abbrevnames,
String[] descnames,
int defaultselected)
{
super(parent, nodeName, description);
this.size = size;
this.optionnames = trim(optionnames, size);
this.optionvalues = trim(optionvalues, size);
this.abbrevnames = trim(abbrevnames, size);
this.descnames = trim(descnames, size);
this.selected = this.defaultselected = defaultselected;
}
private static String[] trim(String[] list, int size) {
if (list.length == size) {
return list;
}
String[] newlist = new String[size];
System.arraycopy(list, 0, newlist, 0, size);
return newlist;
}
private static Object[] trim(Object[] list, int size) {
if (list.length == size) {
return list;
}
Object[] newlist = new Object[size];
System.arraycopy(list, 0, newlist, 0, size);
return newlist;
}
public void restoreDefault() {
if (selected != defaultselected) {
selected = defaultselected;
updateGUI();
}
}
public void updateGUI() {
if (jcombo != null) {
jcombo.setSelectedIndex(this.selected);
}
}
public boolean isDefault() {
return (selected == defaultselected);
}
public Modifier.Iterator getIterator(TestEnvironment env) {
return new SwitchIterator(optionvalues, 1 << selected);
}
public JComponent getJComponent() {
if (jp == null) {
jp = new JPanel();
jp.setLayout(new BorderLayout());
jp.add(new JLabel(getDescription()), BorderLayout.WEST);
jcombo = new JComboBox(descnames);
updateGUI();
jcombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
selected = jcombo.getSelectedIndex();
if (J2DBench.verbose.isEnabled()) {
System.out.println(getOptionString());
}
}
}
});
jp.add(jcombo, BorderLayout.EAST);
}
return jp;
}
public Object getValue() {
return optionvalues[selected];
}
public int getIntValue() {
return ((Integer) optionvalues[selected]).intValue();
}
public boolean getBooleanValue() {
return ((Boolean) optionvalues[selected]).booleanValue();
}
public String getValString() {
return optionnames[selected];
}
int findValueIndex(Object value) {
for (int i = 0; i < size; i++) {
if (optionvalues[i] == value) {
return i;
}
}
return -1;
}
public String getValString(Object value) {
return optionnames[findValueIndex(value)];
}
public String getAbbreviatedModifierDescription(Object value) {
return abbrevnames[findValueIndex(value)];
}
public String setValue(int v) {
return setValue(new Integer(v));
}
public String setValue(boolean v) {
return setValue(new Boolean(v));
}
public String setValue(Object value) {
for (int i = 0; i < size; i++) {
if (optionvalues[i].equals(value)) {
this.selected = i;
updateGUI();
return null;
}
}
return "Bad value";
}
public String setValueFromString(String value) {
for (int i = 0; i < size; i++) {
if (optionnames[i].equals(value)) {
this.selected = i;
updateGUI();
return null;
}
}
return "Bad value";
}
}
public static class BooleanIterator implements Modifier.Iterator {
private Boolean[] list;
private int index;
public static final Boolean[] FalseList = { Boolean.FALSE };
public static final Boolean[] TrueList = { Boolean.TRUE };
public static final Boolean[]
FalseTrueList = { Boolean.FALSE, Boolean.TRUE };
public static final Boolean[]
TrueFalseList = { Boolean.TRUE, Boolean.FALSE };
public BooleanIterator(boolean v) {
this(v ? TrueList : FalseList);
}
public BooleanIterator(Boolean[] list) {
this.list = list;
}
public boolean hasNext() {
return (index < list.length);
}
public Object next() {
if (index >= list.length) {
throw new NoSuchElementException();
}
return list[index++];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
public static class SwitchIterator implements Modifier.Iterator {
private Object[] list;
private int enabled;
private int index;
public SwitchIterator(Object[] list, int enabled) {
this.list = list;
this.enabled = enabled;
}
public boolean hasNext() {
return ((1 << index) <= enabled);
}
public Object next() {
while ((enabled & (1 << index)) == 0) {
index++;
if (index >= list.length) {
throw new NoSuchElementException();
}
}
return list[index++];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}

View file

@ -0,0 +1,459 @@
/*
* Copyright (c) 2002, 2022, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Vector;
public class Result {
public static final int RATE_UNKNOWN = 0;
public static final int WORK_OPS = 1;
public static final int WORK_UNITS = 2;
public static final int WORK_THOUSANDS = 4;
public static final int WORK_MILLIONS = 6;
public static final int WORK_AUTO = 8;
public static final int TIME_SECONDS = 10;
public static final int TIME_MILLIS = 11;
public static final int TIME_MICROS = 12;
public static final int TIME_NANOS = 13;
public static final int TIME_AUTO = 14;
static Group resultoptroot;
static Option.ObjectChoice timeOpt;
static Option.ObjectChoice workOpt;
static Option.ObjectChoice rateOpt;
public static void init() {
resultoptroot = new Group(TestEnvironment.globaloptroot,
"results", "Result Options");
String[] workStrings = {
"units",
"kilounits",
"megaunits",
"autounits",
"ops",
"kiloops",
"megaops",
"autoops",
};
String[] workDescriptions = {
"Test Units",
"Thousands of Test Units",
"Millions of Test Units",
"Auto-scaled Test Units",
"Operations",
"Thousands of Operations",
"Millions of Operations",
"Auto-scaled Operations",
};
Integer[] workObjects = {
new Integer(WORK_UNITS),
new Integer(WORK_THOUSANDS),
new Integer(WORK_MILLIONS),
new Integer(WORK_AUTO),
new Integer(WORK_OPS | WORK_UNITS),
new Integer(WORK_OPS | WORK_THOUSANDS),
new Integer(WORK_OPS | WORK_MILLIONS),
new Integer(WORK_OPS | WORK_AUTO),
};
workOpt = new Option.ObjectChoice(resultoptroot,
"workunits", "Work Units",
workStrings, workObjects,
workStrings, workDescriptions,
0);
String[] timeStrings = {
"sec",
"msec",
"usec",
"nsec",
"autosec",
};
String[] timeDescriptions = {
"Seconds",
"Milliseconds",
"Microseconds",
"Nanoseconds",
"Auto-scaled seconds",
};
Integer[] timeObjects = {
new Integer(TIME_SECONDS),
new Integer(TIME_MILLIS),
new Integer(TIME_MICROS),
new Integer(TIME_NANOS),
new Integer(TIME_AUTO),
};
timeOpt = new Option.ObjectChoice(resultoptroot,
"timeunits", "Time Units",
timeStrings, timeObjects,
timeStrings, timeDescriptions,
0);
String[] rateStrings = {
"unitspersec",
"secsperunit",
};
String[] rateDescriptions = {
"Work units per Time",
"Time units per Work",
};
Boolean[] rateObjects = {
Boolean.FALSE,
Boolean.TRUE,
};
rateOpt = new Option.ObjectChoice(resultoptroot,
"ratio", "Rate Ratio",
rateStrings, rateObjects,
rateStrings, rateDescriptions,
0);
}
public static boolean isTimeUnit(int unit) {
return (unit >= TIME_SECONDS && unit <= TIME_AUTO);
}
public static boolean isWorkUnit(int unit) {
return (unit >= WORK_OPS && unit <= (WORK_AUTO | WORK_OPS));
}
public static String parseRateOpt(String opt) {
int timeScale = timeOpt.getIntValue();
int workScale = workOpt.getIntValue();
boolean invertRate = rateOpt.getBooleanValue();
int divindex = opt.indexOf('/');
if (divindex < 0) {
int unit = parseUnit(opt);
if (isTimeUnit(unit)) {
timeScale = unit;
} else if (isWorkUnit(unit)) {
workScale = unit;
} else {
return "Bad unit: "+opt;
}
} else {
int unit1 = parseUnit(opt.substring(0,divindex));
int unit2 = parseUnit(opt.substring(divindex+1));
if (isTimeUnit(unit1)) {
if (isWorkUnit(unit2)) {
timeScale = unit1;
workScale = unit2;
invertRate = true;
} else if (isTimeUnit(unit2)) {
return "Both time units: "+opt;
} else {
return "Bad denominator: "+opt;
}
} else if (isWorkUnit(unit1)) {
if (isWorkUnit(unit2)) {
return "Both work units: "+opt;
} else if (isTimeUnit(unit2)) {
timeScale = unit2;
workScale = unit1;
invertRate = false;
} else {
return "Bad denominator: "+opt;
}
} else {
return "Bad numerator: "+opt;
}
}
timeOpt.setValue(timeScale);
workOpt.setValue(workScale);
rateOpt.setValue(invertRate);
return null;
}
private static HashMap unitMap;
static {
unitMap = new HashMap();
unitMap.put("U", new Integer(WORK_UNITS));
unitMap.put("M", new Integer(WORK_MILLIONS));
unitMap.put("K", new Integer(WORK_THOUSANDS));
unitMap.put("A", new Integer(WORK_AUTO));
unitMap.put("MU", new Integer(WORK_MILLIONS));
unitMap.put("KU", new Integer(WORK_THOUSANDS));
unitMap.put("AU", new Integer(WORK_AUTO));
unitMap.put("O", new Integer(WORK_UNITS | WORK_OPS));
unitMap.put("NO", new Integer(WORK_UNITS | WORK_OPS));
unitMap.put("MO", new Integer(WORK_MILLIONS | WORK_OPS));
unitMap.put("KO", new Integer(WORK_THOUSANDS | WORK_OPS));
unitMap.put("AO", new Integer(WORK_AUTO | WORK_OPS));
unitMap.put("s", new Integer(TIME_SECONDS));
unitMap.put("m", new Integer(TIME_MILLIS));
unitMap.put("u", new Integer(TIME_MICROS));
unitMap.put("n", new Integer(TIME_NANOS));
unitMap.put("a", new Integer(TIME_AUTO));
}
public static int parseUnit(String c) {
Integer u = (Integer) unitMap.get(c);
if (u != null) {
return u.intValue();
}
return RATE_UNKNOWN;
}
String unitname = "unit";
Test test;
int repsPerRun;
int unitsPerRep;
Vector times;
LinkedHashMap modifiers;
Throwable error;
public Result(Test test) {
this.test = test;
this.repsPerRun = 1;
this.unitsPerRep = 1;
times = new Vector();
}
public void setReps(int reps) {
this.repsPerRun = reps;
}
public void setUnits(int units) {
this.unitsPerRep = units;
}
public void setUnitName(String name) {
this.unitname = name;
}
public void addTime(long time) {
if (J2DBench.printresults.isEnabled()) {
System.out.println(test+" took "+time+"ms for "+
getRepsPerRun()+" reps");
}
times.addElement(new Long(time));
}
public void setError(Throwable t) {
this.error = t;
}
public void setModifiers(LinkedHashMap modifiers) {
this.modifiers = modifiers;
}
public Throwable getError() {
return error;
}
public int getRepsPerRun() {
return repsPerRun;
}
public int getUnitsPerRep() {
return unitsPerRep;
}
public long getUnitsPerRun() {
return ((long) getRepsPerRun()) * ((long) getUnitsPerRep());
}
public LinkedHashMap getModifiers() {
return modifiers;
}
public long getNumRuns() {
return times.size();
}
public long getTime(int index) {
return ((Long) times.elementAt(index)).longValue();
}
public double getRepsPerSecond(int index) {
return (getRepsPerRun() * 1000.0) / getTime(index);
}
public double getUnitsPerSecond(int index) {
return (getUnitsPerRun() * 1000.0) / getTime(index);
}
public long getTotalReps() {
return getRepsPerRun() * getNumRuns();
}
public long getTotalUnits() {
return getUnitsPerRun() * getNumRuns();
}
public long getTotalTime() {
long totalTime = 0;
for (int i = 0; i < times.size(); i++) {
totalTime += getTime(i);
}
return totalTime;
}
public double getAverageRepsPerSecond() {
return (getTotalReps() * 1000.0) / getTotalTime();
}
public double getAverageUnitsPerSecond() {
return (getTotalUnits() * 1000.0) / getTotalTime();
}
public String getAverageString() {
int timeScale = timeOpt.getIntValue();
int workScale = workOpt.getIntValue();
boolean invertRate = rateOpt.getBooleanValue();
double time = getTotalTime();
String timeprefix = "";
switch (timeScale) {
case TIME_AUTO:
case TIME_SECONDS:
time /= 1000;
break;
case TIME_MILLIS:
timeprefix = "m";
break;
case TIME_MICROS:
time *= 1000.0;
timeprefix = "u";
break;
case TIME_NANOS:
time *= 1000000.0;
timeprefix = "n";
break;
}
String workprefix = "";
boolean isOps = (workScale & WORK_OPS) != 0;
String workname = isOps ? "op" : unitname;
double work = isOps ? getTotalReps() : getTotalUnits();
switch (workScale & (~WORK_OPS)) {
case WORK_AUTO:
case WORK_UNITS:
break;
case WORK_THOUSANDS:
work /= 1000.0;
workprefix = "K";
break;
case WORK_MILLIONS:
work /= 1000000.0;
workprefix = "M";
break;
}
if (invertRate) {
double rate = time / work;
if (timeScale == TIME_AUTO) {
if (rate < 1.0) {
rate *= 1000.0;
timeprefix = "m";
if (rate < 1.0) {
rate *= 1000.0;
timeprefix = "u";
if (rate < 1.0) {
rate *= 1000.0;
timeprefix = "n";
}
}
}
}
return rate+" "+timeprefix+"secs/"+workprefix+workname;
} else {
double rate = work / time;
if (workScale == WORK_AUTO) {
if (rate > 1000.0) {
rate /= 1000.0;
workprefix = "K";
if (rate > 1000.0) {
rate /= 1000.0;
workprefix = "M";
}
}
}
return rate+" "+workprefix+workname+"s/"+timeprefix+"sec";
}
}
public void summarize() {
if (error != null) {
System.out.println(test+" skipped due to "+error);
error.printStackTrace(System.out);
} else {
System.out.println(test+" averaged "+getAverageString());
}
if (true) {
Iterator iter_ = modifiers.keySet().iterator();
System.out.print(" with");
String sep = " ";
while (iter_.hasNext()) {
Modifier mod = (Modifier) iter_.next();
Object v = modifiers.get(mod);
System.out.print(sep);
System.out.print(mod.getAbbreviatedModifierDescription(v));
sep = ", ";
}
System.out.println();
}
}
public void write(PrintWriter pw) {
pw.println(" <result "+
"num-reps=\""+getRepsPerRun()+"\" "+
"num-units=\""+getUnitsPerRep()+"\" "+
"name=\""+test.getTreeName()+"\">");
Iterator iter_ = modifiers.keySet().iterator();
while (iter_.hasNext()) {
Modifier mod = (Modifier) iter_.next();
Object v = modifiers.get(mod);
String val = mod.getModifierValueName(v);
pw.println(" <option "+
"key=\""+mod.getTreeName()+"\" "+
"value=\""+val+"\"/>");
}
for (int i = 0; i < getNumRuns(); i++) {
pw.println(" <time value=\""+getTime(i)+"\"/>");
}
pw.println(" </result>");
}
}

View file

@ -0,0 +1,183 @@
/*
* Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Enumeration;
import java.util.Vector;
import java.io.PrintWriter;
public class ResultSet {
static Hashtable preferprops;
static Hashtable ignoreprops;
// Preferred props - will be listed even if undefined
static String[] preferredkeys = {
"java.version",
"java.runtime.version",
"java.class.version",
"java.vm.version",
"java.vm.name",
"java.vm.info",
"java.home",
"java.compiler",
"os.arch",
"os.name",
"os.version",
"user.name",
"sun.cpu.endian",
"sun.cpu.isalist",
};
// Ignored props - will not be copied to results file
static String[] ignoredkeys = {
"user.dir",
"user.home",
"user.timezone",
"path.separator",
"line.separator",
"file.separator",
"file.encoding",
"java.class.path",
"java.library.path",
"java.io.tmpdir",
"java.util.prefs.PreferencesFactory",
"sun.boot.library.path",
};
/*
* Other props, as of 1.4.0, not classified as "preferred" or "ignored"
* Allowed to propagate to the results file if defined.
*
* java.runtime.name
* java.vendor
* java.vendor.url
* java.vendor.url.bug
* java.specification.name
* java.specification.vendor
* java.specification.version
* java.vm.specification.name
* java.vm.specification.vendor
* java.vm.specification.version
* java.vm.vendor
* user.language
* sun.os.patch.level
* sun.arch.data.model
* sun.io.unicode.encoding
*/
static String unknown = "unknown";
static {
preferprops = new Hashtable();
for (int i = 0; i < preferredkeys.length; i++) {
preferprops.put(preferredkeys[i], unknown);
}
ignoreprops = new Hashtable();
for (int i = 0; i < ignoredkeys.length; i++) {
ignoreprops.put(ignoredkeys[i], unknown);
}
}
Hashtable props;
Vector results;
long start;
long end;
String title;
String description;
public ResultSet() {
Properties sysprops = System.getProperties();
props = (Hashtable) preferprops.clone();
Enumeration enum_ = sysprops.keys();
while (enum_.hasMoreElements()) {
Object key = enum_.nextElement();
if (!ignoreprops.containsKey(key)) {
props.put(key, sysprops.get(key));
}
}
results = new Vector();
start = System.currentTimeMillis();
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String desc) {
this.description = desc;
}
public void record(Result result) {
results.addElement(result);
}
public void summarize() {
end = System.currentTimeMillis();
for (int i = 0; i < results.size(); i++) {
((Result) results.elementAt(i)).summarize();
}
}
public void write(PrintWriter pw) {
pw.println("<result-set version=\"0.1\" name=\""+title+"\">");
pw.println(" <test-desc>"+description+"</test-desc>");
pw.println(" <test-date start=\""+start+"\" end=\""+end+"\"/>");
for (int i = 0; i < preferredkeys.length; i++) {
String key = preferredkeys[i];
pw.println(" <sys-prop key=\""+key+
"\" value=\""+props.get(key)+"\"/>");
}
Enumeration enum_ = props.keys();
while (enum_.hasMoreElements()) {
Object key = enum_.nextElement();
if (!preferprops.containsKey(key)) {
pw.println(" <sys-prop key=\""+key+
"\" value=\""+props.get(key)+"\"/>");
}
}
for (int i = 0; i < results.size(); i++) {
((Result) results.elementAt(i)).write(pw);
}
pw.println("</result-set>");
}
}

View file

@ -0,0 +1,290 @@
/*
* Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
public abstract class Test extends Option.Enable {
private DependentLink dependencies;
public Test(Group parent, String nodeName, String description) {
super(parent, nodeName, description, false);
}
public void addDependency(Modifier mod) {
addDependency(mod, null);
}
public void addDependency(Modifier mod, Modifier.Filter filter) {
dependencies = DependentLink.add(dependencies, mod, filter);
}
public void addDependencies(Group g, boolean recursive) {
addDependencies(g, recursive, null);
}
public void addDependencies(Group g, boolean recursive,
Modifier.Filter filter)
{
if (g instanceof Modifier) {
addDependency((Modifier) g, filter);
}
for (Node n = g.getFirstChild(); n != null; n = n.getNext()) {
if (n instanceof Modifier) {
addDependency((Modifier) n, filter);
} else if (recursive && n instanceof Group) {
addDependencies((Group) n, recursive, filter);
}
}
}
public void runTest(TestEnvironment env) {
if (!env.isStopped() && isEnabled()) {
dependencies.recurseAndRun(env, this);
}
}
public void runOneTest(TestEnvironment env) {
if (!env.isStopped()) {
Result result = new Result(this);
env.erase();
Object ctx = initTest(env, result);
result.setModifiers(env.getModifiers());
try {
runTestLoop(env, result, ctx);
} catch (Throwable t) {
result.setError(t);
}
cleanupTest(env, ctx);
// Skip recording results if we were interrupted before
// anything interesting happened...
if (result.getError() != null || result.getNumRuns() != 0) {
if (J2DBench.printresults.isEnabled()) {
result.summarize();
}
env.record(result);
}
ctx = null;
result = null;
env.idle(); // Also done after this method returns...
}
}
public abstract Object initTest(TestEnvironment env, Result result);
public abstract void runTest(Object context, int numReps);
public abstract void cleanupTest(TestEnvironment env, Object context);
public void runTestLoop(TestEnvironment env, Result result, Object ctx) {
// Prime the pump
runTest(ctx, 1);
// Determine the number of reps
int numReps = env.getRepCount();
if (numReps == 0) {
numReps = calibrate(env, ctx);
}
result.setReps(numReps);
int numRuns = env.getRunCount();
for (int i = 0; i < numRuns; i++) {
if (env.idle()) {
break;
}
env.sync();
env.startTiming();
runTest(ctx, numReps);
env.sync();
env.stopTiming();
result.addTime(env.getTimeMillis());
env.flushToScreen();
}
}
public int calibrate(TestEnvironment env, Object ctx) {
long testTime = env.getTestTime();
int numReps = 0;
int totalReps = 0;
// First do one at a time until we get to 1 second elapsed
// But, if we get to 1000 reps we'll start ramping up our
// reps per cycle and throwing sync() calls in to make sure
// we aren't spinning our gears queueing up graphics calls
env.idle();
long now = System.currentTimeMillis();
long startTime = now;
while (numReps < 1000 && now < startTime + 1000) {
runTest(ctx, 1);
numReps++;
now = System.currentTimeMillis();
}
// Time to shift gears into an exponential number of tests
// sync() each time in case batching at a lower level is
// causing us to spin our gears
env.sync();
now = System.currentTimeMillis();
int reps = 250;
while (now < startTime + 1000) {
runTest(ctx, reps);
env.sync();
numReps += reps;
reps *= 2;
now = System.currentTimeMillis();
}
// Now keep estimating how many reps it takes to hit our target
// time exactly, trying it out, and guessing again.
while (now < startTime + testTime) {
int estimate = (int) (numReps * testTime / (now - startTime));
if (estimate <= numReps) {
estimate = numReps+1;
}
runTest(ctx, estimate - numReps);
numReps = estimate;
env.sync();
now = System.currentTimeMillis();
}
// Now make one last estimate of how many reps it takes to
// hit the target exactly in case we overshot.
int estimate = (int) (numReps * testTime / (now - startTime));
if (estimate < 1) {
estimate = 1;
}
return estimate;
}
/*
* Finds a new width (w2) such that
* (w-2) <= w2 <= w
* and w2 is not a multiple of 3 (the X step size)
* and GCD(w2, h) is as small as possible
*/
static int prevw;
public static int adjustWidth(int w, int h) {
int bestv = w;
int bestw = w;
boolean verbose = (prevw != w && J2DBench.verbose.isEnabled());
for (int i = 0; i < 3; i++) {
int w2 = w-i;
int u = w2;
int v = h;
while (u > 0) {
if (u < v) { int t = u; u = v; v = t; }
u -= v;
}
if (verbose) {
System.out.println("w = "+w2+", h = "+h+
", w % 3 == "+(w2 % 3)+
", gcd(w, h) = "+v);
}
if (v < bestv && (w2 % 3) != 0) {
bestv = v;
bestw = w2;
}
}
if (verbose) {
System.out.println("using "+bestw+" (gcd = "+bestv+")");
prevw = w;
}
return bestw;
}
public String toString() {
return "Test("+getTreeName()+")";
}
public static class DependentLink {
public static DependentLink add(DependentLink d, Modifier mod,
Modifier.Filter filter)
{
DependentLink dl = new DependentLink(mod, filter);
if (d == null) {
d = dl;
} else {
DependentLink last = d;
while (last.next != null) {
last = last.next;
}
last.next = dl;
}
return d;
}
private DependentLink next;
private Modifier mod;
private Modifier.Filter filter;
private DependentLink(Modifier mod, Modifier.Filter filter) {
this.mod = mod;
this.filter = filter;
}
public Modifier getModifier() {
return mod;
}
public Modifier.Filter getFilter() {
return filter;
}
public DependentLink getNext() {
return next;
}
public void recurseAndRun(TestEnvironment env, Test test) {
Modifier.Iterator iter = mod.getIterator(env);
while (iter.hasNext()) {
Object val = iter.next();
if (filter == null || filter.isCompatible(val)) {
mod.modifyTest(env, val);
if (next == null) {
test.runOneTest(env);
env.idle(); // One more time outside of runOneTest()
} else {
next.recurseAndRun(env, test);
}
mod.restoreTest(env, val);
}
}
}
}
}

View file

@ -0,0 +1,327 @@
/*
* Copyright (c) 2002, 2022, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench;
import java.awt.AlphaComposite;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.LinkedHashMap;
import j2dbench.tests.GraphicsTests;
public class TestEnvironment implements Node.Visitor {
static Group globaloptroot;
static Group envroot;
static Option.Int outputWidth;
static Option.Int outputHeight;
static Option.Int runCount;
static Option.Int repCount;
static Option.Int testTime;
public static void init() {
globaloptroot = new Group("global", "Global Options");
envroot = new Group(globaloptroot, "env", "Test Environment Options");
outputWidth =
new Option.Int(envroot, "outputwidth",
"Width of Output Window or Image",
1, Integer.MAX_VALUE, 640);
outputHeight =
new Option.Int(envroot, "outputheight",
"Height of Output Window or Image",
1, Integer.MAX_VALUE, 480);
runCount =
new Option.Int(envroot, "runcount",
"Fixed Number of Test Runs per Benchmark",
1, Integer.MAX_VALUE, 5);
repCount =
new Option.Int(envroot, "repcount",
"Fixed Number of Reps (0 means calibrate)",
0, Integer.MAX_VALUE, 0);
testTime =
new Option.Int(envroot, "testtime",
"Target test time to calibrate for",
1, Integer.MAX_VALUE, 2500);
}
public void visit(Node node) {
if (node instanceof Test) {
((Test) node).runTest(this);
}
}
public void runAllTests() {
Group.root.traverse(this);
}
Canvas comp;
Image testImage;
Image srcImage;
boolean stopped;
ResultSet results;
LinkedHashMap modifiers;
Timer timer;
public TestEnvironment() {
results = new ResultSet();
modifiers = new LinkedHashMap();
timer = Timer.getImpl();
}
public void startTiming() {
timer.start();
}
public void stopTiming() {
timer.stop();
}
public long getTimeMillis() {
return timer.getTimeMillis();
}
public long getTimeNanos() {
return timer.getTimeNanos();
}
public Canvas getCanvas() {
if (comp == null) {
final int w = getWidth();
final int h = getHeight();
comp = new Canvas() {
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
};
}
return comp;
}
public Image getSrcImage() {
return srcImage;
}
public void stop() {
stopped = true;
}
public boolean isStopped() {
return stopped;
}
public void setTestImage(Image img) {
this.testImage = img;
}
public void setSrcImage(Image img) {
this.srcImage = img;
}
public void erase() {
Graphics g = getGraphics();
if (g != null) {
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
}
}
public Graphics getGraphics() {
if (testImage != null) {
return testImage.getGraphics();
}
if (comp != null) {
return comp.getGraphics();
}
return null;
}
public int getWidth() {
return outputWidth.getIntValue();
}
public int getHeight() {
return outputHeight.getIntValue();
}
public int getRunCount() {
return runCount.getIntValue();
}
public int getRepCount() {
return repCount.getIntValue();
}
public long getTestTime() {
return testTime.getIntValue();
}
public void sync() {
if (comp == null) {
Toolkit.getDefaultToolkit().sync();
} else {
comp.getToolkit().sync();
}
}
public boolean idle() {
if (!stopped) {
sync();
System.gc();
System.runFinalization();
System.gc();
sync();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
stop();
}
}
return stopped;
}
public void setModifier(Modifier o, Object v) {
modifiers.put(o, v);
}
public Object getModifier(Modifier o) {
return modifiers.get(o);
}
public boolean isEnabled(Modifier o) {
return ((Boolean) modifiers.get(o)).booleanValue();
}
public int getIntValue(Modifier o) {
return ((Integer) modifiers.get(o)).intValue();
}
public void removeModifier(Modifier o) {
modifiers.remove(o);
}
public LinkedHashMap getModifiers() {
return (LinkedHashMap) modifiers.clone();
}
public void record(Result result) {
results.record(result);
}
public void flushToScreen() {
if (testImage != null && comp != null) {
Graphics g = comp.getGraphics();
if (GraphicsTests.hasGraphics2D) {
((Graphics2D) g).setComposite(AlphaComposite.Src);
}
g.drawImage(testImage, 0, 0, null);
g.dispose();
}
}
public void summarize() {
results.summarize();
}
private abstract static class Timer {
public static Timer getImpl() {
try {
System.nanoTime();
return new Nanos();
} catch (NoSuchMethodError e) {
return new Millis();
}
}
public abstract void start();
public abstract void stop();
public abstract long getTimeMillis();
public abstract long getTimeNanos();
private static class Millis extends Timer {
private long millis;
public void start() {
millis = System.currentTimeMillis();
}
public void stop() {
millis = System.currentTimeMillis() - millis;
}
public long getTimeMillis() {
return millis;
}
public long getTimeNanos() {
return millis * 1000 * 1000;
}
}
private static class Nanos extends Timer {
private long nanos;
public void start() {
nanos = System.nanoTime();
}
public void stop() {
nanos = System.nanoTime() - nanos;
}
public long getTimeMillis() {
return (nanos + (500 * 1000)) / (1000 * 1000);
}
public long getTimeNanos() {
return nanos;
}
}
}
}

View file

@ -0,0 +1,535 @@
/*
* Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
/**
* HTMLSeriesReporter.java
*
* Show series data in graphical form.
*/
package j2dbench.report;
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import j2dbench.report.J2DAnalyzer.ResultHolder;
import j2dbench.report.J2DAnalyzer.ResultSetHolder;
import j2dbench.report.J2DAnalyzer.SingleResultSetHolder;
public class HTMLSeriesReporter {
/**
* Flag to indicate - Generate new report or append to existing report
*/
private static final int HTMLGEN_FILE_NEW = 1;
private static final int HTMLGEN_FILE_UPDATE = 2;
/**
* Path to results directory where all results are stored
*/
public static String resultsDir = ".";
/**
* Holds the groups and corresponding group-display-names
*/
public static List groups = new ArrayList();
public static Map groupNames = new HashMap();
/**
* Level at which tests are grouped to be displayed in summary
*/
public static int LEVEL = 2;
private static final DecimalFormat decimalFormat =
new DecimalFormat("0.##");
private static final SimpleDateFormat dateFormat =
new SimpleDateFormat("EEE, MMM d, yyyy G 'at' HH:mm:ss z");
static final Comparator numericComparator = new Comparator() {
public int compare(Object lhs, Object rhs) {
double lval = -1;
try {
lval = Double.parseDouble((String)lhs);
}
catch (NumberFormatException pe) {
}
double rval = -1;
try {
rval = Double.parseDouble((String)rhs);
}
catch (NumberFormatException pe) {
}
double delta = lval - rval;
return delta == 0 ? 0 : delta < 0 ? -1 : 1;
}
};
/**
* Opens a File and returns a PrintWriter instance based on new/update
* option specified in argument.
*/
private static PrintWriter openFile(String name, int nSwitch) {
FileOutputStream file = null;
OutputStreamWriter writer = null;
try {
switch (nSwitch) {
case 1: // HTMLGEN_FILE_NEW
file = new FileOutputStream(name, false);
break;
case 2: // HTMLGEN_FILE_UPDATE
file = new FileOutputStream(name, true);
break;
}
writer = new OutputStreamWriter(file);
} catch (IOException ee) {
System.out.println("Error opening file: " + ee);
System.exit(1);
}
return new PrintWriter(new BufferedWriter(writer));
}
private static void generateSeriesReport(String resultsDir, ArrayList xmlFileNames) {
for (int i = 0; i < xmlFileNames.size(); ++i) {
String xml = (String)xmlFileNames.get(i);
try {
J2DAnalyzer.readResults(xml);
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
// first, display the values of system properties that distinguish the
// sets, and the values of the system properties that are common to all sets
File reportFile = new File(resultsDir, "series.html");
PrintWriter w =
openFile(reportFile.getAbsolutePath(), HTMLGEN_FILE_NEW);
w.println("<html><body bgcolor='#ffffff'>");
w.println("<hr size='1'/><center><h2>J2DBench Series</h2></center><hr size='1'/>");
// collect system properties common to all result sets
// and those unique to only some sets
// first collect all the property keys. these should be the same, but we'll play
// it safe.
// final since referenced from inner class comparator below
final SingleResultSetHolder[] results = new SingleResultSetHolder[J2DAnalyzer.results.size()];
Set propKeys = new HashSet();
for (int i = 0; i < results.length; ++i) {
SingleResultSetHolder srsh = (SingleResultSetHolder)J2DAnalyzer.results.get(i);
Map props = srsh.getProperties();
Set keys = props.keySet();
propKeys.addAll(keys);
results[i] = srsh;
}
Map[] uniqueProps = new Map[results.length];
Map commonProps = new HashMap();
for (int i = 0; i < results.length; ++i) {
Map m = new HashMap();
m.putAll(results[i].getProperties());
uniqueProps[i] = m;
}
{
Iterator iter = propKeys.iterator();
loop: while (iter.hasNext()) {
Object k = iter.next();
Object v = null;
for (int i = 0; i < uniqueProps.length; ++i) {
Map props = uniqueProps[i];
if (i == 0) {
v = props.get(k);
} else {
Object mv = props.get(k);
if (!(v == null ? v == mv : v.equals(mv))) {
// not common, keep this key
continue loop;
}
}
}
// common, so put value in commonProps and remove this key
commonProps.put(k, v);
for (int i = 0; i < uniqueProps.length; ++i) {
uniqueProps[i].remove(k);
}
}
}
String[] hexColor = {
"#fc9505", "#fcd805", "#fc5c05", "#b5fc05", "1cfc05", "#05fc7a",
"#44ff88", "#77ff77", "#aaff66", "#ddff55", "#ffff44", "#ffdd33",
};
Comparator comparator = new Comparator() {
public int compare(Object lhs, Object rhs) {
return ((String)((Map.Entry)lhs).getKey()).compareTo((String)((Map.Entry)rhs).getKey());
}
};
// write table of unique and common properties
w.println("<br/>");
w.println("<table align='center' cols='2' cellspacing='0' cellpadding='0' border='0' width='80%'>");
w.println("<tr><th colspan='2' bgcolor='#aaaaaa'>Result Set Properties</th></tr>");
for (int i = 0; i < results.length; ++i) {
String titl = results[i].getTitle();
String desc = results[i].getDescription();
w.println("<tr bgcolor='" + hexColor[i%hexColor.length] + "'><th>"+titl+"</th><td>"+desc+"</td></tr>");
TreeSet ts = new TreeSet(comparator);
ts.addAll(uniqueProps[i].entrySet());
Iterator iter = ts.iterator();
while (iter.hasNext()) {
Map.Entry e = (Map.Entry)iter.next();
w.println("<tr><td width='30%'><b>"+e.getKey()+"</b></td><td>"+e.getValue()+"</td></tr>");
}
}
w.println("<tr><th colspan='2'>&nbsp;</th></tr>");
w.println("<tr><th colspan='2' bgcolor='#aaaaaa'>Common Properties</th></tr>");
{
TreeSet ts = new TreeSet(comparator);
ts.addAll(commonProps.entrySet());
Iterator iter = ts.iterator();
while (iter.hasNext()) {
Map.Entry e = (Map.Entry)iter.next();
w.println("<tr><td width='30%'><b>"+e.getKey()+"</b></td><td>"+e.getValue()+"</td></tr>");
}
}
w.println("<tr><th colspan='2'>&nbsp;</th></tr>");
w.println("<tr><th colspan='2' bgcolor='#aaaaaa'>Common Test Options</th></tr>");
{
TreeSet ts = new TreeSet(String.CASE_INSENSITIVE_ORDER);
ts.addAll(ResultHolder.commonkeys.keySet());
Iterator iter = ts.iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = ResultHolder.commonkeymap.get(key);
w.println("<tr><td width='30%'><b>"+key+"</b></td><td>"+val+"</td></tr>");
}
}
w.println("</table>");
// for each test that appears in one or more result sets
// for each option that has multiple values
// for each value
// for each result set
// display count and bar
Map testRuns = new HashMap(); // from test name to resultholders
Set testNames = new TreeSet(String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < results.length; ++i) {
Enumeration en = results[i].getResultEnumeration();
while (en.hasMoreElements()) {
ResultHolder rh = (ResultHolder)en.nextElement();
String name = rh.getName();
testNames.add(name);
ArrayList list = (ArrayList)testRuns.get(name);
if (list == null) {
list = new ArrayList();
testRuns.put(name, list);
}
list.add(rh);
}
}
w.println("<hr size='1' width='60%'/>");
w.println("<br/>");
w.println("<table align='center' cols='2' cellspacing='0' cellpadding='0' border='0' width='80%'>");
Iterator iter = testNames.iterator();
while (iter.hasNext()) {
String name = (String)iter.next();
w.println("<tr bgcolor='#aaaaaa'><th colspan='2'>"+name+"</th></tr>");
double bestScore = 0;
// get sorted list of variable options for this test
// optionMap maps each option to a value map. the value map contains all the values,
// sorted depending on the value type (numeric or string). it maps
// from each (string) value to a list of all the resultholders for that value
// value.
Map optionMap = new TreeMap(String.CASE_INSENSITIVE_ORDER);
ArrayList list = (ArrayList)testRuns.get(name);
Iterator riter = list.iterator();
while (riter.hasNext()) {
ResultHolder rh = (ResultHolder)riter.next();
Hashtable options = rh.getOptions();
Set entries = options.entrySet();
Iterator eiter = entries.iterator();
while (eiter.hasNext()) {
Map.Entry e = (Map.Entry)eiter.next();
Object key = e.getKey();
if (ResultHolder.commonkeys.contains(key)) {
continue;
}
Object val = e.getValue();
Map vmap = (Map)optionMap.get(key);
if (vmap == null) {
// determine how to sort
boolean numeric = false;
try {
Integer.parseInt((String)val);
numeric = true;
}
catch (NumberFormatException pe) {
}
Comparator c = numeric ? numericComparator : String.CASE_INSENSITIVE_ORDER;
vmap = new TreeMap(c);
optionMap.put(key, vmap);
}
ArrayList vlist = (ArrayList)vmap.get(val);
if (vlist == null) {
vlist = new ArrayList();
vmap.put(val, vlist);
}
vlist.add(rh);
double score = rh.getScore();
if (score > bestScore) {
bestScore = score;
}
}
}
Iterator oi = optionMap.keySet().iterator();
while (oi.hasNext()) {
String optionName = (String)oi.next();
Map optionValues = (Map)optionMap.get(optionName);
if (optionValues.size() == 1) continue; // don't group by this if only one value
StringBuffer grouping = new StringBuffer();
grouping.append("Grouped by " + optionName + ", Result set");
Iterator oi2 = optionMap.keySet().iterator();
while (oi2.hasNext()) {
String oname2 = (String)oi2.next();
if (oname2.equals(optionName)) continue;
Map ov2 = (Map)optionMap.get(oname2);
if (ov2.size() == 1) continue;
grouping.append(", " + oname2);
Iterator ov2i = ov2.entrySet().iterator();
grouping.append(" (");
boolean comma = false;
while (ov2i.hasNext()) {
if (comma) grouping.append(", ");
grouping.append(((Map.Entry)ov2i.next()).getKey());
comma = true;
}
grouping.append(")");
}
w.println("<tr><td colspan='2'>&nbsp;</td></tr>");
w.println("<tr><td colspan='2'><b>" + grouping.toString() + "</b></td></tr>");
Iterator vi = optionValues.keySet().iterator();
while (vi.hasNext()) {
String valueName = (String)vi.next();
w.print("<tr><td align='right' valign='center' width='10%'>"+valueName+"&nbsp;</td><td>");
ArrayList resultList = (ArrayList)optionValues.get(valueName);
// sort the result list in order of the sets the results come from
// we count on this being a stable sort, otherwise we'd have to also sort
// within each result set on all other variables
Comparator c = new Comparator() {
public int compare(Object lhs, Object rhs) {
ResultSetHolder lh = ((ResultHolder)lhs).rsh;
ResultSetHolder rh = ((ResultHolder)rhs).rsh;
int li = -1;
for (int k = 0; k < results.length; ++k) {
if (results[k] == lh) {
li = k;
break;
}
}
int ri = -1;
for (int k = 0; k < results.length; ++k) {
if (results[k] == rh) {
ri = k;
break;
}
}
return li - ri;
}
};
w.println(" <div style='height: 5'>&nbsp;</div>");
ResultHolder[] sorted = new ResultHolder[resultList.size()];
sorted = (ResultHolder[])resultList.toArray(sorted);
Arrays.sort(sorted, c);
for (int k = 0; k < sorted.length; ++k) {
ResultHolder holder = sorted[k];
String color = null;
for (int n = 0; n < results.length; ++n) {
if (results[n] == holder.rsh) {
color = hexColor[n];
}
}
double score = holder.getScore();
int pix = 0;
if (bestScore > 1) {
double scale = logScale
? Math.log(score)/Math.log(bestScore)
: (score)/(bestScore);
pix = (int)(scale*80.0);
}
w.println(" <div style='width: " + pix +
"%; height: 15; font-size: smaller; valign: center; background-color: " + color+"'>" +
"<div align='right' style='height: 15'>" + (int)score + "&nbsp;</div></div>");
}
w.println("</td></tr>");
}
}
w.println("<tr><td colspan='2'>&nbsp;</td></tr>");
}
w.println("</table>");
w.println("<br/>");
w.println("</body></html>");
w.flush();
w.close();
}
private static void printUsage() {
String usage =
"\njava HTMLSeriesReporter [options] resultfile... " +
" \n\n" +
"where options include: " +
" \n" +
" -r | -results <result directory> " +
"directory to which reports are stored \n" +
" -ls " +
"display using logarithmic scale \n" +
" -resultxml | -xml <xml file path> " +
"path to result XML \n" +
" -group | -g <level> " +
"group-level for tests \n" +
" " +
" [ 1 , 2 , 3 or 4 ] \n" +
" -analyzermode | -am " +
"mode to be used for finding score \n" +
" " +
" [ BEST , WORST , AVERAGE , MIDAVG ] ";
System.out.println(usage);
System.exit(0);
}
static boolean logScale = false;
/**
* main
*/
public static void main(String[] args) {
String resDir = ".";
ArrayList results = new ArrayList();
int group = 2;
/* ---- Analysis Mode ----
BEST = 1;
WORST = 2;
AVERAGE = 3;
MIDAVG = 4;
------------------------ */
int analyzerMode = 4;
try {
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-ls")) {
logScale = true;
} else if (args[i].startsWith("-results") ||
args[i].startsWith("-r"))
{
i++;
resDir = args[i];
} else if (args[i].startsWith("-group") ||
args[i].startsWith("-g"))
{
i++;
group = Integer.parseInt(args[i]);
System.out.println("Grouping Level for tests: " + group);
} else if (args[i].startsWith("-analyzermode") ||
args[i].startsWith("-am"))
{
i++;
String strAnalyzerMode = args[i];
if(strAnalyzerMode.equalsIgnoreCase("BEST")) {
analyzerMode = 0;
} else if (strAnalyzerMode.equalsIgnoreCase("WORST")) {
analyzerMode = 1;
} else if (strAnalyzerMode.equalsIgnoreCase("AVERAGE")) {
analyzerMode = 2;
} else if (strAnalyzerMode.equalsIgnoreCase("MIDAVG")) {
analyzerMode = 3;
} else {
printUsage();
}
System.out.println("Analyzer-Mode: " + analyzerMode);
} else {
results.add(args[i]);
}
}
}
catch(Exception e) {
printUsage();
}
if (resDir != null) {
J2DAnalyzer.setMode(analyzerMode);
HTMLSeriesReporter.generateSeriesReport(resDir, results);
} else {
printUsage();
}
}
}

View file

@ -0,0 +1,367 @@
/*
* Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.report;
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
import j2dbench.report.J2DAnalyzer.ResultHolder;
import j2dbench.report.J2DAnalyzer.ResultSetHolder;
/**
* This simple utility generates a wiki- or html-formatted table, which
* compares the performance of various image loading routines (relative
* to the core Image I/O plugins).
*/
public class IIOComparator {
private static final DecimalFormat decimalFormat =
new DecimalFormat("0.0");
/**
* List of methods, given in the order we want them to appear in
* the printed columns.
*/
private static final String[] methodKeys = new String[] {
"IIO-Core", "IIO-Ext", "Toolkit", "JPEGCodec", "GdkPixBuf"
};
private static final Hashtable allResults = new Hashtable();
private static boolean wikiStyle;
private static void printIIOTable(String resultsFile) {
try {
J2DAnalyzer.readResults(resultsFile);
} catch (Exception e) {
System.err.println("Error reading results file: " +
e.getMessage());
return;
}
Vector results = J2DAnalyzer.results;
int numsets = results.size();
ResultSetHolder base = (ResultSetHolder)results.elementAt(0);
Enumeration basekeys = base.getKeyEnumeration();
String[] keys = toSortedArray(basekeys, false);
// build results table
for (int k = 0; k < keys.length; k++) {
String key = keys[k];
ResultHolder rh = base.getResultByKey(key);
double score = rh.getScore();
Hashtable opts = rh.getOptions();
String imgsize = (String)opts.get("imageio.opts.size");
String content = (String)opts.get("imageio.opts.content");
String testname = "size=" + imgsize + ",content=" + content;
String format = null;
String method = null;
String name = rh.getName();
if (name.equals("imageio.input.image.imageio.reader.tests.read")) {
format = (String)opts.get("imageio.input.image.imageio.opts.format");
String type = format.substring(0, format.indexOf('-'));
format = format.substring(format.indexOf('-')+1);
if (format.equals("jpeg")) {
format = "jpg";
}
method = "IIO-" + (type.equals("core") ? "Core" : "Ext");
} else if (name.equals("imageio.input.image.toolkit.tests.createImage")) {
format = (String)opts.get("imageio.input.image.toolkit.opts.format");
method = "Toolkit";
} else if (name.equals("imageio.input.image.toolkit.tests.gdkLoadImage")) {
format = (String)opts.get("imageio.input.image.toolkit.opts.format");
method = "GdkPixBuf";
} else if (name.equals("imageio.input.image.jpegcodec.tests.decodeAsBufferedImage")) {
format = "jpg";
method = "JPEGCodec";
} else {
System.err.println("skipping unrecognized key: " + name);
continue;
}
//System.out.println(format + ": " + method + " = " + score);
Hashtable fmtResults = (Hashtable)allResults.get(format);
if (fmtResults == null) {
fmtResults = new Hashtable();
allResults.put(format, fmtResults);
}
Hashtable testResults = (Hashtable)fmtResults.get(testname);
if (testResults == null) {
testResults = new Hashtable();
fmtResults.put(testname, testResults);
}
testResults.put(method, new Double(score));
}
if (wikiStyle) {
printWikiTable();
} else {
printHtmlTable();
}
}
private static void printWikiTable() {
// print a table for each format
Enumeration allKeys = allResults.keys();
while (allKeys.hasMoreElements()) {
String format = (String)allKeys.nextElement();
System.out.println("---+++ " + format.toUpperCase());
Hashtable fmtResults = (Hashtable)allResults.get(format);
Enumeration testKeys = fmtResults.keys();
String[] tests = toSortedArray(testKeys, true);
// print the column headers
Hashtable testResults = (Hashtable)fmtResults.get(tests[0]);
String[] methods = new String[testResults.keySet().size()];
for (int k = 0, i = 0; i < methodKeys.length; i++) {
if (testResults.containsKey(methodKeys[i])) {
methods[k++] = methodKeys[i];
}
}
System.out.print("| |");
for (int i = 0; i < methods.length; i++) {
System.out.print(" *" + methods[i] + "* |");
if (i > 0) {
System.out.print(" *%* |");
}
}
System.out.println("");
// print all rows in the table
for (int i = 0; i < tests.length; i++) {
String testname = tests[i];
testResults = (Hashtable)fmtResults.get(testname);
System.out.print("| " + testname + " |");
double baseres = 0.0;
for (int j = 0; j < methods.length; j++) {
Double result = (Double)testResults.get(methods[j]);
double res = result.doubleValue();
System.out.print(" " +
decimalFormat.format(res) +
" | ");
if (j == 0) {
baseres = res;
} else {
double diff = ((res - baseres) / baseres) * 100.0;
System.out.print(" "+
decimalFormat.format(diff) +
" |");
}
}
System.out.println("");
}
System.out.println("");
}
}
private static void printHtmlTable() {
System.out.println("<html><body>\n");
// print a table for each format
Enumeration allKeys = allResults.keys();
while (allKeys.hasMoreElements()) {
String format = (String)allKeys.nextElement();
System.out.println("<h3>" + format.toUpperCase() + "</h3>");
System.out.println("<table border=\"1\">");
Hashtable fmtResults = (Hashtable)allResults.get(format);
Enumeration testKeys = fmtResults.keys();
String[] tests = toSortedArray(testKeys, true);
// print the column headers
Hashtable testResults = (Hashtable)fmtResults.get(tests[0]);
String[] methods = new String[testResults.keySet().size()];
for (int k = 0, i = 0; i < methodKeys.length; i++) {
if (testResults.containsKey(methodKeys[i])) {
methods[k++] = methodKeys[i];
}
}
System.out.print("<tr><td></td>");
for (int i = 0; i < methods.length; i++) {
printHtmlCell("<b>"+methods[i]+"</b>", "#99CCCC", "center");
if (i > 0) {
printHtmlCell("<b>%</b>", "#99CCCC", "center");
}
}
System.out.println("</tr>");
// print all rows in the table
for (int i = 0; i < tests.length; i++) {
String rowcolor = (i % 2 == 0) ? "#FFFFCC" : "#FFFFFF";
String testname = tests[i];
testResults = (Hashtable)fmtResults.get(testname);
System.out.print("<tr>");
printHtmlCell(testname, rowcolor, "left");
double baseres = 0.0;
for (int j = 0; j < methods.length; j++) {
Double result = (Double)testResults.get(methods[j]);
double res = result.doubleValue();
printHtmlCell(decimalFormat.format(res),
rowcolor, "right");
if (j == 0) {
baseres = res;
} else {
double diff = ((res - baseres) / baseres) * 100.0;
String cellcolor;
if (Math.abs(diff) <= 5.0) {
cellcolor = "#CFCFFF";
} else if (diff < -5.0) {
cellcolor = "#CFFFCF";
} else {
cellcolor = "#FFCFCF";
}
String difftext = decimalFormat.format(diff);
if (diff > 0.0) {
difftext = "+" + difftext;
}
printHtmlCell(difftext, cellcolor, "right");
System.out.println("");
}
}
System.out.println("</tr>");
}
System.out.println("</table><br>\n");
}
System.out.println("</body></html>");
}
private static void printHtmlCell(String s, String color, String align) {
System.out.print("<td bgcolor=\"" + color +
"\" align=\"" + align + "\">" + s +
"</td>");
}
private static String[] toSortedArray(Enumeration e, boolean special) {
Vector keylist = new Vector();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();
keylist.add(key);
}
String[] keys = new String[keylist.size()];
keylist.copyInto(keys);
if (special) {
sort2(keys);
} else {
sort(keys);
}
return keys;
}
public static void sort(String[] strs) {
for (int i = 1; i < strs.length; i++) {
for (int j = i; j > 0; j--) {
if (strs[j].compareTo(strs[j-1]) >= 0) {
break;
}
String tmp = strs[j-1];
strs[j-1] = strs[j];
strs[j] = tmp;
}
}
}
public static void sort2(String[] strs) {
for (int i = 1; i < strs.length; i++) {
for (int j = i; j > 0; j--) {
if (compare(strs[j-1], strs[j])) {
break;
}
String tmp = strs[j-1];
strs[j-1] = strs[j];
strs[j] = tmp;
}
}
}
private static int magic(String s) {
if (s.endsWith("random")) {
return 3;
} else if (s.endsWith("photo")) {
return 2;
} else if (s.endsWith("vector")) {
return 1;
} else {
return 0;
}
}
private static boolean compare(String s1, String s2) {
String sizestr1 = s1.substring(s1.indexOf('=')+1, s1.indexOf(','));
String sizestr2 = s2.substring(s2.indexOf('=')+1, s2.indexOf(','));
int size1 = Integer.parseInt(sizestr1);
int size2 = Integer.parseInt(sizestr2);
if (size1 == size2) {
return (magic(s1) < magic(s2));
} else {
return (size1 < size2);
}
}
private static void printUsage() {
System.out.println("java -cp J2DAnalyzer.jar " +
IIOComparator.class.getName() +
" [-wiki] <resultfile>");
}
public static void main(String[] args) {
if (args.length == 2) {
if (args[0].equals("-wiki")) {
wikiStyle = true;
printIIOTable(args[1]);
} else {
printUsage();
}
} else if (args.length == 1) {
printIIOTable(args[0]);
} else {
printUsage();
}
}
}

View file

@ -0,0 +1,835 @@
/*
* Copyright (c) 2002, 2025, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.report;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
public class J2DAnalyzer {
static Vector results = new Vector();
static GroupResultSetHolder groupHolder;
static final int BEST = 1; /* The best score */
static final int WORST = 2; /* The worst score */
static final int AVERAGE = 3; /* Average of all scores */
static final int MIDAVG = 4; /* Average of all but the best and worst */
static int mode = MIDAVG;
public static void usage(PrintStream out) {
out.println("usage:");
out.println(" java -jar J2DAnalyzer.jar [Option]*");
out.println();
out.println("where options are any of the following in any order:");
out.println(" -Help|-Usage "+
"print out this usage statement");
out.println(" -Group:<groupname> "+
"the following result sets are combined into a group");
out.println(" -NoGroup "+
"the following result sets stand on their own");
out.println(" -ShowUncontested "+
"show results even when only result set has a result");
out.println(" -Graph "+
"graph the results visually (using lines of *'s)");
out.println(" -Best "+
"use best time within a resultset");
out.println(" -Worst "+
"use worst time within a resultset");
out.println(" -Average|-Avg "+
"use average of all times within a resultset");
out.println(" -MidAverage|-MidAvg "+
"like -Average but ignore best and worst times");
out.println(" <resultfilename> "+
"load in results from named file");
out.println();
out.println("results within a result set "+
"use Best/Worst/Average mode");
out.println("results within a group "+
"are best of all result sets in that group");
}
public static void main(String[] argv) {
boolean gavehelp = false;
boolean graph = false;
boolean ignoreuncontested = true;
if (argv.length > 0 && argv[0].equalsIgnoreCase("-html")) {
String[] newargs = new String[argv.length-1];
System.arraycopy(argv, 1, newargs, 0, newargs.length);
HTMLSeriesReporter.main(newargs);
return;
}
for (int i = 0; i < argv.length; i++) {
String arg = argv[i];
if (arg.regionMatches(true, 0, "-Group:", 0, 7)) {
groupHolder = new GroupResultSetHolder();
groupHolder.setTitle(arg.substring(7));
results.add(groupHolder);
} else if (arg.equalsIgnoreCase("-NoGroup")) {
groupHolder = null;
} else if (arg.equalsIgnoreCase("-ShowUncontested")) {
ignoreuncontested = false;
} else if (arg.equalsIgnoreCase("-Graph")) {
graph = true;
} else if (arg.equalsIgnoreCase("-Best")) {
mode = BEST;
} else if (arg.equalsIgnoreCase("-Worst")) {
mode = WORST;
} else if (arg.equalsIgnoreCase("-Average") ||
arg.equalsIgnoreCase("-Avg"))
{
mode = AVERAGE;
} else if (arg.equalsIgnoreCase("-MidAverage") ||
arg.equalsIgnoreCase("-MidAvg"))
{
mode = MIDAVG;
} else if (arg.equalsIgnoreCase("-Help") ||
arg.equalsIgnoreCase("-Usage"))
{
usage(System.out);
gavehelp = true;
} else {
readResults(argv[i]);
}
}
if (results.size() == 0) {
if (!gavehelp) {
System.err.println("No results loaded");
usage(System.err);
}
return;
}
int numsets = results.size();
double[] totalscore = new double[numsets];
int[] numwins = new int[numsets];
int[] numties = new int[numsets];
int[] numloss = new int[numsets];
int[] numtests = new int[numsets];
double[] bestscore = new double[numsets];
double[] worstscore = new double[numsets];
double[] bestspread = new double[numsets];
double[] worstspread = new double[numsets];
for (int i = 0; i < numsets; i++) {
bestscore[i] = Double.NEGATIVE_INFINITY;
worstscore[i] = Double.POSITIVE_INFINITY;
bestspread[i] = Double.POSITIVE_INFINITY;
worstspread[i] = Double.NEGATIVE_INFINITY;
}
ResultSetHolder base = (ResultSetHolder) results.elementAt(0);
Enumeration enum_ = base.getKeyEnumeration();
Vector keyvector = new Vector();
while (enum_.hasMoreElements()) {
keyvector.add(enum_.nextElement());
}
String[] keys = new String[keyvector.size()];
keyvector.copyInto(keys);
sort(keys);
enum_ = ResultHolder.commonkeys.keys();
System.out.println("Options common across all tests:");
if (ResultHolder.commonname != null &&
ResultHolder.commonname.length() != 0)
{
System.out.println(" testname="+ResultHolder.commonname);
}
while (enum_.hasMoreElements()) {
Object key = enum_.nextElement();
System.out.println(" "+key+"="+ResultHolder.commonkeymap.get(key));
}
System.out.println();
for (int k = 0; k < keys.length; k++) {
String key = keys[k];
ResultHolder rh = base.getResultByKey(key);
double score = rh.getScore();
double maxscore = score;
int numcontesting = 0;
for (int i = 0; i < numsets; i++) {
ResultSetHolder rsh =
(ResultSetHolder) results.elementAt(i);
ResultHolder rh2 = rsh.getResultByKey(key);
if (rh2 != null) {
if (graph) {
maxscore = Math.max(maxscore, rh2.getBestScore());
}
numcontesting++;
}
}
if (ignoreuncontested && numcontesting < 2) {
continue;
}
System.out.println(rh.getShortKey()+":");
for (int i = 0; i < numsets; i++) {
ResultSetHolder rsh = (ResultSetHolder) results.elementAt(i);
System.out.print(rsh.getTitle()+": ");
ResultHolder rh2 = rsh.getResultByKey(key);
if (rh2 == null) {
System.out.println("not run");
} else {
double score2 = rh2.getScore();
double percent = calcPercent(score, score2);
numtests[i]++;
if (percent < 97.5) {
numloss[i]++;
} else if (percent > 102.5) {
numwins[i]++;
} else {
numties[i]++;
}
totalscore[i] += score2;
if (bestscore[i] < percent) {
bestscore[i] = percent;
}
if (worstscore[i] > percent) {
worstscore[i] = percent;
}
double spread = rh2.getSpread();
if (bestspread[i] > spread) {
bestspread[i] = spread;
}
if (worstspread[i] < spread) {
worstspread[i] = spread;
}
System.out.print(format(score2));
System.out.print(" (var="+spread+"%)");
System.out.print(" ("+percent+"%)");
System.out.println();
if (graph) {
int maxlen = 60;
int avgpos =
(int) Math.round(maxlen * score / maxscore);
Vector scores = rh2.getAllScores();
for (int j = 0; j < scores.size(); j++) {
double s = ((Double) scores.get(j)).doubleValue();
int len = (int) Math.round(maxlen * s / maxscore);
int pos = 0;
while (pos < len) {
System.out.print(pos == avgpos ? '|' : '*');
pos++;
}
while (pos <= avgpos) {
System.out.print(pos == avgpos ? '|' : ' ');
pos++;
}
System.out.println();
}
}
}
}
}
System.out.println();
System.out.println("Summary:");
for (int i = 0; i < numsets; i++) {
ResultSetHolder rsh = (ResultSetHolder) results.elementAt(i);
System.out.println(" "+rsh.getTitle()+": ");
if (numtests[i] == 0) {
System.out.println(" No tests matched reference results");
} else {
double overallscore = totalscore[i]/numtests[i];
System.out.println(" Number of tests: "+numtests[i]);
System.out.printf( " Overall average: %-10.4f%n", overallscore);
System.out.println(" Best spread: "+bestspread[i]+
"% variance");
System.out.println(" Worst spread: "+worstspread[i]+
"% variance");
if (i == 0) {
System.out.println(" (Basis for results comparison)");
} else {
System.out.println(" Comparison to basis:");
System.out.println(" Best result: "+bestscore[i]+
"% of basis");
System.out.println(" Worst result: "+worstscore[i]+
"% of basis");
System.out.println(" Number of wins: "+numwins[i]);
System.out.println(" Number of ties: "+numties[i]);
System.out.println(" Number of losses: "+numloss[i]);
}
}
System.out.println();
}
}
public static void readResults(String filename) {
BufferedReader in;
try {
in = new BufferedReader(new FileReader(filename));
readResults(in);
} catch (IOException e) {
System.out.println(e);
return;
}
}
public static void addResultSet(ResultSetHolder rs) {
if (groupHolder == null) {
results.add(rs);
} else {
groupHolder.addResultSet(rs);
}
}
public static void readResults(BufferedReader in)
throws IOException
{
String xmlver = in.readLine();
if (xmlver == null || !xmlver.startsWith("<?xml version=\"1.0\"")) {
return;
}
while (true) {
String rsline = in.readLine();
if (rsline == null) {
break;
}
rsline = rsline.trim();
if (rsline.startsWith("<result-set version=")) {
String title = getStringAttribute(rsline, "name");
if (title == null) {
title = "No title";
}
SingleResultSetHolder srs = new SingleResultSetHolder();
srs.setTitle(title);
readResultSet(in, srs);
addResultSet(srs);
}
}
}
public static void readResultSet(BufferedReader in,
SingleResultSetHolder srs)
throws IOException
{
String line;
while ((line = in.readLine()) != null) {
line = line.trim();
if (line.startsWith("<test-desc>")) {
int index = line.indexOf("<", 11);
if (index < 0) {
index = line.length();
}
line = line.substring(11, index);
srs.setDescription(line);
} else if (line.startsWith("<sys-prop")) {
String key = getStringAttribute(line, "key");
String val = getStringAttribute(line, "value");
if (key != null && val != null) {
srs.setProperty(key, val);
}
} else if (line.startsWith("<test-date")) {
srs.setStartTime(getLongAttribute(line, "start"));
srs.setEndTime(getLongAttribute(line, "end"));
} else if (line.startsWith("<result")) {
int numreps = getIntAttribute(line, "num-reps");
int numunits = getIntAttribute(line, "num-units");
String name = getStringAttribute(line, "name");
if (numreps > 0 && numunits >= 0 && name != null) {
ResultHolder rh = new ResultHolder(srs);
rh.setName(name);
rh.setReps(numreps);
rh.setUnits(numunits);
readResult(in, rh);
srs.addResult(rh);
}
} else if (line.equals("</result-set>")) {
break;
} else {
System.err.println("Unrecognized line in Result-Set: "+line);
}
}
}
public static void readResult(BufferedReader in, ResultHolder rh)
throws IOException
{
String line;
while ((line = in.readLine()) != null) {
line = line.trim();
if (line.startsWith("<option")) {
String key = getStringAttribute(line, "key");
String val = getStringAttribute(line, "value");
if (key != null && val != null) {
rh.addOption(key, val);
}
} else if (line.startsWith("<time")) {
long ms = getLongAttribute(line, "value");
if (ms >= 0) {
rh.addTime(ms);
}
} else if (line.equals("</result>")) {
break;
} else {
System.err.println("Unrecognized line in Result: "+line);
}
}
}
public static String getStringAttribute(String line, String attrname) {
int index = line.indexOf(attrname+"=");
if (index < 0) {
return null;
}
index += attrname.length()+1;
int endindex;
if (line.charAt(index) == '\"') {
index++;
endindex = line.indexOf('\"', index);
} else {
endindex = -1;
}
if (endindex < 0) {
endindex = line.indexOf(' ', index);
}
if (endindex < 0) {
endindex = line.indexOf('>', index);
}
if (endindex < 0) {
endindex = line.length();
}
return line.substring(index, endindex);
}
public static long getLongAttribute(String line, String attrname) {
String val = getStringAttribute(line, attrname);
if (val == null) {
return -1;
}
try {
return Long.parseLong(val);
} catch (NumberFormatException e) {
return -1;
}
}
public static int getIntAttribute(String line, String attrname) {
String val = getStringAttribute(line, attrname);
if (val == null) {
return -1;
}
try {
return Integer.parseInt(val);
} catch (NumberFormatException e) {
return -1;
}
}
public abstract static class ResultSetHolder {
private String title;
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public abstract Enumeration getKeyEnumeration();
public abstract Enumeration getResultEnumeration();
public abstract ResultHolder getResultByKey(String key);
}
public static class GroupResultSetHolder extends ResultSetHolder {
private Vector members = new Vector();
private Hashtable allresultkeys = new Hashtable();
public void addResultSet(ResultSetHolder rsh) {
members.add(rsh);
Enumeration enum_ = rsh.getResultEnumeration();
while (enum_.hasMoreElements()) {
ResultHolder rh = (ResultHolder) enum_.nextElement();
String key = rh.getKey();
allresultkeys.put(key, key);
}
}
private ResultSetHolder getResultSet(int index) {
return (ResultSetHolder) members.elementAt(index);
}
public Enumeration getKeyEnumeration() {
return allresultkeys.keys();
}
public Enumeration getResultEnumeration() {
return new Enumerator();
}
public ResultHolder getResultByKey(String key) {
ResultHolder best = null;
double bestscore = 0.0;
for (int i = 0; i < members.size(); i++) {
ResultHolder cur = getResultSet(i).getResultByKey(key);
if (cur != null) {
double curscore = cur.getScore();
if (best == null || curscore > bestscore) {
best = cur;
bestscore = curscore;
}
}
}
return best;
}
public class Enumerator implements Enumeration {
Enumeration raw = getKeyEnumeration();
public boolean hasMoreElements() {
return raw.hasMoreElements();
}
public Object nextElement() {
return getResultByKey((String) raw.nextElement());
}
}
}
public static class SingleResultSetHolder extends ResultSetHolder {
private String desc;
private long start;
private long end;
private Hashtable props = new Hashtable();
private Vector results = new Vector();
private Hashtable resultsbykey = new Hashtable();
public void setDescription(String desc) {
this.desc = desc;
}
public String getDescription() {
return desc;
}
public void setStartTime(long ms) {
start = ms;
}
public long getStartTime() {
return start;
}
public void setEndTime(long ms) {
end = ms;
}
public long getEndTime() {
return end;
}
public void setProperty(String key, String value) {
props.put(key, value);
}
public Hashtable getProperties() {
return this.props;
}
public void addResult(ResultHolder rh) {
results.add(rh);
resultsbykey.put(rh.getKey(), rh);
}
public Enumeration getKeyEnumeration() {
return new Enumerator();
}
public Enumeration getResultEnumeration() {
return results.elements();
}
public ResultHolder getResultByKey(String key) {
return (ResultHolder) resultsbykey.get(key);
}
public class Enumerator implements Enumeration {
Enumeration raw = getResultEnumeration();
public boolean hasMoreElements() {
return raw.hasMoreElements();
}
public Object nextElement() {
return ((ResultHolder) raw.nextElement()).getKey();
}
}
}
public static class ResultHolder {
public static Hashtable commonkeymap = new Hashtable();
public static Hashtable commonkeys = new Hashtable();
public static String commonname;
ResultSetHolder rsh;
private String name;
private String key;
private String shortkey;
private int numreps;
private int numunits;
private int numruns;
private long total;
private long longest;
private long shortest;
private Hashtable options = new Hashtable();
private Vector times = new Vector();
public ResultHolder(ResultSetHolder rsh) {
this.rsh = rsh;
}
public void setName(String name) {
this.name = name;
if (commonname == null) {
commonname = name;
} else if (!commonname.equals(name)) {
commonname = "";
}
}
public String getName() {
return name;
}
public String getKey() {
if (key == null) {
key = makeKey(false);
}
return key;
}
public String getShortKey() {
if (shortkey == null) {
shortkey = makeKey(true);
}
return shortkey;
}
private String makeKey(boolean prunecommon) {
String[] keys = new String[options.size()];
Enumeration enum_ = options.keys();
int i = 0;
while (enum_.hasMoreElements()) {
keys[i++] = (String) enum_.nextElement();
}
sort(keys);
String key = (prunecommon && commonname.equals(name)) ? "" : name;
for (i = 0; i < keys.length; i++) {
if (!prunecommon || !commonkeys.containsKey(keys[i])) {
key = key+","+keys[i]+"="+options.get(keys[i]);
}
}
if (key.length() == 0) {
key = name;
} else if (key.startsWith(",")) {
key = key.substring(1);
}
return key;
}
public void setReps(int numreps) {
this.numreps = numreps;
}
public int getReps() {
return numreps;
}
public void setUnits(int numunits) {
this.numunits = numunits;
}
public int getUnits() {
return numunits;
}
public void addOption(String key, String value) {
if (this.key != null) {
throw new InternalError("option added after key was made!");
}
options.put(key, value);
Object commonval = commonkeymap.get(key);
if (commonval == null) {
commonkeymap.put(key, value);
commonkeys.put(key, key);
} else if (!commonval.equals(value)) {
commonkeys.remove(key);
}
}
public Hashtable getOptions() {
return options;
}
public void addTime(long ms) {
times.add(new Long(ms));
if (numruns == 0) {
longest = shortest = ms;
} else {
if (longest < ms) longest = ms;
if (shortest > ms) shortest = ms;
}
total += ms;
numruns++;
}
public double getSpread() {
return calcPercent(shortest, longest - shortest);
}
public double getScore() {
double score = numreps;
if (numunits > 0) {
score *= numunits;
}
long divisor;
if (mode == BEST) {
divisor = shortest;
} else if (mode == WORST) {
divisor = longest;
} else if (mode == AVERAGE || numruns < 3) {
score *= numruns;
divisor = total;
} else {
score *= (numruns-2);
divisor = (total - longest - shortest);
}
score /= divisor;
return score;
}
public double getBestScore() {
double score = numreps;
if (numunits > 0) {
score *= numunits;
}
return score / shortest;
}
public Vector getAllScores() {
Vector scores = new Vector();
double score = numreps;
if (numunits > 0) {
score *= numunits;
}
if (mode == BEST) {
scores.add(new Double(score / shortest));
} else if (mode == WORST) {
scores.add(new Double(score / longest));
} else {
long elimshort, elimlong;
if (mode == AVERAGE || numruns < 3) {
elimshort = elimlong = -1;
} else {
elimshort = shortest;
elimlong = longest;
}
for (int i = 0; i < times.size(); i++) {
long time = ((Long) times.get(i)).longValue();
if (time == elimshort) {
elimshort = -1;
continue;
}
if (time == elimlong) {
elimlong = -1;
continue;
}
scores.add(new Double(score / time));
}
}
return scores;
}
}
public static double calcPercent(double base, double val) {
val /= base;
val *= 10000;
val = Math.rint(val);
return val / 100;
}
public static String format(double val) {
long lval = (long) val;
String ret = String.valueOf(lval);
int digits = ret.length();
if (digits > 17) {
ret = String.valueOf(val);
} else {
val -= lval;
String fraction = String.valueOf(val);
fraction = fraction.substring(fraction.indexOf('.'));
ret += fraction;
int len = digits+5;
if (len < 10) len = 10;
len++;
if (ret.length() > len) {
ret = ret.substring(0, len);
}
}
return ret;
}
public static void sort(String[] strs) {
for (int i = 1; i < strs.length; i++) {
for (int j = i; j > 0; j--) {
if (strs[j].compareTo(strs[j-1]) >= 0) {
break;
}
String tmp = strs[j-1];
strs[j-1] = strs[j];
strs[j] = tmp;
}
}
}
public static void setMode(int mode) {
if(mode >= BEST && mode <= MIDAVG) {
J2DAnalyzer.mode = mode;
}
else {
J2DAnalyzer.mode = MIDAVG;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,533 @@
/*
* Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.AlphaComposite;
import java.awt.RenderingHints;
import java.awt.Polygon;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.awt.geom.AffineTransform;
import java.lang.reflect.Field;
import j2dbench.Destinations;
import j2dbench.Group;
import j2dbench.Option;
import j2dbench.Result;
import j2dbench.Test;
import j2dbench.TestEnvironment;
public abstract class GraphicsTests extends Test {
public static boolean hasGraphics2D;
static {
try {
hasGraphics2D = (Graphics2D.class != null);
} catch (NoClassDefFoundError e) {
}
}
static Color makeAlphaColor(Color opaque, int alpha) {
try {
opaque = new Color(opaque.getRed(),
opaque.getGreen(),
opaque.getBlue(),
alpha);
} catch (NoSuchMethodError e) {
}
return opaque;
}
static Group graphicsroot;
static Group groptroot;
static Option animList;
static Option sizeList;
static Option compRules;
static Option transforms;
static Option doExtraAlpha;
static Option doXor;
static Option doClipping;
static Option renderHint;
// REMIND: transform, etc.
public static void init() {
graphicsroot = new Group("graphics", "Graphics Benchmarks");
graphicsroot.setTabbed();
groptroot = new Group(graphicsroot, "opts", "General Graphics Options");
animList = new Option.IntList(groptroot, "anim",
"Movement of rendering position",
new int[] {0, 1, 2},
new String[] {
"static", "slide", "bounce",
},
new String[] {
"No movement",
"Shift horizontal alignment",
"Bounce around window",
}, 0x4);
sizeList = new Option.IntList(groptroot, "sizes",
"Size of Operations to perform",
new int[] {1, 20, 100, 250, 1000, 4000},
new String[] {
"1x1", "20x20", "100x100", "250x250",
"1000x1000", "4000x4000",
},
new String[] {
"Tiny Shapes (1x1)",
"Small Shapes (20x20)",
"Medium Shapes (100x100)",
"Large Shapes (250x250)",
"X-Large Shapes (1000x1000)",
"Huge Shapes (4000x4000)",
}, 0xa);
if (hasGraphics2D) {
String[] rulenames = {
"Clear",
"Src",
"Dst",
"SrcOver",
"DstOver",
"SrcIn",
"DstIn",
"SrcOut",
"DstOut",
"SrcAtop",
"DstAtop",
"Xor",
};
String[] ruledescs = new String[rulenames.length];
Object[] rules = new Object[rulenames.length];
int j = 0;
int defrule = 0;
for (int i = 0; i < rulenames.length; i++) {
String rulename = rulenames[i];
try {
Field f = AlphaComposite.class.getField(rulename);
rules[j] = f.get(null);
} catch (NoSuchFieldException nsfe) {
continue;
} catch (IllegalAccessException iae) {
continue;
}
if (rules[j] == AlphaComposite.SrcOver) {
defrule = j;
}
rulenames[j] = rulename;
String suffix;
if (rulename.startsWith("Src")) {
suffix = rulename.substring(3);
rulename = "Source";
} else if (rulename.startsWith("Dst")) {
suffix = rulename.substring(3);
rulename = "Dest";
} else {
suffix = "";
}
if (suffix.length() > 0) {
suffix = " "+suffix;
}
ruledescs[j] = rulename+suffix;
j++;
}
compRules =
new Option.ObjectList(groptroot, "alpharule",
"AlphaComposite Rule",
j, rulenames, rules, rulenames,
ruledescs, (1 << defrule));
((Option.ObjectList) compRules).setNumRows(4);
Transform[] xforms = {
Identity.instance,
FTranslate.instance,
Scale2x2.instance,
Rotate15.instance,
ShearX.instance,
ShearY.instance,
};
String[] xformnames = new String[xforms.length];
String[] xformdescs = new String[xforms.length];
for (int i = 0; i < xforms.length; i++) {
xformnames[i] = xforms[i].getShortName();
xformdescs[i] = xforms[i].getDescription();
}
transforms =
new Option.ObjectList(groptroot, "transform",
"Affine Transform",
xforms.length,
xformnames, xforms, xformnames,
xformdescs, 0x1);
((Option.ObjectList) transforms).setNumRows(3);
doExtraAlpha =
new Option.Toggle(groptroot, "extraalpha",
"Render with an \"extra alpha\" of 0.125",
Option.Toggle.Off);
doXor =
new Option.Toggle(groptroot, "xormode",
"Render in XOR mode", Option.Toggle.Off);
doClipping =
new Option.Toggle(groptroot, "clip",
"Render through a complex clip shape",
Option.Toggle.Off);
String[] rhintnames = {
"Default", "Speed", "Quality",
};
renderHint =
new Option.ObjectList(groptroot, "renderhint",
"Rendering Hint",
rhintnames, new Object[] {
RenderingHints.VALUE_RENDER_DEFAULT,
RenderingHints.VALUE_RENDER_SPEED,
RenderingHints.VALUE_RENDER_QUALITY,
}, rhintnames, rhintnames, 1);
}
}
public static class Context {
Graphics graphics;
Dimension outdim;
boolean animate;
int size;
int orgX, orgY;
int initX, initY;
int maxX, maxY;
double pixscale;
}
public GraphicsTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
addDependency(Destinations.destroot);
addDependencies(groptroot, false);
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = createContext();
initContext(env, ctx);
result.setUnits((int) (ctx.pixscale * pixelsTouched(ctx)));
result.setUnitName("pixel");
return ctx;
}
public int pixelsTouched(Context ctx) {
return ctx.outdim.width * ctx.outdim.height;
}
public Context createContext() {
return new Context();
}
public Dimension getOutputSize(int w, int h) {
return new Dimension(w, h);
}
public void initContext(TestEnvironment env, Context ctx) {
ctx.graphics = env.getGraphics();
int w = env.getWidth();
int h = env.getHeight();
ctx.size = env.getIntValue(sizeList);
ctx.outdim = getOutputSize(ctx.size, ctx.size);
ctx.pixscale = 1.0;
if (hasGraphics2D) {
Graphics2D g2d = (Graphics2D) ctx.graphics;
AlphaComposite ac = (AlphaComposite) env.getModifier(compRules);
if (env.isEnabled(doExtraAlpha)) {
ac = AlphaComposite.getInstance(ac.getRule(), 0.125f);
}
g2d.setComposite(ac);
if (env.isEnabled(doXor)) {
g2d.setXORMode(Color.white);
}
if (env.isEnabled(doClipping)) {
Polygon p = new Polygon();
p.addPoint(0, 0);
p.addPoint(w, 0);
p.addPoint(0, h);
p.addPoint(w, h);
p.addPoint(0, 0);
g2d.clip(p);
}
Transform tx = (Transform) env.getModifier(transforms);
Dimension envdim = new Dimension(w, h);
tx.init(g2d, ctx, envdim);
w = envdim.width;
h = envdim.height;
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
env.getModifier(renderHint));
}
switch (env.getIntValue(animList)) {
case 0:
ctx.animate = false;
ctx.maxX = 3;
ctx.maxY = 1;
ctx.orgX = (w - ctx.outdim.width) / 2;
ctx.orgY = (h - ctx.outdim.height) / 2;
break;
case 1:
ctx.animate = true;
ctx.maxX = Math.max(Math.min(32, w - ctx.outdim.width), 3);
ctx.maxY = 1;
ctx.orgX = (w - ctx.outdim.width - ctx.maxX) / 2;
ctx.orgY = (h - ctx.outdim.height) / 2;
break;
case 2:
ctx.animate = true;
ctx.maxX = (w - ctx.outdim.width) + 1;
ctx.maxY = (h - ctx.outdim.height) + 1;
ctx.maxX = adjustWidth(ctx.maxX, ctx.maxY);
ctx.maxX = Math.max(ctx.maxX, 3);
ctx.maxY = Math.max(ctx.maxY, 1);
// ctx.orgX = ctx.orgY = 0;
break;
}
ctx.initX = ctx.maxX / 2;
ctx.initY = ctx.maxY / 2;
}
public void cleanupTest(TestEnvironment env, Object ctx) {
Graphics graphics = ((Context) ctx).graphics;
graphics.dispose();
((Context) ctx).graphics = null;
}
public abstract static class Transform {
public abstract String getShortName();
public abstract String getDescription();
public abstract void init(Graphics2D g2d, Context ctx, Dimension dim);
public static double scaleForPoint(AffineTransform at,
double xorig, double yorig,
double x, double y,
int w, int h)
{
Point2D.Double ptd = new Point2D.Double(x, y);
at.transform(ptd, ptd);
x = ptd.getX();
y = ptd.getY();
double scale = 1.0;
if (x < 0) {
scale = Math.min(scale, xorig / (xorig - x));
} else if (x > w) {
scale = Math.min(scale, (w - xorig) / (x - xorig));
}
if (y < 0) {
scale = Math.min(scale, yorig / (yorig - y));
} else if (y > h) {
scale = Math.min(scale, (h - yorig) / (y - yorig));
}
return scale;
}
public static Dimension scaleForTransform(AffineTransform at,
Dimension dim)
{
int w = dim.width;
int h = dim.height;
Point2D.Double ptd = new Point2D.Double(0, 0);
at.transform(ptd, ptd);
double ox = ptd.getX();
double oy = ptd.getY();
if (ox < 0 || ox > w || oy < 0 || oy > h) {
throw new InternalError("origin outside destination");
}
double scalex = scaleForPoint(at, ox, oy, w, h, w, h);
double scaley = scalex;
scalex = Math.min(scaleForPoint(at, ox, oy, w, 0, w, h), scalex);
scaley = Math.min(scaleForPoint(at, ox, oy, 0, h, w, h), scaley);
if (scalex < 0 || scaley < 0) {
throw new InternalError("could not fit dims to transform");
}
return new Dimension((int) Math.floor(w * scalex),
(int) Math.floor(h * scaley));
}
}
public static class Identity extends Transform {
public static final Identity instance = new Identity();
private Identity() {}
public String getShortName() {
return "ident";
}
public String getDescription() {
return "Identity";
}
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
}
}
public static class FTranslate extends Transform {
public static final FTranslate instance = new FTranslate();
private FTranslate() {}
public String getShortName() {
return "ftrans";
}
public String getDescription() {
return "FTranslate 1.5";
}
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
int w = dim.width;
int h = dim.height;
AffineTransform at = new AffineTransform();
at.translate(1.5, 1.5);
g2d.transform(at);
dim.setSize(w-3, h-3);
}
}
public static class Scale2x2 extends Transform {
public static final Scale2x2 instance = new Scale2x2();
private Scale2x2() {}
public String getShortName() {
return "scale2x2";
}
public String getDescription() {
return "Scale 2x by 2x";
}
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
int w = dim.width;
int h = dim.height;
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0);
g2d.transform(at);
dim.setSize(w/2, h/2);
ctx.pixscale = 4;
}
}
public static class Rotate15 extends Transform {
public static final Rotate15 instance = new Rotate15();
private Rotate15() {}
public String getShortName() {
return "rot15";
}
public String getDescription() {
return "Rotate 15 degrees";
}
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
int w = dim.width;
int h = dim.height;
double theta = Math.toRadians(15);
double cos = Math.cos(theta);
double sin = Math.sin(theta);
double xsize = sin * h + cos * w;
double ysize = sin * w + cos * h;
double scale = Math.min(w / xsize, h / ysize);
xsize *= scale;
ysize *= scale;
AffineTransform at = new AffineTransform();
at.translate((w - xsize) / 2.0, (h - ysize) / 2.0);
at.translate(sin * h * scale, 0.0);
at.rotate(theta);
g2d.transform(at);
dim.setSize(scaleForTransform(at, dim));
}
}
public static class ShearX extends Transform {
public static final ShearX instance = new ShearX();
private ShearX() {}
public String getShortName() {
return "shearx";
}
public String getDescription() {
return "Shear X to the right";
}
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
int w = dim.width;
int h = dim.height;
AffineTransform at = new AffineTransform();
at.translate(0.0, (h - (w*h)/(w + h*0.1)) / 2);
at.shear(0.1, 0.0);
g2d.transform(at);
dim.setSize(scaleForTransform(at, dim));
}
}
public static class ShearY extends Transform {
public static final ShearY instance = new ShearY();
private ShearY() {}
public String getShortName() {
return "sheary";
}
public String getDescription() {
return "Shear Y down";
}
public void init(Graphics2D g2d, Context ctx, Dimension dim) {
int w = dim.width;
int h = dim.height;
AffineTransform at = new AffineTransform();
at.translate((w - (w*h)/(h + w*0.1)) / 2, 0.0);
at.shear(0.0, 0.1);
g2d.transform(at);
dim.setSize(scaleForTransform(at, dim));
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,105 @@
/*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests;
import java.awt.Dimension;
import java.awt.Graphics;
import j2dbench.Group;
import j2dbench.Option;
import j2dbench.TestEnvironment;
public abstract class MiscTests extends GraphicsTests {
static Group miscroot;
static Group copytestroot;
public MiscTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
public static void init() {
miscroot = new Group(graphicsroot, "misc",
"Misc Benchmarks");
copytestroot = new Group(miscroot, "copytests",
"copyArea() Tests");
new CopyArea("copyAreaVert", "Vertical copyArea()", 0, 1);
new CopyArea("copyAreaHoriz", "Horizontal copyArea()", 1, 0);
new CopyArea("copyAreaDiag", "Diagonal copyArea()", 1, 1);
}
private static class CopyArea extends MiscTests {
private int dx, dy;
CopyArea(String nodeName, String desc, int dx, int dy) {
super(copytestroot, nodeName, desc);
this.dx = dx;
this.dy = dy;
}
public Dimension getOutputSize(int w, int h) {
// we add one to each dimension to avoid copying outside the
// bounds of the destination when "bounce" is enabled
return new Dimension(w+1, h+1);
}
public void runTest(Object ctx, int numReps) {
GraphicsTests.Context gctx = (GraphicsTests.Context)ctx;
int size = gctx.size;
int x = gctx.initX;
int y = gctx.initY;
Graphics g = gctx.graphics;
g.translate(gctx.orgX, gctx.orgY);
if (gctx.animate) {
do {
g.copyArea(x, y, size, size, dx, dy);
if ((x -= 3) < 0) x += gctx.maxX;
if ((y -= 1) < 0) y += gctx.maxY;
} while (--numReps > 0);
} else {
do {
g.copyArea(x, y, size, size, dx, dy);
} while (--numReps > 0);
}
g.translate(-gctx.orgX, -gctx.orgY);
}
}
}

View file

@ -0,0 +1,399 @@
/*
* Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests;
import j2dbench.Destinations;
import j2dbench.Group;
import j2dbench.Modifier;
import j2dbench.Option;
import j2dbench.Test;
import j2dbench.Result;
import j2dbench.TestEnvironment;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.image.VolatileImage;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferShort;
import java.awt.image.DataBufferInt;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.awt.image.IndexColorModel;
public abstract class PixelTests extends Test {
static Group pixelroot;
static Group pixeloptroot;
static Group.EnableSet bufimgsrcroot;
static Option doRenderTo;
static Option doRenderFrom;
static Group bufimgtestroot;
static Group rastertestroot;
static Group dbtestroot;
public static void init() {
pixelroot = new Group("pixel", "Pixel Access Benchmarks");
pixeloptroot = new Group(pixelroot, "opts", "Pixel Access Options");
doRenderTo = new Option.Toggle(pixeloptroot, "renderto",
"Render to Image before test",
Option.Toggle.Off);
doRenderFrom = new Option.Toggle(pixeloptroot, "renderfrom",
"Render from Image before test",
Option.Toggle.Off);
// BufferedImage Sources
bufimgsrcroot = new Group.EnableSet(pixelroot, "src",
"BufferedImage Sources");
new BufImg(BufferedImage.TYPE_BYTE_BINARY, 1);
new BufImg(BufferedImage.TYPE_BYTE_BINARY, 2);
new BufImg(BufferedImage.TYPE_BYTE_BINARY, 4);
new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
new BufImg(BufferedImage.TYPE_BYTE_GRAY);
new BufImg(BufferedImage.TYPE_USHORT_555_RGB);
new BufImg(BufferedImage.TYPE_USHORT_565_RGB);
new BufImg(BufferedImage.TYPE_USHORT_GRAY);
new BufImg(BufferedImage.TYPE_3BYTE_BGR);
new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
new BufImg(BufferedImage.TYPE_INT_RGB);
new BufImg(BufferedImage.TYPE_INT_BGR);
new BufImg(BufferedImage.TYPE_INT_ARGB);
// BufferedImage Tests
bufimgtestroot = new Group(pixelroot, "bimgtests",
"BufferedImage Tests");
new BufImgTest.GetRGB();
new BufImgTest.SetRGB();
// Raster Tests
rastertestroot = new Group(pixelroot, "rastests",
"Raster Tests");
new RasTest.GetDataElements();
new RasTest.SetDataElements();
new RasTest.GetPixel();
new RasTest.SetPixel();
// DataBuffer Tests
dbtestroot = new Group(pixelroot, "dbtests",
"DataBuffer Tests");
new DataBufTest.GetElem();
new DataBufTest.SetElem();
}
public PixelTests(Group root, String nodeName, String description) {
super(root, nodeName, description);
addDependency(bufimgsrcroot);
addDependencies(pixeloptroot, false);
}
public static class Context {
BufferedImage bimg;
WritableRaster ras;
DataBuffer db;
int[] pixeldata;
Object elemdata;
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context();
ctx.bimg = ((BufImg) env.getModifier(bufimgsrcroot)).getImage();
if (env.isEnabled(doRenderTo)) {
Graphics2D g2d = ctx.bimg.createGraphics();
g2d.setColor(Color.white);
g2d.fillRect(3, 0, 1, 1);
g2d.dispose();
}
if (env.isEnabled(doRenderFrom)) {
GraphicsConfiguration cfg =
GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
VolatileImage vimg = cfg.createCompatibleVolatileImage(8, 1);
vimg.validate(cfg);
Graphics2D g2d = vimg.createGraphics();
for (int i = 0; i < 100; i++) {
g2d.drawImage(ctx.bimg, 0, 0, null);
}
g2d.dispose();
vimg.flush();
}
result.setUnits(1);
result.setUnitName(getUnitName());
return ctx;
}
public abstract String getUnitName();
public void cleanupTest(TestEnvironment env, Object context) {
}
public static class BufImg extends Option.Enable {
public static int[] rgbvals = {
0x00000000,
0xff0000ff,
0x8000ff00,
0xffffffff
};
static int[] cmap = {
0xff000000, // 0: opaque black
0xffffffff, // 1: opaque white
0x00000000, // 2: transparent black
0x80ffffff, // 3: translucent white
0x00ffffff, // 4: transparent white
0x80000000, // 5: translucent black
0xff333333, // 6: opaque dark gray
0xff666666, // 7: opaque medium gray
0xff999999, // 8: opaque gray
0xffcccccc, // 9: opaque light gray
0xff0000ff, // A: opaque blue
0xff00ff00, // B: opaque green
0xff00ffff, // C: opaque cyan
0xffff0000, // D: opaque red
0xffff00ff, // E: opaque magenta
0xffffff00, // F: opaque yellow
};
int type;
int nbits;
public BufImg(int type) {
super(bufimgsrcroot,
Destinations.BufImg.ShortNames[type],
Destinations.BufImg.Descriptions[type], false);
this.type = type;
this.nbits = 0;
}
public BufImg(int type, int nbits) {
super(bufimgsrcroot,
nbits+"BitBinary",
nbits+"-bit Binary Image", false);
this.type = type;
this.nbits = nbits;
}
public String getModifierValueName(Object val) {
return "BufImg("+getNodeName()+")";
}
public BufferedImage getImage() {
BufferedImage bimg;
if (nbits == 0) {
bimg = new BufferedImage(8, 1, type);
} else {
IndexColorModel icm =
new IndexColorModel(nbits, (1 << nbits),
cmap, 0, (nbits > 1), -1,
DataBuffer.TYPE_BYTE);
// Note that this constructor has bugs pre 1.4...
// bimg = new BufferedImage(64/nbits, 1, type, icm);
WritableRaster wr =
icm.createCompatibleWritableRaster(64/nbits, 1);
bimg = new BufferedImage(icm, wr, false, null);
}
for (int i = 0; i < bimg.getWidth(); i++) {
bimg.setRGB(i, 0, rgbvals[i&3]);
}
return bimg;
}
}
public abstract static class BufImgTest extends PixelTests {
public BufImgTest(String nodeName, String description) {
super(bufimgtestroot, nodeName, description);
}
public String getUnitName() {
return "pixel";
}
public static class GetRGB extends BufImgTest {
public GetRGB() {
super("getrgb", "BufferedImage.getRGB(x, y)");
}
public void runTest(Object context, int numReps) {
BufferedImage bimg = ((Context) context).bimg;
do {
bimg.getRGB(numReps&7, 0);
} while (--numReps > 0);
}
}
public static class SetRGB extends BufImgTest {
public SetRGB() {
super("setrgb", "BufferedImage.setRGB(x, y, rgb)");
}
public void runTest(Object context, int numReps) {
BufferedImage bimg = ((Context) context).bimg;
do {
bimg.setRGB(numReps&7, 0, BufImg.rgbvals[numReps&3]);
} while (--numReps > 0);
}
}
}
public abstract static class RasTest extends PixelTests {
public RasTest(String nodeName, String description) {
super(rastertestroot, nodeName, description);
}
public String getUnitName() {
return "pixel";
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = (Context) super.initTest(env, result);
ctx.ras = ctx.bimg.getRaster();
ctx.pixeldata = ctx.ras.getPixel(0, 0, (int[]) null);
ctx.elemdata = ctx.ras.getDataElements(0, 0, null);
return ctx;
}
public static class GetDataElements extends RasTest {
public GetDataElements() {
super("getdataelem", "Raster.getDataElements(x, y, o)");
}
public void runTest(Object context, int numReps) {
Raster ras = ((Context) context).ras;
Object elemdata = ((Context) context).elemdata;
do {
ras.getDataElements(numReps&7, 0, elemdata);
} while (--numReps > 0);
}
}
public static class SetDataElements extends RasTest {
public SetDataElements() {
super("setdataelem", "WritableRaster.setDataElements(x, y, o)");
}
public void runTest(Object context, int numReps) {
WritableRaster ras = ((Context) context).ras;
Object elemdata = ((Context) context).elemdata;
do {
ras.setDataElements(numReps&7, 0, elemdata);
} while (--numReps > 0);
}
}
public static class GetPixel extends RasTest {
public GetPixel() {
super("getpixel", "Raster.getPixel(x, y, v[])");
}
public void runTest(Object context, int numReps) {
Raster ras = ((Context) context).ras;
int[] pixeldata = ((Context) context).pixeldata;
do {
ras.getPixel(numReps&7, 0, pixeldata);
} while (--numReps > 0);
}
}
public static class SetPixel extends RasTest {
public SetPixel() {
super("setpixel", "WritableRaster.setPixel(x, y, v[])");
}
public void runTest(Object context, int numReps) {
WritableRaster ras = ((Context) context).ras;
int[] pixeldata = ((Context) context).pixeldata;
do {
ras.setPixel(numReps&7, 0, pixeldata);
} while (--numReps > 0);
}
}
}
public abstract static class DataBufTest extends PixelTests {
public DataBufTest(String nodeName, String description) {
super(dbtestroot, nodeName, description);
}
public String getUnitName() {
return "element";
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = (Context) super.initTest(env, result);
ctx.db = ctx.bimg.getRaster().getDataBuffer();
return ctx;
}
public static class GetElem extends DataBufTest {
public GetElem() {
super("getelem", "DataBuffer.getElem(i)");
}
public void runTest(Object context, int numReps) {
DataBuffer db = ((Context) context).db;
do {
db.getElem(numReps&7);
} while (--numReps > 0);
}
}
public static class SetElem extends DataBufTest {
public SetElem() {
super("setelem", "DataBuffer.setElem(i, v)");
}
public void runTest(Object context, int numReps) {
DataBuffer db = ((Context) context).db;
do {
db.setElem(numReps&7, 0);
} while (--numReps > 0);
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,153 @@
/*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.cmm;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.io.IOException;
import java.io.InputStream;
import j2dbench.Group;
import j2dbench.Option;
import j2dbench.Result;
import j2dbench.Test;
import j2dbench.TestEnvironment;
public class CMMTests extends Test {
protected static Group cmmRoot;
protected static Group cmmOptRoot;
protected static Option csList;
protected static Option usePlatformProfiles;
public static void init() {
cmmRoot = new Group("cmm", "Color Management Benchmarks");
cmmRoot.setTabbed();
cmmOptRoot = new Group(cmmRoot, "opts", "General Options");
/*
usePlatformProfiles =
new Option.Enable(cmmOptRoot, "csPlatform",
"Use Platform Profiles", false);
*/
int[] colorspaces = new int[] {
ColorSpace.CS_sRGB,
ColorSpace.CS_GRAY,
ColorSpace.CS_LINEAR_RGB,
ColorSpace.CS_CIEXYZ,
ColorSpace.CS_PYCC
};
String[] csNames = new String[]{
"CS_sRGB",
"CS_GRAY",
"CS_LINEAR_RGB",
"CS_CIEXYZ",
"CS_PYCC"
};
csList = new Option.IntList(cmmOptRoot,
"profiles", "Color Profiles",
colorspaces, csNames, csNames, 0x8);
ColorConversionTests.init();
ProfileTests.init();
}
protected static ColorSpace getColorSpace(TestEnvironment env) {
ColorSpace cs;
boolean usePlatform = true; //(Boolean)env.getModifier(usePlatformProfiles);
int cs_code = env.getIntValue(csList);
if (usePlatform) {
cs = ColorSpace.getInstance(cs_code);
} else {
String resource = "profiles/";
switch (cs_code) {
case ColorSpace.CS_CIEXYZ:
resource += "CIEXYZ.pf";
break;
case ColorSpace.CS_GRAY:
resource += "GRAY.pf";
break;
case ColorSpace.CS_LINEAR_RGB:
resource += "LINEAR_RGB.pf";
break;
case ColorSpace.CS_PYCC:
resource += "PYCC.pf";
break;
case ColorSpace.CS_sRGB:
resource += "sRGB.pf";
break;
default:
throw new RuntimeException("Unknown color space: " + cs_code);
}
try {
InputStream is = CMMTests.class.getResourceAsStream(resource);
ICC_Profile p = ICC_Profile.getInstance(is);
cs = new ICC_ColorSpace(p);
} catch (IOException e) {
throw new RuntimeException("Unable load profile from resource " + resource, e);
}
}
return cs;
}
protected CMMTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
addDependencies(cmmOptRoot, true);
}
public Object initTest(TestEnvironment te, Result result) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void runTest(Object o, int i) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void cleanupTest(TestEnvironment te, Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.cmm;
import j2dbench.Group;
public class ColorConversionTests extends CMMTests {
protected static Group colorConvRoot;
public static void init() {
colorConvRoot = new Group(cmmRoot, "colorconv", "Color Conversion Benchmarks");
colorConvRoot.setTabbed();
DataConversionTests.init();
ColorConvertOpTests.init();
EmbeddedProfileTests.init();
}
protected ColorConversionTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
}

View file

@ -0,0 +1,395 @@
/*
* Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.cmm;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import javax.imageio.ImageIO;
import j2dbench.Group;
import j2dbench.Option;
import j2dbench.Result;
import j2dbench.TestEnvironment;
import j2dbench.tests.iio.IIOTests;
public class ColorConvertOpTests extends ColorConversionTests {
private static class ImageContent {
static ImageContent BLANK = new ImageContent("blank", "Blank (opaque black)");
static ImageContent RANDOM = new ImageContent("random", "Random");
static ImageContent VECTOR = new ImageContent("vector", "Vector Art");
static ImageContent PHOTO= new ImageContent("photo", "Photograph");
public final String name;
public final String descr;
private ImageContent(String name, String descr) {
this.name = name;
this.descr = descr;
}
public static ImageContent[] values() {
return new ImageContent[]{BLANK, RANDOM, VECTOR, PHOTO};
}
}
private static class ImageType {
static ImageType INT_RGB = new ImageType(BufferedImage.TYPE_INT_RGB, "INT_RGB", "TYPE_INT_RGB");
static ImageType INT_ARGB = new ImageType(BufferedImage.TYPE_INT_ARGB, "INT_ARGB", "TYPE_INT_ARGB");
static ImageType INT_ARGB_PRE = new ImageType(BufferedImage.TYPE_INT_ARGB_PRE, "INT_ARGB_PRE", "TYPE_INT_ARGB_PRE");
static ImageType INT_BGR = new ImageType(BufferedImage.TYPE_INT_BGR, "INT_BGR", "TYPE_INT_BGR");
static ImageType BYTE_3BYTE_BGR = new ImageType(BufferedImage.TYPE_3BYTE_BGR, "3BYTE_BGR", "TYPE_3BYTE_BGR");
static ImageType BYTE_4BYTE_ABGR = new ImageType(BufferedImage.TYPE_4BYTE_ABGR, "4BYTE_ABGR", "TYPE_4BYTE_ABGR");
static ImageType BYTE_4BYTE_ABGR_PRE = new ImageType(BufferedImage.TYPE_4BYTE_ABGR_PRE, "4BYTE_ABGR_PRE", "TYPE_4BYTE_ABGR_PRE");
static ImageType BYTE_GRAY = new ImageType(BufferedImage.TYPE_BYTE_GRAY, "BYTE_GRAY", "TYPE_BYTE_GRAY");
static ImageType BYTE_BINARY = new ImageType(BufferedImage.TYPE_BYTE_BINARY, "BYTE_BINARY", "TYPE_BYTE_BINARY");
static ImageType BYTE_INDEXED = new ImageType(BufferedImage.TYPE_BYTE_INDEXED, "BYTE_INDEXED", "TYPE_BYTE_INDEXED");
static ImageType USHORT_565_RGB = new ImageType(BufferedImage.TYPE_USHORT_565_RGB, "USHORT_565_RGB", "TYPE_USHORT_565_RGB");
static ImageType USHORT_555_RGB = new ImageType(BufferedImage.TYPE_USHORT_555_RGB, "USHORT_555_RGB", "TYPE_USHORT_555_RGB");
static ImageType USHORT_GRAY = new ImageType(BufferedImage.TYPE_USHORT_GRAY, "USHORT_GRAY", "TYPE_USHORT_GRAY");
static ImageType COMPATIBLE_DST = new ImageType(0, "Compatible", "Compatible destination");
private ImageType(int type, String abbr, String descr) {
this.type = type;
this.abbrev = abbr;
this.descr = descr;
}
public final int type;
public final String abbrev;
public final String descr;
public static ImageType[] values() {
return new ImageType[]{INT_RGB, INT_ARGB, INT_ARGB_PRE, INT_BGR,
BYTE_3BYTE_BGR, BYTE_4BYTE_ABGR, BYTE_4BYTE_ABGR_PRE,
BYTE_GRAY, BYTE_BINARY, BYTE_INDEXED, USHORT_565_RGB,
USHORT_555_RGB, USHORT_GRAY, COMPATIBLE_DST};
}
}
private static class ListType {
static ListType SRC = new ListType("srcType", "Source Images");
static ListType DST = new ListType("dstType", "Destination Images");
private ListType(String name, String description) {
this.name = name;
this.description = description;
}
public final String name;
public final String description;
}
public static Option createImageTypeList(ListType listType) {
ImageType[] allTypes = ImageType.values();
int num = allTypes.length;
if (listType == ListType.SRC) {
num -= 1; // exclude compatible destination
}
ImageType[] t = new ImageType[num];
String[] names = new String[num];
String[] abbrev = new String[num];
String[] descr = new String[num];
for (int i = 0; i < num; i++) {
t[i] = allTypes[i];
names[i] = t[i].abbrev;
abbrev[i] = t[i].abbrev;
descr[i] = t[i].descr;
}
Option list = new Option.ObjectList(opOptionsRoot,
listType.name, listType.description,
names, t, abbrev, descr, 1);
return list;
}
protected static Group opConvRoot;
protected static Group opOptionsRoot;
protected static Option sizeList;
protected static Option contentList;
protected static Option sourceType;
protected static Option destinationType;
public static void init() {
opConvRoot = new Group(colorConvRoot, "ccop", "ColorConvertOp Tests");
opOptionsRoot = new Group(opConvRoot, "ccopOptions", "Options");
// size list
int[] sizes = new int[] {1, 20, 250, 1000, 4000};
String[] sizeStrs = new String[] {
"1x1", "20x20", "250x250", "1000x1000", "4000x4000"
};
String[] sizeDescs = new String[] {
"Tiny Images (1x1)",
"Small Images (20x20)",
"Medium Images (250x250)",
"Large Images (1000x1000)",
"Huge Images (4000x4000)",
};
sizeList = new Option.IntList(opOptionsRoot,
"size", "Image Size",
sizes, sizeStrs, sizeDescs, 0x4);
((Option.ObjectList) sizeList).setNumRows(5);
// image content
ImageContent[] c = ImageContent.values();
String[] contentStrs = new String[c.length];
String[] contentDescs = new String[c.length];
for (int i = 0; i < c.length; i++) {
contentStrs[i] = c[i].name;
contentDescs[i] = c[i].descr;
};
contentList = new Option.ObjectList(opOptionsRoot,
"content", "Image Content",
contentStrs, c,
contentStrs, contentDescs,
0x8);
sourceType = createImageTypeList(ListType.SRC);
destinationType = createImageTypeList(ListType.DST);
new ConvertImageTest();
new ConvertRasterTest();
new DrawImageTest();
}
public ColorConvertOpTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
addDependencies(opOptionsRoot, true);
}
public Object initTest(TestEnvironment env, Result res) {
return new Context(env, res);
}
public void cleanupTest(TestEnvironment env, Object o) {
Context ctx = (Context)o;
ctx.cs = null;
ctx.op_img = null;
ctx.op_rst = null;
ctx.dst = null;
ctx.src = null;
ctx.graphics = null;
}
private static class Context {
ColorSpace cs;
Graphics2D graphics;
ColorConvertOp op_img;
ColorConvertOp op_rst;
BufferedImage src;
BufferedImage dst;
WritableRaster rsrc;
WritableRaster rdst;
public Context(TestEnvironment env, Result res) {
graphics = (Graphics2D)env.getGraphics();
cs = getColorSpace(env);
// TODO: provide rendering hints
op_img = new ColorConvertOp(cs, null);
ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
op_rst = new ColorConvertOp(sRGB, cs, null);
int size = env.getIntValue(sizeList);
ImageContent content = (ImageContent)env.getModifier(contentList);
ImageType srcType = (ImageType)env.getModifier(sourceType);
src = createBufferedImage(size, size, content, srcType.type);
rsrc = src.getRaster();
ImageType dstType = (ImageType)env.getModifier(destinationType);
if (dstType == ImageType.COMPATIBLE_DST) {
dst = op_img.createCompatibleDestImage(src, null);
} else {
dst = createBufferedImage(size, size, content, dstType.type);
}
// raster always has to be comatible
rdst = op_rst.createCompatibleDestRaster(rsrc);
}
}
private static class ConvertImageTest extends ColorConvertOpTests {
public ConvertImageTest() {
super(opConvRoot, "op_img", "op.filetr(BufferedImage)");
}
public void runTest(Object octx, int numReps) {
final Context ctx = (Context)octx;
final ColorConvertOp op = ctx.op_img;
final BufferedImage src = ctx.src;
BufferedImage dst = ctx.dst;
do {
try {
dst = op.filter(src, dst);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
private static class ConvertRasterTest extends ColorConvertOpTests {
public ConvertRasterTest() {
super(opConvRoot, "op_rst", "op.filetr(Raster)");
}
public void runTest(Object octx, int numReps) {
final Context ctx = (Context)octx;
final ColorConvertOp op = ctx.op_rst;
final Raster src = ctx.rsrc;
WritableRaster dst = ctx.rdst;
do {
try {
dst = op.filter(src, dst);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
private static class DrawImageTest extends ColorConvertOpTests {
public DrawImageTest() {
super(opConvRoot, "op_draw", "drawImage(ColorConvertOp)");
}
public void runTest(Object octx, int numReps) {
final Context ctx = (Context)octx;
final ColorConvertOp op = ctx.op_img;
final Graphics2D g = ctx.graphics;
final BufferedImage src = ctx.src;
do {
g.drawImage(src, op, 0, 0);
} while (--numReps >= 0);
}
}
/**************************************************************************
****** Helper routines
*************************************************************************/
protected static BufferedImage createBufferedImage(int width,
int height,
ImageContent contentType,
int type)
{
BufferedImage image;
image = new BufferedImage(width, height, type);
boolean hasAlpha = image.getColorModel().hasAlpha();
if (contentType == ImageContent.RANDOM) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int rgb = (int) (Math.random() * 0xffffff);
if (hasAlpha) {
rgb |= 0x7f000000;
}
image.setRGB(x, y, rgb);
}
}
}
if (contentType == ImageContent.VECTOR) {
Graphics2D g = image.createGraphics();
if (hasAlpha) {
// fill background with a translucent color
g.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC, 0.5f));
}
g.setColor(Color.blue);
g.fillRect(0, 0, width, height);
g.setComposite(AlphaComposite.Src);
g.setColor(Color.yellow);
g.fillOval(2, 2, width-4, height-4);
g.setColor(Color.red);
g.fillOval(4, 4, width-8, height-8);
g.setColor(Color.green);
g.fillRect(8, 8, width-16, height-16);
g.setColor(Color.white);
g.drawLine(0, 0, width, height);
g.drawLine(0, height, width, 0);
g.dispose();
}
if (contentType == ImageContent.PHOTO) {
Image photo = null;
try {
photo = ImageIO.read(
IIOTests.class.getResourceAsStream("images/photo.jpg"));
} catch (Exception e) {
System.err.println("error loading photo");
e.printStackTrace();
}
Graphics2D g = image.createGraphics();
if (hasAlpha) {
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC,
0.5f));
}
g.drawImage(photo, 0, 0, width, height, null);
g.dispose();
}
return image;
}
}

View file

@ -0,0 +1,197 @@
/*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.cmm;
import java.awt.color.ColorSpace;
import j2dbench.Group;
import j2dbench.Result;
import j2dbench.TestEnvironment;
public class DataConversionTests extends ColorConversionTests {
protected static Group dataConvRoot;
public static void init() {
dataConvRoot = new Group(colorConvRoot, "data", "Data Conversoion Tests");
new FromRGBTest();
new ToRGBTest();
new FromCIEXYZTest();
new ToCIEXYZTest();
}
public DataConversionTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
protected static class Context {
ColorSpace cs;
int numComponents;
float[] val;
float[] rgb;
float[] cie;
TestEnvironment env;
Result res;
public Context(TestEnvironment env, Result result, ColorSpace cs) {
this.cs = cs;
this.env = env;
this.res = result;
numComponents = cs.getNumComponents();
val = new float[numComponents];
for (int i = 0; i < numComponents; i++) {
float min = cs.getMinValue(i);
float max = cs.getMaxValue(i);
val[i] = 0.5f * (max - min);
}
rgb = new float[]{0.5f, 0.5f, 0.5f};
cie = new float[]{0.5f, 0.5f, 0.5f};
}
}
public Object initTest(TestEnvironment env, Result result) {
ColorSpace cs = getColorSpace(env);
return new Context(env, result, cs);
}
public void cleanupTest(TestEnvironment te, Object o) {
}
private static class FromRGBTest extends DataConversionTests {
public FromRGBTest() {
super(dataConvRoot,
"fromRGB",
"ColorSpace.fromRGB()");
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context) ctx;
final ColorSpace cs = ictx.cs;
final float[] rgb = ictx.rgb;
do {
try {
cs.fromRGB(rgb);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
private static class FromCIEXYZTest extends DataConversionTests {
public FromCIEXYZTest() {
super(dataConvRoot,
"fromCIEXYZ",
"ColorSpace.fromCIEXYZ()");
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context) ctx;
final ColorSpace cs = ictx.cs;
final float[] val = ictx.cie;
do {
try {
cs.fromCIEXYZ(val);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
private static class ToCIEXYZTest extends DataConversionTests {
public ToCIEXYZTest() {
super(dataConvRoot,
"toCIEXYZ",
"ColorSpace.toCIEXYZ()");
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context) ctx;
final ColorSpace cs = ictx.cs;
final float[] val = ictx.val;
do {
try {
cs.toCIEXYZ(val);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
private static class ToRGBTest extends DataConversionTests {
public ToRGBTest() {
super(dataConvRoot,
"toRGB",
"ColorSpace.toRGB()");
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context) ctx;
final ColorSpace cs = ictx.cs;
final float[] val = ictx.val;
do {
try {
cs.toRGB(val);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
}

View file

@ -0,0 +1,172 @@
/*
* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.cmm;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import j2dbench.Group;
import j2dbench.Option;
import j2dbench.Result;
import j2dbench.TestEnvironment;
/* This benchmark verifies how changes in cmm library affects image decoding */
public class EmbeddedProfileTests extends ColorConversionTests {
protected static Group grpRoot;
protected static Group grpOptionsRoot;
protected static Option inputImages;
public static void init() {
grpRoot = new Group(colorConvRoot, "embed", "Embedded Profile Tests");
grpOptionsRoot = new Group(grpRoot, "embedOptions", "Options");
inputImages = createImageList();
new ReadImageTest();
}
private static class IccImageResource {
static IccImageResource SMALL = new IccImageResource("images/img_icc_small.jpg", "512x512", "Small: 512x512");
static IccImageResource MEDIUM = new IccImageResource("images/img_icc_medium.jpg", "2048x2048", "Medium: 2048x2048");
static IccImageResource LARGE = new IccImageResource("images/img_icc_large.jpg", "4096x4096", "Large: 4096x4096");
private IccImageResource(String file, String name, String description) {
this.url = CMMTests.class.getResource(file);
this.abbrev = name;
this.description = description;
}
public final URL url;
public final String abbrev;
public final String description;
public static IccImageResource[] values() {
return new IccImageResource[]{SMALL, MEDIUM, LARGE};
}
}
private static Option createImageList() {
IccImageResource[] images = IccImageResource.values();
int num = images.length;
String[] names = new String[num];
String[] abbrev = new String[num];
String[] descr = new String[num];
for (int i = 0; i < num; i++) {
names[i] = images[i].abbrev;
abbrev[i] = images[i].abbrev;
descr[i] = images[i].description;
}
Option list = new Option.ObjectList(grpOptionsRoot,
"Images", "Input Images",
names, images, abbrev, descr, 1);
return list;
}
public EmbeddedProfileTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
addDependencies(grpOptionsRoot, true);
}
private static class Context {
URL input;
public Context(TestEnvironment env, Result res) {
IccImageResource icc_input = (IccImageResource)
env.getModifier(inputImages);
input = icc_input.url;
}
}
public Object initTest(TestEnvironment env, Result res) {
return new Context(env, res);
}
public void cleanupTest(TestEnvironment env, Object o) {
Context ctx = (Context)o;
ctx.input = null;
}
private static class ReadImageTest extends EmbeddedProfileTests {
public ReadImageTest() {
super(grpRoot, "embd_img_read", "ImageReader.read()");
}
public void runTest(Object octx, int numReps) {
final Context ctx = (Context)octx;
final URL url = ctx.input;
ImageInputStream iis = null;
ImageReader reader = null;
try {
iis = ImageIO.createImageInputStream(url.openStream());
reader = (ImageReader) ImageIO.getImageReaders(iis).next();
} catch (IOException e) {
throw new RuntimeException("Unable to run the benchmark", e);
}
do {
try {
reader.setInput(iis);
BufferedImage img = reader.read(0);
reader.reset();
iis = ImageIO.createImageInputStream(url.openStream());
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
}

View file

@ -0,0 +1,128 @@
/*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.cmm;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import j2dbench.Group;
import j2dbench.Result;
import j2dbench.TestEnvironment;
public class ProfileTests extends CMMTests {
protected static Group profileRoot;
public static void init() {
profileRoot = new Group(cmmRoot, "profiles", "Profile Handling Benchmarks");
new ReadHeaderTest();
new GetNumComponentsTest();
}
protected ProfileTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
protected static class Context {
ICC_Profile profile;
TestEnvironment env;
Result res;
public Context(ICC_Profile profile, TestEnvironment env, Result res) {
this.profile = profile;
this.env = env;
this.res = res;
}
}
public Object initTest(TestEnvironment env, Result res) {
ICC_ColorSpace cs = (ICC_ColorSpace) getColorSpace(env);
return new Context(cs.getProfile(), env, res);
}
public void cleanupTest(TestEnvironment env, Object o) {
}
private static class ReadHeaderTest extends ProfileTests {
public ReadHeaderTest() {
super(profileRoot,
"getHeader",
"getData(icSigHead)");
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context) ctx;
final ICC_Profile profile = ictx.profile;
byte[] data = null;
do {
try {
data = profile.getData(ICC_Profile.icSigHead);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
private static class GetNumComponentsTest extends ProfileTests {
public GetNumComponentsTest() {
super(profileRoot,
"getNumComponents",
"getNumComponents");
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context) ctx;
final ICC_Profile profile = ictx.profile;
do {
try {
int num = profile.getNumComponents();
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
}

View file

@ -0,0 +1,197 @@
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.iio;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import j2dbench.Group;
import j2dbench.Option;
import j2dbench.Result;
import j2dbench.Test;
import j2dbench.TestEnvironment;
public abstract class IIOTests extends Test {
protected static final String CONTENT_BLANK = "blank";
protected static final String CONTENT_RANDOM = "random";
protected static final String CONTENT_VECTOR = "vector";
protected static final String CONTENT_PHOTO = "photo";
static boolean hasImageIO;
static {
try {
hasImageIO = (javax.imageio.ImageIO.class != null);
} catch (NoClassDefFoundError e) {
}
}
protected static Group iioRoot;
protected static Group iioOptRoot;
protected static Option sizeList;
protected static Option contentList;
protected static Option listenerTog;
public static void init() {
if (!hasImageIO) {
// REMIND: We currently rely on Image I/O to generate the image
// files that are used in the InputImageTests, so
// unfortunately we need to punt on pre-1.4 JDKs...
return;
}
iioRoot = new Group("imageio", "Image I/O Benchmarks");
iioRoot.setTabbed();
iioOptRoot = new Group(iioRoot, "opts", "General Options");
int[] sizes = new int[] {1, 20, 250, 1000, 4000};
String[] sizeStrs = new String[] {
"1x1", "20x20", "250x250", "1000x1000", "4000x4000"
};
String[] sizeDescs = new String[] {
"Tiny Images (1x1)",
"Small Images (20x20)",
"Medium Images (250x250)",
"Large Images (1000x1000)",
"Huge Images (4000x4000)",
};
sizeList = new Option.IntList(iioOptRoot,
"size", "Image Size",
sizes, sizeStrs, sizeDescs, 0x4);
((Option.ObjectList) sizeList).setNumRows(5);
String[] contentStrs = new String[] {
CONTENT_BLANK, CONTENT_RANDOM, CONTENT_VECTOR, CONTENT_PHOTO,
};
String[] contentDescs = new String[] {
"Blank (opaque black)",
"Random",
"Vector Art",
"Photograph",
};
contentList = new Option.ObjectList(iioOptRoot,
"content", "Image Content",
contentStrs, contentStrs,
contentStrs, contentDescs,
0x8);
InputTests.init();
if (hasImageIO) {
OutputTests.init();
}
}
protected IIOTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
addDependencies(iioOptRoot, true);
}
protected static BufferedImage createBufferedImage(int width,
int height,
String type,
boolean hasAlpha)
{
BufferedImage image;
image = new BufferedImage(width, height, hasAlpha ?
BufferedImage.TYPE_INT_ARGB :
BufferedImage.TYPE_INT_RGB);
if (type.equals(CONTENT_RANDOM)) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int rgb = (int)(Math.random() * 0xffffff);
if (hasAlpha) {
rgb |= 0x7f000000;
}
image.setRGB(x, y, rgb);
}
}
} else if (type.equals(CONTENT_VECTOR)) {
Graphics2D g = image.createGraphics();
if (hasAlpha) {
// fill background with a translucent color
g.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC, 0.5f));
}
g.setColor(Color.blue);
g.fillRect(0, 0, width, height);
g.setComposite(AlphaComposite.Src);
g.setColor(Color.yellow);
g.fillOval(2, 2, width-4, height-4);
g.setColor(Color.red);
g.fillOval(4, 4, width-8, height-8);
g.setColor(Color.green);
g.fillRect(8, 8, width-16, height-16);
g.setColor(Color.white);
g.drawLine(0, 0, width, height);
g.drawLine(0, height, width, 0);
g.dispose();
} else if (type.equals(CONTENT_PHOTO)) {
Image photo = null;
try {
photo = Toolkit.getDefaultToolkit().createImage(
IIOTests.class.getResource("images/photo.jpg"));
} catch (Exception e) {
System.err.println("error loading photo");
e.printStackTrace();
}
Graphics2D g = image.createGraphics();
if (hasAlpha) {
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC,
0.5f));
}
g.drawImage(photo, 0, 0, width, height, null);
g.dispose();
} else { // CONTENT_BLANK
// leave the image empty
}
return image;
}
}

View file

@ -0,0 +1,524 @@
/*
* Copyright (c) 2006, 2020, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.iio;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.event.IIOReadProgressListener;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;
import j2dbench.Group;
import j2dbench.Modifier;
import j2dbench.Option;
import j2dbench.Result;
import j2dbench.Test;
import j2dbench.TestEnvironment;
abstract class InputImageTests extends InputTests {
private static final int TEST_TOOLKIT = 1;
private static final int TEST_IMAGEIO = 2;
private static final int TEST_IMAGEREADER = 3;
private static Group imageRoot;
private static Group toolkitRoot;
private static Group toolkitOptRoot;
private static Option toolkitReadFormatList;
private static Group toolkitTestRoot;
private static Group imageioRoot;
private static Group imageioOptRoot;
private static ImageReaderSpi[] imageioReaderSpis;
private static String[] imageioReadFormatShortNames;
private static Option imageioReadFormatList;
private static Group imageioTestRoot;
private static Group imageReaderRoot;
private static Group imageReaderOptRoot;
private static Option seekForwardOnlyTog;
private static Option ignoreMetadataTog;
private static Option installListenerTog;
private static Group imageReaderTestRoot;
public static void init() {
imageRoot = new Group(inputRoot, "image", "Image Reading Benchmarks");
imageRoot.setTabbed();
// Toolkit Benchmarks
toolkitRoot = new Group(imageRoot, "toolkit", "Toolkit");
toolkitOptRoot = new Group(toolkitRoot, "opts", "Toolkit Options");
String[] tkFormats = new String[] {"gif", "jpg", "png"};
toolkitReadFormatList =
new Option.ObjectList(toolkitOptRoot,
"format", "Image Format",
tkFormats, tkFormats,
tkFormats, tkFormats,
0x0);
toolkitTestRoot = new Group(toolkitRoot, "tests", "Toolkit Tests");
new ToolkitCreateImage();
// Image I/O Benchmarks
if (hasImageIO) {
imageioRoot = new Group(imageRoot, "imageio", "Image I/O");
// Image I/O Options
imageioOptRoot = new Group(imageioRoot, "opts",
"Image I/O Options");
initIIOReadFormats();
imageioReadFormatList =
new Option.ObjectList(imageioOptRoot,
"format", "Image Format",
imageioReadFormatShortNames,
imageioReaderSpis,
imageioReadFormatShortNames,
imageioReadFormatShortNames,
0x0);
// Image I/O Tests
imageioTestRoot = new Group(imageioRoot, "tests",
"Image I/O Tests");
new ImageIORead();
// ImageReader Options
imageReaderRoot = new Group(imageioRoot, "reader",
"ImageReader Benchmarks");
imageReaderOptRoot = new Group(imageReaderRoot, "opts",
"ImageReader Options");
seekForwardOnlyTog =
new Option.Toggle(imageReaderOptRoot,
"seekForwardOnly",
"Seek Forward Only",
Option.Toggle.On);
ignoreMetadataTog =
new Option.Toggle(imageReaderOptRoot,
"ignoreMetadata",
"Ignore Metadata",
Option.Toggle.On);
installListenerTog =
new Option.Toggle(imageReaderOptRoot,
"installListener",
"Install Progress Listener",
Option.Toggle.Off);
// ImageReader Tests
imageReaderTestRoot = new Group(imageReaderRoot, "tests",
"ImageReader Tests");
new ImageReaderRead();
new ImageReaderGetImageMetadata();
}
}
private static void initIIOReadFormats() {
List spis = new ArrayList();
List shortNames = new ArrayList();
ImageIO.scanForPlugins();
IIORegistry registry = IIORegistry.getDefaultInstance();
java.util.Iterator readerspis =
registry.getServiceProviders(ImageReaderSpi.class, false);
while (readerspis.hasNext()) {
// REMIND: there could be more than one non-core plugin for
// a particular format, as is the case for JPEG2000 in the JAI
// IIO Tools package, so we should support that somehow
ImageReaderSpi spi = (ImageReaderSpi)readerspis.next();
String klass = spi.getClass().getName();
String format = spi.getFormatNames()[0].toLowerCase();
String suffix = spi.getFileSuffixes()[0].toLowerCase();
if (suffix == null || suffix.equals("")) {
suffix = format;
}
String shortName;
if (klass.startsWith("com.sun.imageio.plugins")) {
shortName = "core-" + suffix;
} else {
shortName = "ext-" + suffix;
}
spis.add(spi);
shortNames.add(shortName);
}
imageioReaderSpis = new ImageReaderSpi[spis.size()];
imageioReaderSpis = (ImageReaderSpi[])spis.toArray(imageioReaderSpis);
imageioReadFormatShortNames = new String[shortNames.size()];
imageioReadFormatShortNames =
(String[])shortNames.toArray(imageioReadFormatShortNames);
}
protected InputImageTests(Group parent,
String nodeName, String description)
{
super(parent, nodeName, description);
}
public void cleanupTest(TestEnvironment env, Object ctx) {
Context iioctx = (Context)ctx;
iioctx.cleanup(env);
}
private static class Context extends InputTests.Context {
String format;
BufferedImage image;
ImageReader reader;
boolean seekForwardOnly;
boolean ignoreMetadata;
Context(TestEnvironment env, Result result, int testType) {
super(env, result);
String content = (String)env.getModifier(contentList);
if (content == null) {
content = CONTENT_BLANK;
}
// REMIND: add option for non-opaque images
image = createBufferedImage(size, size, content, false);
result.setUnits(size*size);
result.setUnitName("pixel");
if (testType == TEST_IMAGEIO || testType == TEST_IMAGEREADER) {
ImageReaderSpi readerspi =
(ImageReaderSpi)env.getModifier(imageioReadFormatList);
format = readerspi.getFileSuffixes()[0].toLowerCase();
if (testType == TEST_IMAGEREADER) {
seekForwardOnly = env.isEnabled(seekForwardOnlyTog);
ignoreMetadata = env.isEnabled(ignoreMetadataTog);
try {
reader = readerspi.createReaderInstance();
} catch (IOException e) {
System.err.println("error creating reader");
e.printStackTrace();
}
if (env.isEnabled(installListenerTog)) {
reader.addIIOReadProgressListener(
new ReadProgressListener());
}
}
if (format.equals("wbmp")) {
// REMIND: this is a hack to create an image that the
// WBMPImageWriter can handle (a better approach
// would involve checking the ImageTypeSpecifier
// of the writer's default image param)
BufferedImage newimg =
new BufferedImage(size, size,
BufferedImage.TYPE_BYTE_BINARY);
Graphics g = newimg.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
image = newimg;
}
} else if (testType == TEST_TOOLKIT) {
format = (String)env.getModifier(toolkitReadFormatList);
} else { // testType == TEST_JPEGCODEC
format = "jpeg";
}
initInput();
}
void initContents(File f) throws IOException {
ImageIO.write(image, format, f);
}
void initContents(OutputStream out) throws IOException {
ImageIO.write(image, format, out);
}
void cleanup(TestEnvironment env) {
super.cleanup(env);
if (reader != null) {
reader.dispose();
reader = null;
}
}
}
private static class ToolkitCreateImage extends InputImageTests {
private static final Component canvas = new Component() {};
public ToolkitCreateImage() {
super(toolkitTestRoot,
"createImage",
"Toolkit.createImage()");
addDependency(generalSourceRoot,
new Modifier.Filter() {
public boolean isCompatible(Object val) {
// Toolkit handles FILE, URL, and ARRAY, but
// not FILECHANNEL
InputType t = (InputType)val;
return (t.getType() != INPUT_FILECHANNEL);
}
});
addDependencies(toolkitOptRoot, true);
}
public Object initTest(TestEnvironment env, Result result) {
return new Context(env, result, TEST_TOOLKIT);
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final Object input = ictx.input;
final int inputType = ictx.inputType;
final Toolkit tk = Toolkit.getDefaultToolkit();
final MediaTracker mt = new MediaTracker(canvas);
switch (inputType) {
case INPUT_FILE:
String filename = ((File)input).getAbsolutePath();
do {
try {
Image img = tk.createImage(filename);
mt.addImage(img, 0);
mt.waitForID(0, 0);
mt.removeImage(img, 0);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
break;
case INPUT_URL:
do {
try {
Image img = tk.createImage((URL)input);
mt.addImage(img, 0);
mt.waitForID(0, 0);
mt.removeImage(img, 0);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
break;
case INPUT_ARRAY:
do {
try {
Image img = tk.createImage((byte[])input);
mt.addImage(img, 0);
mt.waitForID(0, 0);
mt.removeImage(img, 0);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
break;
default:
throw new IllegalArgumentException("Invalid input type");
}
}
}
private static class ImageIORead extends InputImageTests {
public ImageIORead() {
super(imageioTestRoot,
"imageioRead",
"ImageIO.read()");
addDependency(generalSourceRoot,
new Modifier.Filter() {
public boolean isCompatible(Object val) {
// ImageIO.read() handles FILE, URL, and ARRAY, but
// not FILECHANNEL (well, I suppose we could create
// an ImageInputStream from a FileChannel source,
// but that's not a common use case; FileChannel is
// better handled by the ImageReader tests below)
InputType t = (InputType)val;
return (t.getType() != INPUT_FILECHANNEL);
}
});
addDependencies(imageioOptRoot, true);
}
public Object initTest(TestEnvironment env, Result result) {
return new Context(env, result, TEST_IMAGEIO);
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final Object input = ictx.input;
final int inputType = ictx.inputType;
switch (inputType) {
case INPUT_FILE:
do {
try {
ImageIO.read((File)input);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
break;
case INPUT_URL:
do {
try {
ImageIO.read((URL)input);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
break;
case INPUT_ARRAY:
do {
try {
ByteArrayInputStream bais =
new ByteArrayInputStream((byte[])input);
BufferedInputStream bis =
new BufferedInputStream(bais);
ImageIO.read(bis);
bais.close();
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
break;
default:
throw new IllegalArgumentException("Invalid input type");
}
}
}
private static class ImageReaderRead extends InputImageTests {
public ImageReaderRead() {
super(imageReaderTestRoot,
"read",
"ImageReader.read()");
addDependency(generalSourceRoot);
addDependencies(imageioGeneralOptRoot, true);
addDependencies(imageioOptRoot, true);
addDependencies(imageReaderOptRoot, true);
}
public Object initTest(TestEnvironment env, Result result) {
return new Context(env, result, TEST_IMAGEREADER);
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageReader reader = ictx.reader;
final boolean seekForwardOnly = ictx.seekForwardOnly;
final boolean ignoreMetadata = ictx.ignoreMetadata;
do {
try {
ImageInputStream iis = ictx.createImageInputStream();
reader.setInput(iis, seekForwardOnly, ignoreMetadata);
reader.read(0);
reader.reset();
iis.close();
ictx.closeOriginalStream();
} catch (IOException e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
private static class ImageReaderGetImageMetadata extends InputImageTests {
public ImageReaderGetImageMetadata() {
super(imageReaderTestRoot,
"getImageMetadata",
"ImageReader.getImageMetadata()");
addDependency(generalSourceRoot);
addDependencies(imageioGeneralOptRoot, true);
addDependencies(imageioOptRoot, true);
addDependencies(imageReaderOptRoot, true);
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result, TEST_IMAGEREADER);
// override units since this test doesn't read "pixels"
result.setUnits(1);
result.setUnitName("image");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageReader reader = ictx.reader;
final boolean seekForwardOnly = ictx.seekForwardOnly;
final boolean ignoreMetadata = ictx.ignoreMetadata;
do {
try {
ImageInputStream iis = ictx.createImageInputStream();
reader.setInput(iis, seekForwardOnly, ignoreMetadata);
reader.getImageMetadata(0);
reader.reset();
iis.close();
ictx.closeOriginalStream();
} catch (IOException e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
private static class ReadProgressListener
implements IIOReadProgressListener
{
public void sequenceStarted(ImageReader source, int minIndex) {}
public void sequenceComplete(ImageReader source) {}
public void imageStarted(ImageReader source, int imageIndex) {}
public void imageProgress(ImageReader source, float percentageDone) {}
public void imageComplete(ImageReader source) {}
public void thumbnailStarted(ImageReader source,
int imageIndex, int thumbnailIndex) {}
public void thumbnailProgress(ImageReader source,
float percentageDone) {}
public void thumbnailComplete(ImageReader source) {}
public void readAborted(ImageReader source) {}
}
}

View file

@ -0,0 +1,718 @@
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.iio;
import java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import j2dbench.Group;
import j2dbench.Result;
import j2dbench.TestEnvironment;
abstract class InputStreamTests extends InputTests {
private static Group streamRoot;
private static Group streamTestRoot;
public static void init() {
streamRoot = new Group(inputRoot, "stream",
"Image Stream Benchmarks");
streamTestRoot = new Group(streamRoot, "tests",
"ImageInputStream Tests");
new IISConstruct();
new IISRead();
new IISReadByteArray();
new IISReadFullyByteArray();
new IISReadBit();
new IISReadByte();
new IISReadUnsignedByte();
new IISReadShort();
new IISReadUnsignedShort();
new IISReadInt();
new IISReadUnsignedInt();
new IISReadFloat();
new IISReadLong();
new IISReadDouble();
new IISSkipBytes();
}
protected InputStreamTests(Group parent,
String nodeName, String description)
{
super(parent, nodeName, description);
addDependency(generalSourceRoot);
addDependencies(imageioGeneralOptRoot, true);
}
public void cleanupTest(TestEnvironment env, Object ctx) {
Context iioctx = (Context)ctx;
iioctx.cleanup(env);
}
private static class Context extends InputTests.Context {
ImageInputStream inputStream;
int scanlineStride; // width of a scanline (in bytes)
int length; // length of the entire stream (in bytes)
byte[] byteBuf;
Context(TestEnvironment env, Result result) {
super(env, result);
// 4 bytes per "pixel"
scanlineStride = size * 4;
// tack on an extra 4 bytes, so that in the 1x1 case we can
// call readLong() or readDouble() without hitting EOF
length = (scanlineStride * size) + 4;
// big enough for one scanline
byteBuf = new byte[scanlineStride];
initInput();
try {
inputStream = createImageInputStream();
} catch (IOException e) {
System.err.println("Error creating ImageInputStream");
}
}
void initContents(File f) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
initContents(fos);
} finally {
fos.close();
}
}
void initContents(OutputStream out) throws IOException {
for (int i = 0; i < size; i++) {
out.write(byteBuf);
}
out.write(new byte[4]); // add the 4 byte pad
out.flush();
}
void cleanup(TestEnvironment env) {
super.cleanup(env);
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
System.err.println("error closing stream");
}
inputStream = null;
}
}
}
private static class IISConstruct extends InputStreamTests {
public IISConstruct() {
super(streamTestRoot,
"construct",
"Construct");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(1);
result.setUnitName("stream");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
try {
do {
ImageInputStream iis = ictx.createImageInputStream();
iis.close();
ictx.closeOriginalStream();
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class IISRead extends InputStreamTests {
public IISRead() {
super(streamTestRoot,
"read",
"read()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(1);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos >= length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.read();
pos++;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadByteArray extends InputStreamTests {
public IISReadByteArray() {
super(streamTestRoot,
"readByteArray",
"read(byte[]) (one \"scanline\" at a time)");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(ctx.scanlineStride);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final byte[] buf = ictx.byteBuf;
final int scanlineStride = ictx.scanlineStride;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + scanlineStride > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.read(buf);
pos += scanlineStride;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadFullyByteArray extends InputStreamTests {
public IISReadFullyByteArray() {
super(streamTestRoot,
"readFullyByteArray",
"readFully(byte[]) (one \"scanline\" at a time)");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(ctx.scanlineStride);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final byte[] buf = ictx.byteBuf;
final int scanlineStride = ictx.scanlineStride;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + scanlineStride > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readFully(buf);
pos += scanlineStride;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadBit extends InputStreamTests {
public IISReadBit() {
super(streamTestRoot,
"readBit",
"readBit()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(1);
result.setUnitName("bit");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length * 8;
int pos = 0;
try {
iis.mark();
do {
if (pos >= length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readBit();
pos++;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadByte extends InputStreamTests {
public IISReadByte() {
super(streamTestRoot,
"readByte",
"readByte()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(1);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos >= length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readByte();
pos++;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadUnsignedByte extends InputStreamTests {
public IISReadUnsignedByte() {
super(streamTestRoot,
"readUnsignedByte",
"readUnsignedByte()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(1);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos >= length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readUnsignedByte();
pos++;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadShort extends InputStreamTests {
public IISReadShort() {
super(streamTestRoot,
"readShort",
"readShort()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(2);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + 2 > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readShort();
pos += 2;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadUnsignedShort extends InputStreamTests {
public IISReadUnsignedShort() {
super(streamTestRoot,
"readUnsignedShort",
"readUnsignedShort()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(2);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + 2 > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readUnsignedShort();
pos += 2;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadInt extends InputStreamTests {
public IISReadInt() {
super(streamTestRoot,
"readInt",
"readInt()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(4);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + 4 > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readInt();
pos += 4;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadUnsignedInt extends InputStreamTests {
public IISReadUnsignedInt() {
super(streamTestRoot,
"readUnsignedInt",
"readUnsignedInt()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(4);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + 4 > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readUnsignedInt();
pos += 4;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadFloat extends InputStreamTests {
public IISReadFloat() {
super(streamTestRoot,
"readFloat",
"readFloat()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(4);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + 4 > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readFloat();
pos += 4;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadLong extends InputStreamTests {
public IISReadLong() {
super(streamTestRoot,
"readLong",
"readLong()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(8);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + 8 > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readLong();
pos += 8;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISReadDouble extends InputStreamTests {
public IISReadDouble() {
super(streamTestRoot,
"readDouble",
"readDouble()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(8);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + 8 > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.readDouble();
pos += 8;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
private static class IISSkipBytes extends InputStreamTests {
public IISSkipBytes() {
super(streamTestRoot,
"skipBytes",
"skipBytes() (one \"scanline\" at a time)");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(ctx.scanlineStride);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageInputStream iis = ictx.inputStream;
final int scanlineStride = ictx.scanlineStride;
final int length = ictx.length;
int pos = 0;
try {
iis.mark();
do {
if (pos + scanlineStride > length) {
iis.reset();
iis.mark();
pos = 0;
}
iis.skipBytes(scanlineStride);
pos += scanlineStride;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { iis.reset(); } catch (IOException e) {}
}
}
}
}

View file

@ -0,0 +1,275 @@
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.iio;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageInputStreamSpi;
import javax.imageio.stream.FileCacheImageInputStream;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import j2dbench.Group;
import j2dbench.Option;
import j2dbench.Result;
import j2dbench.TestEnvironment;
abstract class InputTests extends IIOTests {
protected static final int INPUT_FILE = 1;
protected static final int INPUT_URL = 2;
protected static final int INPUT_ARRAY = 3;
protected static final int INPUT_FILECHANNEL = 4;
protected static ImageInputStreamSpi fileChannelIISSpi;
static {
if (hasImageIO) {
ImageIO.scanForPlugins();
IIORegistry registry = IIORegistry.getDefaultInstance();
java.util.Iterator spis =
registry.getServiceProviders(ImageInputStreamSpi.class, false);
while (spis.hasNext()) {
ImageInputStreamSpi spi = (ImageInputStreamSpi)spis.next();
String klass = spi.getClass().getName();
if (klass.endsWith("ChannelImageInputStreamSpi")) {
fileChannelIISSpi = spi;
break;
}
}
}
}
protected static Group inputRoot;
protected static Group inputOptRoot;
protected static Group generalOptRoot;
protected static Group.EnableSet generalSourceRoot;
protected static Option sourceFileOpt;
protected static Option sourceUrlOpt;
protected static Option sourceByteArrayOpt;
protected static Group imageioGeneralOptRoot;
protected static Option sourceFileChannelOpt;
protected static Option useCacheTog;
public static void init() {
inputRoot = new Group(iioRoot, "input", "Input Benchmarks");
inputRoot.setTabbed();
// Options
inputOptRoot = new Group(inputRoot, "opts", "Options");
// General Options
generalOptRoot = new Group(inputOptRoot,
"general", "General Options");
generalSourceRoot = new Group.EnableSet(generalOptRoot,
"source", "Sources");
sourceFileOpt = new InputType("file", "File", INPUT_FILE);
sourceUrlOpt = new InputType("url", "URL", INPUT_URL);
sourceByteArrayOpt = new InputType("byteArray", "byte[]", INPUT_ARRAY);
if (hasImageIO) {
// Image I/O Options
imageioGeneralOptRoot = new Group(inputOptRoot,
"imageio", "Image I/O Options");
if (fileChannelIISSpi != null) {
sourceFileChannelOpt =
new InputType("fileChannel", "FileChannel",
INPUT_FILECHANNEL);
}
useCacheTog = new Option.Toggle(imageioGeneralOptRoot, "useCache",
"ImageIO.setUseCache()",
Option.Toggle.Off);
}
InputImageTests.init();
if (hasImageIO) {
InputStreamTests.init();
}
}
protected InputTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
protected static class InputType extends Option.Enable {
private int type;
public InputType(String nodeName, String description, int type) {
super(generalSourceRoot, nodeName, description, false);
this.type = type;
}
public int getType() {
return type;
}
public String getAbbreviatedModifierDescription(Object value) {
return getModifierValueName(value);
}
public String getModifierValueName(Object val) {
return getNodeName();
}
}
protected abstract static class Context {
int size;
Object input;
int inputType;
InputStream origStream;
Context(TestEnvironment env, Result result) {
size = env.getIntValue(sizeList);
if (hasImageIO) {
if (env.getModifier(useCacheTog) != null) {
ImageIO.setUseCache(env.isEnabled(useCacheTog));
}
}
InputType t = (InputType)env.getModifier(generalSourceRoot);
inputType = t.getType();
}
void initInput() {
if ((inputType == INPUT_FILE) ||
(inputType == INPUT_URL) ||
(inputType == INPUT_FILECHANNEL))
{
try {
// REMIND: this approach will fail for GIF on pre-1.6 VM's
// (since earlier releases do not include a
// GIFImageWriter in the core JDK)
File inputfile = File.createTempFile("iio", ".tmp");
inputfile.deleteOnExit();
initContents(inputfile);
if (inputType == INPUT_FILE) {
input = inputfile;
} else if (inputType == INPUT_FILECHANNEL) {
input = inputfile;
} else { // inputType == INPUT_URL
try {
input = inputfile.toURI().toURL();
} catch (Exception e) {
System.err.println("error creating URL");
}
}
} catch (IOException e) {
System.err.println("error creating image file");
e.printStackTrace();
}
} else {
ByteArrayOutputStream out;
try {
out = new ByteArrayOutputStream();
initContents(out);
} catch (IOException e) {
System.err.println("error creating image array");
e.printStackTrace();
return;
}
input = out.toByteArray();
}
}
abstract void initContents(File f) throws IOException;
abstract void initContents(OutputStream out) throws IOException;
ImageInputStream createImageInputStream() throws IOException {
ImageInputStream iis;
BufferedInputStream bis;
switch (inputType) {
case INPUT_FILE:
iis = new FileImageInputStream((File)input);
break;
case INPUT_URL:
origStream = ((URL)input).openStream();
bis = new BufferedInputStream(origStream);
if (ImageIO.getUseCache()) {
iis = new FileCacheImageInputStream(bis, null);
} else {
iis = new MemoryCacheImageInputStream(bis);
}
break;
case INPUT_ARRAY:
origStream = new ByteArrayInputStream((byte[])input);
bis = new BufferedInputStream(origStream);
if (ImageIO.getUseCache()) {
iis = new FileCacheImageInputStream(bis, null);
} else {
iis = new MemoryCacheImageInputStream(bis);
}
break;
case INPUT_FILECHANNEL:
FileInputStream fis = new FileInputStream((File)input);
origStream = fis;
java.nio.channels.FileChannel fc = fis.getChannel();
iis = fileChannelIISSpi.createInputStreamInstance(fc, false,
null);
break;
default:
iis = null;
break;
}
return iis;
}
void closeOriginalStream() throws IOException {
if (origStream != null) {
origStream.close();
origStream = null;
}
}
void cleanup(TestEnvironment env) {
}
}
}

View file

@ -0,0 +1,356 @@
/*
* Copyright (c) 2006, 2020, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.iio;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.event.IIOWriteProgressListener;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.stream.ImageOutputStream;
import j2dbench.Group;
import j2dbench.Modifier;
import j2dbench.Option;
import j2dbench.Result;
import j2dbench.Test;
import j2dbench.TestEnvironment;
abstract class OutputImageTests extends OutputTests {
private static final int TEST_IMAGEIO = 1;
private static final int TEST_IMAGEWRITER = 2;
private static Group imageRoot;
private static Group imageioRoot;
private static Group imageioOptRoot;
private static ImageWriterSpi[] imageioWriterSpis;
private static String[] imageioWriteFormatShortNames;
private static Option imageioWriteFormatList;
private static Group imageioTestRoot;
private static Group imageWriterRoot;
private static Group imageWriterOptRoot;
private static Option installListenerTog;
private static Group imageWriterTestRoot;
public static void init() {
imageRoot = new Group(outputRoot, "image", "Image Writing Benchmarks");
imageRoot.setTabbed();
// Image I/O Benchmarks
if (hasImageIO) {
imageioRoot = new Group(imageRoot, "imageio", "Image I/O");
// Image I/O Options
imageioOptRoot = new Group(imageioRoot, "opts",
"Image I/O Options");
initIIOWriteFormats();
imageioWriteFormatList =
new Option.ObjectList(imageioOptRoot,
"format", "Image Format",
imageioWriteFormatShortNames,
imageioWriterSpis,
imageioWriteFormatShortNames,
imageioWriteFormatShortNames,
0x0);
// Image I/O Tests
imageioTestRoot = new Group(imageioRoot, "tests",
"Image I/O Tests");
new ImageIOWrite();
// ImageWriter Options
imageWriterRoot = new Group(imageioRoot, "writer",
"ImageWriter Benchmarks");
imageWriterOptRoot = new Group(imageWriterRoot, "opts",
"ImageWriter Options");
installListenerTog =
new Option.Toggle(imageWriterOptRoot,
"installListener",
"Install Progress Listener",
Option.Toggle.Off);
// ImageWriter Tests
imageWriterTestRoot = new Group(imageWriterRoot, "tests",
"ImageWriter Tests");
new ImageWriterWrite();
}
}
private static void initIIOWriteFormats() {
List spis = new ArrayList();
List shortNames = new ArrayList();
ImageIO.scanForPlugins();
IIORegistry registry = IIORegistry.getDefaultInstance();
java.util.Iterator writerspis =
registry.getServiceProviders(ImageWriterSpi.class, false);
while (writerspis.hasNext()) {
// REMIND: there could be more than one non-core plugin for
// a particular format, as is the case for JPEG2000 in the JAI
// IIO Tools package, so we should support that somehow
ImageWriterSpi spi = (ImageWriterSpi)writerspis.next();
String klass = spi.getClass().getName();
String format = spi.getFormatNames()[0].toLowerCase();
String suffix = spi.getFileSuffixes()[0].toLowerCase();
if (suffix == null || suffix.equals("")) {
suffix = format;
}
String shortName;
if (klass.startsWith("com.sun.imageio.plugins")) {
shortName = "core-" + suffix;
} else {
shortName = "ext-" + suffix;
}
spis.add(spi);
shortNames.add(shortName);
}
imageioWriterSpis = new ImageWriterSpi[spis.size()];
imageioWriterSpis = (ImageWriterSpi[])spis.toArray(imageioWriterSpis);
imageioWriteFormatShortNames = new String[shortNames.size()];
imageioWriteFormatShortNames =
(String[])shortNames.toArray(imageioWriteFormatShortNames);
}
protected OutputImageTests(Group parent,
String nodeName, String description)
{
super(parent, nodeName, description);
}
public void cleanupTest(TestEnvironment env, Object ctx) {
Context iioctx = (Context)ctx;
iioctx.cleanup(env);
}
private static class Context extends OutputTests.Context {
String format;
BufferedImage image;
ImageWriter writer;
Context(TestEnvironment env, Result result, int testType) {
super(env, result);
String content = (String)env.getModifier(contentList);
if (content == null) {
content = CONTENT_BLANK;
}
// REMIND: add option for non-opaque images
image = createBufferedImage(size, size, content, false);
result.setUnits(size*size);
result.setUnitName("pixel");
if (testType == TEST_IMAGEIO || testType == TEST_IMAGEWRITER) {
ImageWriterSpi writerspi =
(ImageWriterSpi)env.getModifier(imageioWriteFormatList);
format = writerspi.getFileSuffixes()[0].toLowerCase();
if (testType == TEST_IMAGEWRITER) {
try {
writer = writerspi.createWriterInstance();
} catch (IOException e) {
System.err.println("error creating writer");
e.printStackTrace();
}
if (env.isEnabled(installListenerTog)) {
writer.addIIOWriteProgressListener(
new WriteProgressListener());
}
}
if (format.equals("wbmp")) {
// REMIND: this is a hack to create an image that the
// WBMPImageWriter can handle (a better approach
// would involve checking the ImageTypeSpecifier
// of the writer's default image param)
BufferedImage newimg =
new BufferedImage(size, size,
BufferedImage.TYPE_BYTE_BINARY);
Graphics g = newimg.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
image = newimg;
}
} else { // testType == TEST_JPEGCODEC
format = "jpeg";
}
initOutput();
}
void initContents(File f) throws IOException {
ImageIO.write(image, format, f);
}
void initContents(OutputStream out) throws IOException {
ImageIO.write(image, format, out);
}
void cleanup(TestEnvironment env) {
super.cleanup(env);
if (writer != null) {
writer.dispose();
writer = null;
}
}
}
private static class ImageIOWrite extends OutputImageTests {
public ImageIOWrite() {
super(imageioTestRoot,
"imageioWrite",
"ImageIO.write()");
addDependency(generalDestRoot,
new Modifier.Filter() {
public boolean isCompatible(Object val) {
// ImageIO.write() handles FILE and ARRAY, but
// not FILECHANNEL (well, I suppose we could create
// an ImageOutputStream from a FileChannel source,
// but that's not a common use case; FileChannel is
// better handled by the ImageWriter tests below)
OutputType t = (OutputType)val;
return (t.getType() != OUTPUT_FILECHANNEL);
}
});
addDependencies(imageioOptRoot, true);
}
public Object initTest(TestEnvironment env, Result result) {
return new Context(env, result, TEST_IMAGEIO);
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final Object output = ictx.output;
final BufferedImage image = ictx.image;
final String format = ictx.format;
final int outputType = ictx.outputType;
switch (outputType) {
case OUTPUT_FILE:
do {
try {
ImageIO.write(image, format, (File)output);
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
break;
case OUTPUT_ARRAY:
do {
try {
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
BufferedOutputStream bos =
new BufferedOutputStream(baos);
ImageIO.write(image, format, bos);
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
} while (--numReps >= 0);
break;
default:
throw new IllegalArgumentException("Invalid output type");
}
}
}
private static class ImageWriterWrite extends OutputImageTests {
public ImageWriterWrite() {
super(imageWriterTestRoot,
"write",
"ImageWriter.write()");
addDependency(generalDestRoot);
addDependencies(imageioGeneralOptRoot, true);
addDependencies(imageioOptRoot, true);
addDependencies(imageWriterOptRoot, true);
}
public Object initTest(TestEnvironment env, Result result) {
return new Context(env, result, TEST_IMAGEWRITER);
}
public void runTest(Object ctx, int numReps) {
final Context ictx = (Context)ctx;
final ImageWriter writer = ictx.writer;
final BufferedImage image = ictx.image;
do {
try {
ImageOutputStream ios = ictx.createImageOutputStream();
writer.setOutput(ios);
writer.write(image);
writer.reset();
ios.close();
ictx.closeOriginalStream();
} catch (IOException e) {
e.printStackTrace();
}
} while (--numReps >= 0);
}
}
private static class WriteProgressListener
implements IIOWriteProgressListener
{
public void imageStarted(ImageWriter source, int imageIndex) {}
public void imageProgress(ImageWriter source,
float percentageDone) {}
public void imageComplete(ImageWriter source) {}
public void thumbnailStarted(ImageWriter source,
int imageIndex, int thumbnailIndex) {}
public void thumbnailProgress(ImageWriter source,
float percentageDone) {}
public void thumbnailComplete(ImageWriter source) {}
public void writeAborted(ImageWriter source) {}
}
}

View file

@ -0,0 +1,500 @@
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.iio;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import j2dbench.Group;
import j2dbench.Result;
import j2dbench.TestEnvironment;
abstract class OutputStreamTests extends OutputTests {
private static Group streamRoot;
private static Group streamTestRoot;
public static void init() {
streamRoot = new Group(outputRoot, "stream",
"Image Stream Benchmarks");
streamTestRoot = new Group(streamRoot, "tests",
"ImageOutputStream Tests");
new IOSConstruct();
new IOSWrite();
new IOSWriteByteArray();
new IOSWriteBit();
new IOSWriteByte();
new IOSWriteShort();
new IOSWriteInt();
new IOSWriteFloat();
new IOSWriteLong();
new IOSWriteDouble();
}
protected OutputStreamTests(Group parent,
String nodeName, String description)
{
super(parent, nodeName, description);
addDependency(generalDestRoot);
addDependencies(imageioGeneralOptRoot, true);
}
public void cleanupTest(TestEnvironment env, Object ctx) {
Context iioctx = (Context)ctx;
iioctx.cleanup(env);
}
private static class Context extends OutputTests.Context {
ImageOutputStream outputStream;
int scanlineStride; // width of a scanline (in bytes)
int length; // length of the entire stream (in bytes)
byte[] byteBuf;
Context(TestEnvironment env, Result result) {
super(env, result);
// 4 bytes per "pixel"
scanlineStride = size * 4;
// tack on an extra 4 bytes, so that in the 1x1 case we can
// call writeLong() or writeDouble() before resetting
length = (scanlineStride * size) + 4;
// big enough for one scanline
byteBuf = new byte[scanlineStride];
initOutput();
try {
outputStream = createImageOutputStream();
} catch (IOException e) {
System.err.println("Error creating ImageOutputStream");
}
}
void cleanup(TestEnvironment env) {
super.cleanup(env);
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
System.err.println("error closing stream");
}
outputStream = null;
}
}
}
private static class IOSConstruct extends OutputStreamTests {
public IOSConstruct() {
super(streamTestRoot,
"construct",
"Construct");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(1);
result.setUnitName("stream");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
try {
do {
ImageOutputStream ios = octx.createImageOutputStream();
ios.close();
octx.closeOriginalStream();
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class IOSWrite extends OutputStreamTests {
public IOSWrite() {
super(streamTestRoot,
"write",
"write()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(1);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
final ImageOutputStream ios = octx.outputStream;
final int length = octx.length;
int pos = 0;
try {
ios.mark();
do {
if (pos >= length) {
ios.reset();
ios.mark();
pos = 0;
}
ios.write(0);
pos++;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { ios.reset(); } catch (IOException e) {}
}
}
}
private static class IOSWriteByteArray extends OutputStreamTests {
public IOSWriteByteArray() {
super(streamTestRoot,
"writeByteArray",
"write(byte[]) (one \"scanline\" at a time)");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(ctx.scanlineStride);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
final ImageOutputStream ios = octx.outputStream;
final byte[] buf = octx.byteBuf;
final int scanlineStride = octx.scanlineStride;
final int length = octx.length;
int pos = 0;
try {
ios.mark();
do {
if (pos + scanlineStride > length) {
ios.reset();
ios.mark();
pos = 0;
}
ios.write(buf);
pos += scanlineStride;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { ios.reset(); } catch (IOException e) {}
}
}
}
private static class IOSWriteBit extends OutputStreamTests {
public IOSWriteBit() {
super(streamTestRoot,
"writeBit",
"writeBit()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(1);
result.setUnitName("bit");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
final ImageOutputStream ios = octx.outputStream;
final int length = octx.length * 8; // measured in bits
int pos = 0; // measured in bits
try {
ios.mark();
do {
if (pos >= length) {
ios.reset();
ios.mark();
pos = 0;
}
ios.writeBit(0);
pos++;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { ios.reset(); } catch (IOException e) {}
}
}
}
private static class IOSWriteByte extends OutputStreamTests {
public IOSWriteByte() {
super(streamTestRoot,
"writeByte",
"writeByte()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(1);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
final ImageOutputStream ios = octx.outputStream;
final int length = octx.length;
int pos = 0;
try {
ios.mark();
do {
if (pos >= length) {
ios.reset();
ios.mark();
pos = 0;
}
ios.writeByte(0);
pos++;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { ios.reset(); } catch (IOException e) {}
}
}
}
private static class IOSWriteShort extends OutputStreamTests {
public IOSWriteShort() {
super(streamTestRoot,
"writeShort",
"writeShort()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(2);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
final ImageOutputStream ios = octx.outputStream;
final int length = octx.length;
int pos = 0;
try {
ios.mark();
do {
if (pos + 2 > length) {
ios.reset();
ios.mark();
pos = 0;
}
ios.writeShort(0);
pos += 2;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { ios.reset(); } catch (IOException e) {}
}
}
}
private static class IOSWriteInt extends OutputStreamTests {
public IOSWriteInt() {
super(streamTestRoot,
"writeInt",
"writeInt()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(4);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
final ImageOutputStream ios = octx.outputStream;
final int length = octx.length;
int pos = 0;
try {
ios.mark();
do {
if (pos + 4 > length) {
ios.reset();
ios.mark();
pos = 0;
}
ios.writeInt(0);
pos += 4;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { ios.reset(); } catch (IOException e) {}
}
}
}
private static class IOSWriteFloat extends OutputStreamTests {
public IOSWriteFloat() {
super(streamTestRoot,
"writeFloat",
"writeFloat()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(4);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
final ImageOutputStream ios = octx.outputStream;
final int length = octx.length;
int pos = 0;
try {
ios.mark();
do {
if (pos + 4 > length) {
ios.reset();
ios.mark();
pos = 0;
}
ios.writeFloat(0.0f);
pos += 4;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { ios.reset(); } catch (IOException e) {}
}
}
}
private static class IOSWriteLong extends OutputStreamTests {
public IOSWriteLong() {
super(streamTestRoot,
"writeLong",
"writeLong()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(8);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
final ImageOutputStream ios = octx.outputStream;
final int length = octx.length;
int pos = 0;
try {
ios.mark();
do {
if (pos + 8 > length) {
ios.reset();
ios.mark();
pos = 0;
}
ios.writeLong(0L);
pos += 8;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { ios.reset(); } catch (IOException e) {}
}
}
}
private static class IOSWriteDouble extends OutputStreamTests {
public IOSWriteDouble() {
super(streamTestRoot,
"writeDouble",
"writeDouble()");
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = new Context(env, result);
result.setUnits(8);
result.setUnitName("byte");
return ctx;
}
public void runTest(Object ctx, int numReps) {
final Context octx = (Context)ctx;
final ImageOutputStream ios = octx.outputStream;
final int length = octx.length;
int pos = 0;
try {
ios.mark();
do {
if (pos + 8 > length) {
ios.reset();
ios.mark();
pos = 0;
}
ios.writeDouble(0.0);
pos += 8;
} while (--numReps >= 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try { ios.reset(); } catch (IOException e) {}
}
}
}
}

View file

@ -0,0 +1,231 @@
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.tests.iio;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageOutputStreamSpi;
import javax.imageio.stream.FileCacheImageOutputStream;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import j2dbench.Group;
import j2dbench.Option;
import j2dbench.Result;
import j2dbench.TestEnvironment;
abstract class OutputTests extends IIOTests {
protected static final int OUTPUT_FILE = 1;
protected static final int OUTPUT_ARRAY = 2;
protected static final int OUTPUT_FILECHANNEL = 3;
protected static ImageOutputStreamSpi fileChannelIOSSpi;
static {
if (hasImageIO) {
ImageIO.scanForPlugins();
IIORegistry registry = IIORegistry.getDefaultInstance();
java.util.Iterator spis =
registry.getServiceProviders(ImageOutputStreamSpi.class,
false);
while (spis.hasNext()) {
ImageOutputStreamSpi spi = (ImageOutputStreamSpi)spis.next();
String klass = spi.getClass().getName();
if (klass.endsWith("ChannelImageOutputStreamSpi")) {
fileChannelIOSSpi = spi;
break;
}
}
}
}
protected static Group outputRoot;
protected static Group outputOptRoot;
protected static Group generalOptRoot;
protected static Group.EnableSet generalDestRoot;
protected static Option destFileOpt;
protected static Option destByteArrayOpt;
protected static Group imageioGeneralOptRoot;
protected static Option destFileChannelOpt;
protected static Option useCacheTog;
public static void init() {
outputRoot = new Group(iioRoot, "output", "Output Benchmarks");
outputRoot.setTabbed();
// Options
outputOptRoot = new Group(outputRoot, "opts", "Options");
// General Options
generalOptRoot = new Group(outputOptRoot,
"general", "General Options");
generalDestRoot = new Group.EnableSet(generalOptRoot,
"dest", "Destintations");
destFileOpt = new OutputType("file", "File", OUTPUT_FILE);
destByteArrayOpt = new OutputType("byteArray", "byte[]", OUTPUT_ARRAY);
if (hasImageIO) {
// Image I/O Options
imageioGeneralOptRoot = new Group(outputOptRoot,
"imageio", "Image I/O Options");
if (fileChannelIOSSpi != null) {
destFileChannelOpt =
new OutputType("fileChannel", "FileChannel",
OUTPUT_FILECHANNEL);
}
useCacheTog = new Option.Toggle(imageioGeneralOptRoot, "useCache",
"ImageIO.setUseCache()",
Option.Toggle.Off);
}
OutputImageTests.init();
if (hasImageIO) {
OutputStreamTests.init();
}
}
protected OutputTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
protected static class OutputType extends Option.Enable {
private int type;
public OutputType(String nodeName, String description, int type) {
super(generalDestRoot, nodeName, description, false);
this.type = type;
}
public int getType() {
return type;
}
public String getAbbreviatedModifierDescription(Object value) {
return getModifierValueName(value);
}
public String getModifierValueName(Object val) {
return getNodeName();
}
}
protected abstract static class Context {
int size;
Object output;
int outputType;
OutputStream origStream;
Context(TestEnvironment env, Result result) {
size = env.getIntValue(sizeList);
if (hasImageIO) {
if (env.getModifier(useCacheTog) != null) {
ImageIO.setUseCache(env.isEnabled(useCacheTog));
}
}
OutputType t = (OutputType)env.getModifier(generalDestRoot);
outputType = t.getType();
}
void initOutput() {
if ((outputType == OUTPUT_FILE) ||
(outputType == OUTPUT_FILECHANNEL))
{
try {
File outputfile = File.createTempFile("iio", ".tmp");
outputfile.deleteOnExit();
output = outputfile;
} catch (IOException e) {
System.err.println("error creating temp file");
e.printStackTrace();
}
}
}
ImageOutputStream createImageOutputStream() throws IOException {
ImageOutputStream ios;
switch (outputType) {
case OUTPUT_FILE:
ios = new FileImageOutputStream((File)output);
break;
case OUTPUT_ARRAY:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
if (ImageIO.getUseCache()) {
ios = new FileCacheImageOutputStream(bos, null);
} else {
ios = new MemoryCacheImageOutputStream(bos);
}
break;
case OUTPUT_FILECHANNEL:
FileOutputStream fos = new FileOutputStream((File)output);
origStream = fos;
java.nio.channels.FileChannel fc = fos.getChannel();
ios = fileChannelIOSSpi.createOutputStreamInstance(fc, false,
null);
break;
default:
ios = null;
break;
}
return ios;
}
void closeOriginalStream() throws IOException {
if (origStream != null) {
origStream.close();
origStream = null;
}
}
void cleanup(TestEnvironment env) {
}
}
}

View file

@ -0,0 +1,494 @@
/*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
/*
* (C) Copyright IBM Corp. 2003, All Rights Reserved.
* This technology is protected by multiple US and International
* patents. This notice and attribution to IBM may not be removed.
*/
package j2dbench.tests.text;
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.Bidi;
import java.text.CharacterIterator;
import java.util.Map;
import j2dbench.Group;
import j2dbench.Result;
import j2dbench.TestEnvironment;
public abstract class TextConstructionTests extends TextTests {
static Group constructroot;
static Group constructtestroot;
public static void init() {
// don't even bother with this at all if we don't have Java2 APIs.
if (hasGraphics2D) {
constructroot = new Group(textroot, "construction", "Construction Benchmarks");
constructtestroot = new Group(constructroot, "tests", "Construction Tests");
new GVFromFontString();
new GVFromFontChars();
new GVFromFontCI();
new GVFromFontGlyphs();
new GVFromFontLayout();
// new GVClone(); // not public API!
new TLFromFont();
new TLFromMap();
/*
new TLFromACI();
new TLClone();
new TLJustify();
new TLFromLBM();
*/
}
}
public TextConstructionTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
public static class TCContext extends G2DContext {
char[] chars1;
CharacterIterator ci;
GlyphVector gv;
int[] glyphs;
int flags;
public void init(TestEnvironment env, Result results) {
super.init(env, results);
chars1 = new char[chars.length + 2];
System.arraycopy(chars, 0, chars1, 1, chars.length);
ci = new ArrayCI(chars1, 1, chars.length);
gv = font.createGlyphVector(frc, text);
glyphs = gv.getGlyphCodes(0, gv.getNumGlyphs(), null);
flags = Bidi.requiresBidi(chars, 0, chars.length)
? Font.LAYOUT_LEFT_TO_RIGHT
: Font.LAYOUT_RIGHT_TO_LEFT;
}
}
public Context createContext() {
return new TCContext();
}
public static class GVFromFontString extends TextConstructionTests {
public GVFromFontString() {
super(constructtestroot, "gvfromfontstring", "Call Font.createGlyphVector(FRC, String)");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final String text = tcctx.text;
final FontRenderContext frc = tcctx.frc;
GlyphVector gv;
do {
gv = font.createGlyphVector(frc, text);
} while (--numReps >= 0);
}
}
public static class GVFromFontChars extends TextConstructionTests {
public GVFromFontChars() {
super(constructtestroot, "gvfromfontchars", "Call Font.createGlyphVector(FRC, char[])");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final char[] chars = tcctx.chars;
final FontRenderContext frc = tcctx.frc;
GlyphVector gv;
do {
gv = font.createGlyphVector(frc, chars);
} while (--numReps >= 0);
}
}
public static class GVFromFontCI extends TextConstructionTests {
public GVFromFontCI() {
super(constructtestroot, "gvfromfontci", "Call Font.createGlyphVector(FRC, CharacterIterator)");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final CharacterIterator ci = tcctx.ci;
final FontRenderContext frc = tcctx.frc;
GlyphVector gv;
do {
gv = font.createGlyphVector(frc, ci);
} while (--numReps >= 0);
}
}
public static class GVFromFontGlyphs extends TextConstructionTests {
public GVFromFontGlyphs() {
super(constructtestroot, "gvfromfontglyphs", "Call Font.createGlyphVector(FRC, int[])");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final int[] glyphs = tcctx.glyphs;
final FontRenderContext frc = tcctx.frc;
GlyphVector gv;
do {
gv = font.createGlyphVector(frc, glyphs);
} while (--numReps >= 0);
}
}
public static class GVFromFontLayout extends TextConstructionTests {
public GVFromFontLayout() {
super(constructtestroot, "gvfromfontlayout", "Call Font.layoutGlyphVector(...)");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final char[] chars = tcctx.chars1;
final int start = 1;
final int limit = chars.length - 1;
final FontRenderContext frc = tcctx.frc;
final int flags = tcctx.flags;
GlyphVector gv;
do {
gv = font.layoutGlyphVector(frc, chars, start, limit, flags);
} while (--numReps >= 0);
}
}
/*
* my bad, clone is not public in GlyphVector!
public static class GVClone extends TextConstructionTests {
public GVClone() {
super(constructtestroot, "gvclone", "Call GV.clone");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final GlyphVector origGV = tcctx.gv;
GlyphVector gv;
do {
gv = (GlyphVector)origGV.clone();
} while (--numReps >= 0);
}
}
*/
public static class TLFromFont extends TextConstructionTests {
public TLFromFont() {
super(constructtestroot, "tlfromfont", "TextLayout(String, Font, FRC)");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final String text = tcctx.text;
final FontRenderContext frc = tcctx.frc;
TextLayout tl;
do {
tl = new TextLayout(text, font, frc);
} while (--numReps >= 0);
}
}
public static class TLMapContext extends G2DContext {
Map map;
public void init(TestEnvironment env, Result results) {
super.init(env, results);
map = (Map)env.getModifier(tlmapList);
}
}
public static class TLFromMap extends TextConstructionTests {
public TLFromMap() {
super(constructtestroot, "tlfrommap", "TextLayout(String, Map, FRC)");
}
public Context createContext() {
return new TLMapContext();
}
public void runTest(Object ctx, int numReps) {
TLMapContext tlmctx = (TLMapContext)ctx;
final String text = tlmctx.text;
final FontRenderContext frc = tlmctx.frc;
final Map map = tlmctx.map;
TextLayout tl;
do {
tl = new TextLayout(text, map, frc);
} while (--numReps >= 0);
}
}
public static class ACIContext extends G2DContext {
AttributedCharacterIterator aci;
public void init(TestEnvironment env, Result results) {
super.init(env, results);
AttributedString astr = new AttributedString(text);
}
}
public class TLFromACI extends TextConstructionTests {
public TLFromACI() {
super(constructtestroot, "tlfromaci", "TextLayout(ACI, FRC)");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final String text = tcctx.text;
final FontRenderContext frc = tcctx.frc;
TextLayout tl;
do {
tl = new TextLayout(text, font, frc);
} while (--numReps >= 0);
}
}
public class TLClone extends TextConstructionTests {
public TLClone() {
super(constructtestroot, "tlclone", "call TextLayout.clone()");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final String text = tcctx.text;
final FontRenderContext frc = tcctx.frc;
TextLayout tl;
do {
tl = new TextLayout(text, font, frc);
} while (--numReps >= 0);
}
}
public class TLJustify extends TextConstructionTests {
public TLJustify() {
super(constructtestroot, "tljustify", "call TextLayout.getJustifiedLayout(...)");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final String text = tcctx.text;
final FontRenderContext frc = tcctx.frc;
TextLayout tl;
do {
tl = new TextLayout(text, font, frc);
} while (--numReps >= 0);
}
}
public class TLFromLBM extends TextConstructionTests {
public TLFromLBM() {
super(constructtestroot, "tlfromlbm", "call LineBreakMeasurer.next()");
}
public void runTest(Object ctx, int numReps) {
TCContext tcctx = (TCContext)ctx;
final Font font = tcctx.font;
final String text = tcctx.text;
final FontRenderContext frc = tcctx.frc;
TextLayout tl;
do {
tl = new TextLayout(text, font, frc);
} while (--numReps >= 0);
}
}
public static final class ArrayCI implements CharacterIterator {
char[] chars;
int off;
int max;
int pos;
ArrayCI(char[] chars, int off, int len) {
if (off < 0 || len < 0 || (len > 0 && (chars == null || chars.length - off < len))) {
throw new InternalError("bad ArrayCI params");
}
this.chars = chars;
this.off = off;
this.max = off + len;
this.pos = off;
}
/**
* Sets the position to getBeginIndex() and returns the character at that
* position.
* @return the first character in the text, or DONE if the text is empty
* @see #getBeginIndex()
*/
public char first() {
if (max > off) {
return chars[pos = off];
}
return DONE;
}
/**
* Sets the position to getEndIndex()-1 (getEndIndex() if the text is empty)
* and returns the character at that position.
* @return the last character in the text, or DONE if the text is empty
* @see #getEndIndex()
*/
public char last() {
if (max > off) {
return chars[pos = max - 1];
}
pos = max;
return DONE;
}
/**
* Gets the character at the current position (as returned by getIndex()).
* @return the character at the current position or DONE if the current
* position is off the end of the text.
* @see #getIndex()
*/
public char current() {
return pos == max ? DONE : chars[pos];
}
/**
* Increments the iterator's index by one and returns the character
* at the new index. If the resulting index is greater or equal
* to getEndIndex(), the current index is reset to getEndIndex() and
* a value of DONE is returned.
* @return the character at the new position or DONE if the new
* position is off the end of the text range.
*/
public char next() {
if (++pos < max) {
return chars[pos];
}
pos = max;
return DONE;
}
/**
* Decrements the iterator's index by one and returns the character
* at the new index. If the current index is getBeginIndex(), the index
* remains at getBeginIndex() and a value of DONE is returned.
* @return the character at the new position or DONE if the current
* position is equal to getBeginIndex().
*/
public char previous() {
if (--pos >= off) {
return chars[pos];
}
pos = off;
return DONE;
}
/**
* Sets the position to the specified position in the text and returns that
* character.
* @param position the position within the text. Valid values range from
* getBeginIndex() to getEndIndex(). An IllegalArgumentException is thrown
* if an invalid value is supplied.
* @return the character at the specified position or DONE if the specified position is equal to getEndIndex()
*/
public char setIndex(int position) {
if (position < off || position > max) {
throw new IllegalArgumentException("pos: " + position + " off: " + off + " len: " + (max - off));
}
return ((pos = position) < max) ? chars[position] : DONE;
}
/**
* Returns the start index of the text.
* @return the index at which the text begins.
*/
public int getBeginIndex() {
return off;
}
/**
* Returns the end index of the text. This index is the index of the first
* character following the end of the text.
* @return the index after the last character in the text
*/
public int getEndIndex() {
return max;
}
/**
* Returns the current index.
* @return the current index.
*/
public int getIndex() {
return pos;
}
/**
* Create a copy of this iterator
* @return A copy of this
*/
public Object clone() {
try {
return super.clone();
}
catch (Exception e) {
return new InternalError();
}
}
}
}

View file

@ -0,0 +1,655 @@
/*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
/*
* (C) Copyright IBM Corp. 2003, All Rights Reserved.
* This technology is protected by multiple US and International
* patents. This notice and attribution to IBM may not be removed.
*/
package j2dbench.tests.text;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.font.GlyphMetrics;
import java.awt.font.GlyphVector;
import java.awt.font.TextHitInfo;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.text.Bidi;
import java.util.ArrayList;
import j2dbench.Group;
import j2dbench.Result;
import j2dbench.TestEnvironment;
public abstract class TextMeasureTests extends TextTests {
static Group measureroot;
static Group measuretestroot;
public static void init() {
measureroot = new Group(textroot, "Measuring", "Measuring Benchmarks");
measuretestroot = new Group(measureroot, "tests", "Measuring Tests");
new StringWidth();
new StringBounds();
new CharsWidth();
new CharsBounds();
new FontCanDisplay();
if (hasGraphics2D) {
new GVWidth();
new GVLogicalBounds();
new GVVisualBounds();
new GVPixelBounds();
new GVOutline();
new GVGlyphLogicalBounds();
new GVGlyphVisualBounds();
new GVGlyphPixelBounds();
new GVGlyphOutline();
new GVGlyphTransform();
new GVGlyphMetrics();
new TLAdvance();
new TLAscent();
new TLBounds();
new TLGetCaretInfo();
new TLGetNextHit();
new TLGetCaretShape();
new TLGetLogicalHighlightShape();
new TLHitTest();
new TLOutline();
/*
new FontLineMetrics();
new FontStringBounds();
*/
}
}
public TextMeasureTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
static class SWContext extends TextContext {
FontMetrics fm;
public void init(TestEnvironment env, Result results) {
super.init(env, results);
fm = graphics.getFontMetrics(font);
}
}
public Context createContext() {
return new SWContext();
}
public static class StringWidth extends TextMeasureTests {
public StringWidth() {
super(measuretestroot, "stringWidth", "Measuring String Width");
}
public void runTest(Object ctx, int numReps) {
SWContext swctx = (SWContext)ctx;
String text = swctx.text;
FontMetrics fm = swctx.fm;
int wid = 0;
do {
wid += fm.stringWidth(text);
} while (--numReps >= 0);
}
}
public static class StringBounds extends TextMeasureTests {
public StringBounds() {
super(measuretestroot, "stringBounds", "Measuring String Bounds");
}
public void runTest(Object ctx, int numReps) {
SWContext swctx = (SWContext)ctx;
String text = swctx.text;
FontMetrics fm = swctx.fm;
int wid = 0;
Rectangle r = null;
do {
r = null;
int dx = fm.stringWidth(text);
int dy = fm.getAscent() + fm.getDescent() + fm.getLeading();
int x = 0;
int y = -fm.getAscent();
r = new Rectangle(x, y, dx, dy);
} while (--numReps >= 0);
}
}
public static class CharsWidth extends TextMeasureTests {
public CharsWidth() {
super(measuretestroot, "charsWidth", "Measuring Chars Width");
}
public void runTest(Object ctx, int numReps) {
SWContext swctx = (SWContext)ctx;
FontMetrics fm = swctx.fm;
char[] chars = swctx.chars;
int wid = 0;
do {
wid += fm.charsWidth(chars, 0, chars.length);
} while (--numReps >= 0);
}
}
public static class CharsBounds extends TextMeasureTests {
public CharsBounds() {
super(measuretestroot, "charsBounds", "Measuring Chars Bounds");
}
public void runTest(Object ctx, int numReps) {
SWContext swctx = (SWContext)ctx;
FontMetrics fm = swctx.fm;
char[] chars = swctx.chars;
int wid = 0;
Rectangle r = null;
do {
r = null;
int dx = fm.charsWidth(chars, 0, chars.length);
int dy = fm.getAscent() + fm.getDescent() + fm.getLeading();
int x = 0;
int y = -fm.getAscent();
r = new Rectangle(x, y, dx, dy);
} while (--numReps >= 0);
}
}
public static class FontCanDisplay extends TextMeasureTests {
public FontCanDisplay() {
super(measuretestroot, "fontcandisplay", "Font canDisplay(char)");
}
public void runTest(Object ctx, int numReps) {
Font font = ((TextContext)ctx).font;
boolean b = false;
do {
for (int i = 0; i < 0x10000; i += 0x64) {
b ^= font.canDisplay((char)i);
}
} while (--numReps >= 0);
}
}
public static class GVContext extends G2DContext {
GlyphVector gv;
public void init(TestEnvironment env, Result results) {
super.init(env, results);
int flags = Font.LAYOUT_LEFT_TO_RIGHT;
if (Bidi.requiresBidi(chars, 0, chars.length)) { // assume rtl
flags = Font.LAYOUT_RIGHT_TO_LEFT;
}
gv = font.layoutGlyphVector(frc, chars, 0, chars.length, flags);
// gv options
}
}
public abstract static class GVMeasureTest extends TextMeasureTests {
protected GVMeasureTest(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
public Context createContext() {
return new GVContext();
}
}
public static class GVWidth extends GVMeasureTest {
public GVWidth() {
super(measuretestroot, "gvWidth", "Measuring GV Width");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
double wid = 0;
do {
wid += gv.getGlyphPosition(gv.getNumGlyphs()).getX();
} while (--numReps >= 0);
}
}
public static class GVLogicalBounds extends GVMeasureTest {
public GVLogicalBounds() {
super(measuretestroot, "gvLogicalBounds", "Measuring GV Logical Bounds");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
Rectangle2D r;
do {
r = gv.getLogicalBounds();
} while (--numReps >= 0);
}
}
public static class GVVisualBounds extends GVMeasureTest {
public GVVisualBounds() {
super(measuretestroot, "gvVisualBounds", "Measuring GV Visual Bounds");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
Rectangle2D r;
do {
r = gv.getVisualBounds();
} while (--numReps >= 0);
}
}
public static class GVPixelBounds extends GVMeasureTest {
public GVPixelBounds() {
super(measuretestroot, "gvPixelBounds", "Measuring GV Pixel Bounds");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
Rectangle2D r;
do {
r = gv.getPixelBounds(null, 0, 0); // !!! add opt to provide different frc?
} while (--numReps >= 0);
}
}
public static class GVOutline extends GVMeasureTest {
public GVOutline() {
super(measuretestroot, "gvOutline", "Getting GV Outline");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
Shape s;
do {
s = gv.getOutline();
} while (--numReps >= 0);
}
}
public static class GVGlyphLogicalBounds extends GVMeasureTest {
public GVGlyphLogicalBounds() {
super(measuretestroot, "gvGlyphLogicalBounds", "Measuring GV Glyph Logical Bounds");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
Shape s;
do {
for (int i = 0, e = gv.getNumGlyphs(); i < e; ++i) {
s = gv.getGlyphLogicalBounds(i);
}
} while (--numReps >= 0);
}
}
public static class GVGlyphVisualBounds extends GVMeasureTest {
public GVGlyphVisualBounds() {
super(measuretestroot, "gvGlyphVisualBounds", "Measuring GV Glyph Visual Bounds");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
Shape s;
do {
for (int i = 0, e = gv.getNumGlyphs(); i < e; ++i) {
s = gv.getGlyphVisualBounds(i);
}
} while (--numReps >= 0);
}
}
public static class GVGlyphPixelBounds extends GVMeasureTest {
public GVGlyphPixelBounds() {
super(measuretestroot, "gvGlyphPixelBounds", "Measuring GV Glyph Pixel Bounds");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
Rectangle2D r;
do {
for (int i = 0, e = gv.getNumGlyphs(); i < e; ++i) {
r = gv.getGlyphPixelBounds(i, null, 0, 0); // !!! add opt to provide different frc?
}
} while (--numReps >= 0);
}
}
public static class GVGlyphOutline extends GVMeasureTest {
public GVGlyphOutline() {
super(measuretestroot, "gvGlyphOutline", "Getting GV Glyph Outline");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
Shape s;
do {
for (int i = 0, e = gv.getNumGlyphs(); i < e; ++i) {
s = gv.getGlyphOutline(i);
}
} while (--numReps >= 0);
}
}
public static class GVGlyphTransform extends GVMeasureTest {
public GVGlyphTransform() {
super(measuretestroot, "gvGlyphTransform", "Getting GV Glyph Transform");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
AffineTransform tx;
do {
for (int i = 0, e = gv.getNumGlyphs(); i < e; ++i) {
tx = gv.getGlyphTransform(i);
}
} while (--numReps >= 0);
}
}
public static class GVGlyphMetrics extends GVMeasureTest {
public GVGlyphMetrics() {
super(measuretestroot, "gvGlyphMetrics", "Getting GV Glyph Metrics");
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
GlyphVector gv = gvctx.gv;
GlyphMetrics gm;
do {
for (int i = 0, e = gv.getNumGlyphs(); i < e; ++i) {
gm = gv.getGlyphMetrics(i);
}
} while (--numReps >= 0);
}
}
public static class TLContext extends G2DContext {
TextLayout tl;
public void init(TestEnvironment env, Result results) {
super.init(env, results);
// need more tl options here
tl = new TextLayout(text, font, frc);
}
}
public abstract static class TLMeasureTest extends TextMeasureTests {
protected TLMeasureTest(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
public Context createContext() {
return new TLContext();
}
}
public static class TLAdvance extends TLMeasureTest {
public TLAdvance() {
super(measuretestroot, "tlAdvance", "Measuring TL advance");
}
public void runTest(Object ctx, int numReps) {
TLContext tlctx = (TLContext)ctx;
TextLayout tl = tlctx.tl;
double wid = 0;
do {
wid += tl.getAdvance();
} while (--numReps >= 0);
}
}
public static class TLAscent extends TLMeasureTest {
public TLAscent() {
super(measuretestroot, "tlAscent", "Measuring TL ascent");
}
public void runTest(Object ctx, int numReps) {
TLContext tlctx = (TLContext)ctx;
TextLayout tl = tlctx.tl;
float ht = 0;
do {
ht += tl.getAscent();
} while (--numReps >= 0);
}
}
public static class TLBounds extends TLMeasureTest {
public TLBounds() {
super(measuretestroot, "tlBounds", "Measuring TL advance");
}
public void runTest(Object ctx, int numReps) {
TLContext tlctx = (TLContext)ctx;
TextLayout tl = tlctx.tl;
Rectangle2D r;
do {
r = tl.getBounds();
} while (--numReps >= 0);
}
}
static class TLExContext extends TLContext {
TextHitInfo[] hits;
Rectangle2D lb;
public void init(TestEnvironment env, Result results) {
super.init(env, results);
ArrayList list = new ArrayList(text.length() * 2 + 2);
TextHitInfo hit = TextHitInfo.trailing(-1);
do {
list.add(hit);
hit = tl.getNextRightHit(hit);
} while (hit != null);
hits = (TextHitInfo[])list.toArray(new TextHitInfo[list.size()]);
lb = tl.getBounds();
lb.setRect(lb.getMinX() - 10, lb.getMinY(), lb.getWidth() + 20, lb.getHeight());
}
}
public abstract static class TLExtendedMeasureTest extends TLMeasureTest {
protected TLExtendedMeasureTest(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
public Context createContext() {
return new TLExContext();
}
}
public static class TLGetCaretInfo extends TLExtendedMeasureTest {
public TLGetCaretInfo() {
super(measuretestroot, "tlGetCaretInfo", "Measuring TL caret info");
}
public void runTest(Object ctx, int numReps) {
TLExContext tlctx = (TLExContext)ctx;
TextLayout tl = tlctx.tl;
TextHitInfo[] hits = tlctx.hits;
do {
for (int i = 0; i < hits.length; ++i) {
tl.getCaretInfo(hits[i]);
}
} while (--numReps >= 0);
}
}
public static class TLGetNextHit extends TLExtendedMeasureTest {
public TLGetNextHit() {
super(measuretestroot, "tlGetNextHit", "Measuring TL getNextRight/LeftHit");
}
public void runTest(Object ctx, int numReps) {
TLExContext tlctx = (TLExContext)ctx;
TextLayout tl = tlctx.tl;
TextHitInfo[] hits = tlctx.hits;
TextHitInfo hit;
do {
for (int i = 0; i < hits.length; ++i) {
hit = tl.getNextLeftHit(hits[i]);
}
} while (--numReps >= 0);
}
}
public static class TLGetCaretShape extends TLExtendedMeasureTest {
public TLGetCaretShape() {
super(measuretestroot, "tlGetCaretShape", "Measuring TL getCaretShape");
}
public void runTest(Object ctx, int numReps) {
TLExContext tlctx = (TLExContext)ctx;
TextLayout tl = tlctx.tl;
TextHitInfo[] hits = tlctx.hits;
Shape s;
do {
for (int i = 0; i < hits.length; ++i) {
s = tl.getCaretShape(hits[i]);
}
} while (--numReps >= 0);
}
}
public static class TLGetLogicalHighlightShape extends TLExtendedMeasureTest {
public TLGetLogicalHighlightShape() {
super(measuretestroot, "tlGetLogicalHighlightShape", "Measuring TL getLogicalHighlightShape");
}
public void runTest(Object ctx, int numReps) {
TLExContext tlctx = (TLExContext)ctx;
TextLayout tl = tlctx.tl;
int len = tlctx.text.length();
Rectangle2D lb = tlctx.lb;
Shape s;
if (len < 3) {
do {
s = tl.getLogicalHighlightShape(0, len, lb);
} while (--numReps >= 0);
} else {
do {
for (int i = 3; i < len; ++i) {
s = tl.getLogicalHighlightShape(i-3, i, lb);
}
} while (--numReps >= 0);
}
}
}
public static class TLGetVisualHighlightShape extends TLExtendedMeasureTest {
public TLGetVisualHighlightShape() {
super(measuretestroot, "tlGetVisualHighlightShape", "Measuring TL getVisualHighlightShape");
}
public void runTest(Object ctx, int numReps) {
TLExContext tlctx = (TLExContext)ctx;
TextLayout tl = tlctx.tl;
TextHitInfo[] hits = tlctx.hits;
Rectangle2D lb = tlctx.lb;
Shape s;
if (hits.length < 3) {
do {
s = tl.getVisualHighlightShape(hits[0], hits[hits.length - 1], lb);
} while (--numReps >= 0);
} else {
do {
for (int i = 3; i < hits.length; ++i) {
s = tl.getVisualHighlightShape(hits[i-3], hits[i], lb);
}
} while (--numReps >= 0);
}
}
}
public static class TLHitTest extends TLExtendedMeasureTest {
public TLHitTest() {
super(measuretestroot, "tlHitTest", "Measuring TL hitTest");
}
public void runTest(Object ctx, int numReps) {
TLExContext tlctx = (TLExContext)ctx;
TextLayout tl = tlctx.tl;
int numhits = tlctx.hits.length;
Rectangle2D lb = tlctx.lb;
TextHitInfo hit;
for (int i = 0; i <= numhits; ++i) {
float x = (float)(lb.getMinX() + lb.getWidth() * i / numhits);
float y = (float)(lb.getMinY() + lb.getHeight() * i / numhits);
hit = tl.hitTestChar(x, y, lb);
}
}
}
public static class TLOutline extends TLMeasureTest {
public TLOutline() {
super(measuretestroot, "tlOutline", "Measuring TL outline");
}
public void runTest(Object ctx, int numReps) {
TLContext tlctx = (TLContext)ctx;
TextLayout tl = tlctx.tl;
Shape s;
do {
s = tl.getOutline(null);
} while (--numReps >= 0);
}
}
}

View file

@ -0,0 +1,188 @@
/*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
/*
* (C) Copyright IBM Corp. 2003, All Rights Reserved.
* This technology is protected by multiple US and International
* patents. This notice and attribution to IBM may not be removed.
*/
package j2dbench.tests.text;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.GlyphVector;
import java.awt.font.TextLayout;
import j2dbench.Group;
import j2dbench.Result;
import j2dbench.TestEnvironment;
public abstract class TextRenderTests extends TextTests {
static Group renderroot;
static Group rendertestroot;
public static void init() {
renderroot = new Group(textroot, "Rendering", "Rendering Benchmarks");
rendertestroot = new Group(renderroot, "tests", "Rendering Tests");
new DrawStrings();
new DrawChars();
new DrawBytes();
if (hasGraphics2D) {
new DrawGlyphVectors();
new DrawTextLayouts();
}
}
public TextRenderTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
}
public static class DrawStrings extends TextRenderTests {
public DrawStrings() {
super(rendertestroot, "drawString", "Drawing Strings");
}
public void runTest(Object ctx, int numReps) {
TextContext tctx = (TextContext)ctx;
Graphics g = tctx.graphics;
g.setFont(tctx.font);
String text = tctx.text;
do {
g.drawString(text, 40, 40);
} while (--numReps >= 0);
}
}
public static class DrawChars extends TextRenderTests {
public DrawChars() {
super(rendertestroot, "drawChars", "Drawing Char Arrays");
}
public void runTest(Object ctx, int numReps) {
TextContext tctx = (TextContext)ctx;
Graphics g = tctx.graphics;
char[] chars = tctx.chars;
g.setFont(tctx.font);
do {
g.drawChars(chars, 0, chars.length, 40, 40);
} while (--numReps >= 0);
}
}
public static class DrawBytes extends TextRenderTests {
public DrawBytes() {
super(rendertestroot, "drawBytes", "Drawing Byte Arrays");
}
public void runTest(Object ctx, int numReps) {
TextContext tctx = (TextContext)ctx;
Graphics g = tctx.graphics;
g.setFont(tctx.font);
try {
byte[] bytes = tctx.text.getBytes("ASCII"); // only good for english
do {
g.drawBytes(bytes, 0, bytes.length, 40, 40);
} while (--numReps >= 0);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static class GVContext extends G2DContext {
GlyphVector gv;
public void init(TestEnvironment env, Result results) {
super.init(env, results);
gv = font.createGlyphVector(frc, text);
}
}
public static class DrawGlyphVectors extends TextRenderTests {
public DrawGlyphVectors() {
super(rendertestroot, "drawGlyphVectors", "Drawing GlyphVectors");
}
public Context createContext() {
return new GVContext();
}
public void runTest(Object ctx, int numReps) {
GVContext gvctx = (GVContext)ctx;
Graphics2D g2d = gvctx.g2d;
GlyphVector gv = gvctx.gv;
do {
g2d.drawGlyphVector(gv, 40, 40);
} while (--numReps >= 0);
}
}
public static class TLContext extends G2DContext {
TextLayout tl;
public void init(TestEnvironment env, Result results) {
super.init(env, results);
tl = new TextLayout(text, font, frc);
}
}
public static class DrawTextLayouts extends TextRenderTests {
public DrawTextLayouts() {
super(rendertestroot, "drawTextLayout", "Drawing TextLayouts");
}
public Context createContext() {
return new TLContext();
}
public void runTest(Object ctx, int numReps) {
TLContext tlctx = (TLContext)ctx;
Graphics2D g2d = tlctx.g2d;
TextLayout tl = tlctx.tl;
do {
tl.draw(g2d, 40, 40);
} while (--numReps >= 0);
}
}
}

View file

@ -0,0 +1,719 @@
/*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
/*
* (C) Copyright IBM Corp. 2003, All Rights Reserved.
* This technology is protected by multiple US and International
* patents. This notice and attribution to IBM may not be removed.
*/
package j2dbench.tests.text;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.font.NumericShaper;
import java.awt.font.TextAttribute;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.JComponent;
import j2dbench.Destinations;
import j2dbench.Group;
import j2dbench.Node;
import j2dbench.Option;
import j2dbench.Option.ObjectList;
import j2dbench.Result;
import j2dbench.Test;
import j2dbench.TestEnvironment;
public abstract class TextTests extends Test {
public static boolean hasGraphics2D;
static {
try {
hasGraphics2D = (Graphics2D.class != null);
} catch (NoClassDefFoundError e) {
}
}
// core data
static final int[] tlengths = {
1, 2, 4, 8, 16, 32, 64, 128, 256, 512
};
static final String[] tscripts = {
// german, vietnamese, surrogate, dingbats
"english", "arabic", "greek", "hebrew", "hindi", "japanese", "korean", "thai",
"english-arabic", "english-greek", "english-hindi", "english-arabic-hindi"
};
static final float[] fsizes = {
1f, 6f, 8f, 10f, 12f, 12.5f, 13f, 13.5f, 16f, 20f, 36f, 72f, 128f
};
static final float[] fintsizes = {
1f, 6f, 8f, 10f, 12f, 13f, 16f, 20f, 36f, 72f, 128f
};
// utilties
static Float[] floatObjectList(float[] input) {
Float[] result = new Float[input.length];
for (int i = 0; i < result.length; ++i) {
result[i] = new Float(input[i]);
}
return result;
}
static String[] floatStringList(float[] input) {
return floatStringList("", input, "");
}
static String[] floatStringList(float[] input, String sfx) {
return floatStringList("", input, sfx);
}
static String[] floatStringList(String pfx, float[] input, String sfx) {
String[] result = new String[input.length];
for (int i = 0; i < result.length; ++i) {
result[i] = pfx + input[i] + sfx;
}
return result;
}
static String[] intStringList(int[] input) {
return intStringList("", input, "");
}
static String[] intStringList(int[] input, String sfx) {
return intStringList("", input, sfx);
}
static String[] intStringList(String pfx, int[] input, String sfx) {
String[] result = new String[input.length];
for (int i = 0; i < result.length; ++i) {
result[i] = pfx + input[i] + sfx;
}
return result;
}
static final String[] txNames;
static final String[] txDescNames;
static final AffineTransform[] txList;
static final Map[] maps;
static {
AffineTransform identity = new AffineTransform();
AffineTransform sm_scale = AffineTransform.getScaleInstance(.5, .5);
AffineTransform lg_scale = AffineTransform.getScaleInstance(2, 2);
AffineTransform wide = AffineTransform.getScaleInstance(2, .8);
AffineTransform tall = AffineTransform.getScaleInstance(.8, 2);
AffineTransform x_trans = AffineTransform.getTranslateInstance(50, 0);
AffineTransform y_trans = AffineTransform.getTranslateInstance(0, -30);
AffineTransform xy_trans = AffineTransform.getTranslateInstance(50, -30);
AffineTransform sm_rot = AffineTransform.getRotateInstance(Math.PI / 3);
AffineTransform lg_rot = AffineTransform.getRotateInstance(Math.PI * 4 / 3);
AffineTransform pi2_rot = AffineTransform.getRotateInstance(Math.PI / 2);
AffineTransform x_shear = AffineTransform.getShearInstance(.4, 0);
AffineTransform y_shear = AffineTransform.getShearInstance(0, -.4);
AffineTransform xy_shear = AffineTransform.getShearInstance(.3, .3);
AffineTransform x_flip = AffineTransform.getScaleInstance(-1, 1);
AffineTransform y_flip = AffineTransform.getScaleInstance(1, -1);
AffineTransform xy_flip = AffineTransform.getScaleInstance(-1, -1);
AffineTransform w_rot = AffineTransform.getRotateInstance(Math.PI / 3);
w_rot.scale(2, .8);
AffineTransform w_y_shear = AffineTransform.getShearInstance(0, -.4);
w_y_shear.scale(2, .8);
AffineTransform w_r_trans = AffineTransform.getTranslateInstance(3, -7);
w_r_trans.rotate(Math.PI / 3);
w_r_trans.scale(2, .8);
AffineTransform w_t_rot = AffineTransform.getRotateInstance(Math.PI / 3);
w_t_rot.translate(3, -7);
w_t_rot.scale(2, .8);
AffineTransform w_y_s_r_trans = AffineTransform.getTranslateInstance(3, -7);
w_y_s_r_trans.rotate(Math.PI / 3);
w_y_s_r_trans.shear(0, -.4);
w_y_s_r_trans.scale(2, .8);
txNames = new String[] {
"ident",
"smsc", "lgsc", "wide", "tall",
"xtrn", "ytrn", "xytrn",
"srot", "lrot", "hrot",
"xshr", "yshr", "xyshr",
"flx", "fly", "flxy",
"wr", "wys", "wrt",
"wtr", "wysrt"
};
txDescNames = new String[] {
"Identity",
"Sm Scale", "Lg Scale", "Wide", "Tall",
"X Trans", "Y Trans", "XY Trans",
"Sm Rot", "Lg Rot", "PI/2 Rot",
"X Shear", "Y Shear", "XY Shear",
"FlipX", "FlipY", "FlipXY",
"WRot", "WYShear", "WRTrans",
"WTRot", "WYSRTrans"
};
txList = new AffineTransform[] {
identity,
sm_scale, lg_scale, wide, tall,
x_trans, y_trans, xy_trans,
sm_rot, lg_rot, pi2_rot,
x_shear, y_shear, xy_shear,
x_flip, y_flip, xy_flip,
w_rot, w_y_shear, w_r_trans,
w_t_rot, w_y_s_r_trans,
};
// maps
HashMap fontMap = new HashMap();
fontMap.put(TextAttribute.FONT, new Font("Dialog", Font.ITALIC, 18));
HashMap emptyMap = new HashMap();
HashMap simpleMap = new HashMap();
simpleMap.put(TextAttribute.FAMILY, "Lucida Sans");
simpleMap.put(TextAttribute.SIZE, new Float(14));
simpleMap.put(TextAttribute.FOREGROUND, Color.blue);
HashMap complexMap = new HashMap();
complexMap.put(TextAttribute.FAMILY, "Serif");
complexMap.put(TextAttribute.TRANSFORM, tall);
complexMap.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
complexMap.put(TextAttribute.RUN_DIRECTION,
TextAttribute.RUN_DIRECTION_RTL);
try {
complexMap.put(TextAttribute.NUMERIC_SHAPING,
NumericShaper.getContextualShaper(NumericShaper.ALL_RANGES));
} catch (NoSuchFieldError e) {
}
maps = new Map[] {
fontMap,
emptyMap,
simpleMap,
complexMap,
};
}
static String getString(Object key, int len) {
String keyString = key.toString();
String[] strings = new String[4]; // leave room for index == 3 to return null
int span = Math.min(32, len);
int n = keyString.indexOf('-');
if (n == -1) {
strings[0] = getSimpleString(keyString);
} else {
strings[0] = getSimpleString(keyString.substring(0, n));
int m = keyString.indexOf('-', n+1);
if (m == -1) {
strings[1] = getSimpleString(keyString.substring(n+1));
// 2 to 1 ratio, short spans between 1 and 16 chars long
span = Math.max(1, Math.min(16, len / 3));
} else {
strings[1] = getSimpleString(keyString.substring(n+1, m));
strings[2] = getSimpleString(keyString.substring(m+1));
span = Math.max(1, Math.min(16, len / 4));
}
}
String s = "";
int pos = 0;
int strx = 0;
while (s.length() < len) {
String src;
if (strings[strx] == null) {
src = strings[0]; // use strings[0] twice for each other string
strx = 0;
} else {
src = strings[strx++];
}
if (pos + span > src.length()) {
pos = 0; // we know all strings are longer than span
}
s += src.substring(pos, pos+span);
pos += span;
}
return s.substring(0, len);
}
static HashMap strcache = new HashMap(tscripts.length);
private static String getSimpleString(Object key) {
String s = (String)strcache.get(key);
if (s == null) {
String fname = "textdata/" + key + ".ut8.txt";
try {
InputStream is = TextTests.class.getResourceAsStream(fname);
if (is == null) {
throw new IOException("Can't load resource " + fname);
}
BufferedReader r =
new BufferedReader(new InputStreamReader(is, "utf8"));
StringBuffer buf = new StringBuffer(r.readLine());
while (null != (s = r.readLine())) {
buf.append(" ");
buf.append(s);
}
s = buf.toString();
if (s.charAt(0) == '\ufeff') {
s = s.substring(1);
}
}
catch (IOException e) {
s = "This is a dummy ascii string because " +
fname + " was not found.";
}
strcache.put(key, s);
}
return s;
}
static Group textroot;
static Group txoptroot;
static Group txoptdataroot;
static Group txoptfontroot;
static Group txoptgraphicsroot;
static Group advoptsroot;
static Option tlengthList;
static Option tscriptList;
static Option fnameList;
static Option fstyleList;
static Option fsizeList;
static Option ftxList;
static Option taaList;
static Option tfmTog;
static Option gaaTog;
static Option gtxList;
static Option gvstyList;
static Option tlrunList;
static Option tlmapList;
// core is textlength, text script, font name/style/size/tx, frc
// drawing
// drawString, drawChars, drawBytes, drawGlyphVector, TextLayout.draw, drawAttributedString
// length of text
// 1, 2, 4, 8, 16, 32, 64, 128, 256 chars
// script of text
// simple: latin-1, japanese, arabic, hebrew, indic, thai, surrogate, dingbats
// mixed: latin-1 + x (1, 2, 3, 4 pairs)
// font of text
// name (composite, not), style, size (6, 12, 18, 24, 30, 36, 42, 48, 54, 60), transform (full set)
// text rendering hints
// aa, fm, gaa
// graphics transform (full set)
// (gv) gtx, gpos
// (tl, as) num style runs
//
// querying/measuring
// ascent/descent/leading
// advance
// (gv) lb, vb, pb, glb, gvb, glb, gp, gjust, gmet, gtx
// (tl) bounds, charpos, cursor
//
// construction/layout
// (bidi) no controls, controls, styles
// (gv) createGV, layoutGV
// (tl) TL constructors
// (tm) line break
public static void init() {
textroot = new Group("text", "Text Benchmarks");
textroot.setTabbed();
txoptroot = new Group(textroot, "opts", "Text Options");
txoptroot.setTabbed();
txoptdataroot = new Group(txoptroot, "data", "Text Data");
tlengthList = new Option.IntList(txoptdataroot, "tlength",
"Text Length",
tlengths,
intStringList(tlengths),
intStringList(tlengths, " chars"),
0x10);
((Option.ObjectList) tlengthList).setNumRows(5);
tscriptList = new Option.ObjectList(txoptdataroot, "tscript",
"Text Script",
tscripts,
tscripts,
tscripts,
tscripts,
0x1);
((Option.ObjectList) tscriptList).setNumRows(4);
txoptfontroot = new Group(txoptroot, "font", "Font");
fnameList = new FontOption(txoptfontroot, "fname", "Family Name");
fstyleList = new Option.IntList(txoptfontroot, "fstyle",
"Style",
new int[] {
Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD + Font.ITALIC,
},
new String[] {
"plain", "bold", "italic", "bolditalic",
},
new String[] {
"Plain", "Bold", "Italic", "Bold Italic",
},
0x1);
float[] fsl = hasGraphics2D ? fsizes : fintsizes;
fsizeList = new Option.ObjectList(txoptfontroot, "fsize",
"Size",
floatStringList(fsl),
floatObjectList(fsl),
floatStringList(fsl),
floatStringList(fsl, "pt"),
0x40);
((Option.ObjectList) fsizeList).setNumRows(5);
if (hasGraphics2D) {
ftxList = new Option.ObjectList(txoptfontroot, "ftx",
"Transform",
txDescNames,
txList,
txNames,
txDescNames,
0x1);
((Option.ObjectList) ftxList).setNumRows(6);
txoptgraphicsroot = new Group(txoptroot, "graphics", "Graphics");
String[] taaNames;
Object[] taaHints;
try {
taaNames = new String[] {
"Off", "On",
"LCD_HRGB", "LCD_HBGR", "LCD_VRGB", "LCD_VBGR"
};
taaHints = new Object[] {
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR,
};
} catch (NoSuchFieldError e) {
taaNames = new String[] {
"Off", "On"
};
taaHints = new Object[] {
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON,
};
}
taaList = new Option.ObjectList(txoptgraphicsroot, "textaa",
"Text AntiAlias",
taaNames, taaHints,
taaNames, taaNames,
0x1);
((Option.ObjectList) taaList).setNumRows(6);
// add special TextAAOpt for backwards compatibility with
// older options files
new TextAAOpt();
tfmTog = new Option.Toggle(txoptgraphicsroot, "tfm",
"Fractional Metrics", Option.Toggle.Off);
gaaTog = new Option.Toggle(txoptgraphicsroot, "gaa",
"Graphics AntiAlias", Option.Toggle.Off);
gtxList = new Option.ObjectList(txoptgraphicsroot, "gtx",
"Transform",
txDescNames,
txList,
txNames,
txDescNames,
0x1);
((Option.ObjectList) gtxList).setNumRows(6);
advoptsroot = new Group(txoptroot, "advopts", "Advanced Options");
gvstyList = new Option.IntList(advoptsroot, "gvstyle", "Style",
new int[] { 0, 1, 2, 3 },
new String[] { "std", "wave", "twist", "circle" },
new String[] { "Standard",
"Positions adjusted",
"Glyph angles adjusted",
"Layout to circle"
},
0x1);
int[] runs = { 1, 2, 4, 8 };
tlrunList = new Option.IntList(advoptsroot, "tlruns", "Attribute Runs",
runs,
intStringList(runs),
intStringList(runs, " runs"),
0x1);
String[] tlmapnames = new String[] { "FONT", "Empty", "Simple", "Complex" };
tlmapList = new Option.ObjectList(advoptsroot, "maptype", "Map",
tlmapnames,
maps,
new String[] { "font", "empty", "simple", "complex" },
tlmapnames,
0x1);
}
}
/**
* This "virtual Node" implementation is here to maintain backward
* compatibility with older J2DBench releases, specifically those
* options files that were created before we added LCD-optimized text
* hints in JDK 6. This class will translate the text antialias settings
* from the old "taa" On/Off/Both choice into the new expanded version.
*/
private static class TextAAOpt extends Node {
public TextAAOpt() {
super(txoptgraphicsroot, "taa", "Text AntiAlias");
}
public JComponent getJComponent() {
return null;
}
public void restoreDefault() {
// no-op
}
public void write(PrintWriter pw) {
// no-op (the old "taa" choice will be saved as part of the
// new "textaa" option)
}
public String setOption(String key, String value) {
String opts;
if (value.equals("On")) {
opts = "On";
} else if (value.equals("Off")) {
opts = "Off";
} else if (value.equals("Both")) {
opts = "On,Off";
} else {
return "Bad value";
}
return ((Option.ObjectList)taaList).setValueFromString(opts);
}
}
public static class Context {
void init(TestEnvironment env, Result result) {}
void cleanup(TestEnvironment env) {}
}
public static class TextContext extends Context {
Graphics graphics;
String text;
char[] chars;
Font font;
public void init(TestEnvironment env, Result result) {
// graphics
graphics = env.getGraphics();
// text
String sname = (String)env.getModifier(tscriptList);
int slen = env.getIntValue(tlengthList);
text = getString(sname, slen);
// chars
chars = text.toCharArray();
// font
String fname = (String)env.getModifier(fnameList);
if ("Physical".equals(fname)) {
fname = physicalFontNameFor(sname, slen, text);
}
int fstyle = env.getIntValue(fstyleList);
float fsize = ((Float)env.getModifier(fsizeList)).floatValue();
AffineTransform ftx = (AffineTransform)env.getModifier(ftxList);
font = new Font(fname, fstyle, (int)fsize);
if (hasGraphics2D) {
if (fsize != Math.floor(fsize)) {
font = font.deriveFont(fsize);
}
if (!ftx.isIdentity()) {
font = font.deriveFont(ftx);
}
}
// graphics
if (hasGraphics2D) {
Graphics2D g2d = (Graphics2D)graphics;
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
env.getModifier(taaList));
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
env.isEnabled(tfmTog)
? RenderingHints.VALUE_FRACTIONALMETRICS_ON
: RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
env.isEnabled(gaaTog)
? RenderingHints.VALUE_ANTIALIAS_ON
: RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.transform((AffineTransform)env.getModifier(gtxList));
}
// set result
result.setUnits(text.length());
result.setUnitName("char");
}
public void cleanup(TestEnvironment env) {
graphics.dispose();
graphics = null;
}
}
public static class G2DContext extends TextContext {
Graphics2D g2d;
FontRenderContext frc;
public void init(TestEnvironment env, Result results){
super.init(env, results);
g2d = (Graphics2D)graphics;
frc = g2d.getFontRenderContext();
}
}
public TextTests(Group parent, String nodeName, String description) {
super(parent, nodeName, description);
addDependency(Destinations.destroot);
addDependencies(txoptroot, true);
}
public Context createContext() {
return new TextContext();
}
public Object initTest(TestEnvironment env, Result result) {
Context ctx = createContext();
ctx.init(env, result);
return ctx;
}
public void cleanupTest(TestEnvironment env, Object ctx) {
((Context)ctx).cleanup(env);
}
static Map physicalMap = new HashMap();
public static String physicalFontNameFor(String textname, int textlen, String text) {
Map lenMap = (Map)physicalMap.get(textname);
if (lenMap == null) {
lenMap = new HashMap();
physicalMap.put(textname, lenMap);
}
Integer key = new Integer(textlen);
Font textfont = (Font)lenMap.get(key);
if (textfont == null) {
Font[] fontsToTry = null;
if (lenMap.isEmpty()) {
fontsToTry = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
} else {
Set fontset = new HashSet();
java.util.Iterator iter = lenMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry e = (Map.Entry)iter.next();
fontset.add(e.getValue());
}
fontsToTry = (Font[])fontset.toArray(new Font[fontset.size()]);
}
Font bestFont = null;
int bestCount = 0;
for (int i = 0; i < fontsToTry.length; ++i) {
Font font = fontsToTry[i];
int count = 0;
for (int j = 0, limit = text.length(); j < limit; ++j) {
if (font.canDisplay(text.charAt(j))) {
++count;
}
}
if (count > bestCount) {
bestFont = font;
bestCount = count;
}
}
textfont = bestFont;
lenMap.put(key, textfont);
}
return textfont.getName();
}
static class FontOption extends ObjectList {
static String[] optionnames = {
"default", "serif", "lucida", "physical"
};
static String[] descnames = {
"Default", "Serif", "Lucida Sans", "Physical"
};
public FontOption(Group parent, String nodeName, String description) {
super(parent, nodeName, description,
optionnames, descnames, optionnames, descnames, 0xa);
}
public String getValString(Object value) {
return value.toString();
}
public String getAbbreviatedModifierDescription(Object value) {
return value.toString();
}
}
}

View file

@ -0,0 +1,160 @@
/*
* Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.ui;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Component;
import java.awt.Container;
import java.awt.LayoutManager;
public class CompactLayout implements LayoutManager {
boolean horizontal;
public CompactLayout(boolean horizontal) {
this.horizontal = horizontal;
}
/**
* If the layout manager uses a per-component string,
* adds the component <code>comp</code> to the layout,
* associating it
* with the string specified by <code>name</code>.
*
* @param name the string to be associated with the component
* @param comp the component to be added
*/
public void addLayoutComponent(String name, Component comp) {
}
/**
* Removes the specified component from the layout.
* @param comp the component to be removed
*/
public void removeLayoutComponent(Component comp) {
}
/**
* Calculates the preferred size dimensions for the specified
* container, given the components it contains.
* @param parent the container to be laid out
*
* @see #minimumLayoutSize
*/
public Dimension preferredLayoutSize(Container parent) {
return getSize(parent, false);
}
/**
* Calculates the minimum size dimensions for the specified
* container, given the components it contains.
* @param parent the component to be laid out
* @see #preferredLayoutSize
*/
public Dimension minimumLayoutSize(Container parent) {
return getSize(parent, true);
}
public Dimension getSize(Container parent, boolean minimum) {
int n = parent.getComponentCount();
Insets insets = parent.getInsets();
Dimension d = new Dimension();
for (int i = 0; i < n; i++) {
Component comp = parent.getComponent(i);
if (comp instanceof EnableButton) {
continue;
}
Dimension p = (minimum
? comp.getMinimumSize()
: comp.getPreferredSize());
if (horizontal) {
d.width += p.width;
if (d.height < p.height) {
d.height = p.height;
}
} else {
if (d.width < p.width) {
d.width = p.width;
}
d.height += p.height;
}
}
d.width += (insets.left + insets.right);
d.height += (insets.top + insets.bottom);
return d;
}
/**
* Lays out the specified container.
* @param parent the container to be laid out
*/
public void layoutContainer(Container parent) {
int n = parent.getComponentCount();
Insets insets = parent.getInsets();
Dimension size = parent.getSize();
int c = horizontal ? insets.left : insets.top;
int x, y;
int ebx = size.width - insets.right;
size.width -= (insets.left + insets.right);
size.height -= (insets.top + insets.bottom);
for (int i = 0; i < n; i++) {
Component comp = parent.getComponent(i);
Dimension pref = comp.getPreferredSize();
if (comp instanceof EnableButton) {
ebx -= 4;
ebx -= pref.width;
x = ebx;
y = (insets.top - pref.height) / 2;
} else if (horizontal) {
x = c;
c += pref.width;
y = insets.top;
pref.height = size.height;
} else {
x = insets.left;
pref.width = size.width;
y = c;
c += pref.height;
}
comp.setBounds(x, y, pref.width, pref.height);
}
}
}

View file

@ -0,0 +1,92 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package j2dbench.ui;
import j2dbench.Group;
import j2dbench.Node;
import j2dbench.Option;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Insets;
public class EnableButton extends JButton implements ActionListener {
public static final int SET = 0;
public static final int CLEAR = 1;
public static final int INVERT = 2;
public static final int DEFAULT = 3;
private Group group;
private int type;
public static final String[] icons = {
"Set",
"Clear",
"Invert",
"Default",
};
public EnableButton(Group group, int type) {
super(icons[type]);
this.group = group;
this.type = type;
addActionListener(this);
setMargin(new Insets(0, 0, 0, 0));
setBorderPainted(false);
}
public void actionPerformed(ActionEvent e) {
Node.Iterator children = group.getRecursiveChildIterator();
String newval = (type == SET) ? "enabled" : "disabled";
while (children.hasNext()) {
Node child = children.next();
if (type == DEFAULT) {
child.restoreDefault();
} else if (child instanceof Option.Enable) {
Option.Enable enable = (Option.Enable) child;
if (type == INVERT) {
newval = enable.isEnabled() ? "disabled" : "enabled";
}
enable.setValueFromString(newval);
}
}
}
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class CodePointIM {
// Actually, the main method is not required for InputMethod.
// The following method is added just to tell users that their use is
// not correct and encourage their reading README.txt.
public static void main(String[] args) {
try {
ResourceBundle resource = ResourceBundle.getBundle(
"resources.codepoint",
Locale.getDefault());
System.err.println(resource.getString("warning"));
} catch (MissingResourceException e) {
System.err.println(e.toString());
}
System.exit(1);
}
}

View file

@ -0,0 +1,61 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>README - CodePointIM</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<h1>Code Point Input Method</h1>
<p>
The Code Point Input Method is a simple input method that allows Unicode
characters to be entered using their code point or code unit values.
<p>
The input method accepts three different notations, all using hexadecimal
digits from the set [0-9a-fA-F]:
<br>
<ul>
<li>"\uxxxx": The standard Unicode escape notation of the Java programming
language. This notation allows input of code points up to U+FFFE; the illegal
code point U+FFFF is not allowed.</li>
<li>"\Uxxxxxx": An extended Unicode escape notation specific to this input
method. This notation allows direct input of any Unicode code Point except the
illegal code point U+FFFF. The uppercase "U" indicates that six hexadecimal
digits follow. "xxxxxx" must be between 000000 and 10FFFF.</li>
<li>"\uxxxx\uyyyy": Two consecutive standard Unicode escapes, together
representing a code point between U+10000 and U+10FFFF (a supplementary
character). "xxxx" must be between D800 and DBFF (that is, a high surrogate
value), "yyyy" between DC00 and DFFF (a low surrogate value).</li>
</ul>
In general, the input method passes characters through unchanged. However,
when the user types a "\", the input method enters composition mode. In
composition mode, the user types the desired code point using one of the
notations above, then types a space character to convert to the corresponding
Unicode character and commit. The input method then returns to pass-through
mode until another "\" character is entered.
<p>
While in composition mode, the user can use the left arrow, right arrow,
backspace, and delete keys to edit the sequence. The "\u" or "\U" characters
can only be deleted if they are not followed by hexadecimal digits in the
composition sequence. Deleting the initial "\u" or "\U" returns the input
method to pass-through mode.
<p>
Since the initial "\" character starts composition mode, a user must type two
"\" characters in order to add a single "\" to the text. When an initial "\"
has been entered, but the next character is not "u", "U", or "\", both the "\"
and the subsequent character are committed, and the input method returns to
pass-through mode. Also, typing a new line, or tab character at any time
during composition immediately commits the current composed text.
<p>
Input methods are extensions to the Java Runtime Environment; they cannot be
run as applications. Before you can use an input method, you have to install
it in the JRE, run an application that supports input methods (such as the
JFC demos Notepad and Stylepad), and select the input method. You can learn
more about these steps from the article
"<a href="http://javadesktop.org/articles/InputMethod/index.html">Using Input Methods on the Java Platform</a>"
and more about supplementary character support from the article
"<a href="http://java.sun.com/developer/technicalArticles/Intl/Supplementary/index.html">Supplementary Characters in the Java Platform</a>".
<p>
This input method requires JRE 5.0 or higher.
<br>
</body>
</html>

View file

@ -0,0 +1,29 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>README - CodePointIM</title>
</head>
<body>
<h1>Code Point Input Method</h1>
<p>
Code Point Input Methodは、コードポイントまたはコード単位を使ってUnicode文字を入力するシンプルなインプットメソッドです。
<p>
このインプットメソッドでは、十六進数(0~9、a~f、A~F)を使った3つの入力形式をサポートします。
<br>
<ul>
<li>"\uxxxx":Javaプログラミング言語の標準Unicodeエスケープ表記です。この表記法では、U+0000からU+FFFEまでのコードポイントを入力できます。不正なコードポイントであるU+FFFFは入力できません。</li>
<li>"\Uxxxxxx":このインプットメソッド限定の拡張Unicodeエスケープ表記です。この表記法では、すべての有効なUnicodeコードポイントを直接入力できます。大文字の'U'は、後に6桁の十六進数が続くことを示しています。"xxxxxx"に指定できる値は000000から10FFFFまでで、このうち不正なコードポイントであるU+FFFF(00FFFF)は入力できません。</li>
<li>"\uxxxx\uyyyy":連続する2つの標準Unicodeエスケープ表記です。2つ合わせてU+10000からU+10FFFFまでの範囲のコードポイントを持つ補助文字(supplementary character)を表します。"xxxx"はD800以上DBFF以下(上位サロゲート値)、"yyyy"はDC00以上DFFF以下(下位サロゲート値)の範囲でなければなりません。</li>
</ul>
このインプットメソッドは、通常は入力された文字をそのままアプリケーション・プログラムに渡します(パススルー・モード)。しかし、ユーザが文字'\'をタイプするとコンポジション・モードになり、この状態でユーザは上記の入力形式のいずれかを使って目的のコードポイントを入力し、Spaceキーを押して入力されたコードポイントに相当するUnicode文字に変換・確定することができます。確定によってコンポジション・モードは終了し、その後再び'\'がタイプされるまでインプットメソッドはパススルー・モードで動作します。
<p>
コンポジション・モードでは、ユーザはBackspace、Deleteおよび左右の矢印キーを使って変換テキストを編集することができます。"\u"および"\U"は、変換テキスト中で後続する文字がない場合のみ削除可能です。先頭の"\u"または"\U"を削除すると、インプットメソッドはパススルー・モードに戻ります。
<p>
最初の'\'のタイプによってコンポジション・モードになるため、'\'を確定済みテキストにするためには合計二度タイプする必要があります。'\'の次にタイプされた文字が'u'、'U'、'\'のいずれでもない場合、'\'とその次にタイプされた文字の両方が確定され、インプットメソッドはパススルー・モードに戻ります。また、コンポジション・モード中にTabまたはEnterキーを押すと、インプットメソッドは現在の変換テキストをそのまま確定してパススルー・モードに戻ります。
<p>
インプットメソッドはJava Runtime Environmentの拡張機能であり、アプリケーション・プログラムとして動かすことはできません。インプットメソッドを使用する場合、はじめにインプットメソッドをJREにインストールし、次にインプットメソッドをサポートするアプリケーション・プログラム(例えばJFCデモのNotepadやStylepad)を起動してインプットメソッドを選択してください。これらの手順については"<a href="http://javadesktop.org/articles/InputMethod/index.html">Using Input Methods on the Java Platform</a>"をご参照ください。また、補助文字サポートの概要については"<a href="http://java.sun.com/developer/technicalArticles/Intl/Supplementary/index_ja.html">Javaプラットフォームにおける補助文字のサポート</a>"をご参照ください。
<p>
このインプットメソッドを使用するためには、JRE 5.0以降が必要です。
</body>
</html>

View file

@ -0,0 +1,44 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>自述文件——代码点输入法</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>代码点输入法</h1>
<p>
代码点输入法是一种简单的输入法,使您可以使用 Unicode 字符的代码点或代码单元值来输入 Unicode 字符。
</p>
<p>该输入法接受三种不同的表示法,这三种方法都使用来自字符集 [0-9a-fA-F] 的十六进制数字: <br>
</p>
<ul>
<li>"\uxxxx":Java 编程语言的标准 Unicode 换码表示法。此表示法允许输入不超过 U+FFFE
的代码点;不允许输入非法代码点 U+FFFF。</li>
<li>"\Uxxxxxx":此输入法专用的扩展 Unicode 换码表示法。此表示法允许直接输入任何 Unicode
代码点,但非法代码点 U+FFFF 除外。大写 "U" 表示后跟六个十六进制数字。"xxxxxx" 必须在 000000 和 10FFFF
之间。</li>
<li>"\uxxxx\uyyyy":两个连续的标准 Unicode 换码,共同表示 U+10000 和 U+10FFFF
之间的一个代码点(增补字符)。"xxxx" 必须在 D800 和 DBFF 之间(即高代码值),"yyyy" 必须在 DC00 和 DFFF
之间(低代码值)。</li>
</ul>
一般情况下,输入法仅传递字符而不进行更改。但是,当用户键入 "\"
时,输入法将进入编写模式。在编写模式下,用户使用上述表示法之一键入所需代码点,然后键入空格字符以转换至相应的 Unicode
字符并提交。然后输入法将返回到传递模式,直到用户输入另一个 "\" 字符。
<p>处于编写模式时,用户可以使用左箭头键、右箭头键、Back Space 键和 Delete 键来编辑序列。在编写序列中,只有当 "\u" 或
"\U" 字符后面未跟有十六进制数字时,才可以将 "\u" 或 "\U" 删除。删除初始的 "\u" 或 "\U" 将使输入法返回至传递模式。
</p>
<p>由于初始的 "\" 字符用于启动编写模式,因此为了向文本中添加一个 "\",用户必须键入两个 "\" 字符。如果已输入初始
"\",但下一个字符不是 "u"、"U" 或 "\",则 "\"
和随后一个字符将被提交,并且输入法将返回至传递模式。另外,在编写期间的任何时候键入一个新行或制表符都将立即提交当前编写的文本。
</p>
<p>输入法是 Java 运行环境的扩展;它们不能作为应用程序运行。要使用某个输入法,您必须将其安装在 JRE
中,运行支持输入法的应用程序(例如 JFC 演示版 Notepad 和 Stylepad),并选择该输入法。您可以从“<a
href="http://javadesktop.org/articles/InputMethod/index.html">在 Java
平台上使用输入法</a>”中了解有关这些步骤的更多信息,还可以从“<a
href="http://java.sun.com/developer/technicalArticles/Intl/Supplementary/index.html">Java
平台中的增补字符</a>”中了解有关增补字符支持的更多信息。
</p>
<p>该输入法要求 JRE 5.0 或更高版本。 <br>
</p>
</body>
</html>

View file

@ -0,0 +1,499 @@
/*
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.inputmethods.internal.codepointim;
import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.Rectangle;
import java.awt.event.InputMethodEvent;
import java.awt.event.KeyEvent;
import java.awt.font.TextAttribute;
import java.awt.font.TextHitInfo;
import java.awt.im.InputMethodHighlight;
import java.awt.im.spi.InputMethod;
import java.awt.im.spi.InputMethodContext;
import java.io.IOException;
import java.text.AttributedString;
import java.util.Locale;
/**
* The Code Point Input Method is a simple input method that allows Unicode
* characters to be entered using their code point or code unit values. See the
* accompanying file README.txt for more information.
*
* @author Brian Beck
*/
public class CodePointInputMethod implements InputMethod {
private static final int UNSET = 0;
private static final int ESCAPE = 1; // \u0000 - \uFFFF
private static final int SPECIAL_ESCAPE = 2; // \U000000 - \U10FFFF
private static final int SURROGATE_PAIR = 3; // \uD800\uDC00 - \uDBFF\uDFFF
private InputMethodContext context;
private Locale locale;
private StringBuffer buffer;
private int insertionPoint;
private int format = UNSET;
public CodePointInputMethod() throws IOException {
}
/**
* This is the input method's main routine. The composed text is stored
* in buffer.
*/
public void dispatchEvent(AWTEvent event) {
// This input method handles KeyEvent only.
if (!(event instanceof KeyEvent)) {
return;
}
KeyEvent e = (KeyEvent) event;
int eventID = event.getID();
boolean notInCompositionMode = buffer.length() == 0;
if (eventID == KeyEvent.KEY_PRESSED) {
// If we are not in composition mode, pass through
if (notInCompositionMode) {
return;
}
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
moveCaretLeft();
break;
case KeyEvent.VK_RIGHT:
moveCaretRight();
break;
}
} else if (eventID == KeyEvent.KEY_TYPED) {
char c = e.getKeyChar();
// If we are not in composition mode, wait a back slash
if (notInCompositionMode) {
// If the type character is not a back slash, pass through
if (c != '\\') {
return;
}
startComposition(); // Enter to composition mode
} else {
switch (c) {
case ' ': // Exit from composition mode
finishComposition();
break;
case '\u007f': // Delete
deleteCharacter();
break;
case '\b': // BackSpace
deletePreviousCharacter();
break;
case '\u001b': // Escape
cancelComposition();
break;
case '\n': // Return
case '\t': // Tab
sendCommittedText();
break;
default:
composeUnicodeEscape(c);
break;
}
}
} else { // KeyEvent.KEY_RELEASED
// If we are not in composition mode, pass through
if (notInCompositionMode) {
return;
}
}
e.consume();
}
private void composeUnicodeEscape(char c) {
switch (buffer.length()) {
case 1: // \\
waitEscapeCharacter(c);
break;
case 2: // \\u or \\U
case 3: // \\ux or \\Ux
case 4: // \\uxx or \\Uxx
waitDigit(c);
break;
case 5: // \\uxxx or \\Uxxx
if (format == SPECIAL_ESCAPE) {
waitDigit(c);
} else {
waitDigit2(c);
}
break;
case 6: // \\uxxxx or \\Uxxxx
if (format == SPECIAL_ESCAPE) {
waitDigit(c);
} else if (format == SURROGATE_PAIR) {
waitBackSlashOrLowSurrogate(c);
} else {
beep();
}
break;
case 7: // \\Uxxxxx
// Only SPECIAL_ESCAPE format uses this state.
// Since the second "\\u" of SURROGATE_PAIR format is inserted
// automatically, users don't have to type these keys.
waitDigit(c);
break;
case 8: // \\uxxxx\\u
case 9: // \\uxxxx\\ux
case 10: // \\uxxxx\\uxx
case 11: // \\uxxxx\\uxxx
if (format == SURROGATE_PAIR) {
waitDigit(c);
} else {
beep();
}
break;
default:
beep();
break;
}
}
private void waitEscapeCharacter(char c) {
if (c == 'u' || c == 'U') {
buffer.append(c);
insertionPoint++;
sendComposedText();
format = (c == 'u') ? ESCAPE : SPECIAL_ESCAPE;
} else {
if (c != '\\') {
buffer.append(c);
insertionPoint++;
}
sendCommittedText();
}
}
private void waitDigit(char c) {
if (Character.digit(c, 16) != -1) {
buffer.insert(insertionPoint++, c);
sendComposedText();
} else {
beep();
}
}
private void waitDigit2(char c) {
if (Character.digit(c, 16) != -1) {
buffer.insert(insertionPoint++, c);
char codePoint = (char) getCodePoint(buffer, 2, 5);
if (Character.isHighSurrogate(codePoint)) {
format = SURROGATE_PAIR;
buffer.append("\\u");
insertionPoint = 8;
} else {
format = ESCAPE;
}
sendComposedText();
} else {
beep();
}
}
private void waitBackSlashOrLowSurrogate(char c) {
if (insertionPoint == 6) {
if (c == '\\') {
buffer.append(c);
buffer.append('u');
insertionPoint = 8;
sendComposedText();
} else if (Character.digit(c, 16) != -1) {
buffer.append("\\u");
buffer.append(c);
insertionPoint = 9;
sendComposedText();
} else {
beep();
}
} else {
beep();
}
}
/**
* Send the composed text to the client.
*/
private void sendComposedText() {
AttributedString as = new AttributedString(buffer.toString());
as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
context.dispatchInputMethodEvent(
InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
as.getIterator(), 0,
TextHitInfo.leading(insertionPoint), null);
}
/**
* Send the committed text to the client.
*/
private void sendCommittedText() {
AttributedString as = new AttributedString(buffer.toString());
context.dispatchInputMethodEvent(
InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
as.getIterator(), buffer.length(),
TextHitInfo.leading(insertionPoint), null);
buffer.setLength(0);
insertionPoint = 0;
format = UNSET;
}
/**
* Move the insertion point one position to the left in the composed text.
* Do not let the caret move to the left of the "\\u" or "\\U".
*/
private void moveCaretLeft() {
int len = buffer.length();
if (--insertionPoint < 2) {
insertionPoint++;
beep();
} else if (format == SURROGATE_PAIR && insertionPoint == 7) {
insertionPoint = 8;
beep();
}
context.dispatchInputMethodEvent(
InputMethodEvent.CARET_POSITION_CHANGED,
null, 0,
TextHitInfo.leading(insertionPoint), null);
}
/**
* Move the insertion point one position to the right in the composed text.
*/
private void moveCaretRight() {
int len = buffer.length();
if (++insertionPoint > len) {
insertionPoint = len;
beep();
}
context.dispatchInputMethodEvent(
InputMethodEvent.CARET_POSITION_CHANGED,
null, 0,
TextHitInfo.leading(insertionPoint), null);
}
/**
* Delete the character preceding the insertion point in the composed text.
* If the insertion point is not at the end of the composed text and the
* preceding text is "\\u" or "\\U", ring the bell.
*/
private void deletePreviousCharacter() {
if (insertionPoint == 2) {
if (buffer.length() == 2) {
cancelComposition();
} else {
// Do not allow deletion of the leading "\\u" or "\\U" if there
// are other digits in the composed text.
beep();
}
} else if (insertionPoint == 8) {
if (buffer.length() == 8) {
if (format == SURROGATE_PAIR) {
buffer.deleteCharAt(--insertionPoint);
}
buffer.deleteCharAt(--insertionPoint);
sendComposedText();
} else {
// Do not allow deletion of the second "\\u" if there are other
// digits in the composed text.
beep();
}
} else {
buffer.deleteCharAt(--insertionPoint);
if (buffer.length() == 0) {
sendCommittedText();
} else {
sendComposedText();
}
}
}
/**
* Delete the character following the insertion point in the composed text.
* If the insertion point is at the end of the composed text, ring the bell.
*/
private void deleteCharacter() {
if (insertionPoint < buffer.length()) {
buffer.deleteCharAt(insertionPoint);
sendComposedText();
} else {
beep();
}
}
private void startComposition() {
buffer.append('\\');
insertionPoint = 1;
sendComposedText();
}
private void cancelComposition() {
buffer.setLength(0);
insertionPoint = 0;
sendCommittedText();
}
private void finishComposition() {
int len = buffer.length();
if (len == 6 && format != SPECIAL_ESCAPE) {
char codePoint = (char) getCodePoint(buffer, 2, 5);
if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
buffer.setLength(0);
buffer.append(codePoint);
sendCommittedText();
return;
}
} else if (len == 8 && format == SPECIAL_ESCAPE) {
int codePoint = getCodePoint(buffer, 2, 7);
if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
buffer.setLength(0);
buffer.appendCodePoint(codePoint);
sendCommittedText();
return;
}
} else if (len == 12 && format == SURROGATE_PAIR) {
char[] codePoint = {
(char) getCodePoint(buffer, 2, 5),
(char) getCodePoint(buffer, 8, 11)
};
if (Character.isHighSurrogate(codePoint[0]) && Character.
isLowSurrogate(codePoint[1])) {
buffer.setLength(0);
buffer.append(codePoint);
sendCommittedText();
return;
}
}
beep();
}
private int getCodePoint(StringBuffer sb, int from, int to) {
int value = 0;
for (int i = from; i <= to; i++) {
value = (value << 4) + Character.digit(sb.charAt(i), 16);
}
return value;
}
private static void beep() {
Toolkit.getDefaultToolkit().beep();
}
public void activate() {
if (buffer == null) {
buffer = new StringBuffer(12);
insertionPoint = 0;
}
}
public void deactivate(boolean isTemporary) {
if (!isTemporary) {
buffer = null;
}
}
public void dispose() {
}
public Object getControlObject() {
return null;
}
public void endComposition() {
sendCommittedText();
}
public Locale getLocale() {
return locale;
}
public void hideWindows() {
}
public boolean isCompositionEnabled() {
// always enabled
return true;
}
public void notifyClientWindowChange(Rectangle location) {
}
public void reconvert() {
// not supported yet
throw new UnsupportedOperationException();
}
public void removeNotify() {
}
public void setCharacterSubsets(Character.Subset[] subsets) {
}
public void setCompositionEnabled(boolean enable) {
// not supported yet
throw new UnsupportedOperationException();
}
public void setInputMethodContext(InputMethodContext context) {
this.context = context;
}
/*
* The Code Point Input Method supports all locales.
*/
public boolean setLocale(Locale locale) {
this.locale = locale;
return true;
}
}

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 2002, 2025, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
package com.sun.inputmethods.internal.codepointim;
import java.awt.Image;
import java.awt.im.spi.InputMethodDescriptor;
import java.awt.im.spi.InputMethod;
import java.util.Locale;
/**
* The CodePointInputMethod is a simple input method that allows Unicode
* characters to be entered via their hexadecimal code point values.
*
* The class, CodePointInputMethodDescriptor, provides information about the
* CodePointInputMethod which allows it to be selected and loaded by the
* Input Method Framework.
*/
public class CodePointInputMethodDescriptor implements InputMethodDescriptor {
public CodePointInputMethodDescriptor() {
}
/**
* Creates a new instance of the Code Point input method.
*
* @return a new instance of the Code Point input method
* @throws Exception any exception that may occur while creating the
* input method instance
*/
public InputMethod createInputMethod() throws Exception {
return new CodePointInputMethod();
}
/**
* This input method can be used by any locale.
*/
public Locale[] getAvailableLocales() {
Locale[] locales = {
Locale.ROOT, };
return locales;
}
public synchronized String getInputMethodDisplayName(Locale inputLocale,
Locale displayLanguage) {
return "CodePoint Input Method";
}
public Image getInputMethodIcon(Locale inputLocale) {
return null;
}
public boolean hasDynamicLocaleList() {
return false;
}
}

View file

@ -0,0 +1 @@
com.sun.inputmethods.internal.codepointim.CodePointInputMethodDescriptor

View file

@ -0,0 +1,39 @@
# Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# - Neither the name of Oracle nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# Resource strings for CodePointIM
#
warning=\
This is a demo input method; it cannot be run directly as an application.\n\
Please read the file README.html in this directory to find out how to use \n\
this input method.

View file

@ -0,0 +1,36 @@
# Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# - Neither the name of Oracle nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# Resource strings for CodePointIM
#
warning=Diese Demoeingabemethode kann nicht direkt als Anwendung ausgeführt werden.\nIn der Datei README.html in diesem Verzeichnis erfahren Sie, wie Sie diese \nEingabemethode verwenden.

View file

@ -0,0 +1,36 @@
# Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# - Neither the name of Oracle nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# Resource strings for CodePointIM
#
warning=これはデモ用の入力メソッドです。アプリケーションとして単体で実行する\nことはできません。この入力メソッドの使用方法については、このディレクトリ\nにあるREADME.htmlをご覧ください。

View file

@ -0,0 +1,36 @@
# Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# - Neither the name of Oracle nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# Resource strings for CodePointIM
#
warning=这是演示输入法; 不能将其直接作为应用程序来运行。\n请阅读此目录中的 README.html 文件以了解如何使用\n此输入法。

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
import java.io.File;
import java.io.IOException;
import javax.swing.filechooser.FileSystemView;
/**
* This is a simple example that uses the FileSystemView class.
* You can provide a superclass of the FileSystemView class with your own functionality.
*
* @author Pavel Porvatov
*/
public class ExampleFileSystemView extends FileSystemView {
/**
* Creates a new folder with the default name "New folder". This method is invoked
* when the user presses the "New folder" button.
*/
public File createNewFolder(File containingDir) throws IOException {
File result = new File(containingDir, "New folder");
if (result.exists()) {
throw new IOException("Directory 'New folder' exists");
}
if (!result.mkdir()) {
throw new IOException("Cannot create directory");
}
return result;
}
/**
* Returns a list which appears in a drop-down list of the FileChooser component.
* In this implementation only the home directory is returned.
*/
@Override
public File[] getRoots() {
return new File[] { getHomeDirectory() };
}
/**
* Returns a string that represents a directory or a file in the FileChooser component.
* A string with all upper case letters is returned for a directory.
* A string with all lower case letters is returned for a file.
*/
@Override
public String getSystemDisplayName(File f) {
String displayName = super.getSystemDisplayName(f);
return f.isDirectory() ? displayName.toUpperCase() : displayName.
toLowerCase();
}
}

View file

@ -0,0 +1,193 @@
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* A convenience implementation of the FileView interface that
* manages name, icon, traversable, and file type information.
*
* This implementation will work well with file systems that use
* "dot" extensions to indicate file type. For example: "picture.gif"
* as a gif image.
*
* If the java.io.File ever contains some of this information, such as
* file type, icon, and hidden file inforation, this implementation may
* become obsolete. At minimum, it should be rewritten at that time to
* use any new type information provided by java.io.File
*
* Example:
* JFileChooser chooser = new JFileChooser();
* fileView = new ExampleFileView();
* fileView.putIcon("jpg", new ImageIcon("images/jpgIcon.jpg"));
* fileView.putIcon("gif", new ImageIcon("images/gifIcon.gif"));
* chooser.setFileView(fileView);
*
* @author Jeff Dinkins
*/
public class ExampleFileView extends FileView {
private final Map<String, Icon> icons = new HashMap<String, Icon>();
private final Map<File, String> fileDescriptions =
new HashMap<File, String>();
private final Map<String, String> typeDescriptions =
new HashMap<String, String>();
/**
* The name of the file. Do nothing special here. Let
* the system file view handle this.
* @see FileView#getName
*/
@Override
public String getName(File f) {
return null;
}
/**
* Adds a human readable description of the file.
*/
public void putDescription(File f, String fileDescription) {
fileDescriptions.put(f, fileDescription);
}
/**
* A human readable description of the file.
*
* @see FileView#getDescription
*/
@Override
public String getDescription(File f) {
return fileDescriptions.get(f);
}
/**
* Adds a human readable type description for files. Based on "dot"
* extension strings, e.g: ".gif". Case is ignored.
*/
public void putTypeDescription(String extension, String typeDescription) {
typeDescriptions.put(extension, typeDescription);
}
/**
* Adds a human readable type description for files of the type of
* the passed in file. Based on "dot" extension strings, e.g: ".gif".
* Case is ignored.
*/
public void putTypeDescription(File f, String typeDescription) {
putTypeDescription(getExtension(f), typeDescription);
}
/**
* A human readable description of the type of the file.
*
* @see FileView#getTypeDescription
*/
@Override
public String getTypeDescription(File f) {
return typeDescriptions.get(getExtension(f));
}
/**
* Convenience method that returns the "dot" extension for the
* given file.
*/
private String getExtension(File f) {
String name = f.getName();
if (name != null) {
int extensionIndex = name.lastIndexOf('.');
if (extensionIndex < 0) {
return null;
}
return name.substring(extensionIndex + 1).toLowerCase();
}
return null;
}
/**
* Adds an icon based on the file type "dot" extension
* string, e.g: ".gif". Case is ignored.
*/
public void putIcon(String extension, Icon icon) {
icons.put(extension, icon);
}
/**
* Icon that reperesents this file. Default implementation returns
* null. You might want to override this to return something more
* interesting.
*
* @see FileView#getIcon
*/
@Override
public Icon getIcon(File f) {
Icon icon = null;
String extension = getExtension(f);
if (extension != null) {
icon = icons.get(extension);
}
return icon;
}
/**
* Whether the directory is traversable or not. Generic implementation
* returns true for all directories and special folders.
*
* You might want to subtype ExampleFileView to do somethimg more interesting,
* such as recognize compound documents directories; in such a case you might
* return a special icon for the directory that makes it look like a regular
* document, and return false for isTraversable to not allow users to
* descend into the directory.
*
* @see FileView#isTraversable
*/
@Override
public Boolean isTraversable(File f) {
// if (some_reason) {
// return Boolean.FALSE;
// }
return null; // Use default from FileSystemView
}
}

View file

@ -0,0 +1,850 @@
/*
* Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.util.ArrayList;
import javax.swing.plaf.FileChooserUI;
import javax.swing.plaf.basic.BasicFileChooserUI;
import java.io.File;
import static javax.swing.JFileChooser.*;
/**
*
* A demo which makes extensive use of the file chooser.
*
* @author Jeff Dinkins
*/
@SuppressWarnings("serial")
public class FileChooserDemo extends JPanel implements ActionListener {
public static final String NIMBUS_LAF_NAME = "Nimbus";
private static JFrame frame;
private final List<SupportedLaF> supportedLaFs =
new ArrayList<SupportedLaF>();
private static SupportedLaF nimbusLaF;
private static class SupportedLaF {
private final String name;
private final LookAndFeel laf;
SupportedLaF(String name, LookAndFeel laf) {
this.name = name;
this.laf = laf;
}
@Override
public String toString() {
return name;
}
}
private JButton showButton;
private JCheckBox showAllFilesFilterCheckBox;
private JCheckBox showImageFilesFilterCheckBox;
private JCheckBox showFullDescriptionCheckBox;
private JCheckBox useFileViewCheckBox;
private JCheckBox useFileSystemViewCheckBox;
private JCheckBox accessoryCheckBox;
private JCheckBox setHiddenCheckBox;
private JCheckBox useEmbedInWizardCheckBox;
private JCheckBox useControlsCheckBox;
private JCheckBox enableDragCheckBox;
private JRadioButton singleSelectionRadioButton;
private JRadioButton multiSelectionRadioButton;
private JRadioButton openRadioButton;
private JRadioButton saveRadioButton;
private JRadioButton customButton;
private JComboBox<SupportedLaF> lafComboBox;
private JRadioButton justFilesRadioButton;
private JRadioButton justDirectoriesRadioButton;
private JRadioButton bothFilesAndDirectoriesRadioButton;
private JTextField customField;
private final ExampleFileView fileView;
private final ExampleFileSystemView fileSystemView;
private static final Dimension hpad10 = new Dimension(10, 1);
private static final Dimension vpad20 = new Dimension(1, 20);
private static final Dimension vpad7 = new Dimension(1, 7);
private static final Dimension vpad4 = new Dimension(1, 4);
private static final Insets insets = new Insets(5, 10, 0, 10);
private final FilePreviewer previewer;
private final JFileChooser chooser;
@SuppressWarnings("LeakingThisInConstructor")
public FileChooserDemo() {
UIManager.LookAndFeelInfo[] installedLafs = UIManager.
getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo lafInfo : installedLafs) {
try {
Class<?> lnfClass = Class.forName(lafInfo.getClassName());
LookAndFeel laf = (LookAndFeel) (lnfClass.getDeclaredConstructor().newInstance());
if (laf.isSupportedLookAndFeel()) {
String name = lafInfo.getName();
SupportedLaF supportedLaF = new SupportedLaF(name, laf);
supportedLaFs.add(supportedLaF);
if (NIMBUS_LAF_NAME.equals(name)) {
nimbusLaF = supportedLaF;
}
}
} catch (Exception ignored) {
// If ANYTHING weird happens, don't add this L&F
}
}
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
chooser = new JFileChooser();
previewer = new FilePreviewer(chooser);
// Create Custom FileView
fileView = new ExampleFileView();
fileView.putIcon("jpg", new ImageIcon(getClass().getResource(
"/resources/images/jpgIcon.jpg")));
fileView.putIcon("gif", new ImageIcon(getClass().getResource(
"/resources/images/gifIcon.gif")));
// Create Custom FileSystemView
fileSystemView = new ExampleFileSystemView();
// create a radio listener to listen to option changes
OptionListener optionListener = new OptionListener();
// Create options
openRadioButton = new JRadioButton("Open");
openRadioButton.setSelected(true);
openRadioButton.addActionListener(optionListener);
saveRadioButton = new JRadioButton("Save");
saveRadioButton.addActionListener(optionListener);
customButton = new JRadioButton("Custom");
customButton.addActionListener(optionListener);
customField = new JTextField(8) {
@Override
public Dimension getMaximumSize() {
return new Dimension(getPreferredSize().width,
getPreferredSize().height);
}
};
customField.setText("Doit");
customField.setAlignmentY(JComponent.TOP_ALIGNMENT);
customField.setEnabled(false);
customField.addActionListener(optionListener);
ButtonGroup group1 = new ButtonGroup();
group1.add(openRadioButton);
group1.add(saveRadioButton);
group1.add(customButton);
// filter buttons
showAllFilesFilterCheckBox = new JCheckBox("Show \"All Files\" Filter");
showAllFilesFilterCheckBox.addActionListener(optionListener);
showAllFilesFilterCheckBox.setSelected(true);
showImageFilesFilterCheckBox = new JCheckBox("Show JPG and GIF Filters");
showImageFilesFilterCheckBox.addActionListener(optionListener);
showImageFilesFilterCheckBox.setSelected(false);
accessoryCheckBox = new JCheckBox("Show Preview");
accessoryCheckBox.addActionListener(optionListener);
accessoryCheckBox.setSelected(false);
// more options
setHiddenCheckBox = new JCheckBox("Show Hidden Files");
setHiddenCheckBox.addActionListener(optionListener);
showFullDescriptionCheckBox = new JCheckBox("With File Extensions");
showFullDescriptionCheckBox.addActionListener(optionListener);
showFullDescriptionCheckBox.setSelected(true);
showFullDescriptionCheckBox.setEnabled(false);
useFileViewCheckBox = new JCheckBox("Use FileView");
useFileViewCheckBox.addActionListener(optionListener);
useFileViewCheckBox.setSelected(false);
useFileSystemViewCheckBox = new JCheckBox("Use FileSystemView", false);
useFileSystemViewCheckBox.addActionListener(optionListener);
useEmbedInWizardCheckBox = new JCheckBox("Embed in Wizard");
useEmbedInWizardCheckBox.addActionListener(optionListener);
useEmbedInWizardCheckBox.setSelected(false);
useControlsCheckBox = new JCheckBox("Show Control Buttons");
useControlsCheckBox.addActionListener(optionListener);
useControlsCheckBox.setSelected(true);
enableDragCheckBox = new JCheckBox("Enable Dragging");
enableDragCheckBox.addActionListener(optionListener);
// File or Directory chooser options
ButtonGroup group3 = new ButtonGroup();
justFilesRadioButton = new JRadioButton("Just Select Files");
justFilesRadioButton.setSelected(true);
group3.add(justFilesRadioButton);
justFilesRadioButton.addActionListener(optionListener);
justDirectoriesRadioButton = new JRadioButton("Just Select Directories");
group3.add(justDirectoriesRadioButton);
justDirectoriesRadioButton.addActionListener(optionListener);
bothFilesAndDirectoriesRadioButton = new JRadioButton(
"Select Files or Directories");
group3.add(bothFilesAndDirectoriesRadioButton);
bothFilesAndDirectoriesRadioButton.addActionListener(optionListener);
singleSelectionRadioButton = new JRadioButton("Single Selection", true);
singleSelectionRadioButton.addActionListener(optionListener);
multiSelectionRadioButton = new JRadioButton("Multi Selection");
multiSelectionRadioButton.addActionListener(optionListener);
ButtonGroup group4 = new ButtonGroup();
group4.add(singleSelectionRadioButton);
group4.add(multiSelectionRadioButton);
// Create show button
showButton = new JButton("Show FileChooser");
showButton.addActionListener(this);
showButton.setMnemonic('s');
// Create laf combo box
lafComboBox = new JComboBox<>(supportedLaFs.toArray(new SupportedLaF[0]));
lafComboBox.setSelectedItem(nimbusLaF);
lafComboBox.setEditable(false);
lafComboBox.addActionListener(optionListener);
// ********************************************************
// ******************** Dialog Type ***********************
// ********************************************************
JPanel control1 = new InsetPanel(insets);
control1.setBorder(BorderFactory.createTitledBorder("Dialog Type"));
control1.setLayout(new BoxLayout(control1, BoxLayout.Y_AXIS));
control1.add(Box.createRigidArea(vpad20));
control1.add(openRadioButton);
control1.add(Box.createRigidArea(vpad7));
control1.add(saveRadioButton);
control1.add(Box.createRigidArea(vpad7));
control1.add(customButton);
control1.add(Box.createRigidArea(vpad4));
JPanel fieldWrapper = new JPanel();
fieldWrapper.setLayout(new BoxLayout(fieldWrapper, BoxLayout.X_AXIS));
fieldWrapper.setAlignmentX(Component.LEFT_ALIGNMENT);
fieldWrapper.add(Box.createRigidArea(hpad10));
fieldWrapper.add(Box.createRigidArea(hpad10));
fieldWrapper.add(customField);
control1.add(fieldWrapper);
control1.add(Box.createRigidArea(vpad20));
control1.add(Box.createGlue());
// ********************************************************
// ***************** Filter Controls **********************
// ********************************************************
JPanel control2 = new InsetPanel(insets);
control2.setBorder(BorderFactory.createTitledBorder("Filter Controls"));
control2.setLayout(new BoxLayout(control2, BoxLayout.Y_AXIS));
control2.add(Box.createRigidArea(vpad20));
control2.add(showAllFilesFilterCheckBox);
control2.add(Box.createRigidArea(vpad7));
control2.add(showImageFilesFilterCheckBox);
control2.add(Box.createRigidArea(vpad4));
JPanel checkWrapper = new JPanel();
checkWrapper.setLayout(new BoxLayout(checkWrapper, BoxLayout.X_AXIS));
checkWrapper.setAlignmentX(Component.LEFT_ALIGNMENT);
checkWrapper.add(Box.createRigidArea(hpad10));
checkWrapper.add(Box.createRigidArea(hpad10));
checkWrapper.add(showFullDescriptionCheckBox);
control2.add(checkWrapper);
control2.add(Box.createRigidArea(vpad20));
control2.add(Box.createGlue());
// ********************************************************
// ****************** Display Options *********************
// ********************************************************
JPanel control3 = new InsetPanel(insets);
control3.setBorder(BorderFactory.createTitledBorder("Display Options"));
control3.setLayout(new BoxLayout(control3, BoxLayout.Y_AXIS));
control3.add(Box.createRigidArea(vpad20));
control3.add(setHiddenCheckBox);
control3.add(Box.createRigidArea(vpad7));
control3.add(useFileViewCheckBox);
control3.add(Box.createRigidArea(vpad7));
control3.add(useFileSystemViewCheckBox);
control3.add(Box.createRigidArea(vpad7));
control3.add(accessoryCheckBox);
control3.add(Box.createRigidArea(vpad7));
control3.add(useEmbedInWizardCheckBox);
control3.add(Box.createRigidArea(vpad7));
control3.add(useControlsCheckBox);
control3.add(Box.createRigidArea(vpad7));
control3.add(enableDragCheckBox);
control3.add(Box.createRigidArea(vpad20));
control3.add(Box.createGlue());
// ********************************************************
// ************* File & Directory Options *****************
// ********************************************************
JPanel control4 = new InsetPanel(insets);
control4.setBorder(BorderFactory.createTitledBorder(
"File and Directory Options"));
control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS));
control4.add(Box.createRigidArea(vpad20));
control4.add(justFilesRadioButton);
control4.add(Box.createRigidArea(vpad7));
control4.add(justDirectoriesRadioButton);
control4.add(Box.createRigidArea(vpad7));
control4.add(bothFilesAndDirectoriesRadioButton);
control4.add(Box.createRigidArea(vpad20));
control4.add(singleSelectionRadioButton);
control4.add(Box.createRigidArea(vpad7));
control4.add(multiSelectionRadioButton);
control4.add(Box.createRigidArea(vpad20));
control4.add(Box.createGlue());
// ********************************************************
// **************** Look & Feel Switch ********************
// ********************************************************
JPanel panel = new JPanel();
panel.add(new JLabel("Look and Feel: "));
panel.add(lafComboBox);
panel.add(showButton);
// ********************************************************
// ****************** Wrap 'em all up *********************
// ********************************************************
JPanel wrapper = new JPanel();
wrapper.setLayout(new BoxLayout(wrapper, BoxLayout.X_AXIS));
add(Box.createRigidArea(vpad20));
wrapper.add(Box.createRigidArea(hpad10));
wrapper.add(Box.createRigidArea(hpad10));
wrapper.add(control1);
wrapper.add(Box.createRigidArea(hpad10));
wrapper.add(control2);
wrapper.add(Box.createRigidArea(hpad10));
wrapper.add(control3);
wrapper.add(Box.createRigidArea(hpad10));
wrapper.add(control4);
wrapper.add(Box.createRigidArea(hpad10));
wrapper.add(Box.createRigidArea(hpad10));
add(wrapper);
add(Box.createRigidArea(vpad20));
add(panel);
add(Box.createRigidArea(vpad20));
}
public void actionPerformed(ActionEvent e) {
if (customButton.isSelected()) {
chooser.setApproveButtonText(customField.getText());
}
if (chooser.isMultiSelectionEnabled()) {
chooser.setSelectedFiles(null);
} else {
chooser.setSelectedFile(null);
}
// clear the preview from the previous display of the chooser
JComponent accessory = chooser.getAccessory();
if (accessory != null) {
((FilePreviewer) accessory).loadImage(null);
}
if (useEmbedInWizardCheckBox.isSelected()) {
WizardDialog wizard = new WizardDialog(frame, true);
wizard.setVisible(true);
wizard.dispose();
return;
}
int retval = chooser.showDialog(frame, null);
if (retval == APPROVE_OPTION) {
JOptionPane.showMessageDialog(frame, getResultString());
} else if (retval == CANCEL_OPTION) {
JOptionPane.showMessageDialog(frame,
"User cancelled operation. No file was chosen.");
} else if (retval == ERROR_OPTION) {
JOptionPane.showMessageDialog(frame,
"An error occurred. No file was chosen.");
} else {
JOptionPane.showMessageDialog(frame, "Unknown operation occurred.");
}
}
private void resetFileFilters(boolean enableFilters,
boolean showExtensionInDescription) {
chooser.resetChoosableFileFilters();
if (enableFilters) {
FileFilter jpgFilter = createFileFilter(
"JPEG Compressed Image Files",
showExtensionInDescription, "jpg");
FileFilter gifFilter = createFileFilter("GIF Image Files",
showExtensionInDescription, "gif");
FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files",
showExtensionInDescription, "jpg",
"gif");
chooser.addChoosableFileFilter(bothFilter);
chooser.addChoosableFileFilter(jpgFilter);
chooser.addChoosableFileFilter(gifFilter);
}
}
private FileFilter createFileFilter(String description,
boolean showExtensionInDescription, String... extensions) {
if (showExtensionInDescription) {
description = createFileNameFilterDescriptionFromExtensions(
description, extensions);
}
return new FileNameExtensionFilter(description, extensions);
}
private String createFileNameFilterDescriptionFromExtensions(
String description, String[] extensions) {
String fullDescription = (description == null) ? "(" : description
+ " (";
// build the description from the extension list
fullDescription += "." + extensions[0];
for (int i = 1; i < extensions.length; i++) {
fullDescription += ", .";
fullDescription += extensions[i];
}
fullDescription += ")";
return fullDescription;
}
private class WizardDialog extends JDialog implements ActionListener {
CardLayout cardLayout;
JPanel cardPanel;
JLabel messageLabel;
JButton backButton, nextButton, closeButton;
@SuppressWarnings("LeakingThisInConstructor")
WizardDialog(JFrame frame, boolean modal) {
super(frame, "Embedded JFileChooser Demo", modal);
cardLayout = new CardLayout();
cardPanel = new JPanel(cardLayout);
getContentPane().add(cardPanel, BorderLayout.CENTER);
messageLabel = new JLabel("", JLabel.CENTER);
cardPanel.add(chooser, "fileChooser");
cardPanel.add(messageLabel, "label");
cardLayout.show(cardPanel, "fileChooser");
chooser.addActionListener(this);
JPanel buttonPanel = new JPanel();
backButton = new JButton("< Back");
nextButton = new JButton("Next >");
closeButton = new JButton("Close");
buttonPanel.add(backButton);
buttonPanel.add(nextButton);
buttonPanel.add(closeButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
backButton.setEnabled(false);
getRootPane().setDefaultButton(nextButton);
backButton.addActionListener(this);
nextButton.addActionListener(this);
closeButton.addActionListener(this);
pack();
setLocationRelativeTo(frame);
}
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
String cmd = evt.getActionCommand();
if (src == backButton) {
back();
} else if (src == nextButton) {
FileChooserUI ui = chooser.getUI();
if (ui instanceof BasicFileChooserUI) {
// Workaround for bug 4528663. This is necessary to
// pick up the contents of the file chooser text field.
// This will trigger an APPROVE_SELECTION action.
((BasicFileChooserUI) ui).getApproveSelectionAction().
actionPerformed(null);
} else {
next();
}
} else if (src == closeButton) {
close();
} else if (APPROVE_SELECTION.equals(cmd)) {
next();
} else if (CANCEL_SELECTION.equals(cmd)) {
close();
}
}
private void back() {
backButton.setEnabled(false);
nextButton.setEnabled(true);
cardLayout.show(cardPanel, "fileChooser");
getRootPane().setDefaultButton(nextButton);
chooser.requestFocus();
}
private void next() {
backButton.setEnabled(true);
nextButton.setEnabled(false);
messageLabel.setText(getResultString());
cardLayout.show(cardPanel, "label");
getRootPane().setDefaultButton(closeButton);
closeButton.requestFocus();
}
private void close() {
setVisible(false);
}
@Override
public void dispose() {
chooser.removeActionListener(this);
// The chooser is hidden by CardLayout on remove
// so fix it here
cardPanel.remove(chooser);
chooser.setVisible(true);
super.dispose();
}
}
private String getResultString() {
String resultString;
String filter;
if (chooser.getFileFilter() == null) {
filter = "";
} else {
filter = chooser.getFileFilter().getDescription();
}
String path = null;
boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY);
boolean isMulti = chooser.isMultiSelectionEnabled();
if (isMulti) {
File[] files = chooser.getSelectedFiles();
if (files != null && files.length > 0) {
path = "";
for (File file : files) {
path = path + "<br>" + file.getPath();
}
}
} else {
File file = chooser.getSelectedFile();
if (file != null) {
path = "<br>" + file.getPath();
}
}
if (path != null) {
path = path.replace(" ", "&nbsp;");
filter = filter.replace(" ", "&nbsp;");
resultString =
"<html>You chose " + (isMulti ? "these" : "this") + " " + (isDirMode ? (isMulti
? "directories" : "directory")
: (isMulti ? "files" : "file")) + ": <code>" + path
+ "</code><br><br>with filter: <br><code>" + filter;
} else {
resultString = "Nothing was chosen";
}
return resultString;
}
/** An ActionListener that listens to the radio buttons. */
private class OptionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComponent c = (JComponent) e.getSource();
boolean selected = false;
if (c instanceof JToggleButton) {
selected = ((JToggleButton) c).isSelected();
}
if (c == openRadioButton) {
chooser.setDialogType(OPEN_DIALOG);
customField.setEnabled(false);
repaint();
} else if (c == useEmbedInWizardCheckBox) {
useControlsCheckBox.setEnabled(!selected);
useControlsCheckBox.setSelected(!selected);
chooser.setControlButtonsAreShown(!selected);
} else if (c == useControlsCheckBox) {
chooser.setControlButtonsAreShown(selected);
} else if (c == enableDragCheckBox) {
chooser.setDragEnabled(selected);
} else if (c == saveRadioButton) {
chooser.setDialogType(SAVE_DIALOG);
customField.setEnabled(false);
repaint();
} else if (c == customButton || c == customField) {
customField.setEnabled(true);
chooser.setDialogType(CUSTOM_DIALOG);
repaint();
} else if (c == showAllFilesFilterCheckBox) {
chooser.setAcceptAllFileFilterUsed(selected);
} else if (c == showImageFilesFilterCheckBox) {
resetFileFilters(selected,
showFullDescriptionCheckBox.isSelected());
showFullDescriptionCheckBox.setEnabled(selected);
} else if (c == setHiddenCheckBox) {
chooser.setFileHidingEnabled(!selected);
} else if (c == accessoryCheckBox) {
if (selected) {
chooser.setAccessory(previewer);
} else {
chooser.setAccessory(null);
}
} else if (c == useFileViewCheckBox) {
if (selected) {
chooser.setFileView(fileView);
} else {
chooser.setFileView(null);
}
} else if (c == useFileSystemViewCheckBox) {
if (selected) {
chooser.setFileSystemView(fileSystemView);
} else {
// Restore default behaviour
chooser.setFileSystemView(FileSystemView.getFileSystemView());
}
} else if (c == showFullDescriptionCheckBox) {
resetFileFilters(showImageFilesFilterCheckBox.isSelected(),
selected);
} else if (c == justFilesRadioButton) {
chooser.setFileSelectionMode(FILES_ONLY);
} else if (c == justDirectoriesRadioButton) {
chooser.setFileSelectionMode(DIRECTORIES_ONLY);
} else if (c == bothFilesAndDirectoriesRadioButton) {
chooser.setFileSelectionMode(FILES_AND_DIRECTORIES);
} else if (c == singleSelectionRadioButton) {
if (selected) {
chooser.setMultiSelectionEnabled(false);
}
} else if (c == multiSelectionRadioButton) {
if (selected) {
chooser.setMultiSelectionEnabled(true);
}
} else if (c == lafComboBox) {
SupportedLaF supportedLaF = ((SupportedLaF) lafComboBox.
getSelectedItem());
LookAndFeel laf = supportedLaF.laf;
try {
UIManager.setLookAndFeel(laf);
SwingUtilities.updateComponentTreeUI(frame);
if (chooser != null) {
SwingUtilities.updateComponentTreeUI(chooser);
}
frame.pack();
} catch (UnsupportedLookAndFeelException exc) {
// This should not happen because we already checked
((DefaultComboBoxModel<?>) lafComboBox.getModel()).
removeElement(supportedLaF);
}
}
}
}
private class FilePreviewer extends JComponent implements
PropertyChangeListener {
ImageIcon thumbnail = null;
@SuppressWarnings("LeakingThisInConstructor")
public FilePreviewer(JFileChooser fc) {
setPreferredSize(new Dimension(100, 50));
fc.addPropertyChangeListener(this);
}
public void loadImage(File f) {
if (f == null) {
thumbnail = null;
} else {
ImageIcon tmpIcon = new ImageIcon(f.getPath());
if (tmpIcon.getIconWidth() > 90) {
thumbnail = new ImageIcon(
tmpIcon.getImage().getScaledInstance(90, -1,
Image.SCALE_DEFAULT));
} else {
thumbnail = tmpIcon;
}
}
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
if (isShowing()) {
loadImage((File) e.getNewValue());
repaint();
}
}
}
@Override
public void paint(Graphics g) {
if (thumbnail != null) {
int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;
if (y < 0) {
y = 0;
}
if (x < 5) {
x = 5;
}
thumbnail.paintIcon(this, g, x, y);
}
}
}
public static void main(String[] s) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
/*
* NOTE: By default, the look and feel will be set to the
* Cross Platform Look and Feel (which is currently Metal).
* The following code tries to set the Look and Feel to Nimbus.
* https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html
*/
try {
for (LookAndFeelInfo info : UIManager.
getInstalledLookAndFeels()) {
if (NIMBUS_LAF_NAME.equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ignored) {
}
FileChooserDemo panel = new FileChooserDemo();
frame = new JFrame("FileChooserDemo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add("Center", panel);
frame.pack();
frame.setVisible(true);
}
});
} catch (InterruptedException ex) {
Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,
null,
ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,
null,
ex);
}
}
private static class InsetPanel extends JPanel {
Insets i;
InsetPanel(Insets i) {
this.i = i;
}
@Override
public Insets getInsets() {
return i;
}
}
}

View file

@ -0,0 +1,14 @@
FileChooserDemo demonstrates some of the capabilities of the
JFileChooser object. It brings up a window displaying several
configuration controls that allow you to play with the
JFileChooser options dynamically.
To run the FileChooserDemo demo:
java -jar FileChooserDemo.jar
These instructions assume that this installation's version of the java
command is in your path. If it isn't, then you should either
specify the complete path to the java command or update your
PATH environment variable as described in the installation
instructions for the Java(TM) SE Development Kit.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,113 @@
Font2DTest
-----------
To run Font2DTest:
% java -jar Font2DTest.jar
These instructions assume that the java command is in your path.
If they aren't, then you should either specify the complete path to the commands
or update your PATH environment variable as described in the
installation instructions for the Java(TM) SE Development Kit.
If you wish to modify any of the source code, you may want to extract
the contents of the Font2DTest.jar file by executing this command:
% jar -xvf Font2DTest.jar
-----------------------------------------------------------------------
Introduction
-----------------------------------------------------------------------
Font2DTest is an encompassing application for testing various fonts
found on the user's system. A number of controls are available to
change many attributes of the current font including style, size, and
rendering hints. The user can select from multiple display modes,
such as one Unicode range at a time, all glyphs of a particular font,
user-edited text, or text loaded from a file.
In addition, the user can control which method will
be used to render the text to the screen (or to be printed out).
-----------------------------------------------------------------------
Tips on usage
-----------------------------------------------------------------------
- The "Font" combobox will show a tick mark if some of the characters in
selected unicode range can be displayed by this font. No tick is shown,
if none of the characters can be displayed. A tooltip is shown with this
information. This indication is available only if "Unicode Range" is
selected in "Text to use" combobox.
This feature is enabled by default. For disabling this feature, use
command line flag -disablecandisplaycheck or -dcdc.
java -jar Font2DTest.jar -dcdc
- For the "Font Size" field to have an effect, it is necessary to press
ENTER when finished inputting data in those fields.
- When "Unicode Range" or "All Glyphs" is selected for Text to Use,
the status bar will show the range of the characters that is
currently being displayed. If mouse cursor is pointed to one of
the character drawn, the message will be changed to indicate
what character the cursor is pointing to.
By clicking on a character displayed, one can also "Zoom" a character.
Options can be set to show grids around each character,
or force the number of characters displayed across the screen to be 16.
These features are not available in "User Text" or "File Text" mode.
- The default number of columns in a Unicode Range or All Glyphs drawing
is "fit as many as possible". If this is too hard to read, then you
can force number of columns to be 16. However, this will not resize the
window to fit all 16 columns, so if the font size is too big, this will
overflow the canvas. (Unfortunately, I could not add horizontal space
bar due to design restrictions)
- If font size is too large to fit a character, then a message will
inform that smaller font size or larger canvas size is needed.
- Custom Unicode Range can be displayed by selecting "Custom..."
at the bottom of the Unicode Range menu. This will bring up
a dialog box to specify the starting and ending index
of the unicode characters to be drawn.
- To enter a customized text, select "User Text" from Text to Use menu.
A dialog box with a text area will come up. Enter any text here,
and then press update; the text on screen will then be redrawn to
draw the text just entered. To hide the user text dialog box,
switch to different selection in Text to Use menu.
(Closing the dialog box will not work...)
If a escape sequence of form \uXXXX is entered, it is will be
converted into the character that it maps to.
- drawBytes will only work for characters in Unicode range 0x00-0xFF
by its method definition. This program will warn when such text is
being drawn in "Range Text" mode. But since there is no way to detect
this from User Text, the warning will not be given even though
wrong text seems to be drawn on screen when it contains any character
beyond 0xFF.
- In the "All Glyphs" mode which displays all available glyphs for the
current font, only drawGlyphVector is available as the draw method.
Similary, when "Text File" mode is used, the file will always be wrapped
to canvas width using LineBreakMeasurer, so TextLayout.draw is used.
- With "User Text" mode, no text wrapping operation is done.
When displaying or printing text that does not fit in a given canvas,
the text will overflow to the right side of the page.
- It is also possible to display a text loaded from a file.
Font2DTest will handle is UTF-16 and the platform default encoding.
The text will then be reformatted to fit in the screen with
LineBreakMeasurer, and drawn with TextLayout.draw.
Most major word processor softwares support this format.
- When printing, the program will ask to select 1 of 3 options.
First "Print one full page..." will print as much
characters/lines of text as it can fit in one page, starting from
the character/line that is currently drawn at the top of the page.
Second option, "Print all characters..." will print all characters
that are within the selected range. Third option, "Print all text..."
is similar, and it will print all lines of text that user has put in.
====================================================================

View file

@ -0,0 +1,258 @@
/*
* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
/*
*/
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
import java.util.*;
import java.util.regex.*;
/**
* RangeMenu.java
*
* @author Shinsuke Fukuda
* @author Ankit Patel [Conversion to Swing - 01/07/30]
*/
/// Custom made choice menu that holds data for unicode range
public final class RangeMenu extends JComboBox<String> implements ActionListener {
private static final int[][] UNICODE_RANGES = getUnicodeRanges();
private static final String[] UNICODE_RANGE_NAMES = getUnicodeRangeNames();
private boolean useCustomRange = false;
private int[] customRange = { 0x0000, 0x007f };
/// Custom range dialog variables
private final JDialog customRangeDialog;
private final JTextField customRangeStart = new JTextField( "0000", 4 );
private final JTextField customRangeEnd = new JTextField( "007F", 4 );
private final int CUSTOM_RANGE_INDEX = UNICODE_RANGE_NAMES.length - 1;
/// Parent Font2DTest Object holder
private final Font2DTest parent;
public static final int SURROGATES_AREA_INDEX = 91;
public RangeMenu( Font2DTest demo, JFrame f ) {
super();
parent = demo;
for ( int i = 0; i < UNICODE_RANGE_NAMES.length; i++ )
addItem( UNICODE_RANGE_NAMES[i] );
setSelectedIndex( 0 );
addActionListener( this );
/// Set up custom range dialog...
customRangeDialog = new JDialog( f, "Custom Unicode Range", true );
customRangeDialog.setResizable( false );
JPanel dialogTop = new JPanel();
JPanel dialogBottom = new JPanel();
JButton okButton = new JButton("OK");
JLabel from = new JLabel( "From:" );
JLabel to = new JLabel("To:");
Font labelFont = new Font( "dialog", Font.BOLD, 12 );
from.setFont( labelFont );
to.setFont( labelFont );
okButton.setFont( labelFont );
dialogTop.add( from );
dialogTop.add( customRangeStart );
dialogTop.add( to );
dialogTop.add( customRangeEnd );
dialogBottom.add( okButton );
okButton.addActionListener( this );
customRangeDialog.getContentPane().setLayout( new BorderLayout() );
customRangeDialog.getContentPane().add( "North", dialogTop );
customRangeDialog.getContentPane().add( "South", dialogBottom );
customRangeDialog.pack();
}
/// Return the range that is currently selected
public int[] getSelectedRange() {
if ( useCustomRange ) {
int startIndex, endIndex;
String startText, endText;
String empty = "";
try {
startText = customRangeStart.getText().trim();
endText = customRangeEnd.getText().trim();
if ( startText.equals(empty) && !endText.equals(empty) ) {
endIndex = Integer.parseInt( endText, 16 );
startIndex = endIndex - 7*25;
}
else if ( !startText.equals(empty) && endText.equals(empty) ) {
startIndex = Integer.parseInt( startText, 16 );
endIndex = startIndex + 7*25;
}
else {
startIndex = Integer.parseInt( customRangeStart.getText(), 16 );
endIndex = Integer.parseInt( customRangeEnd.getText(), 16 );
}
}
catch ( Exception e ) {
/// Error in parsing the hex number ---
/// Reset the range to what it was before and return that
customRangeStart.setText( Integer.toString( customRange[0], 16 ));
customRangeEnd.setText( Integer.toString( customRange[1], 16 ));
return customRange;
}
if ( startIndex < 0 )
startIndex = 0;
if ( endIndex > 0xffff )
endIndex = 0xffff;
if ( startIndex > endIndex )
startIndex = endIndex;
customRange[0] = startIndex;
customRange[1] = endIndex;
return customRange;
}
else
return UNICODE_RANGES[ getSelectedIndex() ];
}
/// Function used by loadOptions in Font2DTest main panel
/// to reset setting and range selection
public void setSelectedRange( String name, int start, int end ) {
setSelectedItem( name );
customRange[0] = start;
customRange[1] = end;
parent.fireRangeChanged();
}
/// ActionListener interface function
/// ABP
/// moved JComboBox event code into this fcn from
/// itemStateChanged() method. Part of change to Swing.
public void actionPerformed( ActionEvent e ) {
Object source = e.getSource();
if ( source instanceof JComboBox ) {
String rangeName = (String)((JComboBox<?>)source).getSelectedItem();
if ( rangeName.equals("Custom...") ) {
useCustomRange = true;
customRangeDialog.setLocationRelativeTo(parent);
customRangeDialog.setVisible(true);
}
else {
useCustomRange = false;
}
parent.fireRangeChanged();
}
else if ( source instanceof JButton ) {
/// Since it is only "OK" button that sends any action here...
customRangeDialog.setVisible(false);
}
}
private static int[][] getUnicodeRanges() {
List<Integer> ranges = new ArrayList<>();
ranges.add(0);
Character.UnicodeBlock currentBlock = Character.UnicodeBlock.of(0);
for (int cp = 0x000001; cp < 0x110000; cp++ ) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(cp);
if (currentBlock == null) {
if (ub != null) {
ranges.add(cp);
currentBlock = ub;
}
} else { // being in some unicode range
if (ub == null) {
ranges.add(cp - 1);
currentBlock = null;
} else if (cp == 0x10ffff) { // end of last block
ranges.add(cp);
} else if (! ub.equals(currentBlock)) {
ranges.add(cp - 1);
ranges.add(cp);
currentBlock = ub;
}
}
}
ranges.add(0x00); // for user defined range.
ranges.add(0x7f); // for user defined range.
int[][] returnval = new int[ranges.size() / 2][2];
for (int i = 0 ; i < ranges.size() / 2 ; i++ ) {
returnval[i][0] = ranges.get(2*i);
returnval[i][1] = ranges.get(2*i + 1);
}
return returnval;
}
private static String[] getUnicodeRangeNames() {
String[] names = new String[UNICODE_RANGES.length];
for (int i = 0 ; i < names.length ; i++ ) {
names[i] = titleCase(
Character.UnicodeBlock.of(UNICODE_RANGES[i][0]).toString());
}
names[names.length - 1] = "Custom...";
return names;
}
private static String titleCase(String str) {
str = str.replaceAll("_", " ");
Pattern p = Pattern.compile("(^|\\W)([a-z])");
Matcher m = p.matcher(str.toLowerCase(Locale.ROOT));
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1) + m.group(2).toUpperCase(Locale.ROOT));
}
m.appendTail(sb);
return sb.toString().replace("Cjk", "CJK").replace("Nko", "NKo");
}
}

View file

@ -0,0 +1,96 @@
The classes for the Java2D(TM) demo are contained in the J2Ddemo.jar file.
To run the J2D demo:
% java -jar J2Ddemo.jar
-----------------------------------------------------------------------
Introduction
-----------------------------------------------------------------------
This Java2D demo consists of a set of demos housed in one GUI
framework that uses a JTabbedPane. You can access different groups of
demos by clicking the tabs at the top of the pane. There are demo
groups for Arcs_Curves, Clipping, Colors, Composite, Fonts, Images,
Lines, Mix, Paint, Paths and Transforms. On the right-hand side of the
pane, the GUI framework features individual and global controls for
changing graphics attributes. There's also a memory-usage monitor, and
a monitor for tracking the performance, in frames per second, of
animation demos.
-----------------------------------------------------------------------
Tips on usage
-----------------------------------------------------------------------
Click on one of the tabs at the top of the pane to select a demo group.
When you select a group, a set of surfaces is displayed, each of which
contains one of the group's demos. At the bottom of each surface is
a set of tools for controlling the demo. The tools can be displayed
by selecting the Tools checkbox in the Global Controls panel or
by clicking on the slim strip of gray bumps at the bottom of the demo
panel.
If you click on a demo surface, that demo is laid out by itself. A
new icon button will appear in the demo's tools toolbar one that enables
you to create new instances of that demo's surface.
To run the demo continuously without user interaction, select the
Run Window item in the Options menu and press the run button in the
new window that's displayed. To do this from the command line:
java -jar J2Ddemo.jar -runs=10
To view all the command line options for customizing demo runs:
java -jar J2Ddemo.jar -help
You can run the demos in stand-alone mode by issuing a command like this
java -cp J2Ddemo.jar java2d.demos.Clipping.ClipAnim
You can run the demos in groups by issuing a command like this
java -cp J2Ddemo.jar java2d.DemoGroup Clipping
To increase or decrease the Memory Monitor sampling rate click on the
Memory Monitor's title border, a panel with a TextField will appear.
The J2Ddemo Intro (the 'J2D demo' tab) contains a scene table, click in
the gray border and a table will appear.
Animated demos have a slider to control the animation rate. Bring up
the animated demo toolbar, then click in the gray area of the toolbar
panel, the toolbar goes away and the slider appears.
Demos that have Custom Controls can have their Custom Control Thread
activated and stopped by clicking in the gray area of the demos Custom
Control panel.
-----------------------------------------------------------------------
NOTE about demo surfaces
-----------------------------------------------------------------------
The demo groups are in separate packages with their class files stored
in directories named according to the demo group name. All drawing
demos extend either the Surface, AnimatingSurface, ControlsSurface or
AnimatingControlsSurface classes. Surface is the base class, demos
must implement the Surface's render method. All animated demos extend
either the AnimatingSurface or the AnimatingControlsSurface classes.
Animated demos must implement the reset and step methods. The demos
with gui controls extend either the ControlsSurface or the
AnimatingControlsSurface classes. Demos with controls must implement
the methods in the CustomControlsContext interface.
======================================================================
Here are some resources for learning about and using the Java2D(TM)
OpenJDK group page: https://openjdk.org/groups/2d/
Learning Java 2D: http://www.oracle.com/technetwork/articles/java/java2dpart1-137217.html
Tutorial : http://download.oracle.com/javase/tutorial/2d/
Specification: http://download.oracle.com/javase/8/docs/technotes/guides/2d/spec/j2d-bookTOC.html
Java 2D (TM) API White Paper : http://www.oracle.com/technetwork/java/javase/tech/2d-142228.html
2D FAQ: http://www.oracle.com/technetwork/java/index-137037.html

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 356 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Some files were not shown because too many files have changed in this diff Show more