diff options
author | Vincent Hennebert <vhennebert@apache.org> | 2014-01-13 20:39:34 +0000 |
---|---|---|
committer | Vincent Hennebert <vhennebert@apache.org> | 2014-01-13 20:39:34 +0000 |
commit | 37c00cdf4e9bc4b922c5961bd3f38f7ed0f0d3f0 (patch) | |
tree | a836d0edb3fc9fcc81f410799ffec6621e3e8dc6 | |
parent | 8fe1a6d2368b9c8fbabc447d7356079e5b61a6e7 (diff) | |
parent | e7d05ec67b2652cd6ede79067d42eae8c057c955 (diff) | |
download | xmlgraphics-fop-37c00cdf4e9bc4b922c5961bd3f38f7ed0f0d3f0.tar.gz xmlgraphics-fop-37c00cdf4e9bc4b922c5961bd3f38f7ed0f0d3f0.zip |
Brought the branch in sync with rev. r1556164 of trunk
git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/branches/Temp_InlineContainer@1557840 13f79535-47bb-0310-9956-ffa450edef68
379 files changed, 8408 insertions, 2555 deletions
@@ -579,6 +579,7 @@ list of possible build targets. <include name="org/apache/fop/util/Finalizable.class"/> <include name="org/apache/fop/util/CharUtilities.class"/> <include name="org/apache/fop/util/DecimalFormatCache*.class"/> + <include name="org/apache/fop/render/shading/**"/> </patternset> <!-- PDF transcoder --> <patternset> @@ -1041,10 +1042,8 @@ NOTE: <!-- Checkstyle --> <!-- =================================================================== --> <property name="checkstyle.location" value="${lib-tools}/checkstyle-5.5-all.jar" /> - <property name="checkstyle.noframes.xslt" value="${basedir}/checkstyle-noframes.xsl" /> <property name="checkstyle.config" value="${basedir}/checkstyle-5.5.xml" /> <path id="checkstyle-classpath"> - <path refid="libs-build-classpath"/> <pathelement location="${checkstyle.location}"/> </path> <condition property="checkstyle.avail"> @@ -1052,20 +1051,18 @@ NOTE: <available classname="com.puppycrawl.tools.checkstyle.CheckStyleTask"> <classpath refid="checkstyle-classpath"/> </available> - <available file="${checkstyle.noframes.xslt}"/> <available file="${checkstyle.config}"/> </and> </condition> <target name="checkstyle-avail" unless="checkstyle.avail"> <echo message="Checkstyle support NOT present. Please download it from http://checkstyle.sf.net/ and"/> <echo message="... please provide ${checkstyle.location}"/> - <echo message="... please provide ${checkstyle.noframes.xslt}"/> <echo message="... please provide ${checkstyle.config}"/> </target> <target name="checkstyle" depends="package, checkstyle-avail" if="checkstyle.avail" description="Runs Checkstyle for a code quality report"> <taskdef name="checkstyle" classname="com.puppycrawl.tools.checkstyle.CheckStyleTask" classpathref="checkstyle-classpath"/> <mkdir dir="${build.dir}"/> - <checkstyle config="${checkstyle.config}" failonviolation="false"> + <checkstyle config="${checkstyle.config}" failonviolation="true" maxWarnings="0"> <classpath> <path refid="checkstyle-classpath"/> <pathelement location="${build.classes.dir}"/> @@ -1073,9 +1070,10 @@ NOTE: <pathelement location="${build.codegen-classes.dir}"/> </classpath> <fileset dir="${src.dir}" includes="**/*.java"/> + <fileset dir="${test.dir}" includes="**/*.java"/> <formatter type="xml" toFile="${build.dir}/report_checkstyle.xml"/> + <formatter type="plain"/> </checkstyle> - <xslt in="${build.dir}/report_checkstyle.xml" out="${build.dir}/report_checkstyle.html" style="${checkstyle.noframes.xslt}"/> </target> <!-- =================================================================== --> <!-- PMD --> @@ -1087,6 +1085,7 @@ NOTE: <path refid="libs-tools-build-classpath"/> </classpath> </taskdef> + <mkdir dir="${build.dir}"/> <pmd shortFilenames="true" targetjdk="${javac.target}"> <ruleset>basic</ruleset> <ruleset>rulesets/migrating_to_14.xml</ruleset> @@ -1505,7 +1504,7 @@ NOTE: <!-- Special target for Gump --> <!-- =================================================================== --> <target name="gump" depends="package,transcoder-pkg"/> - <target name="gump-test" depends="junit-all"> + <target name="gump-test" depends="junit-all,checkstyle"> <fail> <condition> <or> diff --git a/checkstyle-5.5.xml b/checkstyle-5.5.xml index fb82878fc..4d499f645 100644 --- a/checkstyle-5.5.xml +++ b/checkstyle-5.5.xml @@ -37,16 +37,26 @@ <!-- ===================================================================================================== --> <module name="SuppressionCommentFilter"> - <property name="offCommentFormat" value="CSOFF\: ([\w\|]+)"/> + <property name="offCommentFormat" value="CSOFF\: (LineLength)"/> <property name="onCommentFormat" value="CSON\: ([\w\|]+)"/> <property name="checkFormat" value="$1"/> </module> <!-- ===================================================================================================== --> + <module name="SuppressionFilter"> + <property name="file" value="${samedir}/checkstyle-suppressions.xml"/> + </module> + <!-- ===================================================================================================== --> <module name="TreeWalker"> <!-- ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... --> + <module name="LineLength"> + <property name="max" value="120"/> + </module> + <!-- ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... --> + + <!-- ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... --> <module name="AnnotationUseStyle"/> <!-- ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... --> @@ -172,10 +182,6 @@ <property name="allowLineBreaks" value="false"/> <property name="tokens" value="BNOT,DEC,DOT,INC,LNOT,UNARY_MINUS,UNARY_PLUS"/> </module> - <module name="NoWhitespaceAfter"> - <property name="allowLineBreaks" value="true"/> - <property name="tokens" value="ARRAY_INIT"/> - </module> <!-- ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... --> <!-- ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... --> diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index 76e282f61..050f5dab4 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -1,8 +1,12 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN" "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> <suppressions> - <suppress files="org/apache/fop/fo/FOPropertyMapping.java" checks="FileLengthCheck"/> - <suppress files="org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java" checks="FileLengthCheck"/> - <suppress files="org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java" checks="FileLengthCheck"/> - <suppress files="org/apache/fop/Version.java" lines="40-50" checks="LineLengthCheck"/> + <suppress files="org/apache/fop/afp/fonts/CharactersetEncoder.java" checks="FinalClass"/> + <suppress files="org/apache/fop/complexscripts/bidi/BidiClass.java" checks="WhitespaceAfter"/> + <suppress files="org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java" checks="SimplifyBooleanReturn"/> + <suppress files="org/apache/fop/complexscripts/scripts/ArabicScriptProcessor.java" checks="SimplifyBooleanReturn"/> + <suppress files="org/apache/fop/complexscripts/util/CharScript.java" checks="SimplifyBooleanReturn"/> + <suppress files="org/apache/fop/render/rtf/rtflib/testdocs/MergedTableCells.java" checks="AvoidNestedBlocks"/> + <suppress files="org/apache/fop/render/rtf/rtflib/testdocs/NestedTable.java" checks="AvoidNestedBlocks"/> + <suppress files="org/apache/fop/fo/flow/MarkersTestCase.java" checks="LocalVariableName"/> </suppressions> diff --git a/examples/fo/basic/leader.fo b/examples/fo/basic/leader.fo index 26ac49005..328d95010 100644 --- a/examples/fo/basic/leader.fo +++ b/examples/fo/basic/leader.fo @@ -2,7 +2,7 @@ <!-- examples for the use of the fo leader --> -<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> +<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" font-family="sans-serif"> <fo:layout-master-set> @@ -272,7 +272,7 @@ <fo:list-item> <!-- insert a bullet --> <fo:list-item-label end-indent="label-end()"> - <fo:block><fo:inline font-size="10pt" font-family="Symbol">·</fo:inline></fo:block> + <fo:block><fo:inline font-size="10pt">·</fo:inline></fo:block> </fo:list-item-label> <!-- list text --> <fo:list-item-body start-indent="body-start()"> @@ -291,7 +291,7 @@ <fo:list-item> <!-- insert a bullet --> <fo:list-item-label end-indent="label-end()"> - <fo:block><fo:inline font-size="10pt" font-family="Symbol">·</fo:inline></fo:block> + <fo:block><fo:inline font-size="10pt">·</fo:inline></fo:block> </fo:list-item-label> <!-- list text --> <fo:list-item-body start-indent="body-start()"> @@ -391,7 +391,7 @@ <fo:table-row line-height="12pt"> <fo:table-cell><fo:block text-align="end">A) </fo:block></fo:table-cell> - <fo:table-cell><fo:block text-align="start">This is some longer sample text<fo:leader leader-pattern="dots" + <fo:table-cell><fo:block text-align="start" text-align-last="justify">This is some longer sample text<fo:leader leader-pattern="dots" leader-pattern-width="8pt" leader-alignment="reference-area" /></fo:block></fo:table-cell> @@ -401,7 +401,7 @@ <fo:table-row line-height="12pt"> <fo:table-cell><fo:block text-align="end">B) </fo:block></fo:table-cell> - <fo:table-cell><fo:block text-align="start">Some text<fo:leader leader-pattern="dots" + <fo:table-cell><fo:block text-align="start" text-align-last="justify">Some text<fo:leader leader-pattern="dots" leader-pattern-width="8pt" leader-alignment="reference-area" /></fo:block></fo:table-cell> @@ -410,7 +410,7 @@ <fo:table-row line-height="12pt"> <fo:table-cell><fo:block text-align="end" >C) </fo:block></fo:table-cell> - <fo:table-cell><fo:block text-align="start">Text<fo:leader leader-pattern="dots" + <fo:table-cell><fo:block text-align="start" text-align-last="justify">Text<fo:leader leader-pattern="dots" leader-pattern-width="8pt" leader-alignment="reference-area" /></fo:block></fo:table-cell> @@ -419,7 +419,7 @@ <fo:table-row line-height="12pt"> <fo:table-cell><fo:block text-align="end">D) </fo:block></fo:table-cell> - <fo:table-cell><fo:block text-align="start">This text is even longer than the first entry <fo:leader leader-pattern="dots" + <fo:table-cell><fo:block text-align="start" text-align-last="justify">This text is even longer than the first entry <fo:leader leader-pattern="dots" leader-pattern-width="8pt" leader-alignment="reference-area" /></fo:block></fo:table-cell> @@ -428,7 +428,7 @@ <fo:table-row line-height="12pt"> <fo:table-cell><fo:block text-align="end">E) </fo:block></fo:table-cell> - <fo:table-cell><fo:block text-align="start">Shorter text example<fo:leader leader-pattern="dots" + <fo:table-cell><fo:block text-align="start" text-align-last="justify">Shorter text example<fo:leader leader-pattern="dots" leader-pattern-width="8pt" leader-alignment="reference-area" /></fo:block></fo:table-cell> diff --git a/lib/fontbox-1.8.0-SNAPSHOT.jar b/lib/fontbox-1.8.3-patched.jar Binary files differindex e20e1ad7b..57460be06 100644 --- a/lib/fontbox-1.8.0-SNAPSHOT.jar +++ b/lib/fontbox-1.8.3-patched.jar diff --git a/lib/pdfbox-1645.patch b/lib/pdfbox-1645.patch new file mode 100644 index 000000000..f9dda73fb --- /dev/null +++ b/lib/pdfbox-1645.patch @@ -0,0 +1,395 @@ +Index: fontbox/src/test/java/org/apache/fontbox/cff/CharStringRendererTest.java +=================================================================== +--- fontbox/src/test/java/org/apache/fontbox/cff/CharStringRendererTest.java (revision 0) ++++ fontbox/src/test/java/org/apache/fontbox/cff/CharStringRendererTest.java (revision 0) +@@ -0,0 +1,28 @@ ++package org.apache.fontbox.cff; ++ ++import java.util.ArrayList; ++import java.util.List; ++ ++import org.junit.Test; ++ ++import static org.junit.Assert.assertTrue; ++ ++public class CharStringRendererTest { ++ ++ @Test ++ public void testArgumentValidation() { ++ CharStringRenderer renderer = new CharStringRenderer(); ++ List<Integer> numbers = new ArrayList<Integer>(); ++ for (int i = 0;i < 4;i++) { ++ numbers.add(1); ++ } ++ assertTrue(renderer.hasValidArguments("vhcurveto", numbers)); ++ numbers.add(1); ++ assertTrue(renderer.hasValidArguments("vvcurveto", numbers)); ++ for (int i = 0;i < 3;i++) { ++ numbers.add(1); ++ } ++ assertTrue(renderer.hasValidArguments("rcurveline", numbers)); ++ } ++ ++} +Index: fontbox/src/main/java/org/apache/fontbox/cff/AFMFormatter.java +=================================================================== +--- fontbox/src/main/java/org/apache/fontbox/cff/AFMFormatter.java (revision 1546564) ++++ fontbox/src/main/java/org/apache/fontbox/cff/AFMFormatter.java (working copy) +@@ -27,7 +27,7 @@ + + /** + * This class creates all needed AFM font metric data from a CFFFont ready to be read from a AFMPaser. +- * ++ * + * @author Villu Ruusmann + * @version $Revision$ + */ +@@ -125,7 +125,7 @@ + metric.name = mapping.getName(); + renderer.render(mapping.toType1Sequence()); + metric.width = renderer.getWidth(); +- metric.bounds = renderer.getBounds(); ++ metric.bounds = renderer.getBounds2D(); + metrics.add(metric); + } + return metrics; +@@ -150,7 +150,7 @@ + } + + /** +- * This class represents the metric of one single character. ++ * This class represents the metric of one single character. + * + */ + private static class CharMetric implements Comparable<CharMetric> +Index: fontbox/src/main/java/org/apache/fontbox/cff/CharStringRenderer.java +=================================================================== +--- fontbox/src/main/java/org/apache/fontbox/cff/CharStringRenderer.java (revision 1546564) ++++ fontbox/src/main/java/org/apache/fontbox/cff/CharStringRenderer.java (working copy) +@@ -16,9 +16,11 @@ + */ + package org.apache.fontbox.cff; + ++import java.awt.Point; + import java.awt.geom.GeneralPath; + import java.awt.geom.Point2D; + import java.awt.geom.Rectangle2D; ++import java.util.HashMap; + import java.util.List; + + import org.apache.commons.logging.Log; +@@ -33,7 +35,7 @@ + { + // TODO CharStringRenderer as abstract Class with two inherited classes according to the Charsstring type.... + private static final Log LOG = LogFactory.getLog(CharStringRenderer.class); +- ++ + private boolean isCharstringType1 = true; + private boolean isFirstCommand = true; + +@@ -42,6 +44,8 @@ + private Point2D referencePoint = null; + private int width = 0; + private boolean hasNonEndCharOp = false; ++ private int[] bbox = {0,0,0,0}; ++ private HashMap<String, String> vStrings; + + /** + * Constructor for the char string renderer. +@@ -100,7 +104,7 @@ + private void handleCommandType2(List<Integer> numbers, CharStringCommand command) + { + String name = CharStringCommand.TYPE2_VOCABULARY.get(command.getKey()); +- ++ checkArguments(name, numbers); + if (!hasNonEndCharOp) + { + hasNonEndCharOp = !"endchar".equals(name); +@@ -176,7 +180,7 @@ + setWidth(numbers.get(0)); + rmoveTo(numbers.get(1), numbers.get(2)); + } +- else ++ else if (numbers.size() == 2) + { + rmoveTo(numbers.get(0), numbers.get(1)); + } +@@ -192,7 +196,7 @@ + setWidth(numbers.get(0)); + rmoveTo(numbers.get(1), Integer.valueOf(0)); + } +- else ++ else if (numbers.size() == 1) + { + rmoveTo(numbers.get(0), Integer.valueOf(0)); + } +@@ -284,6 +288,61 @@ + } + } + ++ void checkArguments(String name, List<Integer> numbers) { ++ if (name == null) { ++ return; ++ } ++ boolean valid = hasValidArguments(name, numbers); ++ if (!valid) { ++ //Initialize the validation strings if not already done ++ if (vStrings == null) { ++ vStrings = new HashMap<String, String>(); ++ vStrings.put("vmoveto", "1 || 2"); ++ vStrings.put("rlineto", "3 || % 2"); ++ vStrings.put("rrcurveto", "7 || % 6"); ++ vStrings.put("rlinecurve", "% 2 || 6 + % 2"); ++ vStrings.put("rcurveline", "% 6 || 2 + % 6"); ++ vStrings.put("rmoveto", "2 || 3"); ++ vStrings.put("hmoveto", "1 || 2"); ++ vStrings.put("vhcurveto", "% 4 || 1 + % 4"); ++ vStrings.put("hvcurveto", "% 4 || 1 + % 4"); ++ vStrings.put("vvcurveto", "% 4 || 1 + % 4"); ++ } ++ LOG.info(String.format("Font has an unexpected number of parameters for operator '%s'. Arguments "+ ++ "size %d did not match pattern '%s'", name, numbers.size(), ++ vStrings.get(name))); ++ } ++ } ++ ++ boolean hasValidArguments(String name, List<Integer> numbers) { ++ boolean valid = true; ++ if (name.equals("vmoveto")) { ++ valid = (numbers.size() == 1 || numbers.size() == 2); ++ } ++ if (name.equals("rlineto")) { ++ valid = (numbers.size() == 3 || numbers.size() % 2 == 0); ++ } ++ if (name.equals("rrcurveto")) { ++ valid = (numbers.size() == 7 || numbers.size() % 6 == 0); ++ } ++ if (name.equals("rlinecurve")) { ++ valid = (numbers.size() % 2 == 0 || (numbers.size() - 6) % 2 == 0); ++ } ++ if (name.equals("rcurveline")) { ++ valid = (numbers.size() % 6 == 0 || (numbers.size() - 2) % 6 == 0); ++ } ++ if (name.equals("rmoveto")) { ++ valid = (numbers.size() == 2 || numbers.size() == 3); ++ } ++ if (name.equals("hmoveto")) { ++ valid = (numbers.size() == 1 || numbers.size() == 2); ++ } ++ if (name.equals("vvcurveto") || name.equals("vhcurveto") || name.equals("hvcurveto")) { ++ valid = (numbers.size() % 4 == 0 || (numbers.size() - 1) % 4 == 0); ++ } ++ return valid; ++ } ++ + /** + * + * @param numbers +@@ -353,11 +412,14 @@ + Point2D point = referencePoint; + if (point == null) + { +- point = path.getCurrentPoint(); +- if (point == null) ++ if (path.getCurrentPoint() == null) + { + point = sidebearingPoint; + } ++ else ++ { ++ point = path.getCurrentPoint(); ++ } + } + referencePoint = null; + path.moveTo((float)(point.getX() + dx.doubleValue()), +@@ -397,15 +459,20 @@ + private void rlineTo(Number dx, Number dy) + { + Point2D point = path.getCurrentPoint(); +- path.lineTo((float)(point.getX() + dx.doubleValue()), +- (float)(point.getY() + dy.doubleValue())); ++ if (point != null) { ++ updateBBox(dx.intValue(), dy.intValue()); ++ path.lineTo((float)(point.getX() + dx.doubleValue()), ++ (float)(point.getY() + dy.doubleValue())); ++ } + } + + private void rrlineTo(List<Integer> numbers) + { + for (int i = 0;i < numbers.size();i += 2) + { +- rlineTo(numbers.get(i), numbers.get(i + 1)); ++ if (numbers.size() - i >= 2) { ++ rlineTo(numbers.get(i), numbers.get(i + 1)); ++ } + } + } + +@@ -415,13 +482,15 @@ + { + for (int i = 0;i < numbers.size();i += 6) + { +- float x1 = numbers.get(i); +- float y1 = numbers.get(i + 1); +- float x2 = numbers.get(i + 2); +- float y2 = numbers.get(i + 3); +- float x3 = numbers.get(i + 4); +- float y3 = numbers.get(i + 5); +- rrcurveTo(x1, y1, x2, y2, x3, y3); ++ if (numbers.size() - i >= 6) { ++ float x1 = numbers.get(i); ++ float y1 = numbers.get(i + 1); ++ float x2 = numbers.get(i + 2); ++ float y2 = numbers.get(i + 3); ++ float x3 = numbers.get(i + 4); ++ float y3 = numbers.get(i + 5); ++ rrcurveTo(x1, y1, x2, y2, x3, y3); ++ } + } + } + } +@@ -429,14 +498,42 @@ + private void rrcurveTo(Number dx1, Number dy1, Number dx2, Number dy2, + Number dx3, Number dy3) + { +- Point2D point = path.getCurrentPoint(); +- float x1 = (float) point.getX() + dx1.floatValue(); +- float y1 = (float) point.getY() + dy1.floatValue(); +- float x2 = x1 + dx2.floatValue(); +- float y2 = y1 + dy2.floatValue(); +- float x3 = x2 + dx3.floatValue(); +- float y3 = y2 + dy3.floatValue(); +- path.curveTo(x1, y1, x2, y2, x3, y3); ++ Point2D p0 = path.getCurrentPoint(); ++ if (p0 != null) { ++ float x1 = (float) p0.getX() + dx1.floatValue(); ++ float y1 = (float) p0.getY() + dy1.floatValue(); ++ float x2 = x1 + dx2.floatValue(); ++ float y2 = y1 + dy2.floatValue(); ++ float x3 = x2 + dx3.floatValue(); ++ float y3 = y2 + dy3.floatValue( ); ++ ++ Point p1 = new Point((int)x1, (int)y1); ++ Point p2 = new Point((int)x2, (int)y2); ++ Point p3 = new Point((int)x3, (int)y3); ++ ++ updateBBox((int)p0.getX(), (int)p0.getY()); ++ updateBBox((int)p3.getX(), (int)p3.getY()); ++ ++ int[] abc = calculateABC((int)p0.getX(), p1.x, p2.x, p3.x); ++ double[] txs = getT(abc); ++ for (double tx : txs) { ++ if (tx > 0 && tx < 1) { ++ int[] XandY = getXandY(tx, new Point((int)p0.getX(), (int)p0.getY()), p1, p2, p3); ++ updateBBox(XandY[0], XandY[1]); ++ } ++ } ++ ++ abc = calculateABC((int)p0.getY(), p1.y, p2.y, p3.y); ++ double[] tys = getT(abc); ++ for (double ty : tys) { ++ if (ty > 0 && ty < 1) { ++ int[] XandY = getXandY(ty, new Point((int)p0.getX(), (int)p0.getY()), p1, p2, p3); ++ updateBBox(XandY[0], XandY[1]); ++ } ++ } ++ ++ path.curveTo(x1, y1, x2, y2, x3, y3); ++ } + } + + +@@ -646,7 +743,9 @@ + private void closePath() + { + referencePoint = path.getCurrentPoint(); +- path.closePath(); ++ if (referencePoint != null) { ++ path.closePath(); ++ } + } + + private void pointSb(Number x, Number y) +@@ -658,11 +757,15 @@ + * Returns the bounds of the renderer path. + * @return the bounds as Rectangle2D + */ +- public Rectangle2D getBounds() ++ public int[] getBounds() + { +- return path.getBounds2D(); ++ return bbox; + } + ++ public Rectangle2D getBounds2D() { ++ return path.getBounds2D(); ++ } ++ + /** + * Returns the width of the current command. + * @return the width +@@ -676,4 +779,61 @@ + { + this.width = aWidth; + } +-} +\ No newline at end of file ++ ++ private int[] calculateABC(int p0, int p1, int p2, int p3) { ++ int[] abc = new int[3]; ++ abc[0] = p0 - 3 * p1 + 3 * p2 - p3; ++ abc[1] = 2 * (-p0 + 2 * p1 - p2); ++ abc[2] = p0 - p1; ++ return abc; ++ } ++ ++ private double[] getT(int[] abc) { ++ double[] t = {-1, -1}; ++ int a = abc[0]; ++ int b = abc[1]; ++ int c = abc[2]; ++ double s = Math.pow(b, 2) - 4 * a * c; ++ if (a == 0) { ++ if (b != 0) { ++ t[0] = -c / b; ++ } ++ return t; ++ } else if (s > 0) { ++ t[0] = (-b + Math.sqrt(s)) / 2 / a; ++ t[1] = (-b - Math.sqrt(s)) / 2 / a; ++ return t; ++ } else if (s == 0) { ++ t[0] = -b / 2 / a; ++ return t; ++ } else { ++ return t; ++ } ++ } ++ ++ private int[] getXandY(double t, Point p0, Point p1, Point p2, Point p3) { ++ int[] XandY = new int[2]; ++ double p0Coeff = Math.pow(1 - t, 3); ++ double p1Coeff = 3 * t * Math.pow(1 - t, 2); ++ double p2Coeff = 3 * Math.pow(t, 2) * (1 - t); ++ double p3Coeff = Math.pow(t, 3); ++ double x = p0Coeff * p0.x + p1Coeff * p1.x + p2Coeff * p2.x + p3Coeff * p3.x; ++ double y = p0Coeff * p0.y + p1Coeff * p1.y + p2Coeff * p2.y + p3Coeff * p3.y; ++ XandY[0] = (int)x; ++ XandY[1] = (int)y; ++ return XandY; ++ } ++ ++ private void updateBBox(int x, int y) { ++ if (x < bbox[0]) { ++ bbox[0] = x; ++ } else if (x > bbox[2]) { ++ bbox[2] = x; ++ } ++ if (y < bbox[1]) { ++ bbox[1] = y; ++ } else if (y > bbox[3]) { ++ bbox[3] = y; ++ } ++ } ++} diff --git a/lib/pdfbox-1646.patch b/lib/pdfbox-1646.patch new file mode 100644 index 000000000..b076ce224 --- /dev/null +++ b/lib/pdfbox-1646.patch @@ -0,0 +1,738 @@ +Index: fontbox/src/main/java/org/apache/fontbox/cff/CFFParser.java +=================================================================== +--- fontbox/src/main/java/org/apache/fontbox/cff/CFFParser.java (revision 1546564) ++++ fontbox/src/main/java/org/apache/fontbox/cff/CFFParser.java (working copy) +@@ -36,7 +36,7 @@ + import org.apache.fontbox.cff.encoding.CFFStandardEncoding; + + /** +- * This class represents a parser for a CFF font. ++ * This class represents a parser for a CFF font. + * @author Villu Ruusmann + * @version $Revision: 1.0 $ + */ +@@ -107,7 +107,11 @@ + { + input.setPosition(0); + } ++ return parse(input); ++ } + ++ public List<CFFFont> parse(CFFDataInput input) throws IOException { ++ this.input = input; + header = readHeader(input); + nameIndex = readIndexData(input); + topDictIndex = readIndexData(input); +@@ -119,6 +123,7 @@ + { + CFFFont font = parseFont(i); + font.setGlobalSubrIndex(globalSubrIndex); ++ font.constructMappings(); + fonts.add(font); + } + return fonts; +@@ -145,7 +150,7 @@ + return cffHeader; + } + +- private static IndexData readIndexData(CFFDataInput input) throws IOException ++ public static IndexData readIndexData(CFFDataInput input) throws IOException + { + int count = input.readCard16(); + IndexData index = new IndexData(count); +@@ -179,7 +184,8 @@ + return dict; + } + +- private static DictData.Entry readEntry(CFFDataInput input) throws IOException ++ private static DictData.Entry readEntry(CFFDataInput input) ++ throws IOException + { + DictData.Entry entry = new DictData.Entry(); + while (true) +@@ -211,13 +217,15 @@ + return entry; + } + +- private static CFFOperator readOperator(CFFDataInput input, int b0) throws IOException ++ private static CFFOperator readOperator(CFFDataInput input, int b0) ++ throws IOException + { + CFFOperator.Key key = readOperatorKey(input, b0); + return CFFOperator.getOperator(key); + } + +- private static CFFOperator.Key readOperatorKey(CFFDataInput input, int b0) throws IOException ++ private static CFFOperator.Key readOperatorKey(CFFDataInput input, int b0) ++ throws IOException + { + if (b0 == 12) + { +@@ -227,7 +235,8 @@ + return new CFFOperator.Key(b0); + } + +- private static Integer readIntegerNumber(CFFDataInput input, int b0) throws IOException ++ private static Integer readIntegerNumber(CFFDataInput input, int b0) ++ throws IOException + { + if (b0 == 28) + { +@@ -263,7 +272,8 @@ + } + } + +- private static Double readRealNumber(CFFDataInput input, int b0) throws IOException ++ private static Double readRealNumber(CFFDataInput input, int b0) ++ throws IOException + { + StringBuffer sb = new StringBuffer(); + boolean done = false; +@@ -446,9 +456,9 @@ + throw new IOException("FDArray is missing for a CIDKeyed Font."); + } + +- int fontDictOffset = fdArrayEntry.getNumber(0).intValue(); +- input.setPosition(fontDictOffset); +- IndexData fdIndex = readIndexData(input); ++ int fontDictOffset = fdArrayEntry.getNumber(0).intValue(); ++ input.setPosition(fontDictOffset); ++ IndexData fdIndex = readIndexData(input); + + List<Map<String, Object>> privateDictionaries = new LinkedList<Map<String, Object>>(); + List<Map<String, Object>> fontDictionaries = new LinkedList<Map<String, Object>>(); +@@ -577,8 +587,8 @@ + { + return CFFStandardString.getName(index); + } +- if (index - 391 <= stringIndex.getCount()) +- { ++ if (index - 391 < stringIndex.getCount()) ++ { + DataInput dataInput = new DataInput(stringIndex.getBytes(index - 391)); + return dataInput.getString(); + } +@@ -620,7 +630,8 @@ + return entry != null ? entry.getArray() : defaultValue; + } + +- private CFFEncoding readEncoding(CFFDataInput dataInput, int[] gids) throws IOException ++ private CFFEncoding readEncoding(CFFDataInput dataInput, int[] gids) ++ throws IOException + { + int format = dataInput.readCard8(); + int baseFormat = format & 0x7f; +@@ -639,7 +650,8 @@ + } + } + +- private Format0Encoding readFormat0Encoding(CFFDataInput dataInput, int format, int[] gids) throws IOException ++ private Format0Encoding readFormat0Encoding(CFFDataInput dataInput, int format, ++ int[] gids) throws IOException + { + Format0Encoding encoding = new Format0Encoding(); + encoding.format = format; +@@ -657,7 +669,8 @@ + return encoding; + } + +- private Format1Encoding readFormat1Encoding(CFFDataInput dataInput, int format, int[] gids) throws IOException ++ private Format1Encoding readFormat1Encoding(CFFDataInput dataInput, int format, ++ int[] gids) throws IOException + { + Format1Encoding encoding = new Format1Encoding(); + encoding.format = format; +@@ -683,7 +696,8 @@ + return encoding; + } + +- private void readSupplement(CFFDataInput dataInput, EmbeddedEncoding encoding) throws IOException ++ private void readSupplement(CFFDataInput dataInput, EmbeddedEncoding encoding) ++ throws IOException + { + encoding.nSups = dataInput.readCard8(); + encoding.supplement = new EmbeddedEncoding.Supplement[encoding.nSups]; +@@ -738,15 +752,14 @@ + fdselect.fds = new int[nGlyphs]; + for (int i = 0; i < fdselect.fds.length; i++) + { +- fdselect.fds[i] = dataInput.readCard8(); +- ++ fdselect.fds[i] = dataInput.readCard8(); + } + return fdselect; + } + + /** + * Read the Format 3 of the FDSelect data structure. +- * ++ * + * @param dataInput + * @param format + * @param nGlyphs +@@ -768,7 +781,6 @@ + r3.first = dataInput.readCard16(); + r3.fd = dataInput.readCard8(); + fdselect.range3[i] = r3; +- + } + + fdselect.sentinel = dataInput.readCard16(); +@@ -902,7 +914,8 @@ + } + } + +- private CFFCharset readCharset(CFFDataInput dataInput, int nGlyphs) throws IOException ++ private CFFCharset readCharset(CFFDataInput dataInput, int nGlyphs) ++ throws IOException + { + int format = dataInput.readCard8(); + if (format == 0) +@@ -923,7 +936,8 @@ + } + } + +- private Format0Charset readFormat0Charset(CFFDataInput dataInput, int format, int nGlyphs) throws IOException ++ private Format0Charset readFormat0Charset(CFFDataInput dataInput, int format, ++ int nGlyphs) throws IOException + { + Format0Charset charset = new Format0Charset(); + charset.format = format; +@@ -936,7 +950,8 @@ + return charset; + } + +- private Format1Charset readFormat1Charset(CFFDataInput dataInput, int format, int nGlyphs) throws IOException ++ private Format1Charset readFormat1Charset(CFFDataInput dataInput, int format, ++ int nGlyphs) throws IOException + { + Format1Charset charset = new Format1Charset(); + charset.format = format; +@@ -957,7 +972,8 @@ + return charset; + } + +- private Format2Charset readFormat2Charset(CFFDataInput dataInput, int format, int nGlyphs) throws IOException ++ private Format2Charset readFormat2Charset(CFFDataInput dataInput, int format, ++ int nGlyphs) throws IOException + { + Format2Charset charset = new Format2Charset(); + charset.format = format; +@@ -981,7 +997,7 @@ + } + + /** +- * Inner class holding the header of a CFF font. ++ * Inner class holding the header of a CFF font. + */ + private static class Header + { +@@ -999,7 +1015,7 @@ + } + + /** +- * Inner class holding the DictData of a CFF font. ++ * Inner class holding the DictData of a CFF font. + */ + private static class DictData + { +@@ -1030,7 +1046,7 @@ + } + + /** +- * {@inheritDoc} ++ * {@inheritDoc} + */ + public String toString() + { +@@ -1038,7 +1054,7 @@ + } + + /** +- * Inner class holding an operand of a CFF font. ++ * Inner class holding an operand of a CFF font. + */ + private static class Entry + { +@@ -1100,7 +1116,7 @@ + } + + /** +- * Inner class representing an embedded CFF encoding. ++ * Inner class representing an embedded CFF encoding. + */ + abstract static class EmbeddedEncoding extends CFFEncoding + { +@@ -1124,7 +1140,7 @@ + } + + /** +- * Inner class representing a supplement for an encoding. ++ * Inner class representing a supplement for an encoding. + */ + static class Supplement + { +@@ -1150,7 +1166,7 @@ + } + + /** +- * Inner class representing a Format0 encoding. ++ * Inner class representing a Format0 encoding. + */ + private static class Format0Encoding extends EmbeddedEncoding + { +@@ -1167,7 +1183,7 @@ + } + + /** +- * Inner class representing a Format1 encoding. ++ * Inner class representing a Format1 encoding. + */ + private static class Format1Encoding extends EmbeddedEncoding + { +@@ -1183,7 +1199,7 @@ + } + + /** +- * Inner class representing a range of an encoding. ++ * Inner class representing a range of an encoding. + */ + private static class Range1 + { +@@ -1193,13 +1209,20 @@ + @Override + public String toString() + { +- return getClass().getName() + "[first=" + first + ", nLeft=" + nLeft + "]"; ++ return getClass().getName() + "[first=" + first + ", nLeft=" ++ + nLeft + "]"; + } ++ ++ @Override ++ public boolean equals(Object obj) { ++ Range1 r = (Range1)obj; ++ return (first == r.first && nLeft == r.nLeft); ++ } + } + } + + /** +- * Inner class representing an embedded CFF charset. ++ * Inner class representing an embedded CFF charset. + */ + abstract static class EmbeddedCharset extends CFFCharset + { +@@ -1211,7 +1234,7 @@ + } + + /** +- * Inner class representing a Format0 charset. ++ * Inner class representing a Format0 charset. + */ + private static class Format0Charset extends EmbeddedCharset + { +@@ -1226,7 +1249,7 @@ + } + + /** +- * Inner class representing a Format1 charset. ++ * Inner class representing a Format1 charset. + */ + private static class Format1Charset extends EmbeddedCharset + { +@@ -1240,7 +1263,7 @@ + } + + /** +- * Inner class representing a range of a charset. ++ * Inner class representing a range of a charset. + */ + private static class Range1 + { +@@ -1256,7 +1279,7 @@ + } + + /** +- * Inner class representing a Format2 charset. ++ * Inner class representing a Format2 charset. + */ + private static class Format2Charset extends EmbeddedCharset + { +@@ -1270,7 +1293,7 @@ + } + + /** +- * Inner class representing a range of a charset. ++ * Inner class representing a range of a charset. + */ + private static class Range2 + { +@@ -1284,4 +1307,8 @@ + } + } + } ++ ++ public IndexData getStringIndex() { ++ return stringIndex; ++ } + } +Index: fontbox/src/main/java/org/apache/fontbox/cff/CFFFont.java +=================================================================== +--- fontbox/src/main/java/org/apache/fontbox/cff/CFFFont.java (revision 1546564) ++++ fontbox/src/main/java/org/apache/fontbox/cff/CFFFont.java (working copy) +@@ -31,7 +31,7 @@ + + /** + * This class represents a CFF/Type2 Font. +- * ++ * + * @author Villu Ruusmann + * @version $Revision$ + */ +@@ -44,6 +44,8 @@ + private CFFEncoding fontEncoding = null; + private CFFCharset fontCharset = null; + private Map<String, byte[]> charStringsDict = new LinkedHashMap<String, byte[]>(); ++ Map<Integer, Mapping> sidMappings = null; ++ ArrayList<Mapping> gidMappings = null; + private IndexData globalSubrIndex = null; + private IndexData localSubrIndex = null; + +@@ -97,6 +99,7 @@ + topDict.put(name, value); + } + } ++ + /** + * Returns the top dictionary. + * @return the dictionary +@@ -107,7 +110,7 @@ + } + + /** +- * Adds the given key/value pair to the private dictionary. ++ * Adds the given key/value pair to the private dictionary. + * @param name the given key + * @param value the given value + */ +@@ -118,7 +121,8 @@ + privateDict.put(name, value); + } + } +- /** ++ ++ /** + * Returns the private dictionary. + * @return the dictionary + */ +@@ -127,14 +131,60 @@ + return privateDict; + } + ++ /** ++ * Returns a mapping for a given GID ++ * @param GID The given GID ++ * @return The found mapping ++ */ ++ public Mapping getMapping(int GID) { ++ return sidMappings.get(GID); ++ } ++ + /** +- * Get the mapping (code/SID/charname/bytes) for this font. +- * @return mappings for codes < 256 and for codes > = 256 +- */ +- public Collection<Mapping> getMappings() ++ * Get the mapping (code/SID/charname/bytes) for this font. ++ * @return mappings for codes < 256 and for codes > = 256 ++ */ ++ public Collection<Mapping> getMappings() { ++ constructMappings(); ++ return sidMappings.values(); ++ } ++ ++ /** ++ * Gets the GID mappings list. ++ */ ++ public ArrayList<Mapping> getGIDMappings() { ++ return gidMappings; ++ } ++ ++ private void constructGIDMap() { ++ gidMappings = new ArrayList<Mapping>(); ++ Mapping notdef = new Mapping(); ++ notdef.setName(".notdef"); ++ gidMappings.add(notdef); ++ for (CFFCharset.Entry entry : fontCharset.getEntries()) ++ { ++ String name = entry.getName(); ++ byte[] bytes = this.charStringsDict.get(name); ++ if (bytes == null) ++ { ++ continue; ++ } ++ Mapping mapping = new Mapping(); ++ mapping.setSID(entry.getSID()); ++ mapping.setName(name); ++ mapping.setBytes(bytes); ++ gidMappings.add(mapping); ++ } ++ } ++ ++ /** ++ * Construct the mappings. ++ */ ++ public void constructMappings() + { +- List<Mapping> mappings = new ArrayList<Mapping>(); +- Set<String> mappedNames = new HashSet<String>(); ++ constructGIDMap(); ++ sidMappings = new LinkedHashMap<Integer, Mapping>(); ++ Set<String> mappedNames = new HashSet<String>(); + for (CFFEncoding.Entry entry : fontEncoding.getEntries()) + { + String charName = fontCharset.getName(entry.getSID()); +@@ -153,7 +203,7 @@ + mapping.setSID(entry.getSID()); + mapping.setName(charName); + mapping.setBytes(bytes); +- mappings.add(mapping); ++ sidMappings.put(mapping.getSID(), mapping); + mappedNames.add(charName); + } + if (fontEncoding instanceof CFFParser.EmbeddedEncoding) +@@ -177,7 +227,7 @@ + mapping.setSID(supplement.getGlyph()); + mapping.setName(charName); + mapping.setBytes(bytes); +- mappings.add(mapping); ++ sidMappings.put(mapping.getSID(), mapping); + mappedNames.add(charName); + } + } +@@ -185,7 +235,7 @@ + int code = 256; + for (CFFCharset.Entry entry : fontCharset.getEntries()) + { +- String name = entry.getName(); ++ String name = entry.getName(); + if (mappedNames.contains(name)) + { + continue; +@@ -201,11 +251,10 @@ + mapping.setName(name); + mapping.setBytes(bytes); + +- mappings.add(mapping); ++ sidMappings.put(mapping.getSID(), mapping); + + mappedNames.add(name); + } +- return mappings; + } + + /** +@@ -215,34 +264,43 @@ + * @return -1 if the SID is missing from the Font. + * @throws IOException + */ +- public int getWidth(int SID) throws IOException { +- int nominalWidth = privateDict.containsKey("nominalWidthX") ? ((Number)privateDict.get("nominalWidthX")).intValue() : 0; +- int defaultWidth = privateDict.containsKey("defaultWidthX") ? ((Number)privateDict.get("defaultWidthX")).intValue() : 1000 ; +- +- for (Mapping m : getMappings() ){ +- if (m.getSID() == SID) { ++ public int getWidth(int SID) throws IOException { ++ int nominalWidth = privateDict.containsKey("nominalWidthX") ? ((Number) privateDict.get("nominalWidthX")).intValue() : 0; ++ int defaultWidth = privateDict.containsKey("defaultWidthX") ? ((Number) privateDict.get("defaultWidthX")).intValue() : 1000; ++ Mapping m = sidMappings.get(SID); ++ if (m != null) { ++ CharStringRenderer csr = getRendererForMapping(m); ++ // ---- If the CharString has a Width nominalWidthX must be added, ++ // otherwise it is the default width. ++ return csr.getWidth() != 0 ? csr.getWidth() + nominalWidth : defaultWidth; ++ } + +- CharStringRenderer csr = null; +- if (((Number)getProperty("CharstringType")).intValue() == 2 ) { +- List<Object> lSeq = m.toType2Sequence(); +- csr = new CharStringRenderer(false); +- csr.render(lSeq); +- } else { +- List<Object> lSeq = m.toType1Sequence(); +- csr = new CharStringRenderer(); +- csr.render(lSeq); +- } ++ // ---- SID Width not found, return the nodef width ++ return getNotDefWidth(defaultWidth, nominalWidth); ++ } + +- // ---- If the CharString has a Width nominalWidthX must be added, +- // otherwise it is the default width. +- return csr.getWidth() != 0 ? csr.getWidth() + nominalWidth : defaultWidth; +- } +- } ++ private CharStringRenderer getRendererForMapping(Mapping m) throws IOException { ++ CharStringRenderer csr = null; ++ if (((Number) getProperty("CharstringType")).intValue() == 2) { ++ List<Object> lSeq = m.toType2Sequence(); ++ csr = new CharStringRenderer(false); ++ csr.render(lSeq); ++ } else { ++ List<Object> lSeq = m.toType1Sequence(); ++ csr = new CharStringRenderer(); ++ csr.render(lSeq); ++ } ++ return csr; ++ } + +- // ---- SID Width not found, return the nodef width +- return getNotDefWidth(defaultWidth, nominalWidth); +- } +- ++ /** ++ * Returns the witdth of the .notdef character. ++ * ++ * @param defaultWidth default width ++ * @param nominalWidth nominal width ++ * @return the calculated width for the .notdef character ++ * @throws IOException if something went wrong ++ */ + protected int getNotDefWidth(int defaultWidth, int nominalWidth) throws IOException { + CharStringRenderer csr; + byte[] glyphDesc = this.getCharStringsDict().get(".notdef"); +@@ -260,6 +318,36 @@ + return csr.getWidth() != 0 ? csr.getWidth() + nominalWidth : defaultWidth; + } + ++ /** ++ * Return the Width value of the given Glyph identifier ++ * ++ * @param SID ++ * @return -1 if the SID is missing from the Font. ++ * @throws IOException ++ */ ++ public int[] getBoundingBox(int SID) throws IOException { ++ Mapping m = sidMappings.get(SID); ++ if (m != null) { ++ CharStringRenderer csr = getRendererForMapping(m); ++ return csr.getBounds(); ++ } ++ // ---- SID Width not found, return the nodef width ++ return new int[4]; ++ } ++ ++ /** ++ * Gets the name of a character from the given SID ++ * @param SID The given SID ++ * @return The name of the found character ++ */ ++ public String getNameOfCharFromCode(int SID) { ++ if (sidMappings.get(SID) != null) { ++ return sidMappings.get(SID).getName(); ++ } else { ++ return ""; ++ } ++ } ++ + /** + * Returns the CFFEncoding of the font. + * @return the encoding +@@ -336,50 +424,51 @@ + + charStringsDict + "]"; + } + ++ /** ++ * Sets the global subroutine index data. ++ * @param globalSubrIndex the IndexData object containing the global subroutines ++ */ ++ public void setGlobalSubrIndex(IndexData globalSubrIndexValue) { ++ globalSubrIndex = globalSubrIndexValue; ++ } + +- /** +- * Sets the global subroutine index data. +- * @param globalSubrIndex the IndexData object containing the global subroutines +- */ +- public void setGlobalSubrIndex(IndexData globalSubrIndex) { +- this.globalSubrIndex = globalSubrIndex; +- } ++ /** ++ * Returns the global subroutine index data. ++ * @return the dictionary ++ */ ++ public IndexData getGlobalSubrIndex() ++ { ++ return globalSubrIndex; ++ } + +- /** +- * Returns the global subroutine index data. +- * @return the dictionary +- */ +- public IndexData getGlobalSubrIndex() { +- return globalSubrIndex; +- } ++ /** ++ * Returns the local subroutine index data. ++ * @return the dictionary ++ */ ++ public IndexData getLocalSubrIndex() ++ { ++ return localSubrIndex; ++ } + +- /** +- * Returns the local subroutine index data. +- * @return the dictionary +- */ +- public IndexData getLocalSubrIndex() { +- return localSubrIndex; +- } ++ /** ++ * Sets the local subroutine index data. ++ * @param localSubrIndexValue the IndexData object containing the local subroutines ++ */ ++ public void setLocalSubrIndex(IndexData localSubrIndexValue) { ++ localSubrIndex = localSubrIndexValue; ++ } + +- /** +- * Sets the local subroutine index data. +- * @param localSubrIndex the IndexData object containing the local subroutines +- */ +- public void setLocalSubrIndex(IndexData localSubrIndex) { +- this.localSubrIndex = localSubrIndex; +- } ++ /** ++ * This class is used for the font mapping. ++ * ++ */ ++ public class Mapping ++ { ++ private int mappedCode; ++ private int mappedSID; ++ private String mappedName; ++ private byte[] mappedBytes; + +- /** +- * This class is used for the font mapping. +- * +- */ +- public class Mapping +- { +- private int mappedCode; +- private int mappedSID; +- private String mappedName; +- private byte[] mappedBytes; +- + /** + * Converts the mapping into a Type1-sequence. + * @return the Type1-sequence +@@ -458,4 +547,4 @@ + this.mappedBytes = bytes; + } + } +-} +\ No newline at end of file ++} diff --git a/lib/xmlgraphics-commons-svn-trunk.jar b/lib/xmlgraphics-commons-svn-trunk.jar Binary files differindex 22b0f5d52..34e4d2b44 100644 --- a/lib/xmlgraphics-commons-svn-trunk.jar +++ b/lib/xmlgraphics-commons-svn-trunk.jar diff --git a/src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java b/src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java index 506629ab2..c6845fb1d 100644 --- a/src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java +++ b/src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java @@ -32,7 +32,6 @@ import java.util.TreeSet; import org.apache.fop.util.License; // CSOFF: LineLength -// CSOFF: NoWhitespaceAfter /** * <p>Utility for generating a Java class representing bidirectional @@ -303,7 +302,7 @@ public final class GenerateBidiClass { sb.setLength(0); out.println("private static byte[] bcL1 = {"); for (int i = 0; i < bcL1.length; i++) { - if (! first) { + if (!first) { sb.append(","); } else { first = false; @@ -327,7 +326,7 @@ public final class GenerateBidiClass { sb.setLength(0); out.println("private static byte[] bcR1 = {"); for (int i = 0; i < bcR1.length; i++) { - if (! first) { + if (!first) { sb.append(","); } else { first = false; @@ -351,7 +350,7 @@ public final class GenerateBidiClass { sb.setLength(0); out.println("private static int[] bcS1 = {"); for (int i = 0; i < bcS1.length; i++) { - if (! first) { + if (!first) { sb.append(","); } else { first = false; @@ -375,7 +374,7 @@ public final class GenerateBidiClass { sb.setLength(0); out.println("private static int[] bcE1 = {"); for (int i = 0; i < bcE1.length; i++) { - if (! first) { + if (!first) { sb.append(","); } else { first = false; @@ -399,7 +398,7 @@ public final class GenerateBidiClass { sb.setLength(0); out.println("private static byte[] bcC1 = {"); for (int i = 0; i < bcC1.length; i++) { - if (! first) { + if (!first) { sb.append(","); } else { first = false; @@ -434,7 +433,7 @@ public final class GenerateBidiClass { if (k >= 0) { return ca [ k ]; } else { - k = - (k + 1); + k = -(k + 1); if (k == 0) { return BidiConstants.L; } else if (ch <= ea [ k - 1 ]) { diff --git a/src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java b/src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java index 0c02e305e..d13ab2534 100644 --- a/src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java +++ b/src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java @@ -40,10 +40,6 @@ import java.util.TreeMap; import org.apache.fop.util.License; // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: InnerAssignmentCheck -// CSOFF: SimplifyBooleanReturnCheck -// CSOFF: EmptyForIteratorPadCheck /** * <p>Utility for generating a Java class and associated data files representing @@ -202,7 +198,7 @@ public final class GenerateBidiTestData { String ucName = sa[1]; if (isBlockStart(ucName)) { String ucBlock = getBlockName(ucName); - if (! im.containsKey(ucBlock)) { + if (!im.containsKey(ucBlock)) { im.put(ucBlock, new int[] { uc, -1, bc }); } else { throw new IllegalArgumentException("duplicate start of block '" + ucBlock + "' at entry: " + line); @@ -223,7 +219,7 @@ public final class GenerateBidiTestData { } else { Integer k = Integer.valueOf(bc); List sl; - if (! sm.containsKey(k)) { + if (!sm.containsKey(k)) { sl = new ArrayList(); sm.put(k, sl); } else { @@ -267,7 +263,7 @@ public final class GenerateBidiTestData { } } // populate intervals from (block) interval map - if (! im.isEmpty()) { + if (!im.isEmpty()) { for (Iterator it = im.values().iterator(); it.hasNext(); ) { int[] ba = (int[]) it.next(); assert (ba != null) && (ba.length > 2); @@ -335,7 +331,7 @@ public final class GenerateBidiTestData { continue; } else if (line.startsWith("#")) { continue; - } else if (line.startsWith(PFX_TYPE) && ! ignoreDeprecatedTypeData) { + } else if (line.startsWith(PFX_TYPE) && !ignoreDeprecatedTypeData) { List lines = new ArrayList(); if ((n = readType(line, b, lines)) < 0) { break; @@ -356,14 +352,14 @@ public final class GenerateBidiTestData { // dump instrumentation if (verbose) { System.out.println(); - if (! ignoreDeprecatedTypeData) { + if (!ignoreDeprecatedTypeData) { System.out.println("Read type ranges : " + numTypeRanges); } System.out.println("Read level specs : " + numLevelSpecs); System.out.println("Read test specs : " + numTestSpecs); System.out.println("Read lines : " + lineNumber); } - if (! ignoreDeprecatedTypeData) { + if (!ignoreDeprecatedTypeData) { td = (int[][]) tdl.toArray(new int [ tdl.size() ] []); } ld = (int[][]) ldl.toArray(new int [ ldl.size() ] []); @@ -378,12 +374,12 @@ public final class GenerateBidiTestData { boolean done = false; int n = 0; lines.add(line); - while (! done) { + while (!done) { switch (testPrefix(b, PFX_LEVELS)) { case 0: // within current levels if ((line = b.readLine()) != null) { n++; - if ((line.length() > 0) && ! line.startsWith("#")) { + if ((line.length() > 0) && !line.startsWith("#")) { lines.add(line); } } else { @@ -509,7 +505,7 @@ public final class GenerateBidiTestData { CharacterIterator ci = new StringCharacterIterator(charRanges); // read initial list delimiter skipSpace(ci); - if (! readStartOfList(ci)) { + if (!readStartOfList(ci)) { badRangeSpec("missing initial list delimiter", charRanges); } // read negation token if present @@ -538,7 +534,7 @@ public final class GenerateBidiTestData { String s; skipSpace(ci); if ((s = maybeReadSeparator(ci)) != null) { - if ((s.length() != 0) && ! s.equals("||")) { + if ((s.length() != 0) && !s.equals("||")) { badRangeSpec("invalid item separator \"" + s + "\"", charRanges); } } @@ -557,10 +553,10 @@ public final class GenerateBidiTestData { } // read terminating list delimiter skipSpace(ci); - if (! readEndOfList(ci)) { + if (!readEndOfList(ci)) { badRangeSpec("missing terminating list delimiter", charRanges); } - if (! atEnd(ci)) { + if (!atEnd(ci)) { badRangeSpec("extraneous content prior to end of line", ci); } if (negated) { @@ -578,9 +574,9 @@ public final class GenerateBidiTestData { } private static void skipSpace(CharacterIterator ci) { - while (! atEnd(ci)) { + while (!atEnd(ci)) { char c = ci.current(); - if (! Character.isWhitespace(c)) { + if (!Character.isWhitespace(c)) { break; } else { ci.next(); @@ -589,7 +585,7 @@ public final class GenerateBidiTestData { } private static boolean maybeReadNext(CharacterIterator ci, char next) { - while (! atEnd(ci)) { + while (!atEnd(ci)) { char c = ci.current(); if (c == next) { ci.next(); @@ -906,7 +902,7 @@ public final class GenerateBidiTestData { List ll = new ArrayList(); // read prefix skipSpace(ci); - if (! maybeReadToken(ci, PFX_LEVELS)) { + if (!maybeReadToken(ci, PFX_LEVELS)) { badLevelSpec("missing prefix \"" + PFX_LEVELS + "\"", ci); } // read level values @@ -924,7 +920,7 @@ public final class GenerateBidiTestData { } // read to end of line skipSpace(ci); - if (! atEnd(ci)) { + if (!atEnd(ci)) { badLevelSpec("extraneous content prior to end of line", ci); } if (ll.size() == 0) { @@ -1007,7 +1003,7 @@ public final class GenerateBidiTestData { List rl = new ArrayList(); // read prefix skipSpace(ci); - if (! maybeReadToken(ci, PFX_REORDER)) { + if (!maybeReadToken(ci, PFX_REORDER)) { badReorderSpec("missing prefix \"" + PFX_REORDER + "\"", ci); } // read reorder values @@ -1023,7 +1019,7 @@ public final class GenerateBidiTestData { } // read to end of line skipSpace(ci); - if (! atEnd(ci)) { + if (!atEnd(ci)) { badReorderSpec("extraneous content prior to end of line", ci); } return createReorderArray(rl, levels); @@ -1066,7 +1062,7 @@ public final class GenerateBidiTestData { CharacterIterator ci = new StringCharacterIterator(line); List cl = new ArrayList(); // read bidi class identifier sequence - while (! atEnd(ci) && ! maybeReadNext(ci, ';')) { + while (!atEnd(ci) && !maybeReadNext(ci, ';')) { skipSpace(ci); int bc; if ((bc = maybeReadBidiClass(ci)) >= 0) { @@ -1086,7 +1082,7 @@ public final class GenerateBidiTestData { } // read to end of line skipSpace(ci); - if (! atEnd(ci)) { + if (!atEnd(ci)) { badTestSpec("extraneous content prior to end of line", ci); } return createTestArray(cl, bs, levels); @@ -1244,7 +1240,7 @@ public final class GenerateBidiTestData { ok = false; } } - if (! ok) { + if (!ok) { System.out.println("Usage: GenerateBidiTestData [-v] [-i] [-d <ucdFile>] [-b <bidiFile>] [-o <outputFile>]"); System.out.println(" defaults:"); if (ignoreDeprecatedTypeData) { diff --git a/src/documentation/intermediate-format-ng/fop-intermediate-format-ng-content.xsd b/src/documentation/intermediate-format-ng/fop-intermediate-format-ng-content.xsd index d6f0c694c..2e58a7f45 100644 --- a/src/documentation/intermediate-format-ng/fop-intermediate-format-ng-content.xsd +++ b/src/documentation/intermediate-format-ng/fop-intermediate-format-ng-content.xsd @@ -38,6 +38,7 @@ <xs:complexContent> <xs:extension base="mf:contentType"> <xs:attribute name="transform" type="xs:string"/> + <xs:attribute name="layer" type="xs:string"/> </xs:extension> </xs:complexContent> </xs:complexType> diff --git a/src/java/org/apache/fop/Version.java b/src/java/org/apache/fop/Version.java index 86861a60b..a8903c74e 100644 --- a/src/java/org/apache/fop/Version.java +++ b/src/java/org/apache/fop/Version.java @@ -40,8 +40,9 @@ public final class Version { } if (version == null) { //Fallback if FOP is used in a development environment - String headURL - = "$HeadURL$"; + // CSOFF: LineLength + String headURL = "$HeadURL$"; + // CSON: LineLength version = headURL; final String pathPrefix = "/xmlgraphics/fop/"; int pos = version.indexOf(pathPrefix); diff --git a/src/java/org/apache/fop/apps/FopConfParser.java b/src/java/org/apache/fop/apps/FopConfParser.java index b4918ef30..b0fa40f45 100644 --- a/src/java/org/apache/fop/apps/FopConfParser.java +++ b/src/java/org/apache/fop/apps/FopConfParser.java @@ -70,16 +70,7 @@ public class FopConfParser { */ public FopConfParser(InputStream fopConfStream, EnvironmentProfile enviro) throws SAXException, IOException { - DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); - Configuration cfg; - try { - cfg = cfgBuilder.build(fopConfStream); - } catch (ConfigurationException e) { - throw new FOPException(e); - } - // The default base URI is taken from the directory in which the fopConf resides - fopFactoryBuilder = new FopFactoryBuilder(enviro).setConfiguration(cfg); - configure(enviro.getDefaultBaseURI(), enviro.getResourceResolver(), cfg); + this(fopConfStream, enviro.getDefaultBaseURI(), enviro); } /** @@ -94,7 +85,8 @@ public class FopConfParser { */ public FopConfParser(InputStream fopConfStream, URI defaultBaseURI, ResourceResolver resourceResolver) throws SAXException, IOException { - this(fopConfStream, EnvironmentalProfileFactory.createDefault(defaultBaseURI, resourceResolver)); + this(fopConfStream, defaultBaseURI, + EnvironmentalProfileFactory.createDefault(defaultBaseURI, resourceResolver)); } /** @@ -123,6 +115,20 @@ public class FopConfParser { } /** + * Constructor that takes the FOP conf and a default base URI and uses the default URI resolver. + * + * @param fopConfFile the FOP conf file + * @param defaultBaseURI the default base URI + * @throws SAXException if a SAX error was thrown parsing the FOP conf + * @throws IOException if an I/O error is thrown while parsing the FOP conf + */ + public FopConfParser(File fopConfFile, URI defaultBaseURI) throws SAXException, IOException { + this(new FileInputStream(fopConfFile), fopConfFile.toURI(), + EnvironmentalProfileFactory.createDefault(defaultBaseURI, + ResourceResolverFactory.createDefaultResourceResolver())); + } + + /** * Constructor that parses the FOP conf and uses the URI resolver given. * * @param fopConfFile the FOP conf file @@ -132,11 +138,24 @@ public class FopConfParser { */ public FopConfParser(File fopConfFile, ResourceResolver resourceResolver) throws SAXException, IOException { - this(new FileInputStream(fopConfFile), - fopConfFile.getAbsoluteFile().getParentFile().toURI(), resourceResolver); + this(new FileInputStream(fopConfFile), fopConfFile.toURI(), resourceResolver); + } + + private FopConfParser(InputStream fopConfStream, URI baseURI, EnvironmentProfile enviro) + throws SAXException, IOException { + DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); + Configuration cfg; + try { + cfg = cfgBuilder.build(fopConfStream); + } catch (ConfigurationException e) { + throw new FOPException(e); + } + // The default base URI is taken from the directory in which the fopConf resides + fopFactoryBuilder = new FopFactoryBuilder(enviro).setConfiguration(cfg); + configure(baseURI, enviro.getResourceResolver(), cfg); } - private void configure(final URI defaultBaseURI, final ResourceResolver resourceResolver, + private void configure(final URI baseURI, final ResourceResolver resourceResolver, Configuration cfg) throws FOPException { if (log.isDebugEnabled()) { log.debug("Initializing FopFactory Configuration"); @@ -174,7 +193,7 @@ public class FopConfParser { if (cfg.getChild("base", false) != null) { try { URI confUri = InternalResourceResolver.getBaseURI(cfg.getChild("base").getValue(null)); - fopFactoryBuilder.setBaseURI(defaultBaseURI.resolve(confUri)); + fopFactoryBuilder.setBaseURI(baseURI.resolve(confUri)); } catch (URISyntaxException use) { LogUtil.handleException(log, use, strict); } @@ -242,8 +261,8 @@ public class FopConfParser { } // configure font manager - new FontManagerConfigurator(cfg, fopFactoryBuilder.getBaseURI(), resourceResolver).configure( - fopFactoryBuilder.getFontManager(), strict); + new FontManagerConfigurator(cfg, baseURI, fopFactoryBuilder.getBaseURI(), resourceResolver) + .configure(fopFactoryBuilder.getFontManager(), strict); // configure image loader framework configureImageLoading(cfg.getChild("image-loading", false), strict); diff --git a/src/java/org/apache/fop/area/AreaTreeParser.java b/src/java/org/apache/fop/area/AreaTreeParser.java index e9f0ffb8c..640f04335 100644 --- a/src/java/org/apache/fop/area/AreaTreeParser.java +++ b/src/java/org/apache/fop/area/AreaTreeParser.java @@ -1057,7 +1057,7 @@ public class AreaTreeParser { } private static final Object[] SUBSET_COMMON = new Object[] { - Trait.PROD_ID}; + Trait.PROD_ID, Trait.LAYER}; private static final Object[] SUBSET_LINK = new Object[] { Trait.INTERNAL_LINK, Trait.EXTERNAL_LINK}; private static final Object[] SUBSET_COLOR = new Object[] { diff --git a/src/java/org/apache/fop/area/Footnote.java b/src/java/org/apache/fop/area/Footnote.java index bc9f27b24..28f3ee523 100644 --- a/src/java/org/apache/fop/area/Footnote.java +++ b/src/java/org/apache/fop/area/Footnote.java @@ -83,7 +83,7 @@ public class Footnote extends BlockParent { @Override public void addBlock(Block child) { addChildArea(child); - this.setBPD(this.getBPD() + child.getBPD()); + setBPD(getBPD() + child.getAllocBPD()); } } diff --git a/src/java/org/apache/fop/area/Trait.java b/src/java/org/apache/fop/area/Trait.java index cd0d4becf..eac9d440d 100644 --- a/src/java/org/apache/fop/area/Trait.java +++ b/src/java/org/apache/fop/area/Trait.java @@ -169,9 +169,11 @@ public final class Trait implements Serializable { /** shift direction trait */ public static final Integer SHIFT_DIRECTION = 42; + /** For optional content groups. */ + public static final Integer LAYER = 43; /** Maximum value used by trait keys */ - public static final int MAX_TRAIT_KEY = 42; + public static final int MAX_TRAIT_KEY = 43; private static final TraitInfo[] TRAIT_INFO = new TraitInfo[MAX_TRAIT_KEY + 1]; @@ -243,6 +245,7 @@ public final class Trait implements Serializable { new TraitInfo("block-progression-direction", Direction.class)); put(SHIFT_DIRECTION, new TraitInfo("shift-direction", Direction.class)); + put(LAYER, new TraitInfo("layer", String.class)); } diff --git a/src/java/org/apache/fop/cli/CommandLineOptions.java b/src/java/org/apache/fop/cli/CommandLineOptions.java index 20fcae223..ad8019a7d 100644 --- a/src/java/org/apache/fop/cli/CommandLineOptions.java +++ b/src/java/org/apache/fop/cli/CommandLineOptions.java @@ -173,9 +173,6 @@ public class CommandLineOptions { //Factory config is set up, now we can create the user agent foUserAgent = factory.newFOUserAgent(); foUserAgent.getRendererOptions().putAll(renderingOptions); - if (targetResolution != 0) { - foUserAgent.setTargetResolution(targetResolution); - } addXSLTParameter("fop-output-format", getOutputFormat()); addXSLTParameter("fop-version", Version.getVersion()); foUserAgent.setConserveMemoryPolicy(conserveMemoryPolicy); @@ -1018,7 +1015,8 @@ public class CommandLineOptions { fopFactoryBuilder.setComplexScriptFeatures(useComplexScriptFeatures); } else { try { - fopFactoryBuilder = new FopConfParser(userConfigFile).getFopFactoryBuilder(); + FopConfParser fopConfParser = new FopConfParser(userConfigFile, baseURI); + fopFactoryBuilder = fopConfParser.getFopFactoryBuilder(); } catch (SAXException e) { throw new FOPException(e); } diff --git a/src/java/org/apache/fop/complexscripts/bidi/BidiClass.java b/src/java/org/apache/fop/complexscripts/bidi/BidiClass.java index eed7b983b..4267e275a 100644 --- a/src/java/org/apache/fop/complexscripts/bidi/BidiClass.java +++ b/src/java/org/apache/fop/complexscripts/bidi/BidiClass.java @@ -21,7 +21,6 @@ package org.apache.fop.complexscripts.bidi; import java.util.Arrays; -// CSOFF: WhitespaceAfterCheck // CSOFF: LineLengthCheck /* diff --git a/src/java/org/apache/fop/complexscripts/bidi/BidiResolver.java b/src/java/org/apache/fop/complexscripts/bidi/BidiResolver.java index 8b78615d4..f1a4d2a69 100644 --- a/src/java/org/apache/fop/complexscripts/bidi/BidiResolver.java +++ b/src/java/org/apache/fop/complexscripts/bidi/BidiResolver.java @@ -32,11 +32,7 @@ import org.apache.fop.area.LineArea; import org.apache.fop.area.inline.InlineArea; import org.apache.fop.fo.pagination.PageSequence; -// CSOFF: EmptyForIteratorPadCheck -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: SimplifyBooleanReturnCheck /** * <p>A utility class for performing bidirectional resolution processing.</p> @@ -140,7 +136,7 @@ public final class BidiResolver { runsNew.addAll(ir.split()); } } - if (! runsNew.equals(runs)) { + if (!runsNew.equals(runs)) { runs = runsNew; } return runs; @@ -180,7 +176,7 @@ public final class BidiResolver { i = e - 1; } } - if (! runsNew.equals(runs)) { + if (!runsNew.equals(runs)) { runs = runsNew; } return runs; @@ -232,7 +228,7 @@ public final class BidiResolver { Vector rv = new Vector(); for (Iterator it = ranges.iterator(); it.hasNext(); ) { DelimitedTextRange r = (DelimitedTextRange) it.next(); - if (! r.isEmpty()) { + if (!r.isEmpty()) { rv.add(r); } } diff --git a/src/java/org/apache/fop/complexscripts/bidi/DelimitedTextRange.java b/src/java/org/apache/fop/complexscripts/bidi/DelimitedTextRange.java index 2f69eb73b..67bb0aae1 100644 --- a/src/java/org/apache/fop/complexscripts/bidi/DelimitedTextRange.java +++ b/src/java/org/apache/fop/complexscripts/bidi/DelimitedTextRange.java @@ -34,10 +34,7 @@ import org.apache.fop.traits.WritingModeTraits; import org.apache.fop.traits.WritingModeTraitsGetter; import org.apache.fop.util.CharUtilities; -// CSOFF: EmptyForIteratorPadCheck -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck /** * The <code>DelimitedTextRange</code> class implements the "delimited text range" as described @@ -151,7 +148,7 @@ public class DelimitedTextRange { TextInterval ti = (TextInterval) it.next(); intervalsNew.addAll(assignLevels(ti, levels)); } - if (! intervalsNew.equals(intervals)) { + if (!intervalsNew.equals(intervals)) { intervals = intervalsNew; } } diff --git a/src/java/org/apache/fop/complexscripts/bidi/InlineRun.java b/src/java/org/apache/fop/complexscripts/bidi/InlineRun.java index c51d95c6e..f8f67f953 100644 --- a/src/java/org/apache/fop/complexscripts/bidi/InlineRun.java +++ b/src/java/org/apache/fop/complexscripts/bidi/InlineRun.java @@ -35,11 +35,6 @@ import org.apache.fop.area.inline.UnresolvedPageNumber; import org.apache.fop.area.inline.WordArea; import org.apache.fop.util.CharUtilities; -// CSOFF: EmptyForIteratorPadCheck -// CSOFF: InnerAssignmentCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: SimplifyBooleanReturnCheck - /** * The <code>InlineRun</code> class is a utility class, the instances of which are used * to capture a sequence of reordering levels associated with an inline area. @@ -179,7 +174,7 @@ public class InlineRun { if (inline instanceof WordArea) { WordArea w = (WordArea) inline; // if not already reversed, then reverse now - if (! w.isReversed()) { + if (!w.isReversed()) { if ((reversals & 1) != 0) { w.reverse(mirror); } else if (mirror && maybeNeedsMirroring()) { @@ -209,10 +204,8 @@ public class InlineRun { } return true; } - } else if ((ir.levels == null) && (levels == null)) { - return true; } else { - return false; + return (ir.levels == null) && (levels == null); } } else { return false; diff --git a/src/java/org/apache/fop/complexscripts/bidi/TextInterval.java b/src/java/org/apache/fop/complexscripts/bidi/TextInterval.java index d904aedbb..e1a42a473 100644 --- a/src/java/org/apache/fop/complexscripts/bidi/TextInterval.java +++ b/src/java/org/apache/fop/complexscripts/bidi/TextInterval.java @@ -28,7 +28,6 @@ import org.apache.fop.fo.flow.Character; import org.apache.fop.fo.flow.Leader; // CSOFF: LineLengthCheck -// CSOFF: SimplifyBooleanReturnCheck /** * <p>The <code>TextInterval</code> class is a utility class, the instances of which are used @@ -102,10 +101,8 @@ class TextInterval { return false; } else if (ti.getStart() != start) { return false; - } else if (ti.getEnd() != end) { - return false; } else { - return true; + return ti.getEnd() == end; } } else { return false; diff --git a/src/java/org/apache/fop/complexscripts/bidi/UnflattenProcessor.java b/src/java/org/apache/fop/complexscripts/bidi/UnflattenProcessor.java index 60ad7ba5b..c511dbd70 100644 --- a/src/java/org/apache/fop/complexscripts/bidi/UnflattenProcessor.java +++ b/src/java/org/apache/fop/complexscripts/bidi/UnflattenProcessor.java @@ -35,10 +35,7 @@ import org.apache.fop.area.inline.SpaceArea; import org.apache.fop.area.inline.TextArea; import org.apache.fop.area.inline.UnresolvedPageNumber; -// CSOFF: EmptyForIteratorPadCheck // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: SimplifyBooleanReturnCheck /** * <p>The <code>UnflattenProcessor</code> class is used to reconstruct (by unflattening) a line @@ -86,10 +83,8 @@ class UnflattenProcessor { private boolean shouldFinishTextContainer(TextArea tc, InlineArea ia) { if ((tcOrig != null) && (tc != tcOrig)) { return true; - } else if ((iaLevelLast != -1) && (ia.getBidiLevel() != iaLevelLast)) { - return true; } else { - return false; + return (iaLevelLast != -1) && (ia.getBidiLevel() != iaLevelLast); } } private void finishTextContainer() { @@ -98,7 +93,7 @@ class UnflattenProcessor { private void finishTextContainer(TextArea tc, InlineArea ia) { if (tcNew != null) { updateIPD(tcNew); - if (! icNew.empty()) { + if (!icNew.empty()) { icNew.peek().addChildArea(tcNew); } else { ilNew.add(tcNew); @@ -113,12 +108,12 @@ class UnflattenProcessor { } private boolean shouldFinishInlineContainer(List<InlineParent> ich, TextArea tc, InlineArea ia) { if ((ich == null) || ich.isEmpty()) { - return ! icOrig.empty(); + return !icOrig.empty(); } else { - if (! icOrig.empty()) { + if (!icOrig.empty()) { InlineParent ic = ich.get(0); InlineParent ic0 = icOrig.peek(); - return (ic != ic0) && ! isInlineParentOf(ic, ic0); + return (ic != ic0) && !isInlineParentOf(ic, ic0); } else { return false; } @@ -128,14 +123,14 @@ class UnflattenProcessor { finishInlineContainer(null, null, null); } private void finishInlineContainer(List<InlineParent> ich, TextArea tc, InlineArea ia) { - if ((ich != null) && ! ich.isEmpty()) { // finish non-matching inner inline container(s) + if ((ich != null) && !ich.isEmpty()) { // finish non-matching inner inline container(s) for (Iterator<InlineParent> it = ich.iterator(); it.hasNext(); ) { InlineParent ic = it.next(); InlineParent ic0 = icOrig.empty() ? null : icOrig.peek(); if (ic0 == null) { assert icNew.empty(); } else if (ic != ic0) { - assert ! icNew.empty(); + assert !icNew.empty(); InlineParent icO0 = icOrig.pop(); InlineParent icN0 = icNew.pop(); assert icO0 != null; @@ -145,7 +140,7 @@ class UnflattenProcessor { } else { icNew.peek().addChildArea(icN0); } - if (! icOrig.empty() && (icOrig.peek() == ic)) { + if (!icOrig.empty() && (icOrig.peek() == ic)) { break; } } else { @@ -153,7 +148,7 @@ class UnflattenProcessor { } } } else { // finish all inline containers - while (! icNew.empty()) { + while (!icNew.empty()) { InlineParent icO0 = icOrig.pop(); InlineParent icN0 = icNew.pop(); assert icO0 != null; @@ -176,8 +171,8 @@ class UnflattenProcessor { finishInlineContainer(); } private void update(List<InlineParent> ich, TextArea tc, InlineArea ia) { - if (! alreadyUnflattened(ia)) { - if ((ich != null) && ! ich.isEmpty()) { + if (!alreadyUnflattened(ia)) { + if ((ich != null) && !ich.isEmpty()) { pushInlineContainers(ich); } if (tc != null) { @@ -345,7 +340,7 @@ class UnflattenProcessor { Area a = ia.getParentArea(); while (a != null) { if (a instanceof InlineArea) { - if ((a instanceof InlineParent) && ! (a instanceof TextArea)) { + if ((a instanceof InlineParent) && !(a instanceof TextArea)) { ich.add((InlineParent) a); } a = ((InlineArea) a) .getParentArea(); diff --git a/src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java b/src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java index b1234d323..694cc9245 100644 --- a/src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java +++ b/src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java @@ -25,12 +25,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.fop.traits.Direction; import org.apache.fop.util.CharUtilities; -// CSOFF: AvoidNestedBlocksCheck -// CSOFF: EmptyForIteratorPadCheck -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: ParameterNumberCheck /** * <p>The <code>UnicodeBidiAlgorithm</code> class implements functionality prescribed by @@ -125,47 +120,39 @@ public final class UnicodeBidiAlgorithm implements BidiConstants { case RLE: // start right-to-left embedding case LRO: // start left-to-right override case RLO: // start right-to-left override - { - int en; /* new embedding level */ - if ((bc == RLE) || (bc == RLO)) { - en = ((ec & ~OVERRIDE) + 1) | 1; - } else { - en = ((ec & ~OVERRIDE) + 2) & ~1; - } - if (en < (MAX_LEVELS + 1)) { - es [ ei++ ] = ec; - if ((bc == LRO) || (bc == RLO)) { - ec = en | OVERRIDE; - } else { - ec = en & ~OVERRIDE; - } + int en; /* new embedding level */ + if ((bc == RLE) || (bc == RLO)) { + en = ((ec & ~OVERRIDE) + 1) | 1; + } else { + en = ((ec & ~OVERRIDE) + 2) & ~1; + } + if (en < (MAX_LEVELS + 1)) { + es [ ei++ ] = ec; + if ((bc == LRO) || (bc == RLO)) { + ec = en | OVERRIDE; } else { - // max levels exceeded, so don't change level or override + ec = en & ~OVERRIDE; } - el = ec; - break; + } else { + // max levels exceeded, so don't change level or override } + el = ec; + break; case PDF: // pop directional formatting - { - el = ec; - if (ei > 0) { - ec = es [ --ei ]; - } else { - // ignore isolated PDF - } - break; + el = ec; + if (ei > 0) { + ec = es [ --ei ]; + } else { + // ignore isolated PDF } + break; case B: // paragraph separator - { - el = ec = defaultLevel; - ei = 0; - break; - } + el = ec = defaultLevel; + ei = 0; + break; default: - { - el = ec; - break; - } + el = ec; + break; } switch (bc) { case BN: @@ -608,7 +595,7 @@ public final class UnicodeBidiAlgorithm implements BidiConstants { private static boolean isRetainedFormatting(int[] ca, int s, int e) { for (int i = s; i < e; i++) { - if (! isRetainedFormatting(ca[i])) { + if (!isRetainedFormatting(ca[i])) { return false; } } @@ -680,7 +667,7 @@ public final class UnicodeBidiAlgorithm implements BidiConstants { } else { chOut = chIn; } - if (! triggered && triggersBidi(chOut)) { + if (!triggered && triggersBidi(chOut)) { triggered = true; } if ((chOut & 0xFF0000) == 0) { diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphClassTable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphClassTable.java index 62926dc5e..301ab846e 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphClassTable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphClassTable.java @@ -23,7 +23,6 @@ import java.util.Iterator; import java.util.List; // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck /** * <p>Base class implementation of glyph class table.</p> @@ -100,7 +99,7 @@ public final class GlyphClassTable extends GlyphMappingTable implements GlyphCla } else { for (Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); - if (! (o instanceof Integer)) { + if (!(o instanceof Integer)) { return false; } } @@ -114,7 +113,7 @@ public final class GlyphClassTable extends GlyphMappingTable implements GlyphCla } else { for (Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); - if (! (o instanceof MappingRange)) { + if (!(o instanceof MappingRange)) { return false; } } @@ -128,7 +127,7 @@ public final class GlyphClassTable extends GlyphMappingTable implements GlyphCla } else { for (Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); - if (! (o instanceof GlyphCoverageTable)) { + if (!(o instanceof GlyphCoverageTable)) { return false; } } @@ -197,7 +196,7 @@ public final class GlyphClassTable extends GlyphMappingTable implements GlyphCla if (it.hasNext()) { Object o = it.next(); if (o instanceof Integer) { - firstGlyph = ((Integer) o) . intValue(); + firstGlyph = ((Integer) o) .intValue(); } else { throw new AdvancedTypographicTableFormatException("illegal entry, first entry must be Integer denoting first glyph value, but is: " + o); } @@ -210,7 +209,7 @@ public final class GlyphClassTable extends GlyphMappingTable implements GlyphCla while (it.hasNext()) { Object o = it.next(); if (o instanceof Integer) { - int gc = ((Integer) o) . intValue(); + int gc = ((Integer) o) .intValue(); gca [ i++ ] = gc; if (gc > gcMax) { gcMax = gc; diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphCoverageTable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphCoverageTable.java index 7e2d0e818..699672439 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphCoverageTable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphCoverageTable.java @@ -27,8 +27,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; // CSOFF: LineLengthCheck -// CSOFF: InnerAssignmentCheck -// CSOFF: NoWhitespaceAfterCheck /** * <p>.Base class implementation of glyph coverage table.</p> @@ -103,7 +101,7 @@ public final class GlyphCoverageTable extends GlyphMappingTable implements Glyph } else { for (Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); - if (! (o instanceof Integer)) { + if (!(o instanceof Integer)) { return false; } } @@ -117,7 +115,7 @@ public final class GlyphCoverageTable extends GlyphMappingTable implements Glyph } else { for (Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); - if (! (o instanceof MappingRange)) { + if (!(o instanceof MappingRange)) { return false; } } @@ -183,7 +181,7 @@ public final class GlyphCoverageTable extends GlyphMappingTable implements Glyph for (Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if (o instanceof Integer) { - int gid = ((Integer) o) . intValue(); + int gid = ((Integer) o) .intValue(); if ((gid >= 0) && (gid < 65536)) { if (gid > gidMax) { map [ i++ ] = gidMax = gid; diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionSubtable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionSubtable.java index eaa16146a..3ef9a0152 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionSubtable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionSubtable.java @@ -20,7 +20,6 @@ package org.apache.fop.complexscripts.fonts; // CSOFF: LineLengthCheck -// CSOFF: InnerAssignmentCheck /** * <p>The <code>GlyphDefinitionSubtable</code> implements an abstract base of a glyph definition subtable, diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java index 0e98e4588..a5942536c 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java @@ -29,7 +29,6 @@ import org.apache.commons.logging.LogFactory; import org.apache.fop.complexscripts.scripts.ScriptProcessor; import org.apache.fop.complexscripts.util.GlyphSequence; -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck /** diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphMappingTable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphMappingTable.java index eef49c399..410f5e544 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphMappingTable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphMappingTable.java @@ -23,8 +23,6 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck /** @@ -162,7 +160,7 @@ public class GlyphMappingTable { int mi; if ((i = Arrays.binarySearch(sa, gid)) >= 0) { mi = getMappedIndex(gid, sa [ i ], ma [ i ]); // matches start of (some) range - } else if ((i = - (i + 1)) == 0) { + } else if ((i = -(i + 1)) == 0) { mi = -1; // precedes first range } else if (gid > ea [ --i ]) { mi = -1; // follows preceding (or last) range diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java index 6600a8256..08c533860 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java @@ -23,7 +23,6 @@ import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.ScriptContextTester; // CSOFF: LineLengthCheck -// CSOFF: ParameterNumberCheck /** * <p>The <code>GlyphPositioningState</code> implements an state object used during glyph positioning diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningSubtable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningSubtable.java index d269a342a..a94fac20f 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningSubtable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningSubtable.java @@ -23,8 +23,6 @@ import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.ScriptContextTester; // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: ParameterNumberCheck /** * <p>The <code>GlyphPositioningSubtable</code> implements an abstract base of a glyph subtable, @@ -90,8 +88,8 @@ public abstract class GlyphPositioningSubtable extends GlyphSubtable implements boolean appliedOneShot = false; while (ps.hasNext()) { boolean applied = false; - if (! appliedOneShot && ps.maybeApplicable()) { - for (int i = 0, n = sta.length; ! applied && (i < n); i++) { + if (!appliedOneShot && ps.maybeApplicable()) { + for (int i = 0, n = sta.length; !applied && (i < n); i++) { if (sequenceIndex < 0) { applied = ps.apply(sta [ i ]); } else if (ps.getPosition() == (sequenceStart + sequenceIndex)) { @@ -102,7 +100,7 @@ public abstract class GlyphPositioningSubtable extends GlyphSubtable implements } } } - if (! applied || ! ps.didConsume()) { + if (!applied || !ps.didConsume()) { ps.applyDefault(); } ps.next(); diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java index b22766013..ecc933ae2 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java @@ -33,9 +33,6 @@ import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.GlyphTester; // CSOFF: LineLengthCheck -// CSOFF: InnerAssignmentCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: ParameterNumberCheck /** * <p>The <code>GlyphPositioningTable</code> class is a glyph table that implements @@ -368,7 +365,7 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof Value[])) { + if (((o = entries.get(0)) == null) || !(o instanceof Value[])) { throw new AdvancedTypographicTableFormatException("illegal entries, single entry must be a Value[], but is: " + ((o != null) ? o.getClass() : null)); } else { Value[] va = (Value[]) o; @@ -412,7 +409,7 @@ public class GlyphPositioningTable extends GlyphTable { int offsetLast = counts[0] + counts[1]; // skip any ignored glyphs prior to first non-ignored glyph for ( ; offset < offsetLast; ++offset) { - if (! ps.isIgnoredGlyph(offset)) { + if (!ps.isIgnoredGlyph(offset)) { break; } else { ps.consume(1); @@ -429,7 +426,7 @@ public class GlyphPositioningTable extends GlyphTable { } // skip any ignored glyphs prior to second non-ignored glyph for ( ; offset < offsetLast; ++offset) { - if (! ps.isIgnoredGlyph(offset)) { + if (!ps.isIgnoredGlyph(offset)) { break; } else { ps.consume(1); @@ -513,7 +510,7 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof PairValues[][])) { + if (((o = entries.get(0)) == null) || !(o instanceof PairValues[][])) { throw new AdvancedTypographicTableFormatException("illegal entries, first (and only) entry must be a PairValues[][], but is: " + ((o != null) ? o.getClass() : null)); } else { pvm = (PairValues[][]) o; @@ -569,27 +566,27 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 5 entries"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphClassTable, but is: " + ((o != null) ? o.getClass() : null)); } else { cdt1 = (GlyphClassTable) o; } - if (((o = entries.get(1)) == null) || ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(1)) == null) || !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an GlyphClassTable, but is: " + ((o != null) ? o.getClass() : null)); } else { cdt2 = (GlyphClassTable) o; } - if (((o = entries.get(2)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(2)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { nc1 = ((Integer)(o)).intValue(); } - if (((o = entries.get(3)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(3)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, fourth entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { nc2 = ((Integer)(o)).intValue(); } - if (((o = entries.get(4)) == null) || ! (o instanceof PairValues[][])) { + if (((o = entries.get(4)) == null) || !(o instanceof PairValues[][])) { throw new AdvancedTypographicTableFormatException("illegal entries, fifth entry must be a PairValues[][], but is: " + ((o != null) ? o.getClass() : null)); } else { pvm = (PairValues[][]) o; @@ -633,7 +630,7 @@ public class GlyphPositioningTable extends GlyphTable { int enw = ps.getWidth(gi2); if ((exa != null) && (ena != null)) { Value v = ena.getAlignmentAdjustment(exa); - v.adjust(- enw, 0, 0, 0); + v.adjust(-enw, 0, 0, 0); if (ps.adjust(v)) { ps.setAdjusted(true); } @@ -704,10 +701,10 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof Anchor[])) { + if (((o = entries.get(0)) == null) || !(o instanceof Anchor[])) { throw new AdvancedTypographicTableFormatException("illegal entries, first (and only) entry must be a Anchor[], but is: " + ((o != null) ? o.getClass() : null)); - } else if ((((Anchor[]) o) . length % 2) != 0) { - throw new AdvancedTypographicTableFormatException("illegal entries, Anchor[] array must have an even number of entries, but has: " + ((Anchor[]) o) . length); + } else if ((((Anchor[]) o) .length % 2) != 0) { + throw new AdvancedTypographicTableFormatException("illegal entries, Anchor[] array must have an even number of entries, but has: " + ((Anchor[]) o) .length); } else { aa = (Anchor[]) o; } @@ -736,7 +733,7 @@ public class GlyphPositioningTable extends GlyphTable { MarkAnchor ma = getMarkAnchor(ciMark, giMark); if (ma != null) { for (int i = 0, n = ps.getPosition(); i < n; i++) { - int gi = ps.getGlyph(- (i + 1)); + int gi = ps.getGlyph(-(i + 1)); if (ps.isMark(gi)) { continue; } else { @@ -746,7 +743,7 @@ public class GlyphPositioningTable extends GlyphTable { // start experimental fix for END OF AYAH in Lateef/Scheherazade int[] aa = ps.getAdjustment(); if (aa[2] == 0) { - v.adjust(0, 0, - ps.getWidth(giMark), 0); + v.adjust(0, 0, -ps.getWidth(giMark), 0); } // end experimental fix for END OF AYAH in Lateef/Scheherazade if (ps.adjust(v)) { @@ -835,22 +832,22 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 4 entries"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof GlyphCoverageTable)) { + if (((o = entries.get(0)) == null) || !(o instanceof GlyphCoverageTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphCoverageTable, but is: " + ((o != null) ? o.getClass() : null)); } else { bct = (GlyphCoverageTable) o; } - if (((o = entries.get(1)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(1)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { nmc = ((Integer)(o)).intValue(); } - if (((o = entries.get(2)) == null) || ! (o instanceof MarkAnchor[])) { + if (((o = entries.get(2)) == null) || !(o instanceof MarkAnchor[])) { throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be a MarkAnchor[], but is: " + ((o != null) ? o.getClass() : null)); } else { maa = (MarkAnchor[]) o; } - if (((o = entries.get(3)) == null) || ! (o instanceof Anchor[][])) { + if (((o = entries.get(3)) == null) || !(o instanceof Anchor[][])) { throw new AdvancedTypographicTableFormatException("illegal entries, fourth entry must be a Anchor[][], but is: " + ((o != null) ? o.getClass() : null)); } else { bam = (Anchor[][]) o; @@ -881,7 +878,7 @@ public class GlyphPositioningTable extends GlyphTable { int mxc = getMaxComponentCount(); if (ma != null) { for (int i = 0, n = ps.getPosition(); i < n; i++) { - int gi = ps.getGlyph(- (i + 1)); + int gi = ps.getGlyph(-(i + 1)); if (ps.isMark(gi)) { continue; } else { @@ -989,27 +986,27 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 5 entries"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof GlyphCoverageTable)) { + if (((o = entries.get(0)) == null) || !(o instanceof GlyphCoverageTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphCoverageTable, but is: " + ((o != null) ? o.getClass() : null)); } else { lct = (GlyphCoverageTable) o; } - if (((o = entries.get(1)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(1)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { nmc = ((Integer)(o)).intValue(); } - if (((o = entries.get(2)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(2)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { mxc = ((Integer)(o)).intValue(); } - if (((o = entries.get(3)) == null) || ! (o instanceof MarkAnchor[])) { + if (((o = entries.get(3)) == null) || !(o instanceof MarkAnchor[])) { throw new AdvancedTypographicTableFormatException("illegal entries, fourth entry must be a MarkAnchor[], but is: " + ((o != null) ? o.getClass() : null)); } else { maa = (MarkAnchor[]) o; } - if (((o = entries.get(4)) == null) || ! (o instanceof Anchor[][][])) { + if (((o = entries.get(4)) == null) || !(o instanceof Anchor[][][])) { throw new AdvancedTypographicTableFormatException("illegal entries, fifth entry must be a Anchor[][][], but is: " + ((o != null) ? o.getClass() : null)); } else { lam = (Anchor[][][]) o; @@ -1125,22 +1122,22 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 4 entries"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof GlyphCoverageTable)) { + if (((o = entries.get(0)) == null) || !(o instanceof GlyphCoverageTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphCoverageTable, but is: " + ((o != null) ? o.getClass() : null)); } else { mct2 = (GlyphCoverageTable) o; } - if (((o = entries.get(1)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(1)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { nmc = ((Integer)(o)).intValue(); } - if (((o = entries.get(2)) == null) || ! (o instanceof MarkAnchor[])) { + if (((o = entries.get(2)) == null) || !(o instanceof MarkAnchor[])) { throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be a MarkAnchor[], but is: " + ((o != null) ? o.getClass() : null)); } else { maa = (MarkAnchor[]) o; } - if (((o = entries.get(3)) == null) || ! (o instanceof Anchor[][])) { + if (((o = entries.get(3)) == null) || !(o instanceof Anchor[][])) { throw new AdvancedTypographicTableFormatException("illegal entries, fourth entry must be a Anchor[][], but is: " + ((o != null) ? o.getClass() : null)); } else { mam = (Anchor[][]) o; @@ -1274,7 +1271,7 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -1367,17 +1364,17 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 3 entries"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphClassTable, but is: " + ((o != null) ? o.getClass() : null)); } else { cdt = (GlyphClassTable) o; } - if (((o = entries.get(1)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(1)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { ngc = ((Integer)(o)).intValue(); } - if (((o = entries.get(2)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(2)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -1467,7 +1464,7 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -1585,7 +1582,7 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -1661,27 +1658,27 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 5 entries"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphClassTable, but is: " + ((o != null) ? o.getClass() : null)); } else { icdt = (GlyphClassTable) o; } - if (((o = entries.get(1)) != null) && ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(1)) != null) && !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an GlyphClassTable, but is: " + o.getClass()); } else { bcdt = (GlyphClassTable) o; } - if (((o = entries.get(2)) != null) && ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(2)) != null) && !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be an GlyphClassTable, but is: " + o.getClass()); } else { lcdt = (GlyphClassTable) o; } - if (((o = entries.get(3)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(3)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, fourth entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { ngc = ((Integer)(o)).intValue(); } - if (((o = entries.get(4)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(4)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, fifth entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -1752,7 +1749,7 @@ public class GlyphPositioningTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -2005,7 +2002,7 @@ public class GlyphPositioningTable extends GlyphTable { boolean first = true; sb.append("{ "); if (xPlacement != 0) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2013,7 +2010,7 @@ public class GlyphPositioningTable extends GlyphTable { sb.append("xPlacement = " + xPlacement); } if (yPlacement != 0) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2021,7 +2018,7 @@ public class GlyphPositioningTable extends GlyphTable { sb.append("yPlacement = " + yPlacement); } if (xAdvance != 0) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2029,7 +2026,7 @@ public class GlyphPositioningTable extends GlyphTable { sb.append("xAdvance = " + xAdvance); } if (yAdvance != 0) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2037,7 +2034,7 @@ public class GlyphPositioningTable extends GlyphTable { sb.append("yAdvance = " + yAdvance); } if (xPlaDevice != null) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2045,7 +2042,7 @@ public class GlyphPositioningTable extends GlyphTable { sb.append("xPlaDevice = " + xPlaDevice); } if (yPlaDevice != null) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2053,7 +2050,7 @@ public class GlyphPositioningTable extends GlyphTable { sb.append("xPlaDevice = " + yPlaDevice); } if (xAdvDevice != null) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2061,7 +2058,7 @@ public class GlyphPositioningTable extends GlyphTable { sb.append("xAdvDevice = " + xAdvDevice); } if (yAdvDevice != null) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2118,7 +2115,7 @@ public class GlyphPositioningTable extends GlyphTable { boolean first = true; sb.append("{ "); if (glyph != 0) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2126,7 +2123,7 @@ public class GlyphPositioningTable extends GlyphTable { sb.append("glyph = " + glyph); } if (value1 != null) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; @@ -2134,7 +2131,7 @@ public class GlyphPositioningTable extends GlyphTable { sb.append("value1 = " + value1); } if (value2 != null) { - if (! first) { + if (!first) { sb.append(", "); } else { first = false; diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java index 330a27593..4f6e4181c 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java @@ -29,7 +29,6 @@ import org.apache.fop.complexscripts.util.GlyphTester; import org.apache.fop.complexscripts.util.ScriptContextTester; // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck /** * <p>The <code>GlyphProcessingState</code> implements a common, base state object used during glyph substitution @@ -459,7 +458,7 @@ public class GlyphProcessingState { int start = index + offset; if (start < 0) { throw new IndexOutOfBoundsException("will attempt index at " + start); - } else if (! reverseOrder && ((start + count) > indexLast)) { + } else if (!reverseOrder && ((start + count) > indexLast)) { throw new IndexOutOfBoundsException("will attempt index at " + (start + count)); } else if (reverseOrder && ((start + 1) < count)) { throw new IndexOutOfBoundsException("will attempt index at " + (start - count)); @@ -469,7 +468,7 @@ public class GlyphProcessingState { } else if (glyphs.length != count) { throw new IllegalArgumentException("glyphs array is non-null, but its length (" + glyphs.length + "), is not equal to count (" + count + ")"); } - if (! reverseOrder) { + if (!reverseOrder) { return getGlyphsForward(start, count, ignoreTester, glyphs, counts); } else { return getGlyphsReverse(start, count, ignoreTester, glyphs, counts); @@ -484,7 +483,7 @@ public class GlyphProcessingState { if (gi == 65535) { ignored++; } else { - if ((ignoreTester == null) || ! ignoreTester.test(gi, getLookupFlags())) { + if ((ignoreTester == null) || !ignoreTester.test(gi, getLookupFlags())) { glyphs [ counted++ ] = gi; } else { ignored++; @@ -506,7 +505,7 @@ public class GlyphProcessingState { if (gi == 65535) { ignored++; } else { - if ((ignoreTester == null) || ! ignoreTester.test(gi, getLookupFlags())) { + if ((ignoreTester == null) || !ignoreTester.test(gi, getLookupFlags())) { glyphs [ counted++ ] = gi; } else { ignored++; @@ -629,7 +628,7 @@ public class GlyphProcessingState { int start = index + offset; if ((start < 0) || (start > indexLast)) { return new int[] { 0, 0 }; - } else if (! reverseOrder) { + } else if (!reverseOrder) { return getGlyphsAvailableForward(start, ignoreTester); } else { return getGlyphsAvailableReverse(start, ignoreTester); @@ -731,7 +730,7 @@ public class GlyphProcessingState { int start = index + offset; if (start < 0) { throw new IndexOutOfBoundsException("will attempt index at " + start); - } else if (! reverseOrder && ((start + count) > indexLast)) { + } else if (!reverseOrder && ((start + count) > indexLast)) { throw new IndexOutOfBoundsException("will attempt index at " + (start + count)); } else if (reverseOrder && ((start + 1) < count)) { throw new IndexOutOfBoundsException("will attempt index at " + (start - count)); @@ -741,7 +740,7 @@ public class GlyphProcessingState { } else if (associations.length != count) { throw new IllegalArgumentException("associations array is non-null, but its length (" + associations.length + "), is not equal to count (" + count + ")"); } - if (! reverseOrder) { + if (!reverseOrder) { return getAssociationsForward(start, count, ignoreTester, associations, counts); } else { return getAssociationsReverse(start, count, ignoreTester, associations, counts); @@ -757,7 +756,7 @@ public class GlyphProcessingState { if (gi == 65535) { ignored++; } else { - if ((ignoreTester == null) || ! ignoreTester.test(gi, getLookupFlags())) { + if ((ignoreTester == null) || !ignoreTester.test(gi, getLookupFlags())) { if (k < count) { associations [ k++ ] = getAssociation(i - index); counted++; @@ -785,7 +784,7 @@ public class GlyphProcessingState { if (gi == 65535) { ignored++; } else { - if ((ignoreTester == null) || ! ignoreTester.test(gi, getLookupFlags())) { + if ((ignoreTester == null) || !ignoreTester.test(gi, getLookupFlags())) { if (k < count) { associations [ k++ ] = getAssociation(i - index); counted++; @@ -1169,7 +1168,7 @@ public class GlyphProcessingState { for (int i = 0, n = ngt; i < n; i++) { GlyphTester gt = gta [ i ]; if (gt != null) { - if (! gt.test(gi, flags)) { + if (!gt.test(gi, flags)) { return false; } } diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionState.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionState.java index 0b599d088..108f26c82 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionState.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionState.java @@ -27,7 +27,6 @@ import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.ScriptContextTester; // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck /** * <p>The <code>GlyphSubstitutionState</code> implements an state object used during glyph substitution @@ -130,7 +129,7 @@ public class GlyphSubstitutionState extends GlyphProcessingState { * @param predication a predication value to add to association A if predications enabled */ public void putGlyph(int glyph, GlyphSequence.CharAssociation a, Object predication) { - if (! ogb.hasRemaining()) { + if (!ogb.hasRemaining()) { ogb = growBuffer(ogb); } ogb.put(glyph); diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionSubtable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionSubtable.java index ebcf35b8d..f4e6fb924 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionSubtable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionSubtable.java @@ -23,7 +23,6 @@ import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.ScriptContextTester; // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck /** * <p>The <code>GlyphSubstitutionSubtable</code> implements an abstract base of a glyph substitution subtable, @@ -90,8 +89,8 @@ public abstract class GlyphSubstitutionSubtable extends GlyphSubtable implements boolean appliedOneShot = false; while (ss.hasNext()) { boolean applied = false; - if (! appliedOneShot && ss.maybeApplicable()) { - for (int i = 0, n = sta.length; ! applied && (i < n); i++) { + if (!appliedOneShot && ss.maybeApplicable()) { + for (int i = 0, n = sta.length; !applied && (i < n); i++) { if (sequenceIndex < 0) { applied = ss.apply(sta [ i ]); } else if (ss.getPosition() == (sequenceStart + sequenceIndex)) { @@ -102,7 +101,7 @@ public abstract class GlyphSubstitutionSubtable extends GlyphSubtable implements } } } - if (! applied || ! ss.didConsume()) { + if (!applied || !ss.didConsume()) { ss.applyDefault(); } ss.next(); diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java index 18aba212c..da708bf45 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java @@ -31,9 +31,7 @@ import org.apache.fop.complexscripts.scripts.ScriptProcessor; import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.GlyphTester; -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck /** * <p>The <code>GlyphSubstitutionTable</code> class is a glyph table that implements @@ -306,7 +304,7 @@ public class GlyphSubstitutionTable extends GlyphTable { Object o = entries.get(0); int delta = 0; if (o instanceof Integer) { - delta = ((Integer) o) . intValue(); + delta = ((Integer) o) .intValue(); } else { throw new AdvancedTypographicTableFormatException("illegal entries entry, must be Integer, but is: " + o); } @@ -440,7 +438,7 @@ public class GlyphSubstitutionTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof int[][])) { + if (((o = entries.get(0)) == null) || !(o instanceof int[][])) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an int[][], but is: " + ((o != null) ? o.getClass() : null)); } else { gsa = (int[][]) o; @@ -801,7 +799,7 @@ public class GlyphSubstitutionTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -894,17 +892,17 @@ public class GlyphSubstitutionTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 3 entries"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphClassTable, but is: " + ((o != null) ? o.getClass() : null)); } else { cdt = (GlyphClassTable) o; } - if (((o = entries.get(1)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(1)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { ngc = ((Integer)(o)).intValue(); } - if (((o = entries.get(2)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(2)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -994,7 +992,7 @@ public class GlyphSubstitutionTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -1113,7 +1111,7 @@ public class GlyphSubstitutionTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -1189,27 +1187,27 @@ public class GlyphSubstitutionTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 5 entries"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(0)) == null) || !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an GlyphClassTable, but is: " + ((o != null) ? o.getClass() : null)); } else { icdt = (GlyphClassTable) o; } - if (((o = entries.get(1)) != null) && ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(1)) != null) && !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, second entry must be an GlyphClassTable, but is: " + o.getClass()); } else { bcdt = (GlyphClassTable) o; } - if (((o = entries.get(2)) != null) && ! (o instanceof GlyphClassTable)) { + if (((o = entries.get(2)) != null) && !(o instanceof GlyphClassTable)) { throw new AdvancedTypographicTableFormatException("illegal entries, third entry must be an GlyphClassTable, but is: " + o.getClass()); } else { lcdt = (GlyphClassTable) o; } - if (((o = entries.get(3)) == null) || ! (o instanceof Integer)) { + if (((o = entries.get(3)) == null) || !(o instanceof Integer)) { throw new AdvancedTypographicTableFormatException("illegal entries, fourth entry must be an Integer, but is: " + ((o != null) ? o.getClass() : null)); } else { ngc = ((Integer)(o)).intValue(); } - if (((o = entries.get(4)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(4)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, fifth entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; @@ -1280,7 +1278,7 @@ public class GlyphSubstitutionTable extends GlyphTable { throw new AdvancedTypographicTableFormatException("illegal entries, " + entries.size() + " entries present, but requires 1 entry"); } else { Object o; - if (((o = entries.get(0)) == null) || ! (o instanceof RuleSet[])) { + if (((o = entries.get(0)) == null) || !(o instanceof RuleSet[])) { throw new AdvancedTypographicTableFormatException("illegal entries, first entry must be an RuleSet[], but is: " + ((o != null) ? o.getClass() : null)); } else { rsa = (RuleSet[]) o; diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java index a3cad4fd7..e5af471af 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java @@ -24,7 +24,6 @@ import java.lang.ref.WeakReference; import java.util.List; import java.util.Map; -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck /** diff --git a/src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java b/src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java index 33f59194b..d130e654a 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java +++ b/src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java @@ -37,12 +37,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.ScriptContextTester; -// CSOFF: EmptyForIteratorPadCheck -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: ParameterNumberCheck -// CSOFF: SimplifyBooleanReturnCheck /** * <p>Base class for all advanced typographic glyph tables.</p> @@ -86,7 +81,7 @@ public class GlyphTable { * @param lookups map from lookup specs to lookup tables */ public GlyphTable(GlyphTable gdef, Map/*<LookupSpec,List<String>>*/ lookups) { - if ((gdef != null) && ! (gdef instanceof GlyphDefinitionTable)) { + if ((gdef != null) && !(gdef instanceof GlyphDefinitionTable)) { throw new AdvancedTypographicTableFormatException("bad glyph definition table"); } else if (lookups == null) { throw new AdvancedTypographicTableFormatException("lookups must be non-null map"); @@ -166,7 +161,7 @@ public class GlyphTable { * create resulting cached state. */ protected void freezeSubtables() { - if (! frozen) { + if (!frozen) { for (Iterator it = lookupTables.values().iterator(); it.hasNext(); ) { LookupTable lt = (LookupTable) it.next(); lt.freezeSubtables(lookupTables); @@ -188,18 +183,18 @@ public class GlyphTable { List/*<LookupSpec>*/ matches = new ArrayList/*<LookupSpec>*/(); for (Iterator it = keys.iterator(); it.hasNext();) { LookupSpec ls = (LookupSpec) it.next(); - if (! "*".equals(script)) { - if (! ls.getScript().equals(script)) { + if (!"*".equals(script)) { + if (!ls.getScript().equals(script)) { continue; } } - if (! "*".equals(language)) { - if (! ls.getLanguage().equals(language)) { + if (!"*".equals(language)) { + if (!ls.getLanguage().equals(language)) { continue; } } - if (! "*".equals(feature)) { - if (! ls.getFeature().equals(feature)) { + if (!"*".equals(feature)) { + if (!ls.getFeature().equals(feature)) { continue; } } @@ -359,17 +354,17 @@ public class GlyphTable { * @param permitWildcard if true the permit wildcard script, language, or feature */ LookupSpec(String script, String language, String feature, boolean permitEmpty, boolean permitWildcard) { - if ((script == null) || (! permitEmpty && (script.length() == 0))) { + if ((script == null) || (!permitEmpty && (script.length() == 0))) { throw new AdvancedTypographicTableFormatException("script must be non-empty string"); - } else if ((language == null) || (! permitEmpty && (language.length() == 0))) { + } else if ((language == null) || (!permitEmpty && (language.length() == 0))) { throw new AdvancedTypographicTableFormatException("language must be non-empty string"); - } else if ((feature == null) || (! permitEmpty && (feature.length() == 0))) { + } else if ((feature == null) || (!permitEmpty && (feature.length() == 0))) { throw new AdvancedTypographicTableFormatException("feature must be non-empty string"); - } else if (! permitWildcard && script.equals("*")) { + } else if (!permitWildcard && script.equals("*")) { throw new AdvancedTypographicTableFormatException("script must not be wildcard"); - } else if (! permitWildcard && language.equals("*")) { + } else if (!permitWildcard && language.equals("*")) { throw new AdvancedTypographicTableFormatException("language must not be wildcard"); - } else if (! permitWildcard && feature.equals("*")) { + } else if (!permitWildcard && feature.equals("*")) { throw new AdvancedTypographicTableFormatException("feature must not be wildcard"); } this.script = script.trim(); @@ -405,14 +400,12 @@ public class GlyphTable { public boolean equals(Object o) { if (o instanceof LookupSpec) { LookupSpec l = (LookupSpec) o; - if (! l.script.equals(script)) { + if (!l.script.equals(script)) { return false; - } else if (! l.language.equals(language)) { - return false; - } else if (! l.feature.equals(feature)) { + } else if (!l.language.equals(language)) { return false; } else { - return true; + return l.feature.equals(feature); } } else { return false; @@ -540,7 +533,7 @@ public class GlyphTable { } } // append at end of list - if (! added && (subtable != null)) { + if (!added && (subtable != null)) { subtables.add(subtable); added = true; } @@ -567,7 +560,7 @@ public class GlyphTable { } if (subtables.size() > 0) { GlyphSubtable st = (GlyphSubtable) subtables.get(0); - if (! st.isCompatible(subtable)) { + if (!st.isCompatible(subtable)) { throw new AdvancedTypographicTableFormatException("subtable " + subtable + " is not compatible with subtable " + st); } } @@ -580,7 +573,7 @@ public class GlyphTable { * @param lookupTables map from lookup table identifers, e.g. "lu4", to lookup tables */ public void freezeSubtables(Map/*<String,LookupTable>*/ lookupTables) { - if (! frozen) { + if (!frozen) { GlyphSubtable[] sta = getSubtables(); resolveLookupReferences(sta, lookupTables); this.subtablesArray = sta; @@ -1305,7 +1298,7 @@ public class GlyphTable { Class c = r0.getClass(); for (int i = 1, n = rules.length; i < n; i++) { Rule r = rules[i]; - if ((r != null) && ! c.isInstance(r)) { + if ((r != null) && !c.isInstance(r)) { throw new AdvancedTypographicTableFormatException("rules[" + i + "] is not an instance of " + c.getName()); } } diff --git a/src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java b/src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java index 4fa6c3b62..de083a995 100644 --- a/src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java +++ b/src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java @@ -33,10 +33,6 @@ import org.apache.fop.fonts.truetype.OFDirTabEntry; import org.apache.fop.fonts.truetype.OFTableName; import org.apache.fop.fonts.truetype.OpenFont; -// CSOFF: AvoidNestedBlocksCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: InnerAssignmentCheck -// CSOFF: SimplifyBooleanReturnCheck // CSOFF: LineLengthCheck /** @@ -3791,7 +3787,7 @@ public final class OTFAdvancedTypographicTableReader { } else { boolean first = true; for (int i = 0; i < ia.length; i++) { - if (! first) { + if (!first) { sb.append(' '); } else { first = false; diff --git a/src/java/org/apache/fop/complexscripts/scripts/ArabicScriptProcessor.java b/src/java/org/apache/fop/complexscripts/scripts/ArabicScriptProcessor.java index 1d310b21d..5e68c8763 100644 --- a/src/java/org/apache/fop/complexscripts/scripts/ArabicScriptProcessor.java +++ b/src/java/org/apache/fop/complexscripts/scripts/ArabicScriptProcessor.java @@ -33,10 +33,6 @@ import org.apache.fop.complexscripts.util.GlyphContextTester; import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.ScriptContextTester; -// CSOFF: AvoidNestedBlocksCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: InnerAssignmentCheck -// CSOFF: SimplifyBooleanReturnCheck // CSOFF: LineLengthCheck /** @@ -159,11 +155,11 @@ public class ArabicScriptProcessor extends DefaultScriptProcessor { } else { int s = a.getStart(); int e = a.getEnd(); - if (! hasFinalPrecedingContext(ca, nc, s, e)) { + if (!hasFinalPrecedingContext(ca, nc, s, e)) { return false; } else if (forcesFinalThisContext(ca, nc, s, e)) { return true; - } else if (! hasFinalFollowingContext(ca, nc, s, e)) { + } else if (!hasFinalFollowingContext(ca, nc, s, e)) { return false; } else { return true; @@ -180,9 +176,9 @@ public class ArabicScriptProcessor extends DefaultScriptProcessor { } else { int s = a.getStart(); int e = a.getEnd(); - if (! hasInitialPrecedingContext(ca, nc, s, e)) { + if (!hasInitialPrecedingContext(ca, nc, s, e)) { return false; - } else if (! hasInitialFollowingContext(ca, nc, s, e)) { + } else if (!hasInitialFollowingContext(ca, nc, s, e)) { return false; } else { return true; @@ -211,9 +207,9 @@ public class ArabicScriptProcessor extends DefaultScriptProcessor { } else { int s = a.getStart(); int e = a.getEnd(); - if (! hasLigaturePrecedingContext(ca, nc, s, e)) { + if (!hasLigaturePrecedingContext(ca, nc, s, e)) { return false; - } else if (! hasLigatureFollowingContext(ca, nc, s, e)) { + } else if (!hasLigatureFollowingContext(ca, nc, s, e)) { return false; } else { return true; @@ -230,11 +226,11 @@ public class ArabicScriptProcessor extends DefaultScriptProcessor { } else { int s = a.getStart(); int e = a.getEnd(); - if (! hasMedialPrecedingContext(ca, nc, s, e)) { + if (!hasMedialPrecedingContext(ca, nc, s, e)) { return false; - } else if (! hasMedialThisContext(ca, nc, s, e)) { + } else if (!hasMedialThisContext(ca, nc, s, e)) { return false; - } else if (! hasMedialFollowingContext(ca, nc, s, e)) { + } else if (!hasMedialFollowingContext(ca, nc, s, e)) { return false; } else { return true; diff --git a/src/java/org/apache/fop/complexscripts/scripts/DevanagariScriptProcessor.java b/src/java/org/apache/fop/complexscripts/scripts/DevanagariScriptProcessor.java index 0459863ee..e3843f444 100644 --- a/src/java/org/apache/fop/complexscripts/scripts/DevanagariScriptProcessor.java +++ b/src/java/org/apache/fop/complexscripts/scripts/DevanagariScriptProcessor.java @@ -24,11 +24,6 @@ import org.apache.commons.logging.LogFactory; import org.apache.fop.complexscripts.util.GlyphSequence; -// CSOFF: AvoidNestedBlocksCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: WhitespaceAfter -// CSOFF: InnerAssignmentCheck -// CSOFF: SimplifyBooleanReturnCheck // CSOFF: LineLengthCheck /** @@ -109,7 +104,7 @@ public class DevanagariScriptProcessor extends IndicScriptProcessor { } private static boolean containsHalfConsonant(GlyphSequence gs, int k) { - Boolean half = (Boolean) gs.getAssociation(k) . getPredication("half"); + Boolean half = (Boolean) gs.getAssociation(k) .getPredication("half"); return (half != null) ? half.booleanValue() : false; } @@ -134,7 +129,7 @@ public class DevanagariScriptProcessor extends IndicScriptProcessor { // first candidate target is after first non-half consonant for (int i = 0; i < ng; i++) { if ((i != source) && containsConsonant(gs, i)) { - if (! containsHalfConsonant(gs, i)) { + if (!containsHalfConsonant(gs, i)) { c1 = i + 1; break; } @@ -142,7 +137,7 @@ public class DevanagariScriptProcessor extends IndicScriptProcessor { } // second candidate target is after last non-prebase matra after first candidate or before first syllable or vedic mark for (int i = (c1 >= 0) ? c1 : 0; i < ng; i++) { - if (containsMatra(gs, i) && ! containsPreBaseMatra(gs, i)) { + if (containsMatra(gs, i) && !containsPreBaseMatra(gs, i)) { c2 = i + 1; } else if (containsOtherMark(gs, i)) { c2 = i; @@ -159,7 +154,7 @@ public class DevanagariScriptProcessor extends IndicScriptProcessor { } private static boolean containsReph(GlyphSequence gs, int k) { - Boolean rphf = (Boolean) gs.getAssociation(k) . getPredication("rphf"); + Boolean rphf = (Boolean) gs.getAssociation(k) .getPredication("rphf"); return (rphf != null) ? rphf.booleanValue() : false; } @@ -503,13 +498,13 @@ public class DevanagariScriptProcessor extends IndicScriptProcessor { } } static boolean isC(int c) { - return isType(c,C_C); + return isType(c, C_C); } static boolean isR(int c) { - return isType(c,C_C) && hasR(c); + return isType(c, C_C) && hasR(c); } static boolean isV(int c) { - return isType(c,C_V); + return isType(c, C_V); } static boolean isN(int c) { return c == 0x093C; @@ -518,10 +513,10 @@ public class DevanagariScriptProcessor extends IndicScriptProcessor { return c == 0x094D; } static boolean isM(int c) { - return isType(c,C_M); + return isType(c, C_M); } static boolean isPreM(int c) { - return isType(c,C_M) && hasFlag(c,C_PRE); + return isType(c, C_M) && hasFlag(c, C_PRE); } static boolean isX(int c) { switch (typeOf(c)) { @@ -535,10 +530,10 @@ public class DevanagariScriptProcessor extends IndicScriptProcessor { } } static boolean hasR(int c) { - return hasFlag(c,C_R); + return hasFlag(c, C_R); } static boolean hasN(int c) { - return hasFlag(c,C_N); + return hasFlag(c, C_N); } } diff --git a/src/java/org/apache/fop/complexscripts/scripts/GujaratiScriptProcessor.java b/src/java/org/apache/fop/complexscripts/scripts/GujaratiScriptProcessor.java index dc97e79a8..e4519623e 100644 --- a/src/java/org/apache/fop/complexscripts/scripts/GujaratiScriptProcessor.java +++ b/src/java/org/apache/fop/complexscripts/scripts/GujaratiScriptProcessor.java @@ -24,11 +24,6 @@ import org.apache.commons.logging.LogFactory; import org.apache.fop.complexscripts.util.GlyphSequence; -// CSOFF: AvoidNestedBlocksCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: WhitespaceAfter -// CSOFF: InnerAssignmentCheck -// CSOFF: SimplifyBooleanReturnCheck // CSOFF: LineLengthCheck /** @@ -109,7 +104,7 @@ public class GujaratiScriptProcessor extends IndicScriptProcessor { } private static boolean containsHalfConsonant(GlyphSequence gs, int k) { - Boolean half = (Boolean) gs.getAssociation(k) . getPredication("half"); + Boolean half = (Boolean) gs.getAssociation(k) .getPredication("half"); return (half != null) ? half.booleanValue() : false; } @@ -134,7 +129,7 @@ public class GujaratiScriptProcessor extends IndicScriptProcessor { // first candidate target is after first non-half consonant for (int i = 0; i < ng; i++) { if ((i != source) && containsConsonant(gs, i)) { - if (! containsHalfConsonant(gs, i)) { + if (!containsHalfConsonant(gs, i)) { c1 = i + 1; break; } @@ -142,7 +137,7 @@ public class GujaratiScriptProcessor extends IndicScriptProcessor { } // second candidate target is after last non-prebase matra after first candidate or before first syllable or vedic mark for (int i = (c1 >= 0) ? c1 : 0; i < ng; i++) { - if (containsMatra(gs, i) && ! containsPreBaseMatra(gs, i)) { + if (containsMatra(gs, i) && !containsPreBaseMatra(gs, i)) { c2 = i + 1; } else if (containsOtherMark(gs, i)) { c2 = i; @@ -159,7 +154,7 @@ public class GujaratiScriptProcessor extends IndicScriptProcessor { } private static boolean containsReph(GlyphSequence gs, int k) { - Boolean rphf = (Boolean) gs.getAssociation(k) . getPredication("rphf"); + Boolean rphf = (Boolean) gs.getAssociation(k) .getPredication("rphf"); return (rphf != null) ? rphf.booleanValue() : false; } @@ -503,13 +498,13 @@ public class GujaratiScriptProcessor extends IndicScriptProcessor { } } static boolean isC(int c) { - return isType(c,C_C); + return isType(c, C_C); } static boolean isR(int c) { - return isType(c,C_C) && hasR(c); + return isType(c, C_C) && hasR(c); } static boolean isV(int c) { - return isType(c,C_V); + return isType(c, C_V); } static boolean isN(int c) { return c == 0x0ABC; @@ -518,10 +513,10 @@ public class GujaratiScriptProcessor extends IndicScriptProcessor { return c == 0x0ACD; } static boolean isM(int c) { - return isType(c,C_M); + return isType(c, C_M); } static boolean isPreM(int c) { - return isType(c,C_M) && hasFlag(c,C_PRE); + return isType(c, C_M) && hasFlag(c, C_PRE); } static boolean isX(int c) { switch (typeOf(c)) { @@ -535,10 +530,10 @@ public class GujaratiScriptProcessor extends IndicScriptProcessor { } } static boolean hasR(int c) { - return hasFlag(c,C_R); + return hasFlag(c, C_R); } static boolean hasN(int c) { - return hasFlag(c,C_N); + return hasFlag(c, C_N); } } diff --git a/src/java/org/apache/fop/complexscripts/scripts/GurmukhiScriptProcessor.java b/src/java/org/apache/fop/complexscripts/scripts/GurmukhiScriptProcessor.java index 262d56864..9c4d49f59 100644 --- a/src/java/org/apache/fop/complexscripts/scripts/GurmukhiScriptProcessor.java +++ b/src/java/org/apache/fop/complexscripts/scripts/GurmukhiScriptProcessor.java @@ -25,11 +25,6 @@ import org.apache.commons.logging.LogFactory; import org.apache.fop.complexscripts.fonts.GlyphDefinitionTable; import org.apache.fop.complexscripts.util.GlyphSequence; -// CSOFF: AvoidNestedBlocksCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: WhitespaceAfter -// CSOFF: InnerAssignmentCheck -// CSOFF: SimplifyBooleanReturnCheck // CSOFF: LineLengthCheck /** @@ -110,7 +105,7 @@ public class GurmukhiScriptProcessor extends IndicScriptProcessor { } private static boolean containsHalfConsonant(GlyphSequence gs, int k) { - Boolean half = (Boolean) gs.getAssociation(k) . getPredication("half"); + Boolean half = (Boolean) gs.getAssociation(k) .getPredication("half"); return (half != null) ? half.booleanValue() : false; } @@ -135,7 +130,7 @@ public class GurmukhiScriptProcessor extends IndicScriptProcessor { // first candidate target is after first non-half consonant for (int i = 0; i < ng; i++) { if ((i != source) && containsConsonant(gs, i)) { - if (! containsHalfConsonant(gs, i)) { + if (!containsHalfConsonant(gs, i)) { c1 = i + 1; break; } @@ -143,7 +138,7 @@ public class GurmukhiScriptProcessor extends IndicScriptProcessor { } // second candidate target is after last non-prebase matra after first candidate or before first syllable or vedic mark for (int i = (c1 >= 0) ? c1 : 0; i < ng; i++) { - if (containsMatra(gs, i) && ! containsPreBaseMatra(gs, i)) { + if (containsMatra(gs, i) && !containsPreBaseMatra(gs, i)) { c2 = i + 1; } else if (containsOtherMark(gs, i)) { c2 = i; @@ -160,7 +155,7 @@ public class GurmukhiScriptProcessor extends IndicScriptProcessor { } private static boolean containsReph(GlyphSequence gs, int k) { - Boolean rphf = (Boolean) gs.getAssociation(k) . getPredication("rphf"); + Boolean rphf = (Boolean) gs.getAssociation(k) .getPredication("rphf"); return (rphf != null) ? rphf.booleanValue() : false; } @@ -504,13 +499,13 @@ public class GurmukhiScriptProcessor extends IndicScriptProcessor { } } static boolean isC(int c) { - return isType(c,C_C); + return isType(c, C_C); } static boolean isR(int c) { - return isType(c,C_C) && hasR(c); + return isType(c, C_C) && hasR(c); } static boolean isV(int c) { - return isType(c,C_V); + return isType(c, C_V); } static boolean isN(int c) { return c == 0x0A3C; @@ -519,10 +514,10 @@ public class GurmukhiScriptProcessor extends IndicScriptProcessor { return c == 0x0A4D; } static boolean isM(int c) { - return isType(c,C_M); + return isType(c, C_M); } static boolean isPreM(int c) { - return isType(c,C_M) && hasFlag(c,C_PRE); + return isType(c, C_M) && hasFlag(c, C_PRE); } static boolean isX(int c) { switch (typeOf(c)) { @@ -536,10 +531,10 @@ public class GurmukhiScriptProcessor extends IndicScriptProcessor { } } static boolean hasR(int c) { - return hasFlag(c,C_R); + return hasFlag(c, C_R); } static boolean hasN(int c) { - return hasFlag(c,C_N); + return hasFlag(c, C_N); } @Override diff --git a/src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java b/src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java index c16c9fe0c..fcabad396 100644 --- a/src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java +++ b/src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java @@ -36,13 +36,6 @@ import org.apache.fop.complexscripts.util.GlyphContextTester; import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.ScriptContextTester; -// CSOFF: AvoidNestedBlocksCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: InnerAssignmentCheck -// CSOFF: SimplifyBooleanReturnCheck -// CSOFF: EmptyForIteratorPadCheck -// CSOFF: WhitespaceAfterCheck -// CSOFF: ParameterNumberCheck // CSOFF: LineLengthCheck /** @@ -222,7 +215,7 @@ public class IndicScriptProcessor extends DefaultScriptProcessor { } private GlyphSequence[] syllabize(GlyphSequence gs, String script, String language) { - return Syllabizer.getSyllabizer(script, language, getSyllabizerClass()) . syllabize(gs); + return Syllabizer.getSyllabizer(script, language, getSyllabizerClass()) .syllabize(gs); } private GlyphSequence unsyllabize(GlyphSequence gs, GlyphSequence[] sa) { @@ -384,12 +377,10 @@ public class IndicScriptProcessor extends DefaultScriptProcessor { public boolean equals(Object o) { if (o instanceof Syllabizer) { Syllabizer s = (Syllabizer) o; - if (! s.script.equals(script)) { - return false; - } else if (! s.language.equals(language)) { + if (!s.script.equals(script)) { return false; } else { - return true; + return s.language.equals(language); } } else { return false; @@ -408,7 +399,7 @@ public class IndicScriptProcessor extends DefaultScriptProcessor { } return d; } - private static Map<String,Syllabizer> syllabizers = new HashMap<String,Syllabizer>(); + private static Map<String, Syllabizer> syllabizers = new HashMap<String, Syllabizer>(); static Syllabizer getSyllabizer(String script, String language, Class<? extends Syllabizer> syllabizerClass) { String sid = makeSyllabizerId(script, language); Syllabizer s = syllabizers.get(sid); diff --git a/src/java/org/apache/fop/complexscripts/scripts/ScriptProcessor.java b/src/java/org/apache/fop/complexscripts/scripts/ScriptProcessor.java index 72d092b12..cfcc4ff59 100644 --- a/src/java/org/apache/fop/complexscripts/scripts/ScriptProcessor.java +++ b/src/java/org/apache/fop/complexscripts/scripts/ScriptProcessor.java @@ -31,11 +31,7 @@ import org.apache.fop.complexscripts.util.CharScript; import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.ScriptContextTester; -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: ParameterNumberCheck -// CSOFF: SimplifyBooleanReturnCheck /** * <p>Abstract script processor base class for which an implementation of the substitution and positioning methods @@ -278,14 +274,12 @@ public abstract class ScriptProcessor { public boolean equals(Object o) { if (o instanceof AssembledLookupsKey) { AssembledLookupsKey k = (AssembledLookupsKey) o; - if (! table.equals(k.table)) { + if (!table.equals(k.table)) { return false; - } else if (! Arrays.equals(features, k.features)) { - return false; - } else if (! lookups.equals(k.lookups)) { + } else if (!Arrays.equals(features, k.features)) { return false; } else { - return true; + return lookups.equals(k.lookups); } } else { return false; diff --git a/src/java/org/apache/fop/complexscripts/util/CharScript.java b/src/java/org/apache/fop/complexscripts/util/CharScript.java index e81313aef..6809be609 100644 --- a/src/java/org/apache/fop/complexscripts/util/CharScript.java +++ b/src/java/org/apache/fop/complexscripts/util/CharScript.java @@ -28,12 +28,6 @@ import java.util.Set; import org.apache.fop.util.CharUtilities; -// CSOFF: AvoidNestedBlocksCheck -// CSOFF: InnerAssignmentCheck -// CSOFF: LineLengthCheck -// CSOFF: SimplifyBooleanReturnCheck -// CSOFF: WhitespaceAfterCheck - /** * <p>Script related utilities.</p> * @@ -41,6 +35,8 @@ import org.apache.fop.util.CharUtilities; */ public final class CharScript { + // CSOFF: LineLength + // // The following script codes are based on ISO 15924. Codes less than 1000 are // official assignments from 15924; those equal to or greater than 1000 are FOP @@ -754,16 +750,14 @@ public final class CharScript { case SCRIPT_UNCODED: break; default: - { - Integer v = (Integer) e.getValue(); - assert v != null; - int c = v.intValue(); - if (c > cMax) { - cMax = c; - sMax = s; - } - break; + Integer v = (Integer) e.getValue(); + assert v != null; + int c = v.intValue(); + if (c > cMax) { + cMax = c; + sMax = s; } + break; } } if (sMax < 0) { @@ -823,7 +817,7 @@ public final class CharScript { * @return a script tag */ public static String scriptTagFromCode(int code) { - Map<Integer,String> m = getScriptTagsMap(); + Map<Integer, String> m = getScriptTagsMap(); if (m != null) { String tag; if ((tag = m.get(Integer.valueOf(code))) != null) { @@ -842,7 +836,7 @@ public final class CharScript { * @return a script code */ public static int scriptCodeFromTag(String tag) { - Map<String,Integer> m = getScriptCodeMap(); + Map<String, Integer> m = getScriptCodeMap(); if (m != null) { Integer c; if ((c = m.get(tag)) != null) { @@ -855,8 +849,8 @@ public final class CharScript { } } - private static Map<Integer,String> scriptTagsMap = null; - private static Map<String,Integer> scriptCodeMap = null; + private static Map<Integer, String> scriptTagsMap = null; + private static Map<String, Integer> scriptCodeMap = null; private static void putScriptTag(Map tm, Map cm, int code, String tag) { assert tag != null; @@ -868,8 +862,8 @@ public final class CharScript { } private static void makeScriptMaps() { - HashMap<Integer,String> tm = new HashMap<Integer,String>(); - HashMap<String,Integer> cm = new HashMap<String,Integer>(); + HashMap<Integer, String> tm = new HashMap<Integer, String>(); + HashMap<String, Integer> cm = new HashMap<String, Integer>(); putScriptTag(tm, cm, SCRIPT_HEBREW, "hebr"); putScriptTag(tm, cm, SCRIPT_MONGOLIAN, "mong"); putScriptTag(tm, cm, SCRIPT_ARABIC, "arab"); @@ -915,14 +909,14 @@ public final class CharScript { scriptCodeMap = cm; } - private static Map<Integer,String> getScriptTagsMap() { + private static Map<Integer, String> getScriptTagsMap() { if (scriptTagsMap == null) { makeScriptMaps(); } return scriptTagsMap; } - private static Map<String,Integer> getScriptCodeMap() { + private static Map<String, Integer> getScriptCodeMap() { if (scriptCodeMap == null) { makeScriptMaps(); } diff --git a/src/java/org/apache/fop/complexscripts/util/GlyphSequence.java b/src/java/org/apache/fop/complexscripts/util/GlyphSequence.java index 696d2c8d3..e59dc9b32 100644 --- a/src/java/org/apache/fop/complexscripts/util/GlyphSequence.java +++ b/src/java/org/apache/fop/complexscripts/util/GlyphSequence.java @@ -26,10 +26,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck -// CSOFF: WhitespaceAfterCheck -// CSOFF: NoWhitespaceAfterCheck /** * <p>A GlyphSequence encapsulates a sequence of character codes, a sequence of glyph codes, @@ -639,10 +636,10 @@ public class GlyphSequence implements Cloneable { private final int offset; private final int count; private final int[] subIntervals; - private Map<String,Object> predications; + private Map<String, Object> predications; // class state - private static volatile Map<String,PredicationMerger> predicationMergers; + private static volatile Map<String, PredicationMerger> predicationMergers; interface PredicationMerger { Object merge(String key, Object v1, Object v2); @@ -724,7 +721,7 @@ public class GlyphSequence implements Cloneable { public boolean contained(int offset, int count) { int s = offset; int e = offset + count; - if (! isDisjoint()) { + if (!isDisjoint()) { int s0 = getStart(); int e0 = getEnd(); return (s0 >= s) && (e0 <= e); @@ -748,7 +745,7 @@ public class GlyphSequence implements Cloneable { */ public void setPredication(String key, Object value) { if (predications == null) { - predications = new HashMap<String,Object>(); + predications = new HashMap<String, Object>(); } if (predications != null) { predications.put(key, value); @@ -775,7 +772,7 @@ public class GlyphSequence implements Cloneable { */ public void mergePredication(String key, Object value) { if (predications == null) { - predications = new HashMap<String,Object>(); + predications = new HashMap<String, Object>(); } if (predications != null) { if (predications.containsKey(key)) { @@ -813,7 +810,7 @@ public class GlyphSequence implements Cloneable { */ public void mergePredications(CharAssociation ca) { if (ca.predications != null) { - for (Map.Entry<String,Object> e : ca.predications.entrySet()) { + for (Map.Entry<String, Object> e : ca.predications.entrySet()) { mergePredication(e.getKey(), e.getValue()); } } @@ -824,7 +821,7 @@ public class GlyphSequence implements Cloneable { try { CharAssociation ca = (CharAssociation) super.clone(); if (predications != null) { - ca.predications = new HashMap<String,Object>(predications); + ca.predications = new HashMap<String, Object>(predications); } return ca; } catch (CloneNotSupportedException e) { @@ -839,7 +836,7 @@ public class GlyphSequence implements Cloneable { */ public static void setPredicationMerger(String key, PredicationMerger pm) { if (predicationMergers == null) { - predicationMergers = new HashMap<String,PredicationMerger>(); + predicationMergers = new HashMap<String, PredicationMerger>(); } if (predicationMergers != null) { predicationMergers.put(key, pm); diff --git a/src/java/org/apache/fop/complexscripts/util/NumberConverter.java b/src/java/org/apache/fop/complexscripts/util/NumberConverter.java index 08b4a4434..bfb8b6571 100644 --- a/src/java/org/apache/fop/complexscripts/util/NumberConverter.java +++ b/src/java/org/apache/fop/complexscripts/util/NumberConverter.java @@ -23,9 +23,6 @@ import java.util.ArrayList; import java.util.List; // CSOFF: LineLengthCheck -// CSOFF: InnerAssignmentCheck -// CSOFF: NoWhitespaceAfterCheck -// CSOFF: AvoidNestedBlocksCheck /** * <p>Implementation of Number to String Conversion algorithm specified by @@ -186,10 +183,10 @@ public class NumberConverter { separators.add(token.toArray(new Integer [ token.size() ])); } } - if (! separators.isEmpty()) { + if (!separators.isEmpty()) { this.prefix = separators.remove(0); } - if (! separators.isEmpty()) { + if (!separators.isEmpty()) { this.suffix = separators.remove(separators.size() - 1); } this.separators = separators.toArray(new Integer [ separators.size() ] []); @@ -260,33 +257,27 @@ public class NumberConverter { int s = token[0].intValue(); switch (s) { case (int) '1': - { - fn = formatNumberAsDecimal(number, (int) '1', 1); - break; - } + fn = formatNumberAsDecimal(number, (int) '1', 1); + break; case (int) 'W': case (int) 'w': - { - fn = formatNumberAsWord(number, (s == (int) 'W') ? Character.UPPERCASE_LETTER : Character.LOWERCASE_LETTER); - break; - } + fn = formatNumberAsWord(number, (s == (int) 'W') ? Character.UPPERCASE_LETTER : Character.LOWERCASE_LETTER); + break; case (int) 'A': // handled as numeric sequence case (int) 'a': // handled as numeric sequence case (int) 'I': // handled as numeric special case (int) 'i': // handled as numeric special default: - { - if (isStartOfDecimalSequence(s)) { - fn = formatNumberAsDecimal(number, s, 1); - } else if (isStartOfAlphabeticSequence(s)) { - fn = formatNumberAsSequence(number, s, getSequenceBase(s), null); - } else if (isStartOfNumericSpecial(s)) { - fn = formatNumberAsSpecial(number, s); - } else { - fn = null; - } - break; + if (isStartOfDecimalSequence(s)) { + fn = formatNumberAsDecimal(number, s, 1); + } else if (isStartOfAlphabeticSequence(s)) { + fn = formatNumberAsSequence(number, s, getSequenceBase(s), null); + } else if (isStartOfNumericSpecial(s)) { + fn = formatNumberAsSpecial(number, s); + } else { + fn = null; } + break; } } else if ((token.length == 2) && (token[0] == (int) 'W') && (token[1] == (int) 'w')) { fn = formatNumberAsWord(number, Character.TITLECASE_LETTER); diff --git a/src/java/org/apache/fop/complexscripts/util/UTF32.java b/src/java/org/apache/fop/complexscripts/util/UTF32.java index 225966f54..b0f92eb88 100644 --- a/src/java/org/apache/fop/complexscripts/util/UTF32.java +++ b/src/java/org/apache/fop/complexscripts/util/UTF32.java @@ -21,7 +21,6 @@ package org.apache.fop.complexscripts.util; import org.apache.fop.util.CharUtilities; -// CSOFF: InnerAssignmentCheck /** * <p>UTF32 related utilities.</p> diff --git a/src/java/org/apache/fop/fo/Constants.java b/src/java/org/apache/fop/fo/Constants.java index 28f02a762..086cbca40 100644 --- a/src/java/org/apache/fop/fo/Constants.java +++ b/src/java/org/apache/fop/fo/Constants.java @@ -816,8 +816,11 @@ public interface Constants { /** Scope for table header */ int PR_X_HEADER_COLUMN = 290; + /** For specifying PDF optional content group (layer) binding. */ + int PR_X_LAYER = 291; + /** Number of property constants defined */ - int PROPERTY_COUNT = 290; + int PROPERTY_COUNT = 291; // compound property constants diff --git a/src/java/org/apache/fop/fo/FOPropertyMapping.java b/src/java/org/apache/fop/fo/FOPropertyMapping.java index 36e3f21c4..cc4fe9e2c 100644 --- a/src/java/org/apache/fop/fo/FOPropertyMapping.java +++ b/src/java/org/apache/fop/fo/FOPropertyMapping.java @@ -2721,6 +2721,13 @@ public final class FOPropertyMapping implements Constants { m.addEnum("auto", getEnumProperty(EN_AUTO, "AUTO")); m.setDefault("auto"); addPropertyMaker("z-index", m); + + // fox:layer + m = new StringProperty.Maker(PR_X_LAYER); + m.setInherited(false); + m.setDefault(""); + addPropertyMaker("fox:layer", m); + } private void createShorthandProperties() { diff --git a/src/java/org/apache/fop/fo/FObj.java b/src/java/org/apache/fop/fo/FObj.java index 92dc9fd73..8532b27da 100644 --- a/src/java/org/apache/fop/fo/FObj.java +++ b/src/java/org/apache/fop/fo/FObj.java @@ -74,7 +74,8 @@ public abstract class FObj extends FONode implements Constants { private int bidiLevel = -1; // The value of properties relevant for all fo objects - private String id = null; + private String id; + private String layer; // End of property values /** @@ -148,7 +149,7 @@ public abstract class FObj extends FONode implements Constants { String attributeName = attList.getQName(i); String attributeValue = attList.getValue(i); Property prop = propertyList.getPropertyForAttribute(attList, attributeName, attributeValue); - if (prop.equals(value)) { + if (prop != null && prop.equals(value)) { return attributeName; } } @@ -173,6 +174,7 @@ public abstract class FObj extends FONode implements Constants { */ public void bind(PropertyList pList) throws FOPException { id = pList.get(PR_ID).getString(); + layer = pList.get(PR_X_LAYER).getString(); } /** @@ -583,6 +585,16 @@ public abstract class FObj extends FONode implements Constants { return (id != null && id.length() > 0); } + /** @return the "layer" property. */ + public String getLayer() { + return layer; + } + + /** @return whether this object has an layer set */ + public boolean hasLayer() { + return (layer != null && layer.length() > 0); + } + /** {@inheritDoc} */ public String getNamespaceURI() { return FOElementMapping.URI; @@ -611,7 +623,7 @@ public abstract class FObj extends FONode implements Constants { if (bidiLevel >= 0) { if ((this.bidiLevel < 0) || (bidiLevel < this.bidiLevel)) { this.bidiLevel = bidiLevel; - if (parent != null) { + if ((parent != null) && !isBidiPropagationBoundary()) { FObj foParent = (FObj) parent; int parentBidiLevel = foParent.getBidiLevel(); if ((parentBidiLevel < 0) || (bidiLevel < parentBidiLevel)) { @@ -646,10 +658,25 @@ public abstract class FObj extends FONode implements Constants { return level; } } + if (isBidiInheritanceBoundary()) { + break; + } } return -1; } + protected boolean isBidiBoundary(boolean propagate) { + return false; + } + + private boolean isBidiInheritanceBoundary() { + return isBidiBoundary(false); + } + + private boolean isBidiPropagationBoundary() { + return isBidiBoundary(true); + } + /** * Add a new extension attachment to this FObj. * (see org.apache.fop.fo.FONode for details) diff --git a/src/java/org/apache/fop/fo/expr/FunctionBase.java b/src/java/org/apache/fop/fo/expr/FunctionBase.java index 707424b86..e5e346060 100644 --- a/src/java/org/apache/fop/fo/expr/FunctionBase.java +++ b/src/java/org/apache/fop/fo/expr/FunctionBase.java @@ -36,7 +36,8 @@ public abstract class FunctionBase implements Function { /** {@inheritDoc} */ public Property getOptionalArgDefault(int index, PropertyInfo pi) throws PropertyException { if (index >= getOptionalArgsCount()) { - PropertyException e = new PropertyException(new IndexOutOfBoundsException("illegal optional argument index")); + PropertyException e = new PropertyException( + new IndexOutOfBoundsException("illegal optional argument index")); e.setPropertyInfo(pi); throw e; } else { diff --git a/src/java/org/apache/fop/fo/expr/PropertyParser.java b/src/java/org/apache/fop/fo/expr/PropertyParser.java index cac115d6e..26c8f6c1b 100644 --- a/src/java/org/apache/fop/fo/expr/PropertyParser.java +++ b/src/java/org/apache/fop/fo/expr/PropertyParser.java @@ -385,7 +385,8 @@ public final class PropertyParser extends PropertyTokenizer { } int numArgs = args.size(); if (numArgs < numReq) { - throw new PropertyException("Expected " + numReq + " required arguments, but only " + numArgs + " specified"); + throw new PropertyException("Expected " + numReq + " required arguments, but only " + + numArgs + " specified"); } else { for (int i = 0; i < numOpt; i++) { if (args.size() < (numReq + i + 1)) { diff --git a/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java b/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java index 09b47f02a..82db43e59 100644 --- a/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java +++ b/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java @@ -66,6 +66,8 @@ public class ExtensionElementMapping extends ElementMapping { PROPERTY_ATTRIBUTES.add("border-before-end-radius"); PROPERTY_ATTRIBUTES.add("border-after-start-radius"); PROPERTY_ATTRIBUTES.add("border-after-end-radius"); + //Optional content groups (layers) + PROPERTY_ATTRIBUTES.add("layer"); } /** diff --git a/src/java/org/apache/fop/fo/flow/BlockContainer.java b/src/java/org/apache/fop/fo/flow/BlockContainer.java index b8616c1ce..b250a117c 100644 --- a/src/java/org/apache/fop/fo/flow/BlockContainer.java +++ b/src/java/org/apache/fop/fo/flow/BlockContainer.java @@ -98,7 +98,8 @@ public class BlockContainer extends FObj implements BreakPropertySet, WritingMod referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); span = pList.get(PR_SPAN).getEnum(); writingModeTraits = new WritingModeTraits( - WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum())); + WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()), + pList.getExplicit(PR_WRITING_MODE) != null); disableColumnBalancing = pList.get(PR_X_DISABLE_COLUMN_BALANCING).getEnum(); } @@ -280,6 +281,14 @@ public class BlockContainer extends FObj implements BreakPropertySet, WritingMod return writingModeTraits.getWritingMode(); } + /** + * Obtain writing mode explicit indicator. + * @return the writing mode explicit indicator + */ + public boolean getExplicitWritingMode() { + return writingModeTraits.getExplicitWritingMode(); + } + /** {@inheritDoc} */ public String getLocalName() { return "block-container"; @@ -292,5 +301,10 @@ public class BlockContainer extends FObj implements BreakPropertySet, WritingMod public int getNameId() { return FO_BLOCK_CONTAINER; } -} + @Override + protected boolean isBidiBoundary(boolean propagate) { + return getExplicitWritingMode(); + } + +} diff --git a/src/java/org/apache/fop/fo/flow/InlineContainer.java b/src/java/org/apache/fop/fo/flow/InlineContainer.java index bcff3dc72..5c95fa34e 100644 --- a/src/java/org/apache/fop/fo/flow/InlineContainer.java +++ b/src/java/org/apache/fop/fo/flow/InlineContainer.java @@ -87,7 +87,8 @@ public class InlineContainer extends FObj { overflow = pList.get(PR_OVERFLOW).getEnum(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingModeTraits = new WritingModeTraits( - WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum())); + WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()), + pList.getExplicit(PR_WRITING_MODE) != null); } /** @@ -194,6 +195,14 @@ public class InlineContainer extends FObj { return writingModeTraits.getWritingMode(); } + /** + * Obtain writing mode explicit indicator. + * @return the writing mode explicit indicator + */ + public boolean getExplicitWritingMode() { + return writingModeTraits.getExplicitWritingMode(); + } + public Direction getInlineProgressionDirection() { return writingModeTraits.getInlineProgressionDirection(); } @@ -224,4 +233,9 @@ public class InlineContainer extends FObj { return true; } + @Override + protected boolean isBidiBoundary(boolean propagate) { + return getExplicitWritingMode(); + } + } diff --git a/src/java/org/apache/fop/fo/flow/table/Table.java b/src/java/org/apache/fop/fo/flow/table/Table.java index 983954e79..e1252e45e 100644 --- a/src/java/org/apache/fop/fo/flow/table/Table.java +++ b/src/java/org/apache/fop/fo/flow/table/Table.java @@ -139,7 +139,8 @@ public class Table extends TableFObj implements ColumnNumberManagerHolder, Break tableOmitFooterAtBreak = pList.get(PR_TABLE_OMIT_FOOTER_AT_BREAK).getEnum(); tableOmitHeaderAtBreak = pList.get(PR_TABLE_OMIT_HEADER_AT_BREAK).getEnum(); writingModeTraits = new WritingModeTraits( - WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum())); + WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()), + pList.getExplicit(PR_WRITING_MODE) != null); //Bind extension properties widowContentLimit = pList.get(PR_X_WIDOW_CONTENT_LIMIT).getLength(); @@ -554,6 +555,11 @@ public class Table extends TableFObj implements ColumnNumberManagerHolder, Break return writingModeTraits.getWritingMode(); } + /** {@inheritDoc} */ + public boolean getExplicitWritingMode() { + return writingModeTraits.getExplicitWritingMode(); + } + /** @return the "fox:widow-content-limit" extension FO trait */ public Length getWidowContentLimit() { return widowContentLimit; @@ -620,4 +626,9 @@ public class Table extends TableFObj implements ColumnNumberManagerHolder, Break return ranges; } + @Override + protected boolean isBidiBoundary(boolean propagate) { + return getExplicitWritingMode(); + } + } diff --git a/src/java/org/apache/fop/fo/pagination/PageSequence.java b/src/java/org/apache/fop/fo/pagination/PageSequence.java index 368b69f90..ba874d31f 100644 --- a/src/java/org/apache/fop/fo/pagination/PageSequence.java +++ b/src/java/org/apache/fop/fo/pagination/PageSequence.java @@ -96,7 +96,8 @@ public class PageSequence extends AbstractPageSequence implements WritingModeTra masterReference = pList.get(PR_MASTER_REFERENCE).getString(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingModeTraits = new WritingModeTraits( - WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum())); + WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()), + pList.getExplicit(PR_WRITING_MODE) != null); if (masterReference == null || masterReference.equals("")) { missingPropertyError("master-reference"); } @@ -403,6 +404,16 @@ public class PageSequence extends AbstractPageSequence implements WritingModeTra } } + /** + * {@inheritDoc} + */ + public boolean getExplicitWritingMode() { + if (writingModeTraits != null) { + return writingModeTraits.getExplicitWritingMode(); + } else { + return false; + } + } @Override protected Stack collectDelimitedTextRanges(Stack ranges, DelimitedTextRange currentRange) { @@ -423,6 +434,11 @@ public class PageSequence extends AbstractPageSequence implements WritingModeTra return ranges; } + @Override + protected boolean isBidiBoundary(boolean propagate) { + return true; + } + /** * Releases a page-sequence's children after the page-sequence has been fully processed. */ diff --git a/src/java/org/apache/fop/fo/properties/GenericShorthandParser.java b/src/java/org/apache/fop/fo/properties/GenericShorthandParser.java index ac3d4d13a..140b96aac 100644 --- a/src/java/org/apache/fop/fo/properties/GenericShorthandParser.java +++ b/src/java/org/apache/fop/fo/properties/GenericShorthandParser.java @@ -83,13 +83,17 @@ public class GenericShorthandParser implements ShorthandParser { PropertyList propertyList) throws PropertyException { Property prop = null; + String vProperty = ""; // Try each of the stored values in turn Iterator iprop = property.getList().iterator(); while (iprop.hasNext() && prop == null) { Property p = (Property)iprop.next(); + if (p.getNCname() != null) { + vProperty += p.getNCname() + " "; + } prop = maker.convertShorthandProperty(propertyList, p, null); - propertyList.validatePropertyValue(p.getNCname(), prop, property); } + propertyList.validatePropertyValue(vProperty.trim(), prop, property); return prop; } diff --git a/src/java/org/apache/fop/fonts/FontManagerConfigurator.java b/src/java/org/apache/fop/fonts/FontManagerConfigurator.java index fc2ce06a6..72c1684b6 100644 --- a/src/java/org/apache/fop/fonts/FontManagerConfigurator.java +++ b/src/java/org/apache/fop/fonts/FontManagerConfigurator.java @@ -48,20 +48,24 @@ public class FontManagerConfigurator { private final Configuration cfg; - private final URI defaultBaseUri; + private final URI baseURI; + + private final URI fallbackURI; private final ResourceResolver resourceResolver; /** * Main constructor * @param cfg the font manager configuration object - * @param defaultBaseUri the default URI base to use for URI resolution + * @param baseURI the URI against which to resolve relative URIs + * @param fallbackURI the URI to use as a fallback if font-base is unspecified * @param resourceResolver the resource resolver */ - public FontManagerConfigurator(Configuration cfg, URI defaultBaseUri, + public FontManagerConfigurator(Configuration cfg, URI baseURI, URI fallbackURI, ResourceResolver resourceResolver) { this.cfg = cfg; - this.defaultBaseUri = defaultBaseUri; + this.baseURI = baseURI; + this.fallbackURI = fallbackURI; this.resourceResolver = resourceResolver; } @@ -77,13 +81,13 @@ public class FontManagerConfigurator { URI fontBase = InternalResourceResolver.getBaseURI(cfg.getChild("font-base") .getValue(null)); fontManager.setResourceResolver(ResourceResolverFactory.createInternalResourceResolver( - defaultBaseUri.resolve(fontBase), resourceResolver)); + baseURI.resolve(fontBase), resourceResolver)); } catch (URISyntaxException use) { LogUtil.handleException(log, use, true); } } else { fontManager.setResourceResolver(ResourceResolverFactory.createInternalResourceResolver( - defaultBaseUri, resourceResolver)); + fallbackURI, resourceResolver)); } // caching (fonts) if (cfg.getChild("use-cache", false) != null) { diff --git a/src/java/org/apache/fop/fonts/FontTriplet.java b/src/java/org/apache/fop/fonts/FontTriplet.java index 2c1d89088..9392cc8b9 100644 --- a/src/java/org/apache/fop/fonts/FontTriplet.java +++ b/src/java/org/apache/fop/fonts/FontTriplet.java @@ -27,7 +27,8 @@ import java.io.Serializable; */ public class FontTriplet implements Comparable<FontTriplet>, Serializable { - public static final FontTriplet DEFAULT_FONT_TRIPLET = new FontTriplet("any", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL); + public static final FontTriplet DEFAULT_FONT_TRIPLET + = new FontTriplet("any", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL); /** serial version UID */ private static final long serialVersionUID = 1168991106658033508L; diff --git a/src/java/org/apache/fop/fonts/apps/TTFReader.java b/src/java/org/apache/fop/fonts/apps/TTFReader.java index f8c7360a4..f63e2bb07 100644 --- a/src/java/org/apache/fop/fonts/apps/TTFReader.java +++ b/src/java/org/apache/fop/fonts/apps/TTFReader.java @@ -39,7 +39,6 @@ import org.apache.fop.fonts.truetype.FontFileReader; import org.apache.fop.fonts.truetype.OFFontLoader; import org.apache.fop.fonts.truetype.TTFFile; -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck /** diff --git a/src/java/org/apache/fop/fonts/truetype/OTFSubSetFile.java b/src/java/org/apache/fop/fonts/truetype/OTFSubSetFile.java index dbea48216..4d0cce67a 100644 --- a/src/java/org/apache/fop/fonts/truetype/OTFSubSetFile.java +++ b/src/java/org/apache/fop/fonts/truetype/OTFSubSetFile.java @@ -451,7 +451,8 @@ public class OTFSubSetFile extends OTFFile { localUniques = foundLocalUniquesB.get(subsetFDSelect.get(subsetGlyphs.get(gid)).getNewFDIndex()); byte[] data = charStringsIndex.getValue(gid); subsetLocalIndexSubr = fdSubrs.get(subsetFDSelect.get(subsetGlyphs.get(gid)).getNewFDIndex()); - subsetLocalSubrCount = foundLocalUniques.get(subsetFDSelect.get(subsetGlyphs.get(gid)).getNewFDIndex()).size(); + subsetLocalSubrCount = foundLocalUniques.get( + subsetFDSelect.get(subsetGlyphs.get(gid)).getNewFDIndex()).size(); data = readCharStringData(data, subsetLocalSubrCount); subsetCharStringsIndex.add(data); } @@ -561,8 +562,12 @@ public class OTFSubSetFile extends OTFFile { int privateOffset = privateEntry.getOperands().get(1).intValue(); Map<String, DICTEntry> privateDICT = cffReader.getPrivateDict(privateEntry); - int localSubrOffset = privateOffset + privateDICT.get("Subrs").getOperands().get(0).intValue(); - localIndexSubr = cffReader.readIndex(localSubrOffset); + if (privateDICT.get("Subrs") != null) { + int localSubrOffset = privateOffset + privateDICT.get("Subrs").getOperands().get(0).intValue(); + localIndexSubr = cffReader.readIndex(localSubrOffset); + } else { + localIndexSubr = cffReader.readIndex(null); + } } globalIndexSubr = cffReader.getGlobalIndexSubr(); diff --git a/src/java/org/apache/fop/fonts/type1/AFMFile.java b/src/java/org/apache/fop/fonts/type1/AFMFile.java index f6bc3b163..2aa718ea0 100644 --- a/src/java/org/apache/fop/fonts/type1/AFMFile.java +++ b/src/java/org/apache/fop/fonts/type1/AFMFile.java @@ -319,7 +319,7 @@ public class AFMFile { */ public void addCharMetrics(AFMCharMetrics metrics) { String name = metrics.getCharName(); - if (metrics.getUnicodeSequence() == null) { + if (metrics.getUnicodeSequence() == null && name.equals(".notdef")) { //Ignore as no Unicode assignment is possible return; } diff --git a/src/java/org/apache/fop/fonts/type1/Type1FontLoader.java b/src/java/org/apache/fop/fonts/type1/Type1FontLoader.java index 853e23eb5..716faa61e 100644 --- a/src/java/org/apache/fop/fonts/type1/Type1FontLoader.java +++ b/src/java/org/apache/fop/fonts/type1/Type1FontLoader.java @@ -173,7 +173,21 @@ public class Type1FontLoader extends FontLoader { addUnencodedBasedOnAFM(afm); } } else { - if (pfm.getCharSet() >= 0 && pfm.getCharSet() <= 2) { + if (pfm.getCharSet() == 2 && !pfm.getCharSetName().equals("Symbol")) { + int[] table = new int[256]; + String[] charNameMap = new String[256]; + int j = 0; + for (int i = pfm.getFirstChar(); i < pfm.getLastChar(); i++) { + if (j < table.length) { + table[j] = i; + table[j + 1] = i; + j += 2; + } + charNameMap[i] = String.format("x%03o", i); + } + CodePointMapping mapping = new CodePointMapping("custom", table, charNameMap); + singleFont.setEncoding(mapping); + } else if (pfm.getCharSet() >= 0 && pfm.getCharSet() <= 2) { singleFont.setEncoding(pfm.getCharSetName() + "Encoding"); } else { log.warn("The PFM reports an unsupported encoding (" @@ -393,10 +407,7 @@ public class Type1FontLoader extends FontLoader { List<AFMCharMetrics> chars = afm.getCharMetrics(); for (AFMCharMetrics charMetrics : chars) { if (charMetrics.getCharCode() >= 0) { - String u = charMetrics.getUnicodeSequence(); - if (u != null && u.length() == 1) { - mappingCount++; - } + mappingCount++; } } // ...and now build the table. @@ -409,6 +420,10 @@ public class Type1FontLoader extends FontLoader { String unicodes = charMetrics.getUnicodeSequence(); if (unicodes == null) { log.info("No Unicode mapping for glyph: " + charMetrics); + table[idx] = charMetrics.getCharCode(); + idx++; + table[idx] = charMetrics.getCharCode(); + idx++; } else if (unicodes.length() == 1) { table[idx] = charMetrics.getCharCode(); idx++; diff --git a/src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java b/src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java index 3ab267d43..3da6974a6 100644 --- a/src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java @@ -867,6 +867,7 @@ public class BlockContainerLayoutManager extends SpacedBorderedPaddedBlockLayout transferForeignAttributes(viewportBlockArea); TraitSetter.setProducerID(viewportBlockArea, getBlockContainerFO().getId()); + TraitSetter.setLayer(viewportBlockArea, getBlockContainerFO().getLayer()); TraitSetter.addBorders(viewportBlockArea, getBlockContainerFO().getCommonBorderPaddingBackground(), discardBorderBefore, discardBorderAfter, false, false, this); diff --git a/src/java/org/apache/fop/layoutmgr/BlockLayoutManager.java b/src/java/org/apache/fop/layoutmgr/BlockLayoutManager.java index 4129b65bd..d3bdc7b85 100644 --- a/src/java/org/apache/fop/layoutmgr/BlockLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/BlockLayoutManager.java @@ -359,7 +359,7 @@ public class BlockLayoutManager extends SpacedBorderedPaddedBlockLayoutManager curBlockArea.setIPD(super.getContentAreaIPD()); - curBlockArea.setBidiLevel(getBlockFO().getBidiLevel()); + curBlockArea.setBidiLevel(getBlockFO().getBidiLevelRecursive()); TraitSetter.addBreaks(curBlockArea, getBlockFO().getBreakBefore(), getBlockFO().getBreakAfter()); @@ -380,6 +380,7 @@ public class BlockLayoutManager extends SpacedBorderedPaddedBlockLayoutManager getBlockFO().getCommonBorderPaddingBackground(), startIndent, endIndent, this); + TraitSetter.setLayer(curBlockArea, getBlockFO().getLayer()); curBlockArea.setLocale(getBlockFO().getCommonHyphenation().getLocale()); curBlockArea.setLocation(FONode.getLocatorString(getBlockFO().getLocator())); diff --git a/src/java/org/apache/fop/layoutmgr/TraitSetter.java b/src/java/org/apache/fop/layoutmgr/TraitSetter.java index 739d535ca..af40f0681 100644 --- a/src/java/org/apache/fop/layoutmgr/TraitSetter.java +++ b/src/java/org/apache/fop/layoutmgr/TraitSetter.java @@ -617,4 +617,15 @@ public final class TraitSetter { area.addTrait(Trait.PROD_ID, id); } } + + /** + * Sets the optional content group layer as a trait on the area. + * @param area the area to set the traits on + * @param layer the layer ID to set + */ + public static void setLayer(Area area, String layer) { + if (layer != null && layer.length() > 0) { + area.addTrait(Trait.LAYER, layer); + } + } } diff --git a/src/java/org/apache/fop/layoutmgr/inline/InlineLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/InlineLayoutManager.java index dd80db1d1..61dcf45c9 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/InlineLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/InlineLayoutManager.java @@ -213,6 +213,7 @@ public class InlineLayoutManager extends InlineStackingLayoutManager { } if (fobj instanceof Inline || fobj instanceof BasicLink) { TraitSetter.setProducerID(area, fobj.getId()); + TraitSetter.setLayer(area, fobj.getLayer()); } return area; } diff --git a/src/java/org/apache/fop/layoutmgr/list/ListBlockLayoutManager.java b/src/java/org/apache/fop/layoutmgr/list/ListBlockLayoutManager.java index 44a9720a4..062a67b38 100644 --- a/src/java/org/apache/fop/layoutmgr/list/ListBlockLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/list/ListBlockLayoutManager.java @@ -238,6 +238,8 @@ public class ListBlockLayoutManager extends SpacedBorderedPaddedBlockLayoutManag int contentIPD = referenceIPD - getIPIndents(); curBlockArea.setIPD(contentIPD); + curBlockArea.setBidiLevel(getListBlockFO().getBidiLevel()); + setCurrentArea(curBlockArea); } return curBlockArea; diff --git a/src/java/org/apache/fop/layoutmgr/list/ListItemContentLayoutManager.java b/src/java/org/apache/fop/layoutmgr/list/ListItemContentLayoutManager.java index f017da381..b16c9dfc4 100644 --- a/src/java/org/apache/fop/layoutmgr/list/ListItemContentLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/list/ListItemContentLayoutManager.java @@ -181,6 +181,7 @@ public class ListItemContentLayoutManager extends BlockStackingLayoutManager imp //TODO: Check - itemIPD never set? curBlockArea.setIPD(itemIPD); //curBlockArea.setHeight(); + curBlockArea.setBidiLevel(getPartFO().getBidiLevel()); TraitSetter.setProducerID(curBlockArea, getPartFO().getId()); diff --git a/src/java/org/apache/fop/layoutmgr/list/ListItemLayoutManager.java b/src/java/org/apache/fop/layoutmgr/list/ListItemLayoutManager.java index 344f6722b..773506632 100644 --- a/src/java/org/apache/fop/layoutmgr/list/ListItemLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/list/ListItemLayoutManager.java @@ -628,6 +628,8 @@ public class ListItemLayoutManager extends SpacedBorderedPaddedBlockLayoutManage int contentIPD = referenceIPD - getIPIndents(); curBlockArea.setIPD(contentIPD); + curBlockArea.setBidiLevel(fo.getBidiLevel()); + setCurrentArea(curBlockArea); } return curBlockArea; diff --git a/src/java/org/apache/fop/layoutmgr/table/TableAndCaptionLayoutManager.java b/src/java/org/apache/fop/layoutmgr/table/TableAndCaptionLayoutManager.java index 0582a0283..aaa896ce3 100644 --- a/src/java/org/apache/fop/layoutmgr/table/TableAndCaptionLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/table/TableAndCaptionLayoutManager.java @@ -184,6 +184,7 @@ public class TableAndCaptionLayoutManager extends BlockStackingLayoutManager { Area parentArea = parentLayoutManager.getParentArea(curBlockArea); int referenceIPD = parentArea.getIPD(); curBlockArea.setIPD(referenceIPD); + curBlockArea.setBidiLevel(getTableAndCaptionFO().getBidiLevel()); // Get reference IPD from parentArea setCurrentArea(curBlockArea); // ??? for generic operations } diff --git a/src/java/org/apache/fop/layoutmgr/table/TableCaptionLayoutManager.java b/src/java/org/apache/fop/layoutmgr/table/TableCaptionLayoutManager.java index 66f7ad9f2..8823c0fae 100644 --- a/src/java/org/apache/fop/layoutmgr/table/TableCaptionLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/table/TableCaptionLayoutManager.java @@ -180,6 +180,7 @@ public class TableCaptionLayoutManager extends BlockStackingLayoutManager { Area parentArea = parentLayoutManager.getParentArea(curBlockArea); int referenceIPD = parentArea.getIPD(); curBlockArea.setIPD(referenceIPD); + curBlockArea.setBidiLevel(getTableCaptionFO().getBidiLevel()); // Get reference IPD from parentArea setCurrentArea(curBlockArea); // ??? for generic operations } diff --git a/src/java/org/apache/fop/layoutmgr/table/TableCellLayoutManager.java b/src/java/org/apache/fop/layoutmgr/table/TableCellLayoutManager.java index 2122df5ae..b2851c1b0 100644 --- a/src/java/org/apache/fop/layoutmgr/table/TableCellLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/table/TableCellLayoutManager.java @@ -442,12 +442,14 @@ public class TableCellLayoutManager extends BlockStackingLayoutManager Block[][] blocks = new Block[getTableCell().getNumberRowsSpanned()][getTableCell() .getNumberColumnsSpanned()]; GridUnit[] gridUnits = (GridUnit[]) primaryGridUnit.getRows().get(startRow); + int level = getTableCell().getBidiLevelRecursive(); for (int x = 0; x < getTableCell().getNumberColumnsSpanned(); x++) { GridUnit gu = gridUnits[x]; BorderInfo border = gu.getBorderBefore(borderBeforeWhich); int borderWidth = border.getRetainedWidth() / 2; if (borderWidth > 0) { - addBorder(blocks, startRow, x, Trait.BORDER_BEFORE, border, firstOnPage); + addBorder(blocks, startRow, x, Trait.BORDER_BEFORE, border, + firstOnPage, level); adjustYOffset(blocks[startRow][x], -borderWidth); adjustBPD(blocks[startRow][x], -borderWidth); } @@ -458,7 +460,8 @@ public class TableCellLayoutManager extends BlockStackingLayoutManager BorderInfo border = gu.getBorderAfter(borderAfterWhich); int borderWidth = border.getRetainedWidth() / 2; if (borderWidth > 0) { - addBorder(blocks, endRow, x, Trait.BORDER_AFTER, border, lastOnPage); + addBorder(blocks, endRow, x, Trait.BORDER_AFTER, border, + lastOnPage, level); adjustBPD(blocks[endRow][x], -borderWidth); } } @@ -467,7 +470,8 @@ public class TableCellLayoutManager extends BlockStackingLayoutManager BorderInfo border = gridUnits[0].getBorderStart(); int borderWidth = border.getRetainedWidth() / 2; if (borderWidth > 0) { - addBorder(blocks, y, 0, Trait.BORDER_START, border, inFirstColumn); + addBorder(blocks, y, 0, Trait.BORDER_START, border, + inFirstColumn, level); adjustXOffset(blocks[y][0], borderWidth); adjustIPD(blocks[y][0], -borderWidth); } @@ -475,7 +479,7 @@ public class TableCellLayoutManager extends BlockStackingLayoutManager borderWidth = border.getRetainedWidth() / 2; if (borderWidth > 0) { addBorder(blocks, y, gridUnits.length - 1, Trait.BORDER_END, border, - inLastColumn); + inLastColumn, level); adjustIPD(blocks[y][gridUnits.length - 1], -borderWidth); } } @@ -512,10 +516,12 @@ public class TableCellLayoutManager extends BlockStackingLayoutManager if (getTableCell().getDisplayAlign() == EN_CENTER) { Block space = new Block(); space.setBPD((cellBPD - usedBPD) / 2); + space.setBidiLevel(getTableCell().getBidiLevelRecursive()); curBlockArea.addBlock(space); } else if (getTableCell().getDisplayAlign() == EN_AFTER) { Block space = new Block(); space.setBPD(cellBPD - usedBPD); + space.setBidiLevel(getTableCell().getBidiLevelRecursive()); curBlockArea.addBlock(space); } } @@ -591,11 +597,12 @@ public class TableCellLayoutManager extends BlockStackingLayoutManager } private void addBorder(Block[][] blocks, int i, int j, Integer side, BorderInfo border, - boolean outer) { + boolean outer, int level) { if (blocks[i][j] == null) { blocks[i][j] = new Block(); blocks[i][j].addTrait(Trait.IS_REFERENCE_AREA, Boolean.TRUE); blocks[i][j].setPositioning(Block.ABSOLUTE); + blocks[i][j].setBidiLevel(level); } blocks[i][j].addTrait(side, BorderProps.makeRectangular(border.getStyle(), border.getRetainedWidth(), border.getColor(), @@ -630,6 +637,7 @@ public class TableCellLayoutManager extends BlockStackingLayoutManager block.setBPD(bpd); block.setXOffset(xoffset + startIndent - paddingStart); block.setYOffset(yoffset + borderBeforeWidth); + block.setBidiLevel(getTableCell().getBidiLevelRecursive()); return block; } @@ -655,6 +663,7 @@ public class TableCellLayoutManager extends BlockStackingLayoutManager curBlockArea.setXOffset(xoffset + startIndent); curBlockArea.setYOffset(yoffset); curBlockArea.setIPD(cellIPD); + curBlockArea.setBidiLevel(getTableCell().getBidiLevelRecursive()); /*Area parentArea =*/ parentLayoutManager.getParentArea(curBlockArea); // Get reference IPD from parentArea diff --git a/src/java/org/apache/fop/pdf/AbstractPDFStream.java b/src/java/org/apache/fop/pdf/AbstractPDFStream.java index 41eed4885..13bd1bda1 100644 --- a/src/java/org/apache/fop/pdf/AbstractPDFStream.java +++ b/src/java/org/apache/fop/pdf/AbstractPDFStream.java @@ -143,7 +143,7 @@ public abstract class AbstractPDFStream extends PDFObject { */ protected int outputStreamData(StreamCache encodedStream, OutputStream out) throws IOException { int length = 0; - byte[] p = encode("stream\n"); + byte[] p = encode("\nstream\n"); out.write(p); length += p.length; @@ -186,7 +186,7 @@ public abstract class AbstractPDFStream extends PDFObject { throws IOException { int bytesWritten = 0; //Stream header - byte[] buf = encode("stream\n"); + byte[] buf = encode("\nstream\n"); out.write(buf); bytesWritten += buf.length; diff --git a/src/java/org/apache/fop/pdf/PDFDictionary.java b/src/java/org/apache/fop/pdf/PDFDictionary.java index 6bacd31a3..ae0b950fd 100644 --- a/src/java/org/apache/fop/pdf/PDFDictionary.java +++ b/src/java/org/apache/fop/pdf/PDFDictionary.java @@ -131,7 +131,7 @@ public class PDFDictionary extends PDFObject { } else { textBuffer.append('\n'); } - textBuffer.append(">>\n"); + textBuffer.append(">>"); } } diff --git a/src/java/org/apache/fop/pdf/PDFDocument.java b/src/java/org/apache/fop/pdf/PDFDocument.java index ff9f61201..bcd54fcb9 100644 --- a/src/java/org/apache/fop/pdf/PDFDocument.java +++ b/src/java/org/apache/fop/pdf/PDFDocument.java @@ -155,6 +155,12 @@ public class PDFDocument { private List<PDFLaunch> launches = new ArrayList<PDFLaunch>(); + private List<PDFLayer> layers; + + private List<PDFNavigator> navigators; + + private List<PDFNavigatorAction> navigatorActions; + private PDFFactory factory; private FileIDGenerator fileIDGenerator; @@ -477,6 +483,24 @@ public class PDFDocument { if (obj instanceof PDFGoToRemote) { this.gotoremotes.add((PDFGoToRemote) obj); } + if (obj instanceof PDFLayer) { + if (this.layers == null) { + this.layers = new ArrayList<PDFLayer>(); + } + this.layers.add((PDFLayer) obj); + } + if (obj instanceof PDFNavigator) { + if (this.navigators == null) { + this.navigators = new ArrayList<PDFNavigator>(); + } + this.navigators.add((PDFNavigator) obj); + } + if (obj instanceof PDFNavigatorAction) { + if (this.navigatorActions == null) { + this.navigatorActions = new ArrayList<PDFNavigatorAction>(); + } + this.navigatorActions.add((PDFNavigatorAction) obj); + } } /** @@ -890,6 +914,34 @@ public class PDFDocument { } /** + * + */ + public PDFReference resolveExtensionReference(String id) { + if (layers != null) { + for (PDFLayer layer : layers) { + if (layer.hasId(id)) { + return layer.makeReference(); + } + } + } + if (navigators != null) { + for (PDFNavigator navigator : navigators) { + if (navigator.hasId(id)) { + return navigator.makeReference(); + } + } + } + if (navigatorActions != null) { + for (PDFNavigatorAction action : navigatorActions) { + if (action.hasId(id)) { + return action.makeReference(); + } + } + } + return null; + } + + /** * Writes out the entire document * * @param stream the OutputStream to output the document to @@ -1009,7 +1061,7 @@ public class PDFDocument { streamIndirectObjects(trailerObjects, stream); TrailerDictionary trailerDictionary = createTrailerDictionary(); long startxref = trailerOutputHelper.outputCrossReferenceObject(stream, trailerDictionary); - String trailer = "startxref\n" + startxref + "\n%%EOF\n"; + String trailer = "\nstartxref\n" + startxref + "\n%%EOF\n"; stream.write(encode(trailer)); } diff --git a/src/java/org/apache/fop/pdf/PDFFactory.java b/src/java/org/apache/fop/pdf/PDFFactory.java index 631499af1..070630274 100644 --- a/src/java/org/apache/fop/pdf/PDFFactory.java +++ b/src/java/org/apache/fop/pdf/PDFFactory.java @@ -310,12 +310,7 @@ public class PDFFactory { theFunctionDataStream, theFilter); - PDFFunction oldfunc = getDocument().findFunction(function); - if (oldfunc == null) { - getDocument().registerObject(function); - } else { - function = oldfunc; - } + function = registerFunction(function); return (function); } @@ -352,12 +347,7 @@ public class PDFFactory { PDFFunction function = new PDFFunction(theFunctionType, theDomain, theRange, theCZero, theCOne, theInterpolationExponentN); - PDFFunction oldfunc = getDocument().findFunction(function); - if (oldfunc == null) { - getDocument().registerObject(function); - } else { - function = oldfunc; - } + function = registerFunction(function); return (function); } @@ -407,12 +397,7 @@ public class PDFFactory { theRange, theFunctions, theBounds, theEncode); - PDFFunction oldfunc = getDocument().findFunction(function); - if (oldfunc == null) { - getDocument().registerObject(function); - } else { - function = oldfunc; - } + function = registerFunction(function); return (function); } @@ -434,14 +419,23 @@ public class PDFFactory { theRange, theFunctionDataStream); + function = registerFunction(function); + return (function); + + } + + /** + * Registers a function against the document + * @param function The function to register + */ + public PDFFunction registerFunction(PDFFunction function) { PDFFunction oldfunc = getDocument().findFunction(function); if (oldfunc == null) { getDocument().registerObject(function); } else { function = oldfunc; } - return (function); - + return function; } /* ========================= shadings ================================== */ @@ -481,20 +475,7 @@ public class PDFFactory { theBBox, theAntiAlias, theDomain, theMatrix, theFunction); - PDFShading oldshad = getDocument().findShading(shading); - if (oldshad == null) { - getDocument().registerObject(shading); - } else { - shading = oldshad; - } - - // add this shading to resources - if (res != null) { - res.getPDFResources().addShading(shading); - } else { - getDocument().getResources().addShading(shading); - } - + shading = registerShading(res, shading); return (shading); } @@ -534,18 +515,7 @@ public class PDFFactory { theDomain, theFunction, theExtend); - PDFShading oldshad = getDocument().findShading(shading); - if (oldshad == null) { - getDocument().registerObject(shading); - } else { - shading = oldshad; - } - - if (res != null) { - res.getPDFResources().addShading(shading); - } else { - getDocument().getResources().addShading(shading); - } + shading = registerShading(res, shading); return (shading); } @@ -591,18 +561,7 @@ public class PDFFactory { theBitsPerFlag, theDecode, theFunction); - PDFShading oldshad = getDocument().findShading(shading); - if (oldshad == null) { - getDocument().registerObject(shading); - } else { - shading = oldshad; - } - - if (res != null) { - res.getPDFResources().addShading(shading); - } else { - getDocument().getResources().addShading(shading); - } + shading = registerShading(res, shading); return (shading); } @@ -645,6 +604,17 @@ public class PDFFactory { theBitsPerComponent, theDecode, theVerticesPerRow, theFunction); + shading = registerShading(res, shading); + + return (shading); + } + + /** + * Registers a shading object against the document + * @param res The PDF resource context + * @param shading The shading object to be registered + */ + public PDFShading registerShading(PDFResourceContext res, PDFShading shading) { PDFShading oldshad = getDocument().findShading(shading); if (oldshad == null) { getDocument().registerObject(shading); @@ -652,13 +622,13 @@ public class PDFFactory { shading = oldshad; } + // add this shading to resources if (res != null) { res.getPDFResources().addShading(shading); } else { getDocument().getResources().addShading(shading); } - - return (shading); + return shading; } /* ========================= patterns ================================== */ @@ -707,6 +677,22 @@ public class PDFFactory { return (pattern); } + public PDFPattern registerPattern(PDFResourceContext res, PDFPattern pattern) { + PDFPattern oldpatt = getDocument().findPattern(pattern); + if (oldpatt == null) { + getDocument().registerObject(pattern); + } else { + pattern = oldpatt; + } + + if (res != null) { + res.getPDFResources().addPattern(pattern); + } else { + getDocument().getResources().addPattern(pattern); + } + return pattern; + } + /** * Make a smooth shading pattern * @@ -1821,4 +1807,28 @@ public class PDFFactory { return obj; } + public PDFLayer makeLayer(String id) { + PDFLayer layer = new PDFLayer(id); + getDocument().registerObject(layer); + return layer; + } + + public PDFSetOCGStateAction makeSetOCGStateAction(String id) { + PDFSetOCGStateAction action = new PDFSetOCGStateAction(id); + getDocument().registerObject(action); + return action; + } + + public PDFTransitionAction makeTransitionAction(String id) { + PDFTransitionAction action = new PDFTransitionAction(id); + getDocument().registerObject(action); + return action; + } + + public PDFNavigator makeNavigator(String id) { + PDFNavigator navigator = new PDFNavigator(id); + getDocument().registerObject(navigator); + return navigator; + } + } diff --git a/src/java/org/apache/fop/pdf/PDFFunction.java b/src/java/org/apache/fop/pdf/PDFFunction.java index f424569b9..09cbd9708 100644 --- a/src/java/org/apache/fop/pdf/PDFFunction.java +++ b/src/java/org/apache/fop/pdf/PDFFunction.java @@ -22,6 +22,10 @@ package org.apache.fop.pdf; // Java... import java.util.List; +import org.apache.fop.render.shading.Function; +import org.apache.fop.render.shading.FunctionDelegate; +import org.apache.fop.render.shading.FunctionPattern; + /** * class representing a PDF Function. * @@ -33,126 +37,9 @@ import java.util.List; * * All PDF Functions have a FunctionType (0,2,3, or 4), a Domain, and a Range. */ -public class PDFFunction extends PDFObject { - // Guts common to all function types - - /** - * Required: The Type of function (0,2,3,4) default is 0. - */ - protected int functionType = 0; // Default - - /** - * Required: 2 * m Array of Double numbers which are possible inputs to the function - */ - protected List domain = null; - - /** - * Required: 2 * n Array of Double numbers which are possible outputs to the function - */ - protected List range = null; - - /* ********************TYPE 0***************************** */ - // FunctionType 0 specific function guts - - /** - * Required: Array containing the Integer size of the Domain and Range, respectively. - * Note: This is really more like two seperate integers, sizeDomain, and sizeRange, - * but since they're expressed as an array in PDF, my implementation reflects that. - */ - protected List size = null; - - /** - * Required for Type 0: Number of Bits used to represent each sample value. - * Limited to 1,2,4,8,12,16,24, or 32 - */ - protected int bitsPerSample = 1; - - /** - * Optional for Type 0: order of interpolation between samples. - * Limited to linear (1) or cubic (3). Default is 1 - */ - protected int order = 1; - - /** - * Optional for Type 0: A 2 * m array of Doubles which provides a - * linear mapping of input values to the domain. - * - * Required for Type 3: A 2 * k array of Doubles that, taken - * in pairs, map each subset of the domain defined by Domain - * and the Bounds array to the domain of the corresponding function. - * Should be two values per function, usually (0,1), - * as in [0 1 0 1] for 2 functions. - */ - protected List encode = null; - - /** - * Optional for Type 0: A 2 * n array of Doubles which provides - * a linear mapping of sample values to the range. Defaults to Range. - */ - protected List decode = null; - - /** - * Optional For Type 0: A stream of sample values - */ - - /** - * Required For Type 4: Postscript Calculator function - * composed of arithmetic, boolean, and stack operators + boolean constants - */ - protected StringBuffer functionDataStream = null; - - /** - * Required (possibly) For Type 0: A vector of Strings for the - * various filters to be used to decode the stream. - * These are how the string is compressed. Flate, LZW, etc. - */ - protected List filter = null; - /* *************************TYPE 2************************** */ - - /** - * Required For Type 2: An Array of n Doubles defining - * the function result when x=0. Default is [0]. - */ - protected List cZero = null; - - /** - * Required For Type 2: An Array of n Doubles defining - * the function result when x=1. Default is [1]. - */ - protected List cOne = null; +public class PDFFunction extends PDFObject implements Function { - /** - * Required for Type 2: The interpolation exponent. - * Each value x will return n results. - * Must be greater than 0. - */ - protected double interpolationExponentN = 1; - - /* *************************TYPE 3************************** */ - - /** - * Required for Type 3: An vector of PDFFunctions which - * form an array of k single input functions making up - * the stitching function. - */ - protected List functions = null; - - /** - * Optional for Type 3: An array of (k-1) Doubles that, - * in combination with Domain, define the intervals to which - * each function from the Functions array apply. Bounds - * elements must be in order of increasing magnitude, - * and each value must be within the value of Domain. - * k is the number of functions. - * If you pass null, it will output (1/k) in an array of k-1 elements. - * This makes each function responsible for an equal amount of the stitching function. - * It makes the gradient even. - */ - protected List bounds = null; - // See encode above, as it's also part of Type 3 Functions. - - /* *************************TYPE 4************************** */ - // See 'data' above. + private FunctionDelegate delegate; /** * create an complete Function object of Type 0, A Sampled function. @@ -211,26 +98,13 @@ public class PDFFunction extends PDFObject { * @param theFunctionType This is the type of function (0,2,3, or 4). * It should be 0 as this is the constructor for sampled functions. */ - public PDFFunction(int theFunctionType, List theDomain, - List theRange, List theSize, int theBitsPerSample, - int theOrder, List theEncode, List theDecode, - StringBuffer theFunctionDataStream, List theFilter) { - super(); - - this.functionType = 0; // dang well better be 0; - this.size = theSize; - this.bitsPerSample = theBitsPerSample; - this.order = theOrder; // int - this.encode = theEncode; // vector of int - this.decode = theDecode; // vector of int - this.functionDataStream = theFunctionDataStream; - this.filter = theFilter; // vector of Strings - - // the domain and range are actually two dimensional arrays. - // so if there's not an even number of items, bad stuff - // happens. - this.domain = theDomain; - this.range = theRange; + public PDFFunction(int theFunctionType, List<Double> theDomain, + List<Double> theRange, List<Double> theSize, int theBitsPerSample, + int theOrder, List<Double> theEncode, List<Double> theDecode, + StringBuffer theFunctionDataStream, List<String> theFilter) { + delegate = new FunctionDelegate(this, theFunctionType, theDomain, theRange, + theSize, theBitsPerSample, theOrder, theEncode, theDecode, + theFunctionDataStream, theFilter); } /** @@ -260,20 +134,11 @@ public class PDFFunction extends PDFObject { * PDF Spec page 268 * @param theFunctionType The type of the function, which should be 2. */ - public PDFFunction(int theFunctionType, List theDomain, - List theRange, List theCZero, List theCOne, + public PDFFunction(int theFunctionType, List<Double> theDomain, + List<Double> theRange, List<Double> theCZero, List<Double> theCOne, double theInterpolationExponentN) { - super(); - - this.functionType = 2; // dang well better be 2; - - this.cZero = theCZero; - this.cOne = theCOne; - this.interpolationExponentN = theInterpolationExponentN; - - - this.domain = theDomain; - this.range = theRange; + delegate = new FunctionDelegate(this, theFunctionType, theDomain, theRange, + theCZero, theCOne, theInterpolationExponentN); } @@ -312,18 +177,11 @@ public class PDFFunction extends PDFObject { * @param theFunctionType This is the function type. It should be 3, * for a stitching function. */ - public PDFFunction(int theFunctionType, List theDomain, - List theRange, List theFunctions, - List theBounds, List theEncode) { - super(); - - this.functionType = 3; // dang well better be 3; - - this.functions = theFunctions; - this.bounds = theBounds; - this.encode = theEncode; - this.domain = theDomain; - this.range = theRange; + public PDFFunction(int theFunctionType, List<Double> theDomain, + List<Double> theRange, List<Function> theFunctions, + List<Double> theBounds, List<Double> theEncode) { + delegate = new FunctionDelegate(this, theFunctionType, theDomain, theRange, + theFunctions, theBounds, theEncode); } @@ -349,20 +207,12 @@ public class PDFFunction extends PDFObject { * @param theFunctionType The type of function which should be 4, as this is * a Postscript calculator function */ - public PDFFunction(int theFunctionType, List theDomain, - List theRange, StringBuffer theFunctionDataStream) { - super(); - - this.functionType = 4; // dang well better be 4; - this.functionDataStream = theFunctionDataStream; - - this.domain = theDomain; - - this.range = theRange; - + public PDFFunction(int theFunctionType, List<Double> theDomain, + List<Double> theRange, StringBuffer theFunctionDataStream) { + delegate = new FunctionDelegate(this, theFunctionType, theDomain, theRange, + theFunctionDataStream); } - /** * represent as PDF. Whatever the FunctionType is, the correct * representation spits out. The sets of required and optional @@ -375,319 +225,13 @@ public class PDFFunction extends PDFObject { * @return the PDF string. */ public byte[] toPDF() { - int vectorSize = 0; - int numberOfFunctions = 0; - int tempInt = 0; - StringBuffer p = new StringBuffer(256); - p.append("<< \n/FunctionType " + this.functionType + " \n"); - - // FunctionType 0 - if (this.functionType == 0) { - if (this.domain != null) { - // DOMAIN - p.append("/Domain [ "); - vectorSize = this.domain.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.domain.get(tempInt)) - + " "); - } - - p.append("] \n"); - } else { - p.append("/Domain [ 0 1 ] \n"); - } - - // SIZE - if (this.size != null) { - p.append("/Size [ "); - vectorSize = this.size.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.size.get(tempInt)) - + " "); - } - p.append("] \n"); - } - // ENCODE - if (this.encode != null) { - p.append("/Encode [ "); - vectorSize = this.encode.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.encode.get(tempInt)) - + " "); - } - p.append("] \n"); - } else { - p.append("/Encode [ "); - vectorSize = this.functions.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append("0 1 "); - } - p.append("] \n"); - - } - - // BITSPERSAMPLE - p.append("/BitsPerSample " + this.bitsPerSample); - - // ORDER (optional) - if (this.order == 1 || this.order == 3) { - p.append(" \n/Order " + this.order + " \n"); - } - - // RANGE - if (this.range != null) { - p.append("/Range [ "); - vectorSize = this.range.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.range.get(tempInt)) - + " "); - } - - p.append("] \n"); - } - - // DECODE - if (this.decode != null) { - p.append("/Decode [ "); - vectorSize = this.decode.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.decode.get(tempInt)) - + " "); - } - - p.append("] \n"); - } - - // LENGTH - if (this.functionDataStream != null) { - p.append("/Length " + (this.functionDataStream.length() + 1) - + " \n"); - } - - // FILTER? - if (this.filter != null) { // if there's a filter - vectorSize = this.filter.size(); - p.append("/Filter "); - if (vectorSize == 1) { - p.append("/" + ((String)this.filter.get(0)) - + " \n"); - } else { - p.append("[ "); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append("/" + ((String)this.filter.get(0)) - + " "); - } - p.append("] \n"); - } - } - p.append(">>"); - - // stream representing the function - if (this.functionDataStream != null) { - p.append("\nstream\n" + this.functionDataStream - + "\nendstream"); - } - - // end of if FunctionType 0 - - } else if (this.functionType == 2) { - // DOMAIN - if (this.domain != null) { - p.append("/Domain [ "); - vectorSize = this.domain.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.domain.get(tempInt)) - + " "); - } - - p.append("] \n"); - } else { - p.append("/Domain [ 0 1 ] \n"); - } - - - // RANGE - if (this.range != null) { - p.append("/Range [ "); - vectorSize = this.range.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.range.get(tempInt)) - + " "); - } - - p.append("] \n"); - } - - // FunctionType, C0, C1, N are required in PDF - - // C0 - if (this.cZero != null) { - p.append("/C0 [ "); - vectorSize = this.cZero.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.cZero.get(tempInt)) - + " "); - } - p.append("] \n"); - } - - // C1 - if (this.cOne != null) { - p.append("/C1 [ "); - vectorSize = this.cOne.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.cOne.get(tempInt)) - + " "); - } - p.append("] \n"); - } - - // N: The interpolation Exponent - p.append("/N " - + PDFNumber.doubleOut(new Double(this.interpolationExponentN)) - + " \n"); - - p.append(">>"); - - } else if (this.functionType - == 3) { // fix this up when my eyes uncross - // DOMAIN - if (this.domain != null) { - p.append("/Domain [ "); - vectorSize = this.domain.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.domain.get(tempInt)) - + " "); - } - p.append("] \n"); - } else { - p.append("/Domain [ 0 1 ] \n"); - } - - // RANGE - if (this.range != null) { - p.append("/Range [ "); - vectorSize = this.range.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.range.get(tempInt)) - + " "); - } - - p.append("] \n"); - } - - // FUNCTIONS - if (this.functions != null) { - p.append("/Functions [ "); - numberOfFunctions = this.functions.size(); - for (tempInt = 0; tempInt < numberOfFunctions; tempInt++) { - p.append(((PDFFunction)this.functions.get(tempInt)).referencePDF() - + " "); - - } - p.append("] \n"); - } - - - // ENCODE - if (this.encode != null) { - p.append("/Encode [ "); - vectorSize = this.encode.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.encode.get(tempInt)) - + " "); - } - - p.append("] \n"); - } else { - p.append("/Encode [ "); - vectorSize = this.functions.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append("0 1 "); - } - p.append("] \n"); - - } - - - // BOUNDS, required, but can be empty - p.append("/Bounds [ "); - if (this.bounds != null) { - - vectorSize = this.bounds.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.bounds.get(tempInt)) - + " "); - } - - } else { - if (this.functions != null) { - // if there are n functions, - // there must be n-1 bounds. - // so let each function handle an equal portion - // of the whole. e.g. if there are 4, then [ 0.25 0.25 0.25 ] - - String functionsFraction = PDFNumber.doubleOut(new Double(1.0 - / ((double)numberOfFunctions))); - - for (tempInt = 0; tempInt + 1 < numberOfFunctions; - tempInt++) { - - p.append(functionsFraction + " "); - } - functionsFraction = null; // clean reference. - - } - - } - p.append("]\n>>"); - } else if (this.functionType - == 4) { // fix this up when my eyes uncross - // DOMAIN - if (this.domain != null) { - p.append("/Domain [ "); - vectorSize = this.domain.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.domain.get(tempInt)) - + " "); - } - - p.append("] \n"); - } else { - p.append("/Domain [ 0 1 ] \n"); - } - - // RANGE - if (this.range != null) { - p.append("/Range [ "); - vectorSize = this.range.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.range.get(tempInt)) - + " "); - } - - p.append("] \n"); - } - - // LENGTH - if (this.functionDataStream != null) { - p.append("/Length " + (this.functionDataStream.length() + 1) - + " \n"); - } - - p.append(">>"); - - // stream representing the function - if (this.functionDataStream != null) { - p.append("\nstream\n{ " + this.functionDataStream - + " }\nendstream"); - } - - - } + return toByteString(); + } - return encode(p.toString()); + public byte[] toByteString() { + FunctionPattern pattern = new FunctionPattern(this); + return encode(pattern.toWriteableString()); } /** {@inheritDoc} */ @@ -702,96 +246,155 @@ public class PDFFunction extends PDFObject { return false; } PDFFunction func = (PDFFunction)obj; - if (functionType != func.functionType) { + if (delegate.getFunctionType() != func.getFunctionType()) { return false; } - if (bitsPerSample != func.bitsPerSample) { + if (delegate.getBitsPerSample() != func.getBitsPerSample()) { return false; } - if (order != func.order) { + if (delegate.getOrder() != func.getOrder()) { return false; } - if (interpolationExponentN != func.interpolationExponentN) { + if (delegate.getInterpolationExponentN() != func.getInterpolationExponentN()) { return false; } - if (domain != null) { - if (!domain.equals(func.domain)) { + if (delegate.getDomain() != null) { + if (!delegate.getDomain().equals(func.getDomain())) { return false; } - } else if (func.domain != null) { + } else if (func.getDomain() != null) { return false; } - if (range != null) { - if (!range.equals(func.range)) { + if (delegate.getRange() != null) { + if (!delegate.getRange().equals(func.getRange())) { return false; } - } else if (func.range != null) { + } else if (func.getRange() != null) { return false; } - if (size != null) { - if (!size.equals(func.size)) { + if (delegate.getSize() != null) { + if (!delegate.getSize().equals(func.getSize())) { return false; } - } else if (func.size != null) { + } else if (func.getSize() != null) { return false; } - if (encode != null) { - if (!encode.equals(func.encode)) { + if (delegate.getEncode() != null) { + if (!delegate.getEncode().equals(func.getEncode())) { return false; } - } else if (func.encode != null) { + } else if (func.getEncode() != null) { return false; } - if (decode != null) { - if (!decode.equals(func.decode)) { + if (delegate.getDecode() != null) { + if (!delegate.getDecode().equals(func.getDecode())) { return false; } - } else if (func.decode != null) { + } else if (func.getDecode() != null) { return false; } - if (functionDataStream != null) { - if (!functionDataStream.equals(func.functionDataStream)) { + if (delegate.getDataStream() != null) { + if (!delegate.getDataStream().equals(func.getDataStream())) { return false; } - } else if (func.functionDataStream != null) { + } else if (func.getDataStream() != null) { return false; } - if (filter != null) { - if (!filter.equals(func.filter)) { + if (delegate.getFilter() != null) { + if (!delegate.getFilter().equals(func.getFilter())) { return false; } - } else if (func.filter != null) { + } else if (func.getFilter() != null) { return false; } - if (cZero != null) { - if (!cZero.equals(func.cZero)) { + if (delegate.getCZero() != null) { + if (!delegate.getCZero().equals(func.getCZero())) { return false; } - } else if (func.cZero != null) { + } else if (func.getCZero() != null) { return false; } - if (cOne != null) { - if (!cOne.equals(func.cOne)) { + if (delegate.getCOne() != null) { + if (!delegate.getCOne().equals(func.getCOne())) { return false; } - } else if (func.cOne != null) { + } else if (func.getCOne() != null) { return false; } - if (functions != null) { - if (!functions.equals(func.functions)) { + if (delegate.getFunctions() != null) { + if (!delegate.getFunctions().equals(func.getFunctions())) { return false; } - } else if (func.functions != null) { + } else if (func.getFunctions() != null) { return false; } - if (bounds != null) { - if (!bounds.equals(func.bounds)) { + if (delegate.getBounds() != null) { + if (!delegate.getBounds().equals(func.getBounds())) { return false; } - } else if (func.bounds != null) { + } else if (func.getBounds() != null) { return false; } return true; } + public int getFunctionType() { + return delegate.getFunctionType(); + } + + public List<Double> getBounds() { + return delegate.getBounds(); + } + + public List<Double> getDomain() { + return delegate.getDomain(); + } + + public List<Double> getSize() { + return delegate.getSize(); + } + + public List<String> getFilter() { + return delegate.getFilter(); + } + + public List<Double> getEncode() { + return delegate.getEncode(); + } + + public List<Function> getFunctions() { + return delegate.getFunctions(); + } + + public int getBitsPerSample() { + return delegate.getBitsPerSample(); + } + + public double getInterpolationExponentN() { + return delegate.getInterpolationExponentN(); + } + + public int getOrder() { + return delegate.getOrder(); + } + + public List<Double> getRange() { + return delegate.getRange(); + } + + public List<Double> getDecode() { + return delegate.getDecode(); + } + + public StringBuffer getDataStream() { + return delegate.getDataStream(); + } + + public List<Double> getCZero() { + return delegate.getCZero(); + } + + public List<Double> getCOne() { + return delegate.getCOne(); + } } diff --git a/src/java/org/apache/fop/pdf/PDFIdentifiedDictionary.java b/src/java/org/apache/fop/pdf/PDFIdentifiedDictionary.java new file mode 100644 index 000000000..c2d033aec --- /dev/null +++ b/src/java/org/apache/fop/pdf/PDFIdentifiedDictionary.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.pdf; + +/** + * Identified Dictionary. + */ +public class PDFIdentifiedDictionary extends PDFDictionary { + + private final String id; + + public PDFIdentifiedDictionary(String id) { + this.id = id; + } + + public String getId() { + return this.id; + } + + public boolean hasId(String id) { + return (this.id != null) && (id != null) && this.id.equals(id); + } + +} + diff --git a/src/java/org/apache/fop/pdf/PDFLayer.java b/src/java/org/apache/fop/pdf/PDFLayer.java new file mode 100644 index 000000000..f8f434e87 --- /dev/null +++ b/src/java/org/apache/fop/pdf/PDFLayer.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.pdf; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * Optional Content Group Dictionary, which we will call a 'layer'. + */ +public class PDFLayer extends PDFIdentifiedDictionary { + + public abstract static class Resolver { + private boolean resolved; + private PDFLayer layer; + private Object extension; + public Resolver(PDFLayer layer, Object extension) { + this.layer = layer; + this.extension = extension; + } + public PDFLayer getLayer() { + return layer; + } + public Object getExtension() { + return extension; + } + public void resolve() { + if (!resolved) { + performResolution(); + resolved = true; + } + } + protected void performResolution() { + } + } + + private Resolver resolver; + + public PDFLayer(String id) { + super(id); + put("Type", new PDFName("OCG")); + } + + @Override + public int output(OutputStream stream) throws IOException { + if (resolver != null) { + resolver.resolve(); + } + return super.output(stream); + } + + public void setResolver(Resolver resolver) { + this.resolver = resolver; + } + + public void populate(Object name, Object intent, Object usage) { + if (name != null) { + put("Name", name); + } + if (intent != null) { + put("Intent", intent); + } + if (usage != null) { + put("Usage", usage); + } + } + +} + diff --git a/src/java/org/apache/fop/pdf/PDFNavigator.java b/src/java/org/apache/fop/pdf/PDFNavigator.java new file mode 100644 index 000000000..fdb97469b --- /dev/null +++ b/src/java/org/apache/fop/pdf/PDFNavigator.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.pdf; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * Navigation Node Dictionary, which we call a 'navigator'. + * This class is used to for sub-page navigation. + */ +public class PDFNavigator extends PDFIdentifiedDictionary { + + public abstract static class Resolver { + private boolean resolved; + private PDFNavigator navigator; + private Object extension; + public Resolver(PDFNavigator navigator, Object extension) { + this.navigator = navigator; + this.extension = extension; + } + public PDFNavigator getNavigator() { + return navigator; + } + public Object getExtension() { + return extension; + } + public void resolve() { + if (!resolved) { + performResolution(); + resolved = true; + } + } + protected void performResolution() { + } + } + + private Resolver resolver; + + public PDFNavigator(String id) { + super(id); + put("Type", new PDFName("NavNode")); + } + + @Override + public int output(OutputStream stream) throws IOException { + if (resolver != null) { + resolver.resolve(); + } + return super.output(stream); + } + + public void setResolver(Resolver resolver) { + this.resolver = resolver; + } + + public void populate(Object nextAction, Object nextNode, Object prevAction, Object prevNode, Object duration) { + if (nextAction != null) { + put("NA", nextAction); + } + if (nextNode != null) { + put("Next", nextNode); + } + if (prevAction != null) { + put("PA", prevAction); + } + if (prevNode != null) { + put("Prev", prevNode); + } + if (duration != null) { + put("Dur", duration); + } + } + +} + diff --git a/src/java/org/apache/fop/pdf/PDFNavigatorAction.java b/src/java/org/apache/fop/pdf/PDFNavigatorAction.java new file mode 100644 index 000000000..ba32269b5 --- /dev/null +++ b/src/java/org/apache/fop/pdf/PDFNavigatorAction.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.pdf; + +public abstract class PDFNavigatorAction extends PDFIdentifiedDictionary { + + protected PDFNavigatorAction(String id) { + super(id); + } + +} diff --git a/src/java/org/apache/fop/pdf/PDFPaintingState.java b/src/java/org/apache/fop/pdf/PDFPaintingState.java index 29d022f61..f6528a30c 100644 --- a/src/java/org/apache/fop/pdf/PDFPaintingState.java +++ b/src/java/org/apache/fop/pdf/PDFPaintingState.java @@ -44,8 +44,6 @@ import org.apache.fop.util.AbstractPaintingState; * previous state then the necessary values can be overridden. * The current transform behaves differently to other values as the * matrix is combined with the current resolved value. - * It is impossible to optimise the result without analysing the all - * the possible combinations after completing. */ public class PDFPaintingState extends org.apache.fop.util.AbstractPaintingState { @@ -187,6 +185,36 @@ public class PDFPaintingState extends org.apache.fop.util.AbstractPaintingState return newState; } + public void setLayer(String layer) { + getPDFData().setLayer(layer); + } + + public String getLayer() { + return getPDFData().getLayer(); + } + + public boolean getLayerChanged() { + String layerCurrent = getLayer(); + if (layerCurrent == null) { + return false; + } else if (getStateStack().isEmpty()) { + return true; + } else { + for (int i = getStackLevel(); i > 0; --i) { + String layerPrev = ((PDFData) getStateStack().get(i - 1)).getLayer(); + if (layerPrev == null) { + continue; + } else { + // Both current and prior are set, so, if same, then we know layer + // didn't change (and can stop search), otherwise it did change. + return !layerCurrent.equals(layerPrev); + } + } + // Current layer set, but no prior saved layer set, so must have changed. + return true; + } + } + /** {@inheritDoc} */ @Override protected AbstractData instantiateData() { @@ -209,7 +237,7 @@ public class PDFPaintingState extends org.apache.fop.util.AbstractPaintingState AbstractData data = getData(); AbstractData copy = (AbstractData)data.clone(); data.clearTransform(); - getStateStack().add(copy); + getStateStack().push(copy); } private PDFData getPDFData() { diff --git a/src/java/org/apache/fop/pdf/PDFPattern.java b/src/java/org/apache/fop/pdf/PDFPattern.java index b9e042815..df4b0233d 100644 --- a/src/java/org/apache/fop/pdf/PDFPattern.java +++ b/src/java/org/apache/fop/pdf/PDFPattern.java @@ -23,6 +23,9 @@ import java.io.IOException; import java.io.OutputStream; import java.util.List; +import org.apache.fop.render.shading.Pattern; +import org.apache.fop.render.shading.Shading; + /** * class representing a PDF Function. * @@ -33,7 +36,7 @@ import java.util.List; * * All PDF Functions have a FunctionType (0,2,3, or 4), a Domain, and a Range. */ -public class PDFPattern extends PDFPathPaint { +public class PDFPattern extends PDFPathPaint implements Pattern { /** * The resources associated with this pattern @@ -146,13 +149,14 @@ public class PDFPattern extends PDFPathPaint { * @param theExtGState optional: the extended graphics state, if used. * @param theMatrix Optional:List of Doubles that specify the matrix. */ - public PDFPattern(int thePatternType, PDFShading theShading, + public PDFPattern(int thePatternType, Shading theShading, List theXUID, StringBuffer theExtGState, List theMatrix) { super(); this.patternType = 2; // thePatternType; - this.shading = theShading; + assert theShading instanceof PDFShading; + this.shading = (PDFShading)theShading; this.xUID = theXUID; // this isn't really implemented, so it should always be null. // I just don't want to have to add a new parameter once it is implemented. @@ -259,7 +263,7 @@ public class PDFPattern extends PDFPathPaint { vectorSize = this.xUID.size(); p.append("/XUID [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(((Integer)this.xUID.get(tempInt)) + " "); + p.append((this.xUID.get(tempInt)) + " "); } p.append("] \n"); } @@ -290,7 +294,7 @@ public class PDFPattern extends PDFPathPaint { vectorSize = this.xUID.size(); p.append("/XUID [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(((Integer)this.xUID.get(tempInt)) + " "); + p.append((this.xUID.get(tempInt)) + " "); } p.append("] \n"); } diff --git a/src/java/org/apache/fop/pdf/PDFResources.java b/src/java/org/apache/fop/pdf/PDFResources.java index cded7c00a..6d09d5738 100644 --- a/src/java/org/apache/fop/pdf/PDFResources.java +++ b/src/java/org/apache/fop/pdf/PDFResources.java @@ -37,8 +37,8 @@ import org.apache.fop.fonts.base14.ZapfDingbats; /** * Class representing a /Resources object. * - * /Resources object contain a list of references to the fonts for the - * document + * /Resources object contain a list of references to the fonts, patterns, + * shadings, etc., for the document. */ public class PDFResources extends PDFDictionary { @@ -73,6 +73,9 @@ public class PDFResources extends PDFDictionary { /** Map of ICC color spaces (key: ICC profile description) */ protected Map<String, PDFICCBasedColorSpace> iccColorSpaces = new LinkedHashMap<String, PDFICCBasedColorSpace>(); + /** Named properties */ + protected Map<String, PDFReference> properties = new LinkedHashMap<String, PDFReference>(); + /** * create a /Resources object. * @@ -191,6 +194,25 @@ public class PDFResources extends PDFDictionary { return cs; } + /** + * Add a named property. + * + * @param name name of property + * @param property reference to property value + */ + public void addProperty(String name, PDFReference property) { + this.properties.put(name, property); + } + + /** + * Get a named property. + * + * @param name name of property + */ + public PDFReference getProperty(String name) { + return this.properties.get(name); + } + @Override public int output(OutputStream stream) throws IOException { populateDictionary(); @@ -253,6 +275,14 @@ public class PDFResources extends PDFDictionary { } put("ColorSpace", dict); } + + if (!properties.isEmpty()) { + PDFDictionary dict = new PDFDictionary(this); + for (String name : properties.keySet()) { + dict.put(name, properties.get(name)); + } + put("Properties", dict); + } } } diff --git a/src/java/org/apache/fop/pdf/PDFSetOCGStateAction.java b/src/java/org/apache/fop/pdf/PDFSetOCGStateAction.java new file mode 100644 index 000000000..a47c5cd59 --- /dev/null +++ b/src/java/org/apache/fop/pdf/PDFSetOCGStateAction.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.pdf; + +import java.io.IOException; +import java.io.OutputStream; + +public class PDFSetOCGStateAction extends PDFNavigatorAction { + + public abstract static class Resolver { + private boolean resolved; + private PDFSetOCGStateAction action; + private Object extension; + public Resolver(PDFSetOCGStateAction action, Object extension) { + this.action = action; + this.extension = extension; + } + public PDFSetOCGStateAction getAction() { + return action; + } + public Object getExtension() { + return extension; + } + public void resolve() { + if (!resolved) { + performResolution(); + resolved = true; + } + } + protected void performResolution() { + } + } + + private Resolver resolver; + + public PDFSetOCGStateAction(String id) { + super(id); + put("Type", new PDFName("Action")); + put("S", new PDFName("SetOCGState")); + } + + @Override + public int output(OutputStream stream) throws IOException { + if (resolver != null) { + resolver.resolve(); + } + return super.output(stream); + } + + public void setResolver(Resolver resolver) { + this.resolver = resolver; + } + + public void populate(Object state, Object preserveRB, Object nextAction) { + if (state != null) { + put("State", state); + } + if (preserveRB != null) { + put("PreserveRB", preserveRB); + } + if (nextAction != null) { + put("Next", nextAction); + } + } +} diff --git a/src/java/org/apache/fop/pdf/PDFShading.java b/src/java/org/apache/fop/pdf/PDFShading.java index 62012b9b2..3f7b2b4b0 100644 --- a/src/java/org/apache/fop/pdf/PDFShading.java +++ b/src/java/org/apache/fop/pdf/PDFShading.java @@ -22,6 +22,10 @@ package org.apache.fop.pdf; // Java... import java.util.List; +import org.apache.fop.render.shading.Function; +import org.apache.fop.render.shading.Shading; +import org.apache.fop.render.shading.ShadingPattern; + /** * class representing a PDF Smooth Shading object. * @@ -32,7 +36,7 @@ import java.util.List; * * All PDF Functions have a shadingType (0,2,3, or 4), a Domain, and a Range. */ -public class PDFShading extends PDFObject { +public class PDFShading extends PDFObject implements Shading { // Guts common to all function types /** @@ -205,7 +209,7 @@ public class PDFShading extends PDFObject { public PDFShading(int theShadingType, PDFDeviceColorSpace theColorSpace, List theBackground, List theBBox, boolean theAntiAlias, List theCoords, - List theDomain, PDFFunction theFunction, + List theDomain, Function theFunction, List theExtend) { super(); this.shadingType = theShadingType; // 2 or 3 @@ -216,7 +220,8 @@ public class PDFShading extends PDFObject { this.coords = theCoords; this.domain = theDomain; - this.function = theFunction; + assert theFunction instanceof PDFFunction; + this.function = (PDFFunction)theFunction; this.extend = theExtend; } @@ -335,197 +340,8 @@ public class PDFShading extends PDFObject { * @return the PDF string. */ public String toPDFString() { - int vectorSize; - int tempInt; - StringBuffer p = new StringBuffer(128); - p.append("<<\n/ShadingType " + this.shadingType + " \n"); - if (this.colorSpace != null) { - p.append("/ColorSpace /" - + this.colorSpace.getName() + " \n"); - } - - if (this.background != null) { - p.append("/Background [ "); - vectorSize = this.background.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.background.get(tempInt)) - + " "); - } - p.append("] \n"); - } - - if (this.bBox - != null) { // I've never seen an example, so I guess this is right. - p.append("/BBox [ "); - vectorSize = this.bBox.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.bBox.get(tempInt)) - + " "); - } - p.append("] \n"); - } - - if (this.antiAlias) { - p.append("/AntiAlias " + this.antiAlias + " \n"); - } - - // Here's where we differentiate based on what type it is. - if (this.shadingType == 1) { // function based shading - if (this.domain != null) { - p.append("/Domain [ "); - vectorSize = this.domain.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.domain.get(tempInt)) - + " "); - } - p.append("] \n"); - } else { - p.append("/Domain [ 0 1 ] \n"); - } - - if (this.matrix != null) { - p.append("/Matrix [ "); - vectorSize = this.matrix.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.matrix.get(tempInt)) - + " "); - } - p.append("] \n"); - } - - if (this.function != null) { - p.append("/Function "); - p.append(this.function.referencePDF() + " \n"); - } - } else if ((this.shadingType == 2) - || (this.shadingType - == 3)) { // 2 is axial shading (linear gradient) - // 3 is radial shading (circular gradient) - if (this.coords != null) { - p.append("/Coords [ "); - vectorSize = this.coords.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.coords.get(tempInt)) - + " "); - } - p.append("] \n"); - } - - // DOMAIN - if (this.domain != null) { - p.append("/Domain [ "); - vectorSize = this.domain.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(PDFNumber.doubleOut((Double)this.domain.get(tempInt)) - + " "); - } - p.append("] \n"); - } else { - p.append("/Domain [ 0 1 ] \n"); - } - - if (this.extend != null) { - p.append("/Extend [ "); - vectorSize = this.extend.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(((Boolean)this.extend.get(tempInt)) + " "); - } - - p.append("] \n"); - } else { - p.append("/Extend [ true true ] \n"); - } - - - if (this.function != null) { - p.append("/Function "); - p.append(this.function.referencePDF() + " \n"); - } - - - } else if ((this.shadingType == 4) || (this.shadingType == 6) - || (this.shadingType - == 7)) { // 4:Free-form Gouraud-shaded triangle meshes - // 6:coons patch meshes - // 7://tensor product patch meshes (which no one ever uses) - if (this.bitsPerCoordinate > 0) { - p.append("/BitsPerCoordinate " + this.bitsPerCoordinate - + " \n"); - } else { - p.append("/BitsPerCoordinate 1 \n"); - } - - if (this.bitsPerComponent > 0) { - p.append("/BitsPerComponent " + this.bitsPerComponent - + " \n"); - } else { - p.append("/BitsPerComponent 1 \n"); - } - - if (this.bitsPerFlag > 0) { - p.append("/BitsPerFlag " + this.bitsPerFlag + " \n"); - } else { - p.append("/BitsPerFlag 2 \n"); - } - - if (this.decode != null) { - p.append("/Decode [ "); - vectorSize = this.decode.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(((Boolean)this.decode.get(tempInt)) + " "); - } - - p.append("] \n"); - } - - if (this.function != null) { - p.append("/Function "); - p.append(this.function.referencePDF() + " \n"); - } - - } else if (this.shadingType - == 5) { // Lattice Free form gouraud-shaded triangle mesh - - if (this.bitsPerCoordinate > 0) { - p.append("/BitsPerCoordinate " + this.bitsPerCoordinate - + " \n"); - } else { - p.append("/BitsPerCoordinate 1 \n"); - } - - if (this.bitsPerComponent > 0) { - p.append("/BitsPerComponent " + this.bitsPerComponent - + " \n"); - } else { - p.append("/BitsPerComponent 1 \n"); - } - - if (this.decode != null) { - p.append("/Decode [ "); - vectorSize = this.decode.size(); - for (tempInt = 0; tempInt < vectorSize; tempInt++) { - p.append(((Boolean)this.decode.get(tempInt)) + " "); - } - - p.append("] \n"); - } - - if (this.function != null) { - p.append("/Function "); - p.append(this.function.referencePDF() + " \n"); - } - - if (this.verticesPerRow > 0) { - p.append("/VerticesPerRow " + this.verticesPerRow + " \n"); - } else { - p.append("/VerticesPerRow 2 \n"); - } - - } - - p.append(">>"); - - return (p.toString()); + ShadingPattern pattern = new ShadingPattern(this); + return pattern.toString(colorSpace, shadingType, background, bBox, antiAlias); } /** {@inheritDoc} */ @@ -623,4 +439,173 @@ public class PDFShading extends PDFObject { } return true; } + + /** + * A method to write a type 1 shading object + * @param p The StringBuffer to write the shading object + * @return Returns the StringBuffer to which the shading object was written + */ + public StringBuffer handleShadingType1(StringBuffer p) { + if (this.domain != null) { + p.append("/Domain [ "); + for (int domainIndex = 0; domainIndex < domain.size(); domainIndex++) { + p.append(PDFNumber.doubleOut((Double)this.domain.get(domainIndex)) + + " "); + } + p.append("] \n"); + } else { + p.append("/Domain [ 0 1 ] \n"); + } + + if (this.matrix != null) { + p.append("/Matrix [ "); + for (int matrixIndex = 0; matrixIndex < matrix.size(); matrixIndex++) { + p.append(PDFNumber.doubleOut((Double)this.matrix.get(matrixIndex)) + + " "); + } + p.append("] \n"); + } + + if (this.function != null) { + p.append("/Function "); + p.append(this.function.referencePDF() + " \n"); + } + return p; + } + + /** + * A method to write a type 2 or 3 shading object + * @param p The StringBuffer to write the shading object + * @return Returns the StringBuffer to which the shading object was written + */ + public StringBuffer handleShadingType2or3(StringBuffer p) { + // 3 is radial shading (circular gradient) + if (this.coords != null) { + p.append("/Coords [ "); + for (int coordIndex = 0; coordIndex < coords.size(); coordIndex++) { + p.append(PDFNumber.doubleOut((Double)this.coords.get(coordIndex)) + + " "); + } + p.append("] \n"); + } + + // DOMAIN + if (this.domain != null) { + p.append("/Domain [ "); + for (int domainIndex = 0; domainIndex < domain.size(); domainIndex++) { + p.append(PDFNumber.doubleOut((Double)this.domain.get(domainIndex)) + + " "); + } + p.append("] \n"); + } else { + p.append("/Domain [ 0 1 ] \n"); + } + + if (this.extend != null) { + p.append("/Extend [ "); + for (int extendIndex = 0; extendIndex < extend.size(); extendIndex++) { + p.append((this.extend.get(extendIndex)) + " "); + } + + p.append("] \n"); + } else { + p.append("/Extend [ true true ] \n"); + } + + + if (this.function != null) { + p.append("/Function "); + p.append(this.function.referencePDF() + " \n"); + } + + return p; + } + + /** + * A method to write a type 4, 6 or 7 shading object + * @param p The StringBuffer to write the shading object + * @return Returns the StringBuffer to which the shading object was written + */ + public StringBuffer handleShadingType4or6or7(StringBuffer p) { + // 6:coons patch meshes + // 7://tensor product patch meshes (which no one ever uses) + if (this.bitsPerCoordinate > 0) { + p.append("/BitsPerCoordinate " + this.bitsPerCoordinate + + " \n"); + } else { + p.append("/BitsPerCoordinate 1 \n"); + } + + if (this.bitsPerComponent > 0) { + p.append("/BitsPerComponent " + this.bitsPerComponent + + " \n"); + } else { + p.append("/BitsPerComponent 1 \n"); + } + + if (this.bitsPerFlag > 0) { + p.append("/BitsPerFlag " + this.bitsPerFlag + " \n"); + } else { + p.append("/BitsPerFlag 2 \n"); + } + + if (this.decode != null) { + p.append("/Decode [ "); + for (int decodeIndex = 0; decodeIndex < decode.size(); decodeIndex++) { + p.append((this.decode.get(decodeIndex)) + " "); + } + + p.append("] \n"); + } + + if (this.function != null) { + p.append("/Function "); + p.append(this.function.referencePDF() + " \n"); + } + + return p; + } + + /** + * A method to write a type 5 shading object + * @param p The StringBuffer to write the shading object + * @return Returns the StringBuffer to which the shading object was written + */ + public StringBuffer handleShadingType5(StringBuffer p) { + if (this.bitsPerCoordinate > 0) { + p.append("/BitsPerCoordinate " + this.bitsPerCoordinate + + " \n"); + } else { + p.append("/BitsPerCoordinate 1 \n"); + } + + if (this.bitsPerComponent > 0) { + p.append("/BitsPerComponent " + this.bitsPerComponent + + " \n"); + } else { + p.append("/BitsPerComponent 1 \n"); + } + + if (this.decode != null) { + p.append("/Decode [ "); + for (int decodeIndex = 0; decodeIndex < decode.size(); decodeIndex++) { + p.append((this.decode.get(decodeIndex)) + " "); + } + + p.append("] \n"); + } + + if (this.function != null) { + p.append("/Function "); + p.append(this.function.referencePDF() + " \n"); + } + + if (this.verticesPerRow > 0) { + p.append("/VerticesPerRow " + this.verticesPerRow + " \n"); + } else { + p.append("/VerticesPerRow 2 \n"); + } + + return p; + } } diff --git a/src/java/org/apache/fop/pdf/PDFTransitionAction.java b/src/java/org/apache/fop/pdf/PDFTransitionAction.java new file mode 100644 index 000000000..01f8fcf21 --- /dev/null +++ b/src/java/org/apache/fop/pdf/PDFTransitionAction.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.pdf; + +import java.io.IOException; +import java.io.OutputStream; + +public class PDFTransitionAction extends PDFNavigatorAction { + + public abstract static class Resolver { + private boolean resolved; + private PDFTransitionAction action; + private Object extension; + public Resolver(PDFTransitionAction action, Object extension) { + this.action = action; + this.extension = extension; + } + public PDFTransitionAction getAction() { + return action; + } + public Object getExtension() { + return extension; + } + public void resolve() { + if (!resolved) { + performResolution(); + resolved = true; + } + } + protected void performResolution() { + } + } + + private Resolver resolver; + + public PDFTransitionAction(String id) { + super(id); + put("Type", new PDFName("Action")); + put("S", new PDFName("Trans")); + } + + @Override + public int output(OutputStream stream) throws IOException { + if (resolver != null) { + resolver.resolve(); + } + return super.output(stream); + } + + public void setResolver(Resolver resolver) { + this.resolver = resolver; + } + + public void populate(Object transition, Object nextAction) { + if (transition != null) { + put("Trans", transition); + } + if (nextAction != null) { + put("Next", nextAction); + } + } +} diff --git a/src/java/org/apache/fop/render/AbstractRenderer.java b/src/java/org/apache/fop/render/AbstractRenderer.java index e274e5c4b..9a94e0cc6 100644 --- a/src/java/org/apache/fop/render/AbstractRenderer.java +++ b/src/java/org/apache/fop/render/AbstractRenderer.java @@ -28,6 +28,7 @@ import java.io.OutputStream; import java.util.List; import java.util.Locale; import java.util.Set; +import java.util.Stack; import org.w3c.dom.Document; @@ -112,8 +113,12 @@ public abstract class AbstractRenderer /** the currently active PageViewport */ protected PageViewport currentPageViewport; + /* warned XML handlers */ private Set warnedXMLHandlers; + /* layers stack */ + private Stack<String> layers; + /** {@inheritDoc} */ public abstract void setupFontInfo(FontInfo fontInfo) throws FOPException; @@ -471,6 +476,10 @@ public abstract class AbstractRenderer * @param children The children to render within the block viewport */ protected void renderBlockViewport(BlockViewport bv, List children) { + boolean inNewLayer = false; + if (maybeStartLayer(bv)) { + inNewLayer = true; + } // clip and position viewport if necessary if (bv.getPositioning() == Block.ABSOLUTE) { // save positions @@ -506,6 +515,7 @@ public abstract class AbstractRenderer currentIPPosition = saveIP; currentBPPosition = saveBP + bv.getAllocBPD(); } + maybeEndLayer(bv, inNewLayer); } /** @@ -573,6 +583,10 @@ public abstract class AbstractRenderer protected void renderBlock(Block block) { assert block != null; List children = block.getChildAreas(); + boolean inNewLayer = false; + if (maybeStartLayer(block)) { + inNewLayer = true; + } if (block instanceof BlockViewport) { if (children != null) { renderBlockViewport((BlockViewport) block, children); @@ -607,6 +621,45 @@ public abstract class AbstractRenderer currentBPPosition = saveBP + block.getAllocBPD(); } } + maybeEndLayer(block, inNewLayer); + } + + /** + * Establish new optional content group layer. + * @param layer name of layer + */ + protected abstract void startLayer(String layer); + + /** + * Finish current optional content group layer. + */ + protected abstract void endLayer(); + + protected boolean maybeStartLayer(Area area) { + String layer = (String) area.getTrait(Trait.LAYER); + if (layer != null) { + if (layers == null) { + layers = new Stack<String>(); + } + if (layers.empty() || !layers.peek().equals(layer)) { + layers.push(layer); + startLayer(layer); + return true; + } + } + return false; + } + + protected void maybeEndLayer(Area area, boolean inNewLayer) { + if (inNewLayer) { + assert layers != null; + assert !layers.empty(); + String layer = (String) area.getTrait(Trait.LAYER); + assert layer != null; + assert layers.peek().equals(layer); + endLayer(); + layers.pop(); + } } /** @@ -746,6 +799,10 @@ public abstract class AbstractRenderer * @param ip the inline parent to render */ protected void renderInlineParent(InlineParent ip) { + boolean inNewLayer = false; + if (maybeStartLayer(ip)) { + inNewLayer = true; + } int level = ip.getBidiLevel(); List children = ip.getChildAreas(); renderInlineAreaBackAndBorders(ip); @@ -782,6 +839,7 @@ public abstract class AbstractRenderer } currentIPPosition = saveIP + ip.getAllocIPD(); currentBPPosition = saveBP; + maybeEndLayer(ip, inNewLayer); } /** diff --git a/src/java/org/apache/fop/render/afp/AFPFontConfig.java b/src/java/org/apache/fop/render/afp/AFPFontConfig.java index aef0b666c..149973edd 100644 --- a/src/java/org/apache/fop/render/afp/AFPFontConfig.java +++ b/src/java/org/apache/fop/render/afp/AFPFontConfig.java @@ -316,8 +316,8 @@ public final class AFPFontConfig implements FontConfig { private final String characterset; - private CIDKeyedFontConfig(List<FontTriplet> triplets, String type, String codePage, - String encoding, String characterset, String name, CharacterSetType charsetType, boolean embeddable, String uri) { + private CIDKeyedFontConfig(List<FontTriplet> triplets, String type, String codePage, String encoding, + String characterset, String name, CharacterSetType charsetType, boolean embeddable, String uri) { super(triplets, type, codePage, encoding, name, embeddable, uri); this.characterset = characterset; this.charsetType = charsetType; diff --git a/src/java/org/apache/fop/render/afp/AFPPainter.java b/src/java/org/apache/fop/render/afp/AFPPainter.java index 12713bb24..aaa702afa 100644 --- a/src/java/org/apache/fop/render/afp/AFPPainter.java +++ b/src/java/org/apache/fop/render/afp/AFPPainter.java @@ -164,7 +164,7 @@ public class AFPPainter extends AbstractIFPainter<AFPDocumentHandler> { } /** {@inheritDoc} */ - public void startGroup(AffineTransform transform) throws IFException { + public void startGroup(AffineTransform transform, String layer) throws IFException { try { saveGraphicsState(); concatenateTransformationMatrix(transform); diff --git a/src/java/org/apache/fop/render/afp/AFPRendererConfig.java b/src/java/org/apache/fop/render/afp/AFPRendererConfig.java index 90cc6e767..a943f5aad 100644 --- a/src/java/org/apache/fop/render/afp/AFPRendererConfig.java +++ b/src/java/org/apache/fop/render/afp/AFPRendererConfig.java @@ -103,7 +103,8 @@ public final class AFPRendererConfig implements RendererConfig { } } - private final EnumMap<AFPRendererOption, Object> params = new EnumMap<AFPRendererOption, Object>(AFPRendererOption.class); + private final EnumMap<AFPRendererOption, Object> params + = new EnumMap<AFPRendererOption, Object>(AFPRendererOption.class); private final EnumMap<ImagesModeOptions, Object> imageModeParams = new EnumMap<ImagesModeOptions, Object>(ImagesModeOptions.class); diff --git a/src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java b/src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java index 2dd046fa9..f69fe2091 100644 --- a/src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java +++ b/src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java @@ -126,8 +126,8 @@ public abstract class AbstractIFPainter<T extends IFDocumentHandler> implements } /** {@inheritDoc} */ - public void startGroup(AffineTransform[] transforms) throws IFException { - startGroup(combine(transforms)); + public void startGroup(AffineTransform[] transforms, String layer) throws IFException { + startGroup(combine(transforms), layer); } /** diff --git a/src/java/org/apache/fop/render/intermediate/IFGraphicContext.java b/src/java/org/apache/fop/render/intermediate/IFGraphicContext.java index 868615360..c1742be1f 100644 --- a/src/java/org/apache/fop/render/intermediate/IFGraphicContext.java +++ b/src/java/org/apache/fop/render/intermediate/IFGraphicContext.java @@ -89,6 +89,7 @@ public class IFGraphicContext extends GraphicContext { public static class Group { private AffineTransform[] transforms; + private String layer; /** * Construct a Group. @@ -106,6 +107,16 @@ public class IFGraphicContext extends GraphicContext { this(new AffineTransform[] {transform}); } + /** + * Construct a layer Group, i.e., a Group with no transforms + * but with a optional content group layer label. + * @param layer a layer label + */ + public Group(String layer) { + this(); + this.layer = layer; + } + /** Default constructor. */ public Group() { this(EMPTY_TRANSFORM_ARRAY); @@ -116,12 +127,17 @@ public class IFGraphicContext extends GraphicContext { return this.transforms; } + /** @return layer */ + public String getLayer() { + return this.layer; + } + /** * @param painter a painter * @throws IFException in not caught */ public void start(IFPainter painter) throws IFException { - painter.startGroup(transforms); + painter.startGroup(transforms, layer); } /** @@ -136,6 +152,11 @@ public class IFGraphicContext extends GraphicContext { public String toString() { StringBuffer sb = new StringBuffer("group: "); IFUtil.toString(getTransforms(), sb); + if ((layer != null) && (layer.length() > 0)) { + sb.append(" layer("); + sb.append(layer); + sb.append(')'); + } return sb.toString(); } diff --git a/src/java/org/apache/fop/render/intermediate/IFPainter.java b/src/java/org/apache/fop/render/intermediate/IFPainter.java index 599292287..d43b5cb85 100644 --- a/src/java/org/apache/fop/render/intermediate/IFPainter.java +++ b/src/java/org/apache/fop/render/intermediate/IFPainter.java @@ -113,19 +113,21 @@ public interface IFPainter { /** * Starts a new group of graphical elements. Corresponds to SVG's g element. * @param transforms a series of transformation matrices establishing the new coordinate system + * @param layer an optional layer label (or null if none) * @throws IFException if an error occurs while handling this element */ - void startGroup(AffineTransform[] transforms) throws IFException; + void startGroup(AffineTransform[] transforms, String layer) throws IFException; /** * Starts a new group of graphical elements. Corresponds to SVG's g element. * @param transform the transformation matrix establishing the new coordinate system + * @param layer an optional layer label (or null if none) * @throws IFException if an error occurs while handling this element */ - void startGroup(AffineTransform transform) throws IFException; + void startGroup(AffineTransform transform, String layer) throws IFException; /** - * Ends the current group and restores the previous coordinate system. + * Ends the current group and restores the previous coordinate system (and layer). * @throws IFException if an error occurs while handling this element */ void endGroup() throws IFException; diff --git a/src/java/org/apache/fop/render/intermediate/IFParser.java b/src/java/org/apache/fop/render/intermediate/IFParser.java index 1af1d4a06..519726291 100644 --- a/src/java/org/apache/fop/render/intermediate/IFParser.java +++ b/src/java/org/apache/fop/render/intermediate/IFParser.java @@ -592,7 +592,8 @@ public class IFParser implements IFConstants { String transform = attributes.getValue("transform"); AffineTransform[] transforms = AffineTransformArrayParser.createAffineTransform(transform); - painter.startGroup(transforms); + String layer = attributes.getValue("layer"); + painter.startGroup(transforms, layer); } public void endElement() throws IFException { @@ -800,8 +801,8 @@ public class IFParser implements IFConstants { } painter.drawImage(uri, new Rectangle(x, y, width, height)); } - resetForeignAttributes(); resetStructureTreeElement(); + resetForeignAttributes(); inForeignObject = false; } diff --git a/src/java/org/apache/fop/render/intermediate/IFRenderer.java b/src/java/org/apache/fop/render/intermediate/IFRenderer.java index 30ceda108..e40a8f6b3 100644 --- a/src/java/org/apache/fop/render/intermediate/IFRenderer.java +++ b/src/java/org/apache/fop/render/intermediate/IFRenderer.java @@ -742,6 +742,12 @@ public class IFRenderer extends AbstractPathOrientedRenderer { protected void renderBlockViewport(BlockViewport bv, List children) { //Essentially the same code as in the super class but optimized for the IF + // Handle new layer. + boolean inNewLayer = false; + if (maybeStartLayer(bv)) { + inNewLayer = true; + } + //This is the content-rect Dimension dim = new Dimension(bv.getIPD(), bv.getBPD()); viewportDimensionStack.push(dim); @@ -842,6 +848,7 @@ public class IFRenderer extends AbstractPathOrientedRenderer { currentBPPosition += bv.getAllocBPD(); } viewportDimensionStack.pop(); + maybeEndLayer(bv, inNewLayer); } /** {@inheritDoc} */ @@ -849,7 +856,7 @@ public class IFRenderer extends AbstractPathOrientedRenderer { StructureTreeElement structElem = (StructureTreeElement) viewport.getTrait(Trait.STRUCTURE_TREE_ELEMENT); establishStructureTreeElement(structElem); - pushdID(viewport); + pushID(viewport); Dimension dim = new Dimension(viewport.getIPD(), viewport.getBPD()); viewportDimensionStack.push(dim); super.renderInlineViewport(viewport); @@ -896,9 +903,26 @@ public class IFRenderer extends AbstractPathOrientedRenderer { } /** {@inheritDoc} */ + protected void startLayer(String layer) { + if (log.isTraceEnabled()) { + log.trace("startLayer() layer=" + layer); + } + saveGraphicsState(); + pushGroup(new IFGraphicContext.Group(layer)); + } + + /** {@inheritDoc} */ + protected void endLayer() { + if (log.isTraceEnabled()) { + log.trace("endLayer()"); + } + restoreGraphicsState(); + } + + /** {@inheritDoc} */ protected void renderInlineArea(InlineArea inlineArea) { saveInlinePosIfTargetable(inlineArea); - pushdID(inlineArea); + pushID(inlineArea); super.renderInlineArea(inlineArea); popID(inlineArea); } @@ -965,7 +989,7 @@ public class IFRenderer extends AbstractPathOrientedRenderer { log.trace("renderBlock() " + block); } saveBlockPosIfTargetable(block); - pushdID(block); + pushID(block); IFContext context = documentHandler.getContext(); Locale oldLocale = context.getLanguage(); context.setLanguage(block.getLocale()); @@ -977,7 +1001,7 @@ public class IFRenderer extends AbstractPathOrientedRenderer { popID(block); } - private void pushdID(Area area) { + private void pushID(Area area) { String prodID = (String) area.getTrait(Trait.PROD_ID); if (prodID != null) { ids.push(prodID); diff --git a/src/java/org/apache/fop/render/intermediate/IFSerializer.java b/src/java/org/apache/fop/render/intermediate/IFSerializer.java index 1ffd42863..395e79719 100644 --- a/src/java/org/apache/fop/render/intermediate/IFSerializer.java +++ b/src/java/org/apache/fop/render/intermediate/IFSerializer.java @@ -428,21 +428,24 @@ implements IFConstants, IFPainter, IFDocumentNavigationHandler { } /** {@inheritDoc} */ - public void startGroup(AffineTransform[] transforms) throws IFException { - startGroup(IFUtil.toString(transforms)); + public void startGroup(AffineTransform[] transforms, String layer) throws IFException { + startGroup(IFUtil.toString(transforms), layer); } /** {@inheritDoc} */ - public void startGroup(AffineTransform transform) throws IFException { - startGroup(IFUtil.toString(transform)); + public void startGroup(AffineTransform transform, String layer) throws IFException { + startGroup(IFUtil.toString(transform), layer); } - private void startGroup(String transform) throws IFException { + private void startGroup(String transform, String layer) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } + if (layer != null && layer.length() > 0) { + addAttribute(atts, "layer", layer); + } handler.startElement(EL_GROUP, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); diff --git a/src/java/org/apache/fop/render/java2d/Java2DPainter.java b/src/java/org/apache/fop/render/java2d/Java2DPainter.java index 07440ff0b..328d1a4f8 100644 --- a/src/java/org/apache/fop/render/java2d/Java2DPainter.java +++ b/src/java/org/apache/fop/render/java2d/Java2DPainter.java @@ -143,7 +143,7 @@ public class Java2DPainter extends AbstractIFPainter<Java2DDocumentHandler> { } /** {@inheritDoc} */ - public void startGroup(AffineTransform transform) throws IFException { + public void startGroup(AffineTransform transform, String layer) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); diff --git a/src/java/org/apache/fop/render/java2d/Java2DRenderer.java b/src/java/org/apache/fop/render/java2d/Java2DRenderer.java index a98aff353..d343c55d8 100644 --- a/src/java/org/apache/fop/render/java2d/Java2DRenderer.java +++ b/src/java/org/apache/fop/render/java2d/Java2DRenderer.java @@ -476,6 +476,14 @@ public abstract class Java2DRenderer extends AbstractPathOrientedRenderer implem } /** {@inheritDoc} */ + protected void startLayer(String layer) { + } + + /** {@inheritDoc} */ + protected void endLayer() { + } + + /** {@inheritDoc} */ protected List breakOutOfStateStack() { log.debug("Block.FIXED --> break out"); List breakOutList; diff --git a/src/java/org/apache/fop/render/pcl/PCLPainter.java b/src/java/org/apache/fop/render/pcl/PCLPainter.java index c51ee834f..f934eed8c 100644 --- a/src/java/org/apache/fop/render/pcl/PCLPainter.java +++ b/src/java/org/apache/fop/render/pcl/PCLPainter.java @@ -126,7 +126,7 @@ public class PCLPainter extends AbstractIFPainter<PCLDocumentHandler> implements } /** {@inheritDoc} */ - public void startGroup(AffineTransform transform) throws IFException { + public void startGroup(AffineTransform transform, String layer) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); diff --git a/src/java/org/apache/fop/render/pdf/PDFContentGenerator.java b/src/java/org/apache/fop/render/pdf/PDFContentGenerator.java index dde6b0ef3..ac7b1d905 100644 --- a/src/java/org/apache/fop/render/pdf/PDFContentGenerator.java +++ b/src/java/org/apache/fop/render/pdf/PDFContentGenerator.java @@ -30,6 +30,7 @@ import org.apache.fop.pdf.PDFDocument; import org.apache.fop.pdf.PDFFilterList; import org.apache.fop.pdf.PDFNumber; import org.apache.fop.pdf.PDFPaintingState; +import org.apache.fop.pdf.PDFReference; import org.apache.fop.pdf.PDFResourceContext; import org.apache.fop.pdf.PDFStream; import org.apache.fop.pdf.PDFText; @@ -55,7 +56,7 @@ public class PDFContentGenerator { private PDFColorHandler colorHandler; /** drawing state */ - protected PDFPaintingState currentState = null; + protected PDFPaintingState currentState; /** Text generation utility holding the current font status */ protected PDFTextUtil textutil; @@ -156,15 +157,23 @@ public class PDFContentGenerator { */ protected void comment(String text) { if (WRITE_COMMENTS) { - currentStream.add("% " + text + "\n"); + getStream().add("% " + text + "\n"); } } /** Save graphics state. */ protected void saveGraphicsState() { endTextObject(); - currentState.save(); - currentStream.add("q\n"); + getState().save(); + getStream().add("q\n"); + } + + /** Save graphics state with optional layer. */ + protected void saveGraphicsState(String layer) { + endTextObject(); + getState().save(); + maybeBeginLayer(layer); + getStream().add("q\n"); } /** @@ -174,9 +183,9 @@ public class PDFContentGenerator { */ protected void saveGraphicsState(String structElemType, int sequenceNum) { endTextObject(); - currentState.save(); + getState().save(); beginMarkedContentSequence(structElemType, sequenceNum); - currentStream.add("q\n"); + getStream().add("q\n"); } /** @@ -208,18 +217,18 @@ public class PDFContentGenerator { if (structElemType != null) { String actualTextProperty = actualText == null ? "" : " /ActualText " + PDFText.escapeText(actualText); - currentStream.add(structElemType + " <</MCID " + String.valueOf(mcid) + getStream().add(structElemType + " <</MCID " + String.valueOf(mcid) + actualTextProperty + ">>\n" + "BDC\n"); } else { - currentStream.add("/Artifact\nBMC\n"); + getStream().add("/Artifact\nBMC\n"); this.inArtifactMode = true; } this.inMarkedContentSequence = true; } void endMarkedContentSequence() { - currentStream.add("EMC\n"); + getStream().add("EMC\n"); this.inMarkedContentSequence = false; this.inArtifactMode = false; } @@ -231,9 +240,10 @@ public class PDFContentGenerator { */ protected void restoreGraphicsState(boolean popState) { endTextObject(); - currentStream.add("Q\n"); + getStream().add("Q\n"); + maybeEndLayer(); if (popState) { - currentState.restore(); + getState().restore(); } } @@ -251,11 +261,42 @@ public class PDFContentGenerator { */ protected void restoreGraphicsStateAccess() { endTextObject(); - currentStream.add("Q\n"); + getStream().add("Q\n"); if (this.inMarkedContentSequence) { endMarkedContentSequence(); } - currentState.restore(); + getState().restore(); + } + + private void maybeBeginLayer(String layer) { + if ((layer != null) && (layer.length() > 0)) { + getState().setLayer(layer); + beginOptionalContent(layer); + } + } + + private void maybeEndLayer() { + if (getState().getLayerChanged()) { + endOptionalContent(); + } + } + + private int ocNameIndex = 0; + + private void beginOptionalContent(String layerId) { + String name; + PDFReference layer = document.resolveExtensionReference(layerId); + if (layer != null) { + name = "oc" + ++ocNameIndex; + document.getResources().addProperty(name, layer); + } else { + name = "unknown"; + } + getStream().add("/OC /" + name + " BDC\n"); + } + + private void endOptionalContent() { + getStream().add("EMC\n"); } /** Indicates the beginning of a text object. */ @@ -310,8 +351,8 @@ public class PDFContentGenerator { public void concatenate(AffineTransform transform) { this.transform = transform; if (!transform.isIdentity()) { - currentState.concatenate(transform); - currentStream.add(CTMHelper.toPDFString(transform, false) + " cm\n"); + getState().concatenate(transform); + getStream().add(CTMHelper.toPDFString(transform, false) + " cm\n"); } } @@ -333,7 +374,7 @@ public class PDFContentGenerator { * @param content the PDF content */ public void add(String content) { - currentStream.add(content); + getStream().add(content); } /** @@ -350,9 +391,9 @@ public class PDFContentGenerator { * @param width line width in points */ public void updateLineWidth(float width) { - if (currentState.setLineWidth(width)) { + if (getState().setLineWidth(width)) { //Only write if value has changed WRT the current line width - currentStream.add(format(width) + " w\n"); + getStream().add(format(width) + " w\n"); } } @@ -362,7 +403,7 @@ public class PDFContentGenerator { */ public void updateCharacterSpacing(float value) { if (getState().setCharacterSpacing(value)) { - currentStream.add(format(value) + " Tc\n"); + getStream().add(format(value) + " Tc\n"); } } @@ -400,7 +441,7 @@ public class PDFContentGenerator { if (pdf != null) { colorHandler.establishColor(pdf, col, fill); } else { - setColor(col, fill, this.currentStream); + setColor(col, fill, getStream()); } } diff --git a/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java b/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java index 0a3d34ef4..648cdce7a 100644 --- a/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java +++ b/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java @@ -306,8 +306,7 @@ public class PDFDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); } } else if (extension instanceof PDFDictionaryAttachment) { - PDFDictionaryAttachment dictionaryExtension = (PDFDictionaryAttachment) extension; - pdfUtil.renderDictionaryExtension(dictionaryExtension, currentPage); + pdfUtil.renderDictionaryExtension((PDFDictionaryAttachment) extension, currentPage); } else if (extension != null) { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); diff --git a/src/java/org/apache/fop/render/pdf/PDFPainter.java b/src/java/org/apache/fop/render/pdf/PDFPainter.java index d9fdd399c..f85328b8b 100644 --- a/src/java/org/apache/fop/render/pdf/PDFPainter.java +++ b/src/java/org/apache/fop/render/pdf/PDFPainter.java @@ -143,8 +143,8 @@ public class PDFPainter extends AbstractIFPainter<PDFDocumentHandler> { } /** {@inheritDoc} */ - public void startGroup(AffineTransform transform) throws IFException { - generator.saveGraphicsState(); + public void startGroup(AffineTransform transform, String layer) throws IFException { + generator.saveGraphicsState(layer); generator.concatenate(toPoints(transform)); } diff --git a/src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java b/src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java index 962cd7847..4352dae6c 100644 --- a/src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java +++ b/src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java @@ -27,6 +27,7 @@ import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.EnumMap; +import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; @@ -55,24 +56,33 @@ import org.apache.fop.pdf.PDFFileSpec; import org.apache.fop.pdf.PDFICCBasedColorSpace; import org.apache.fop.pdf.PDFICCStream; import org.apache.fop.pdf.PDFInfo; +import org.apache.fop.pdf.PDFLayer; import org.apache.fop.pdf.PDFMetadata; import org.apache.fop.pdf.PDFName; import org.apache.fop.pdf.PDFNames; +import org.apache.fop.pdf.PDFNavigator; +import org.apache.fop.pdf.PDFNull; import org.apache.fop.pdf.PDFNumber; import org.apache.fop.pdf.PDFOutputIntent; import org.apache.fop.pdf.PDFPage; import org.apache.fop.pdf.PDFPageLabels; import org.apache.fop.pdf.PDFReference; +import org.apache.fop.pdf.PDFSetOCGStateAction; import org.apache.fop.pdf.PDFText; +import org.apache.fop.pdf.PDFTransitionAction; import org.apache.fop.pdf.PDFXMode; import org.apache.fop.pdf.Version; import org.apache.fop.pdf.VersionController; +import org.apache.fop.render.pdf.extensions.PDFActionExtension; +import org.apache.fop.render.pdf.extensions.PDFArrayExtension; +import org.apache.fop.render.pdf.extensions.PDFCollectionEntryExtension; import org.apache.fop.render.pdf.extensions.PDFDictionaryAttachment; -import org.apache.fop.render.pdf.extensions.PDFDictionaryEntryExtension; -import org.apache.fop.render.pdf.extensions.PDFDictionaryEntryType; import org.apache.fop.render.pdf.extensions.PDFDictionaryExtension; import org.apache.fop.render.pdf.extensions.PDFDictionaryType; import org.apache.fop.render.pdf.extensions.PDFEmbeddedFileAttachment; +import org.apache.fop.render.pdf.extensions.PDFObjectType; +import org.apache.fop.render.pdf.extensions.PDFPageExtension; +import org.apache.fop.render.pdf.extensions.PDFReferenceExtension; import static org.apache.fop.render.pdf.PDFEncryptionOption.ENCRYPTION_PARAMS; import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_ACCESSCONTENT; @@ -260,10 +270,189 @@ class PDFRenderingUtil { public void renderDictionaryExtension(PDFDictionaryAttachment attachment, PDFPage currentPage) { PDFDictionaryExtension extension = attachment.getExtension(); - if (extension.getDictionaryType() == PDFDictionaryType.Catalog) { + PDFDictionaryType type = extension.getDictionaryType(); + if (type == PDFDictionaryType.Action) { + addNavigatorAction(extension); + } else if (type == PDFDictionaryType.Layer) { + addLayer(extension); + } else if (type == PDFDictionaryType.Navigator) { + addNavigator(extension); + } else { + renderDictionaryExtension(extension, currentPage); + } + } + + public void addLayer(PDFDictionaryExtension extension) { + assert extension.getDictionaryType() == PDFDictionaryType.Layer; + String id = extension.getProperty(PDFDictionaryExtension.PROPERTY_ID); + if ((id != null) && (id.length() > 0)) { + PDFLayer layer = pdfDoc.getFactory().makeLayer(id); + layer.setResolver(new PDFLayer.Resolver(layer, extension) { + public void performResolution() { + PDFDictionaryExtension extension = (PDFDictionaryExtension) getExtension(); + Object name = extension.findEntryValue("Name"); + Object intent = extension.findEntryValue("Intent"); + Object usage = makeDictionary(extension.findEntryValue("Usage")); + getLayer().populate(name, intent, usage); + } + }); + } + } + + public void addNavigatorAction(PDFDictionaryExtension extension) { + assert extension.getDictionaryType() == PDFDictionaryType.Action; + String id = extension.getProperty(PDFDictionaryExtension.PROPERTY_ID); + if ((id != null) && (id.length() > 0)) { + String type = extension.getProperty(PDFActionExtension.PROPERTY_TYPE); + if (type != null) { + if (type.equals("SetOCGState")) { + PDFSetOCGStateAction action = pdfDoc.getFactory().makeSetOCGStateAction(id); + action.setResolver(new PDFSetOCGStateAction.Resolver(action, extension) { + public void performResolution() { + PDFDictionaryExtension extension = (PDFDictionaryExtension) getExtension(); + Object state = makeArray(extension.findEntryValue("State")); + Object preserveRB = extension.findEntryValue("PreserveRB"); + Object nextAction = makeDictionaryOrArray(extension.findEntryValue("Next")); + getAction().populate(state, preserveRB, nextAction); + } + }); + } else if (type.equals("Trans")) { + PDFTransitionAction action = pdfDoc.getFactory().makeTransitionAction(id); + action.setResolver(new PDFTransitionAction.Resolver(action, extension) { + public void performResolution() { + PDFDictionaryExtension extension = (PDFDictionaryExtension) getExtension(); + Object transition = makeDictionary(extension.findEntryValue("Trans")); + Object nextAction = makeDictionaryOrArray(extension.findEntryValue("Next")); + getAction().populate(transition, nextAction); + } + }); + } else { + throw new UnsupportedOperationException(); + } + } + } + } + + public void addNavigator(PDFDictionaryExtension extension) { + assert extension.getDictionaryType() == PDFDictionaryType.Navigator; + String id = extension.getProperty(PDFDictionaryExtension.PROPERTY_ID); + if ((id != null) && (id.length() > 0)) { + PDFNavigator navigator = pdfDoc.getFactory().makeNavigator(id); + navigator.setResolver(new PDFNavigator.Resolver(navigator, extension) { + public void performResolution() { + PDFDictionaryExtension extension = (PDFDictionaryExtension) getExtension(); + Object nextAction = makeDictionary(extension.findEntryValue("NA")); + Object next = makeDictionary(extension.findEntryValue("Next")); + Object prevAction = makeDictionary(extension.findEntryValue("PA")); + Object prev = makeDictionary(extension.findEntryValue("Prev")); + Object duration = extension.findEntryValue("Dur"); + getNavigator().populate(nextAction, next, prevAction, prev, duration); + } + }); + } + } + + private Object makeArray(Object value) { + if (value == null) { + return null; + } else if (value instanceof PDFReferenceExtension) { + return resolveReference((PDFReferenceExtension) value); + } else if (value instanceof List<?>) { + return populateArray(new PDFArray(), (List<?>) value); + } else { + throw new IllegalArgumentException(); + } + } + + private Object populateArray(PDFArray array, List<?> entries) { + for (PDFCollectionEntryExtension entry : (List<PDFCollectionEntryExtension>) entries) { + PDFObjectType type = entry.getType(); + if (type == PDFObjectType.Array) { + array.add(makeArray(entry.getValue())); + } else if (type == PDFObjectType.Boolean) { + array.add(entry.getValueAsBoolean()); + } else if (type == PDFObjectType.Dictionary) { + array.add(makeDictionary(entry.getValue())); + } else if (type == PDFObjectType.Name) { + array.add(new PDFName(entry.getValueAsString())); + } else if (type == PDFObjectType.Number) { + array.add(new PDFNumber(entry.getValueAsNumber())); + } else if (type == PDFObjectType.Reference) { + array.add(resolveReference((PDFReferenceExtension) entry)); + } else if (type == PDFObjectType.String) { + array.add(entry.getValue()); + } + } + return array; + } + + private Object makeDictionary(Object value) { + if (value == null) { + return null; + } else if (value instanceof PDFReferenceExtension) { + return resolveReference((PDFReferenceExtension) value); + } else if (value instanceof List<?>) { + return populateDictionary(new PDFDictionary(), (List<?>) value); + } else { + throw new IllegalArgumentException(); + } + } + + private Object populateDictionary(PDFDictionary dictionary, List<?> entries) { + for (PDFCollectionEntryExtension entry : (List<PDFCollectionEntryExtension>) entries) { + PDFObjectType type = entry.getType(); + String key = entry.getKey(); + if (type == PDFObjectType.Array) { + dictionary.put(key, makeArray(entry.getValue())); + } else if (type == PDFObjectType.Boolean) { + dictionary.put(key, entry.getValueAsBoolean()); + } else if (type == PDFObjectType.Dictionary) { + dictionary.put(key, makeDictionary(entry.getValue())); + } else if (type == PDFObjectType.Name) { + dictionary.put(key, new PDFName(entry.getValueAsString())); + } else if (type == PDFObjectType.Number) { + dictionary.put(key, new PDFNumber(entry.getValueAsNumber())); + } else if (type == PDFObjectType.Reference) { + dictionary.put(key, resolveReference((PDFReferenceExtension) entry)); + } else if (type == PDFObjectType.String) { + dictionary.put(key, entry.getValue()); + } + } + return dictionary; + } + + private Object makeDictionaryOrArray(Object value) { + if (value == null) { + return null; + } else if (value instanceof PDFReferenceExtension) { + return resolveReference((PDFReferenceExtension) value); + } else if (value instanceof List<?>) { + if (hasKeyedEntry((List<?>) value)) { + return populateDictionary(new PDFDictionary(), (List<?>) value); + } else { + return populateArray(new PDFArray(), (List<?>) value); + } + } else { + throw new IllegalArgumentException(); + } + } + + private boolean hasKeyedEntry(List<?> entries) { + for (PDFCollectionEntryExtension entry : (List<PDFCollectionEntryExtension>) entries) { + if (entry.getKey() != null) { + return true; + } + } + return false; + } + + public void renderDictionaryExtension(PDFDictionaryExtension extension, PDFPage currentPage) { + PDFDictionaryType type = extension.getDictionaryType(); + if (type == PDFDictionaryType.Catalog) { augmentDictionary(pdfDoc.getRoot(), extension); - } else if (extension.getDictionaryType() == PDFDictionaryType.Page) { - if (extension.matchesPageNumber(currentPage.getPageIndex() + 1)) { + } else if (type == PDFDictionaryType.Page) { + assert extension instanceof PDFPageExtension; + if (((PDFPageExtension) extension).matchesPageNumber(currentPage.getPageIndex() + 1)) { augmentDictionary(currentPage, extension); } } else { @@ -272,9 +461,12 @@ class PDFRenderingUtil { } private PDFDictionary augmentDictionary(PDFDictionary dictionary, PDFDictionaryExtension extension) { - for (PDFDictionaryEntryExtension entry : extension.getEntries()) { + for (PDFCollectionEntryExtension entry : extension.getEntries()) { if (entry instanceof PDFDictionaryExtension) { - dictionary.put(entry.getKey(), augmentDictionary(new PDFDictionary(dictionary), (PDFDictionaryExtension) entry)); + dictionary.put(entry.getKey(), + augmentDictionary(new PDFDictionary(dictionary), (PDFDictionaryExtension) entry)); + } else if (entry instanceof PDFArrayExtension) { + dictionary.put(entry.getKey(), augmentArray(new PDFArray(dictionary), (PDFArrayExtension) entry)); } else { augmentDictionary(dictionary, entry); } @@ -282,22 +474,68 @@ class PDFRenderingUtil { return dictionary; } - private void augmentDictionary(PDFDictionary dictionary, PDFDictionaryEntryExtension entry) { - PDFDictionaryEntryType type = entry.getType(); + private void augmentDictionary(PDFDictionary dictionary, PDFCollectionEntryExtension entry) { + PDFObjectType type = entry.getType(); String key = entry.getKey(); - if (type == PDFDictionaryEntryType.Boolean) { + if (type == PDFObjectType.Boolean) { dictionary.put(key, entry.getValueAsBoolean()); - } else if (type == PDFDictionaryEntryType.Name) { + } else if (type == PDFObjectType.Name) { dictionary.put(key, new PDFName(entry.getValueAsString())); - } else if (type == PDFDictionaryEntryType.Number) { + } else if (type == PDFObjectType.Number) { dictionary.put(key, new PDFNumber(entry.getValueAsNumber())); - } else if (type == PDFDictionaryEntryType.String) { + } else if (type == PDFObjectType.Reference) { + assert entry instanceof PDFReferenceExtension; + dictionary.put(key, resolveReference((PDFReferenceExtension) entry)); + } else if (type == PDFObjectType.String) { dictionary.put(key, entry.getValueAsString()); } else { throw new IllegalStateException(); } } + private Object resolveReference(PDFReferenceExtension entry) { + PDFReference reference = (PDFReference) entry.getResolvedReference(); + if (reference == null) { + reference = pdfDoc.resolveExtensionReference(entry.getReferenceId()); + if (reference != null) { + entry.setResolvedReference(reference); + } + return reference; + } + return PDFNull.INSTANCE; + } + + private PDFArray augmentArray(PDFArray array, PDFArrayExtension extension) { + for (PDFCollectionEntryExtension entry : extension.getEntries()) { + if (entry instanceof PDFDictionaryExtension) { + array.add(augmentDictionary(new PDFDictionary(array), (PDFDictionaryExtension) entry)); + } else if (entry instanceof PDFArrayExtension) { + array.add(augmentArray(new PDFArray(array), (PDFArrayExtension) entry)); + } else { + augmentArray(array, entry); + } + } + return array; + } + + private void augmentArray(PDFArray array, PDFCollectionEntryExtension entry) { + PDFObjectType type = entry.getType(); + if (type == PDFObjectType.Boolean) { + array.add(entry.getValueAsBoolean()); + } else if (type == PDFObjectType.Name) { + array.add(new PDFName(entry.getValueAsString())); + } else if (type == PDFObjectType.Number) { + array.add(new PDFNumber(entry.getValueAsNumber())); + } else if (type == PDFObjectType.Reference) { + assert entry instanceof PDFReferenceExtension; + array.add(resolveReference((PDFReferenceExtension) entry)); + } else if (type == PDFObjectType.String) { + array.add(entry.getValueAsString()); + } else { + throw new IllegalStateException(); + } + } + public PDFDocument setupPDFDocument(OutputStream out) throws IOException { if (this.pdfDoc != null) { throw new IllegalStateException("PDFDocument already set up"); diff --git a/src/java/org/apache/fop/render/pdf/PDFStructureTreeBuilder.java b/src/java/org/apache/fop/render/pdf/PDFStructureTreeBuilder.java index 4d34b8be4..985974b80 100644 --- a/src/java/org/apache/fop/render/pdf/PDFStructureTreeBuilder.java +++ b/src/java/org/apache/fop/render/pdf/PDFStructureTreeBuilder.java @@ -358,6 +358,7 @@ class PDFStructureTreeBuilder implements StructureTreeEventHandler { } public StructureTreeElement startNode(String name, Attributes attributes, StructureTreeElement parent) { + assert parent == null || parent instanceof PDFStructElem; PDFStructElem parentElem = parent == null ? ancestors.getFirst() : (PDFStructElem) parent; PDFStructElem structElem = createStructureElement(name, parentElem, attributes, pdfFactory, eventBroadcaster); diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFActionElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFActionElement.java new file mode 100644 index 000000000..e4a5747e6 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFActionElement.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +import org.xml.sax.Attributes; +import org.xml.sax.Locator; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.fo.Constants; +import org.apache.fop.fo.FONode; +import org.apache.fop.fo.PropertyList; + +// CSOFF: LineLengthCheck + +/** + * Extension element for pdf:action. + */ +public class PDFActionElement extends PDFDictionaryElement { + + public static final String ATT_TYPE = PDFActionExtension.PROPERTY_TYPE; + + /** + * Main constructor + * @param parent parent FO node + */ + PDFActionElement(FONode parent) { + super(parent, PDFDictionaryType.Action); + } + + @Override + public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { + super.processNode(elementName, locator, attlist, propertyList); + String type = attlist.getValue(ATT_TYPE); + if (type != null) { + getDictionaryExtension().setProperty(PDFActionExtension.PROPERTY_TYPE, type); + } + } + + @Override + public void startOfNode() throws FOPException { + super.startOfNode(); + if (parent.getNameId() != Constants.FO_DECLARATIONS) { + invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); + } + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFActionExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFActionExtension.java new file mode 100644 index 000000000..778b8a203 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFActionExtension.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +// CSOFF: LineLengthCheck + +public class PDFActionExtension extends PDFDictionaryExtension { + + public static final String PROPERTY_TYPE = "type"; + + PDFActionExtension() { + super(PDFDictionaryType.Action); + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFArrayElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFArrayElement.java new file mode 100644 index 000000000..1f3ba22b2 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFArrayElement.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +import org.xml.sax.Attributes; +import org.xml.sax.Locator; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.fo.FONode; +import org.apache.fop.fo.PropertyList; + +// CSOFF: LineLengthCheck + +/** + * Extension element for pdf:array. + */ +public class PDFArrayElement extends PDFCollectionEntryElement { + + private PDFArrayExtension extension; + + /** + * Main constructor + * @param parent parent FO node + */ + PDFArrayElement(FONode parent) { + super(parent, PDFObjectType.Array, new PDFArrayExtension()); + } + + public PDFArrayExtension getArrayExtension() { + assert getExtension() instanceof PDFArrayExtension; + return (PDFArrayExtension) getExtension(); + } + + @Override + public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { + super.processNode(elementName, locator, attlist, propertyList); + } + + @Override + public void startOfNode() throws FOPException { + super.startOfNode(); + } + + @Override + protected void addChildNode(FONode child) throws FOPException { + PDFArrayExtension extension = getArrayExtension(); + if (child instanceof PDFCollectionEntryElement) { + PDFCollectionEntryExtension entry = ((PDFCollectionEntryElement) child).getExtension(); + if (entry.getKey() == null) { + extension.addEntry(entry); + } + } + } + + @Override + public void endOfNode() throws FOPException { + super.endOfNode(); + } + + @Override + public String getLocalName() { + return PDFObjectType.Array.elementName(); + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFArrayExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFArrayExtension.java new file mode 100644 index 000000000..80c6c94e4 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFArrayExtension.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +import java.util.List; +import java.util.Map; + +// CSOFF: LineLengthCheck + +public class PDFArrayExtension extends PDFCollectionExtension { + + private static final long serialVersionUID = -1L; + + private Map<String, String> properties; + private List<PDFCollectionEntryExtension> entries; + + PDFArrayExtension() { + super(PDFObjectType.Array); + this.properties = new java.util.HashMap<String, String>(); + this.entries = new java.util.ArrayList<PDFCollectionEntryExtension>(); + } + + @Override + public void setValue(Object value) { + throw new UnsupportedOperationException(); + } + + @Override + public Object getValue() { + return getEntries(); + } + + public void setProperty(String name, String value) { + properties.put(name, value); + } + + public String getProperty(String name) { + return properties.get(name); + } + + @Override + public void addEntry(PDFCollectionEntryExtension entry) { + if (entry.getKey() != null) { + throw new IllegalArgumentException(); + } else { + entries.add(entry); + } + } + + public List<PDFCollectionEntryExtension> getEntries() { + return entries; + } + + public PDFCollectionEntryExtension getLastEntry() { + if (entries.size() > 0) { + return entries.get(entries.size() - 1); + } else { + return null; + } + } + + @Override + public String getElementName() { + return PDFObjectType.Array.elementName(); + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFCatalogElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFCatalogElement.java new file mode 100644 index 000000000..029357d22 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFCatalogElement.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.fo.Constants; +import org.apache.fop.fo.FONode; + +// CSOFF: LineLengthCheck + +/** + * Extension element for pdf:catalog. + */ +public class PDFCatalogElement extends PDFDictionaryElement { + + PDFCatalogElement(FONode parent) { + super(parent, PDFDictionaryType.Catalog); + } + + @Override + public void startOfNode() throws FOPException { + super.startOfNode(); + if (parent.getNameId() != Constants.FO_DECLARATIONS) { + invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); + } + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFCatalogExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFCatalogExtension.java new file mode 100644 index 000000000..381f6fbe8 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFCatalogExtension.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +// CSOFF: LineLengthCheck + +public class PDFCatalogExtension extends PDFDictionaryExtension { + + PDFCatalogExtension() { + super(PDFDictionaryType.Catalog); + } +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFCollectionEntryElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFCollectionEntryElement.java new file mode 100644 index 000000000..4185ceef0 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFCollectionEntryElement.java @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +import org.xml.sax.Attributes; +import org.xml.sax.Locator; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.fo.FONode; +import org.apache.fop.fo.PropertyList; + +// CSOFF: LineLengthCheck + +/** + * Extension element for collection entries: pdf:{array,boolean,dictionary,name,number,reference,string}. The specific type + * of entry is established at construction type. + */ +public class PDFCollectionEntryElement extends AbstractPDFExtensionElement { + + public static final String ATT_KEY = PDFCollectionEntryExtension.PROPERTY_KEY; + + private PDFCollectionEntryExtension extension; + private StringBuffer characters; + + PDFCollectionEntryElement(FONode parent, PDFObjectType type, PDFCollectionEntryExtension extension) { + super(parent); + this.extension = extension; + } + + PDFCollectionEntryElement(FONode parent, PDFObjectType type) { + this(parent, type, createExtension(type)); + } + + private static PDFCollectionEntryExtension createExtension(PDFObjectType type) { + if (type == PDFObjectType.Reference) { + return new PDFReferenceExtension(); + } else { + return new PDFCollectionEntryExtension(type); + } + } + + public PDFCollectionEntryExtension getExtension() { + return extension; + } + + @Override + public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { + if (parent instanceof PDFDictionaryElement) { + String key = attlist.getValue(ATT_KEY); + if (key == null) { + missingPropertyError(ATT_KEY); + } else if (key.length() == 0) { + invalidPropertyValueError(ATT_KEY, key, null); + } else { + extension.setKey(key); + } + } + } + + @Override + public void startOfNode() throws FOPException { + super.startOfNode(); + if (parent instanceof PDFDictionaryElement) { + if (!PDFDictionaryType.hasValueOfElementName(parent.getLocalName())) { + invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), null); + } + } + } + + @Override + protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { + if (capturePCData(extension.getType())) { + if (characters == null) { + characters = new StringBuffer((length < 16) ? 16 : length); + } + characters.append(data, start, length); + } + } + + private boolean capturePCData(PDFObjectType type) { + if (type == PDFObjectType.Array) { + return false; + } else if (type == PDFObjectType.Dictionary) { + return false; + } else { + return (type != PDFObjectType.Reference); + } + } + + @Override + public void endOfNode() throws FOPException { + if (capturePCData(extension.getType())) { + if (extension.getType() == PDFObjectType.Boolean) { + String value = (characters != null) ? characters.toString() : ""; + if (!value.equals("true") && !value.equals("false")) { + invalidPropertyValueError("<value>", value, null); + } + extension.setValue(Boolean.valueOf(value)); + } else if (extension.getType() == PDFObjectType.Name) { + String value = (characters != null) ? characters.toString() : ""; + if (value.length() == 0) { + invalidPropertyValueError("<value>", value, null); + } + extension.setValue(value); + } else if (extension.getType() == PDFObjectType.Number) { + String value = (characters != null) ? characters.toString() : ""; + try { + double d = Double.parseDouble(value); + if (Math.abs(Math.floor(d) - d) < 1E-10) { + extension.setValue(Long.valueOf((long) d)); + } else { + extension.setValue(Double.valueOf(d)); + } + } catch (NumberFormatException e) { + invalidPropertyValueError("<value>", value, null); + } + } else if (extension.getType() == PDFObjectType.String) { + String value = (characters != null) ? characters.toString() : ""; + extension.setValue(value); + } + } + super.endOfNode(); + } + + @Override + public String getLocalName() { + return extension.getType().elementName(); + } +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/AbstractPDFDictionaryElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFCollectionEntryExtension.java index 9de7e95da..d28f1602f 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/AbstractPDFDictionaryElement.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFCollectionEntryExtension.java @@ -19,25 +19,25 @@ package org.apache.fop.render.pdf.extensions; -import org.apache.fop.fo.FONode; - // CSOFF: LineLengthCheck -/** - * Base class for the PDF dictionary related extension elements. - */ -public abstract class AbstractPDFDictionaryElement extends AbstractPDFExtensionElement { - - public static final String ATT_KEY = PDFDictionaryEntryExtension.PROPERTY_KEY; - - /** - * Default constructor - * - * @param parent parent of this node - * @see org.apache.fop.fo.FONode#FONode(FONode) - */ - public AbstractPDFDictionaryElement(FONode parent) { - super(parent); +public class PDFCollectionEntryExtension extends PDFObjectExtension { + + public static final String PROPERTY_KEY = "key"; + + /* Non-empty key if used as dictionary entry, otherwise must be null. */ + private String key; + + PDFCollectionEntryExtension(PDFObjectType type) { + super(type); } -} + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFCollectionExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFCollectionExtension.java new file mode 100644 index 000000000..228d69c79 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFCollectionExtension.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +// CSOFF: LineLengthCheck + +public abstract class PDFCollectionExtension extends PDFCollectionEntryExtension { + + protected PDFCollectionExtension(PDFObjectType type) { + super(type); + } + + public abstract void addEntry(PDFCollectionEntryExtension entry); + + public abstract PDFCollectionEntryExtension getLastEntry(); + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryAttachment.java b/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryAttachment.java index 19e5ce07a..3832619ba 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryAttachment.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryAttachment.java @@ -43,14 +43,13 @@ public class PDFDictionaryAttachment extends PDFExtensionAttachment { } public void toSAX(ContentHandler handler) throws SAXException { - PDFDictionaryType dictionaryType = extension.getDictionaryType(); int pageNumber = 0; - if (dictionaryType == PDFDictionaryType.Page) { + if (extension instanceof PDFPageExtension) { if (handler instanceof GenerationHelperContentHandler) { Object context = ((GenerationHelperContentHandler) handler).getContentHandlerContext(); if (context instanceof IFContext) { int pageIndex = ((IFContext) context).getPageIndex(); - if ((pageIndex >= 0) && extension.matchesPageNumber(pageIndex + 1)) { + if ((pageIndex >= 0) && ((PDFPageExtension) extension).matchesPageNumber(pageIndex + 1)) { pageNumber = pageIndex + 1; } else { pageNumber = -1; @@ -69,24 +68,40 @@ public class PDFDictionaryAttachment extends PDFExtensionAttachment { String qn = PREFIX + ":" + ln; attributes = extractIFAttributes(attributes, dictionary); handler.startElement(CATEGORY, ln, qn, attributes); - for (PDFDictionaryEntryExtension entry : dictionary.getEntries()) { + for (PDFCollectionEntryExtension entry : dictionary.getEntries()) { toSAX(handler, entry); } handler.endElement(CATEGORY, ln, qn); } - private void toSAX(ContentHandler handler, PDFDictionaryEntryExtension entry) throws SAXException { + private void toSAX(ContentHandler handler, PDFArrayExtension array) throws SAXException { + AttributesImpl attributes = new AttributesImpl(); + String ln = array.getElementName(); + String qn = PREFIX + ":" + ln; + attributes = extractIFAttributes(attributes, array); + handler.startElement(CATEGORY, ln, qn, attributes); + for (PDFCollectionEntryExtension entry : array.getEntries()) { + toSAX(handler, entry); + } + handler.endElement(CATEGORY, ln, qn); + } + + private void toSAX(ContentHandler handler, PDFCollectionEntryExtension entry) throws SAXException { if (entry instanceof PDFDictionaryExtension) { toSAX(handler, (PDFDictionaryExtension) entry); + } else if (entry instanceof PDFArrayExtension) { + toSAX(handler, (PDFArrayExtension) entry); } else { AttributesImpl attributes = new AttributesImpl(); String ln = entry.getElementName(); String qn = PREFIX + ":" + ln; attributes = extractIFAttributes(attributes, entry); handler.startElement(CATEGORY, ln, qn, attributes); - char[] characters = entry.getValueAsXMLEscapedString().toCharArray(); - if (characters.length > 0) { - handler.characters(characters, 0, characters.length); + if (!(entry instanceof PDFReferenceExtension)) { + char[] characters = entry.getValueAsXMLEscapedString().toCharArray(); + if (characters.length > 0) { + handler.characters(characters, 0, characters.length); + } } handler.endElement(CATEGORY, ln, qn); } @@ -94,16 +109,27 @@ public class PDFDictionaryAttachment extends PDFExtensionAttachment { private static AttributesImpl extractIFAttributes(AttributesImpl attributes, PDFDictionaryExtension dictionary) { PDFDictionaryType type = dictionary.getDictionaryType(); - if (type == PDFDictionaryType.Catalog) { - // no specific attriburtes + if (dictionary.usesIDAttribute()) { + String idName = PDFDictionaryElement.ATT_ID; + String id = dictionary.getProperty(PDFDictionaryExtension.PROPERTY_ID); + if (id != null) { + attributes.addAttribute(null, idName, idName, "ID", id); + } + } + if (type == PDFDictionaryType.Action) { + String actionTypeName = PDFActionElement.ATT_TYPE; + String actionType = dictionary.getProperty(PDFActionExtension.PROPERTY_TYPE); + if (actionType != null) { + attributes.addAttribute(null, actionTypeName, actionTypeName, "CDATA", actionType); + } } else if (type == PDFDictionaryType.Page) { - String pageNumbersName = PDFDictionaryExtension.PROPERTY_PAGE_NUMBERS; + String pageNumbersName = PDFPageExtension.PROPERTY_PAGE_NUMBERS; String pageNumbers = dictionary.getProperty(pageNumbersName); if (pageNumbers != null) { attributes.addAttribute(null, pageNumbersName, pageNumbersName, "CDATA", pageNumbers); } } else if (type == PDFDictionaryType.Dictionary) { - String keyName = PDFDictionaryEntryExtension.PROPERTY_KEY; + String keyName = PDFCollectionEntryElement.ATT_KEY; String key = dictionary.getKey(); if (key != null) { attributes.addAttribute(null, keyName, keyName, "CDATA", key); @@ -112,12 +138,28 @@ public class PDFDictionaryAttachment extends PDFExtensionAttachment { return attributes; } - private static AttributesImpl extractIFAttributes(AttributesImpl attributes, PDFDictionaryEntryExtension entry) { - String keyName = PDFDictionaryEntryExtension.PROPERTY_KEY; + private static AttributesImpl extractIFAttributes(AttributesImpl attributes, PDFArrayExtension array) { + String keyName = PDFCollectionEntryExtension.PROPERTY_KEY; + String key = array.getKey(); + if (key != null) { + attributes.addAttribute(null, keyName, keyName, "CDATA", key); + } + return attributes; + } + + private static AttributesImpl extractIFAttributes(AttributesImpl attributes, PDFCollectionEntryExtension entry) { + String keyName = PDFCollectionEntryElement.ATT_KEY; String key = entry.getKey(); if (key != null) { attributes.addAttribute(null, keyName, keyName, "CDATA", key); } + if (entry instanceof PDFReferenceExtension) { + String refid = ((PDFReferenceExtension) entry).getReferenceId(); + if (refid != null) { + String refidName = PDFReferenceElement.ATT_REFID; + attributes.addAttribute(null, refidName, refidName, "IDREF", refid); + } + } return attributes; } diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryElement.java index 0920f3a78..9dc127da6 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryElement.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryElement.java @@ -23,7 +23,6 @@ import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.apache.fop.apps.FOPException; -import org.apache.fop.fo.Constants; import org.apache.fop.fo.FONode; import org.apache.fop.fo.PropertyList; import org.apache.fop.fo.extensions.ExtensionAttachment; @@ -34,38 +33,54 @@ import org.apache.fop.fo.extensions.ExtensionAttachment; * Extension element for dictionaries: pdf:{catalog,page,dictionary}. The specific type * of dictionary is established at construction type. */ -public class PDFDictionaryElement extends AbstractPDFDictionaryElement { +public class PDFDictionaryElement extends PDFCollectionEntryElement { - public static final String ATT_PAGE_NUMBERS = PDFDictionaryExtension.PROPERTY_PAGE_NUMBERS; - - private PDFDictionaryExtension extension; + public static final String ATT_ID = PDFDictionaryExtension.PROPERTY_ID; /** * Main constructor * @param parent parent FO node */ PDFDictionaryElement(FONode parent, PDFDictionaryType type) { - super(parent); - this.extension = new PDFDictionaryExtension(type); + super(parent, PDFObjectType.Dictionary, createExtension(type)); + } + + private static PDFDictionaryExtension createExtension(PDFDictionaryType type) { + if (type == PDFDictionaryType.Action) { + return new PDFActionExtension(); + } else if (type == PDFDictionaryType.Catalog) { + return new PDFCatalogExtension(); + } else if (type == PDFDictionaryType.Layer) { + return new PDFLayerExtension(); + } else if (type == PDFDictionaryType.Navigator) { + return new PDFNavigatorExtension(); + } else if (type == PDFDictionaryType.Page) { + return new PDFPageExtension(); + } else { + return new PDFDictionaryExtension(type); + } } - public PDFDictionaryExtension getExtension() { - return extension; + public PDFDictionaryExtension getDictionaryExtension() { + assert getExtension() instanceof PDFDictionaryExtension; + return (PDFDictionaryExtension) getExtension(); } @Override public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { - if (extension.getDictionaryType() == PDFDictionaryType.Catalog) { - // no specific properties - } else if (extension.getDictionaryType() == PDFDictionaryType.Page) { - String pageNumbers = attlist.getValue(ATT_PAGE_NUMBERS); - if (pageNumbers != null) { - extension.setProperty(ATT_PAGE_NUMBERS, pageNumbers); + PDFDictionaryExtension extension = getDictionaryExtension(); + if (extension.usesIDAttribute()) { + String id = attlist.getValue(ATT_ID); + if (id != null) { + extension.setProperty(PDFDictionaryExtension.PROPERTY_ID, id); } - } else if (extension.getDictionaryType() == PDFDictionaryType.Dictionary) { + } + if (extension.getDictionaryType() == PDFDictionaryType.Dictionary) { String key = attlist.getValue(ATT_KEY); if (key == null) { - missingPropertyError(ATT_KEY); + if (parent instanceof PDFDictionaryElement) { + missingPropertyError(ATT_KEY); + } } else if (key.length() == 0) { invalidPropertyValueError(ATT_KEY, key, null); } else { @@ -78,16 +93,18 @@ public class PDFDictionaryElement extends AbstractPDFDictionaryElement { public void startOfNode() throws FOPException { super.startOfNode(); String localName = getLocalName(); - if (localName.equals("catalog")) { - if (parent.getNameId() != Constants.FO_DECLARATIONS) { - invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); - } + if (localName.equals("action")) { + // handled in PDFActionElement subclass + } else if (localName.equals("catalog")) { + // handled in PDFCatalogElement subclass + } else if (localName.equals("layer")) { + // handled in PDFLayerElement subclass + } else if (localName.equals("navigator")) { + // handled in PDFNavigattorElement subclass } else if (localName.equals("page")) { - if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { - invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPM"); - } + // handled in PDFPageElement subclass } else if (localName.equals("dictionary")) { - if (!PDFDictionaryType.hasValueOfElementName(parent.getLocalName())) { + if (!PDFDictionaryType.hasValueOfElementName(parent.getLocalName()) && !PDFObjectType.Array.elementName().equals(parent.getLocalName())) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), null); } } else { @@ -97,14 +114,15 @@ public class PDFDictionaryElement extends AbstractPDFDictionaryElement { @Override protected void addChildNode(FONode child) throws FOPException { + PDFDictionaryExtension extension = getDictionaryExtension(); if (child instanceof PDFDictionaryElement) { - PDFDictionaryExtension extension = ((PDFDictionaryElement) child).getExtension(); - if (extension.getDictionaryType() == PDFDictionaryType.Dictionary) { - this.extension.addEntry(extension); + PDFDictionaryExtension entry = ((PDFDictionaryElement) child).getDictionaryExtension(); + if (entry.getDictionaryType() == PDFDictionaryType.Dictionary) { + extension.addEntry(entry); } - } else if (child instanceof PDFDictionaryEntryElement) { - PDFDictionaryEntryExtension extension = ((PDFDictionaryEntryElement) child).getExtension(); - this.extension.addEntry(extension); + } else if (child instanceof PDFCollectionEntryElement) { + PDFCollectionEntryExtension entry = ((PDFCollectionEntryElement) child).getExtension(); + extension.addEntry(entry); } } @@ -115,12 +133,13 @@ public class PDFDictionaryElement extends AbstractPDFDictionaryElement { @Override public String getLocalName() { + PDFDictionaryExtension extension = getDictionaryExtension(); return extension.getDictionaryType().elementName(); } @Override protected ExtensionAttachment instantiateExtensionAttachment() { - return new PDFDictionaryAttachment(extension); + return new PDFDictionaryAttachment(getDictionaryExtension()); } } diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryEntryElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryEntryElement.java deleted file mode 100644 index bcdb90c2c..000000000 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryEntryElement.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* $Id$ */ - -package org.apache.fop.render.pdf.extensions; - -import org.xml.sax.Attributes; -import org.xml.sax.Locator; - -import org.apache.fop.apps.FOPException; -import org.apache.fop.fo.FONode; -import org.apache.fop.fo.PropertyList; - -// CSOFF: LineLengthCheck - -/** - * Extension element for dictionary entries: pdf:{boolean,name,number,string}. The specific type - * of entry is established at construction type. - */ -public class PDFDictionaryEntryElement extends AbstractPDFDictionaryElement { - - private PDFDictionaryEntryExtension extension; - private StringBuffer characters; - - /** - * Main constructor - * @param parent parent FO node - */ - PDFDictionaryEntryElement(FONode parent, PDFDictionaryEntryType type) { - super(parent); - this.extension = new PDFDictionaryEntryExtension(type); - } - - public PDFDictionaryEntryExtension getExtension() { - return extension; - } - - @Override - public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { - String key = attlist.getValue("key"); - if (key == null) { - missingPropertyError("key"); - } else if (key.length() == 0) { - invalidPropertyValueError("key", key, null); - } else { - extension.setKey(key); - } - } - - @Override - public void startOfNode() throws FOPException { - super.startOfNode(); - if (!PDFDictionaryType.hasValueOfElementName(parent.getLocalName())) { - invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), null); - } - } - - @Override - protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { - if (characters == null) { - characters = new StringBuffer((length < 16) ? 16 : length); - } - characters.append(data, start, length); - } - - @Override - public void endOfNode() throws FOPException { - String value = (characters != null) ? characters.toString() : ""; - if (extension.getType() == PDFDictionaryEntryType.Boolean) { - if (!value.equals("true") && !value.equals("false")) { - invalidPropertyValueError("<value>", value, null); - } - } else if (extension.getType() == PDFDictionaryEntryType.Name) { - if (value.length() == 0) { - invalidPropertyValueError("<value>", value, null); - } - } else if (extension.getType() == PDFDictionaryEntryType.Number) { - try { - Double.valueOf(value); - } catch (NumberFormatException e) { - invalidPropertyValueError("<value>", value, null); - } - } else if (extension.getType() != PDFDictionaryEntryType.String) { - throw new IllegalStateException(); - } - extension.setValue(value); - super.endOfNode(); - } - - @Override - public String getLocalName() { - return extension.getType().elementName(); - } -} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryExtension.java index d4b11cdb4..50b6f3a83 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryExtension.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryExtension.java @@ -24,24 +24,36 @@ import java.util.Map; // CSOFF: LineLengthCheck -public class PDFDictionaryExtension extends PDFDictionaryEntryExtension { +public class PDFDictionaryExtension extends PDFCollectionExtension { + public static final String PROPERTY_ID = "id"; public static final String PROPERTY_PAGE_NUMBERS = "page-numbers"; private static final long serialVersionUID = -1L; private PDFDictionaryType dictionaryType; private Map<String, String> properties; - private List<PDFDictionaryEntryExtension> entries; + private List<PDFCollectionEntryExtension> entries; PDFDictionaryExtension() { + this(PDFDictionaryType.Dictionary); } PDFDictionaryExtension(PDFDictionaryType dictionaryType) { - super(PDFDictionaryEntryType.Dictionary); + super(PDFObjectType.Dictionary); this.dictionaryType = dictionaryType; this.properties = new java.util.HashMap<String, String>(); - this.entries = new java.util.ArrayList<PDFDictionaryEntryExtension>(); + this.entries = new java.util.ArrayList<PDFCollectionEntryExtension>(); + } + + @Override + public void setValue(Object value) { + throw new UnsupportedOperationException(); + } + + @Override + public Object getValue() { + return getEntries(); } public PDFDictionaryType getDictionaryType() { @@ -56,15 +68,40 @@ public class PDFDictionaryExtension extends PDFDictionaryEntryExtension { return properties.get(name); } - public void addEntry(PDFDictionaryEntryExtension entry) { - entries.add(entry); + @Override + public void addEntry(PDFCollectionEntryExtension entry) { + if ((entry.getKey() == null) || (entry.getKey().length() == 0)) { + throw new IllegalArgumentException(); + } else { + entries.add(entry); + } } - public List<PDFDictionaryEntryExtension> getEntries() { + public List<PDFCollectionEntryExtension> getEntries() { return entries; } - public PDFDictionaryEntryExtension getLastEntry() { + public PDFCollectionEntryExtension findEntry(String key) { + for (PDFCollectionEntryExtension entry : entries) { + String entryKey = entry.getKey(); + if ((entryKey != null) && entryKey.equals(key)) { + return entry; + } + } + return null; + } + + public Object findEntryValue(String key) { + for (PDFCollectionEntryExtension entry : entries) { + String entryKey = entry.getKey(); + if ((entryKey != null) && entryKey.equals(key)) { + return entry.getValue(); + } + } + return null; + } + + public PDFCollectionEntryExtension getLastEntry() { if (entries.size() > 0) { return entries.get(entries.size() - 1); } else { @@ -72,48 +109,8 @@ public class PDFDictionaryExtension extends PDFDictionaryEntryExtension { } } - /** - * Determine if page dictionary and page number matches. - * @param pageNumber page number, where first page number is 1 - * @return true if this dictionary is a page dictionary and specified page number matches specified page-number property - */ - public boolean matchesPageNumber(int pageNumber) { - if (dictionaryType != PDFDictionaryType.Page) { - return false; - } - String pageNumbers = getProperty(PROPERTY_PAGE_NUMBERS); - if ((pageNumbers == null) || (pageNumbers.length() == 0)) { - return false; - } else if (pageNumbers.equals("*")) { - return true; - } else { - for (String interval : pageNumbers.split("\\s*,\\s*")) { - String[] components = interval.split("\\s*-\\s*"); - if (components.length < 1) { - continue; - } else { - try { - int start = Integer.parseInt(components[0]); - int end = 0; - if (components.length > 1) { - if (!components[1].equals("LAST")) { - end = Integer.parseInt(components[1]); - } - } - if ((end == 0) && (pageNumber == start)) { - return true; - } else if ((end > start) && (pageNumber >= start) && (pageNumber < end)) { - return true; - } else { - continue; - } - } catch (NumberFormatException e) { - continue; - } - } - } - } - return false; + public boolean usesIDAttribute() { + return dictionaryType.usesIDAttribute(); } @Override diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryType.java b/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryType.java index edd95160a..a49a5fc8c 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryType.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryType.java @@ -25,17 +25,28 @@ package org.apache.fop.render.pdf.extensions; * Enumeration type for PDF dictionary extension elements. */ public enum PDFDictionaryType { - Dictionary("dictionary"), // generic (nested) dictionary element - Catalog("catalog"), // catalog dictionary element - Page("page"); // page dictionary element + Action("action", true), // action dictionary element + Catalog("catalog"), // catalog dictionary element + Dictionary("dictionary"), // generic (nested) dictionary element + Layer("layer", true), // optional content group dictionary element + Navigator("navigator", true), // navigation node dictionary element + Page("page"); // page dictionary element private String elementName; - PDFDictionaryType(String elementName) { + private boolean usesIDAttribute; + PDFDictionaryType(String elementName, boolean usesIDAttribute) { this.elementName = elementName; + this.usesIDAttribute = usesIDAttribute; + } + PDFDictionaryType(String elementName) { + this(elementName, false); } public String elementName() { return elementName; } + public boolean usesIDAttribute() { + return usesIDAttribute; + } static PDFDictionaryType valueOfElementName(String elementName) { for (PDFDictionaryType type : values()) { if (type.elementName.equals(elementName)) { diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFElementMapping.java b/src/java/org/apache/fop/render/pdf/extensions/PDFElementMapping.java index 3e063e24b..1fba80796 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFElementMapping.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFElementMapping.java @@ -41,17 +41,56 @@ public class PDFElementMapping extends ElementMapping { protected void initialize() { if (foObjs == null) { foObjs = new java.util.HashMap<String, Maker>(); + // pdf:action + foObjs.put(PDFDictionaryType.Action.elementName(), new PDFActionElementMaker()); + // pdf:array + foObjs.put(PDFObjectType.Array.elementName(), new PDFArrayElementMaker()); + // pdf:boolean + foObjs.put(PDFObjectType.Boolean.elementName(), new PDFCollectionEntryElementMaker(PDFObjectType.Boolean)); + // pdf:catalog + foObjs.put(PDFDictionaryType.Catalog.elementName(), new PDFCatalogElementMaker()); + // pdf:dictionary + foObjs.put(PDFDictionaryType.Dictionary.elementName(), new PDFDictionaryElementMaker()); // pdf:embedded-file foObjs.put(PDFEmbeddedFileElement.ELEMENT, new PDFEmbeddedFileElementMaker()); - // pdf:{catalog,page} et al. - for (PDFDictionaryType type : PDFDictionaryType.values()) { - foObjs.put(type.elementName(), new PDFDictionaryElementMaker(type)); - } - for (PDFDictionaryEntryType type : PDFDictionaryEntryType.values()) { - if (type != PDFDictionaryEntryType.Dictionary) { - foObjs.put(type.elementName(), new PDFDictionaryEntryElementMaker(type)); - } - } + // pdf:name + foObjs.put(PDFObjectType.Name.elementName(), new PDFCollectionEntryElementMaker(PDFObjectType.Name)); + // pdf:number + foObjs.put(PDFObjectType.Number.elementName(), new PDFCollectionEntryElementMaker(PDFObjectType.Number)); + // pdf:navigator + foObjs.put(PDFDictionaryType.Navigator.elementName(), new PDFNavigatorElementMaker()); + // pdf:layer + foObjs.put(PDFDictionaryType.Layer.elementName(), new PDFLayerElementMaker()); + // pdf:page + foObjs.put(PDFDictionaryType.Page.elementName(), new PDFPageElementMaker()); + // pdf:reference + foObjs.put(PDFObjectType.Reference.elementName(), new PDFReferenceElementMaker()); + // pdf:string + foObjs.put(PDFObjectType.String.elementName(), new PDFCollectionEntryElementMaker(PDFObjectType.String)); + } + } + + static class PDFActionElementMaker extends ElementMapping.Maker { + public FONode make(FONode parent) { + return new PDFActionElement(parent); + } + } + + static class PDFArrayElementMaker extends ElementMapping.Maker { + public FONode make(FONode parent) { + return new PDFArrayElement(parent); + } + } + + static class PDFCatalogElementMaker extends ElementMapping.Maker { + public FONode make(FONode parent) { + return new PDFCatalogElement(parent); + } + } + + static class PDFDictionaryElementMaker extends ElementMapping.Maker { + public FONode make(FONode parent) { + return new PDFDictionaryElement(parent, PDFDictionaryType.Dictionary); } } @@ -61,23 +100,38 @@ public class PDFElementMapping extends ElementMapping { } } - static class PDFDictionaryElementMaker extends ElementMapping.Maker { - private PDFDictionaryType dictionaryType; - PDFDictionaryElementMaker(PDFDictionaryType dictionaryType) { - this.dictionaryType = dictionaryType; + static class PDFLayerElementMaker extends ElementMapping.Maker { + public FONode make(FONode parent) { + return new PDFLayerElement(parent); } + } + + static class PDFNavigatorElementMaker extends ElementMapping.Maker { public FONode make(FONode parent) { - return new PDFDictionaryElement(parent, dictionaryType); + return new PDFNavigatorElement(parent); } } - static class PDFDictionaryEntryElementMaker extends ElementMapping.Maker { - private PDFDictionaryEntryType entryType; - PDFDictionaryEntryElementMaker(PDFDictionaryEntryType entryType) { + static class PDFPageElementMaker extends ElementMapping.Maker { + public FONode make(FONode parent) { + return new PDFPageElement(parent); + } + } + + static class PDFCollectionEntryElementMaker extends ElementMapping.Maker { + private PDFObjectType entryType; + PDFCollectionEntryElementMaker(PDFObjectType entryType) { this.entryType = entryType; } public FONode make(FONode parent) { - return new PDFDictionaryEntryElement(parent, entryType); + return new PDFCollectionEntryElement(parent, entryType); } } + + static class PDFReferenceElementMaker extends ElementMapping.Maker { + public FONode make(FONode parent) { + return new PDFReferenceElement(parent); + } + } + } diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java b/src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java index f14f1e7d6..2fd14058e 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java @@ -49,7 +49,7 @@ public class PDFExtensionHandler extends DefaultHandler implements ContentHandle private Attributes lastAttributes; // PDFDictionaryAttachment related - private Stack<PDFDictionaryExtension> dictionaries = new Stack<PDFDictionaryExtension>(); + private Stack<PDFCollectionExtension> collections = new Stack<PDFCollectionExtension>(); private boolean captureContent; private StringBuffer characters; @@ -58,29 +58,78 @@ public class PDFExtensionHandler extends DefaultHandler implements ContentHandle if (PDFExtensionAttachment.CATEGORY.equals(uri)) { if (localName.equals(PDFEmbeddedFileAttachment.ELEMENT)) { lastAttributes = new AttributesImpl(attributes); - } else if (PDFDictionaryType.hasValueOfElementName(localName)) { - PDFDictionaryExtension dictionary = new PDFDictionaryExtension(PDFDictionaryType.valueOfElementName(localName)); - String key = attributes.getValue(PDFDictionaryEntryExtension.PROPERTY_KEY); + } else if (PDFDictionaryType.Action.elementName().equals(localName)) { + PDFActionExtension action = new PDFActionExtension(); + String id = attributes.getValue(PDFDictionaryElement.ATT_ID); + if (id != null) { + action.setProperty(PDFDictionaryExtension.PROPERTY_ID, id); + } + String type = attributes.getValue(PDFActionElement.ATT_TYPE); + if (type != null) { + action.setProperty(PDFActionExtension.PROPERTY_TYPE, type); + } + collections.push(action); + } else if (PDFObjectType.Array.elementName().equals(localName)) { + PDFArrayExtension array = new PDFArrayExtension(); + String key = attributes.getValue(PDFCollectionEntryElement.ATT_KEY); + if (key != null) { + array.setKey(key); + } + collections.push(array); + } else if (PDFDictionaryType.Catalog.elementName().equals(localName)) { + PDFCatalogExtension catalog = new PDFCatalogExtension(); + collections.push(catalog); + } else if (PDFDictionaryType.Dictionary.elementName().equals(localName)) { + PDFDictionaryExtension dictionary = new PDFDictionaryExtension(); + String key = attributes.getValue(PDFCollectionEntryElement.ATT_KEY); if (key != null) { dictionary.setKey(key); } - if (dictionary.getDictionaryType() == PDFDictionaryType.Page) { - String pageNumbers = attributes.getValue(PDFDictionaryElement.ATT_PAGE_NUMBERS); - if (pageNumbers != null) { - dictionary.setProperty(PDFDictionaryElement.ATT_PAGE_NUMBERS, pageNumbers); - } + collections.push(dictionary); + } else if (PDFDictionaryType.Layer.elementName().equals(localName)) { + PDFLayerExtension layer = new PDFLayerExtension(); + String id = attributes.getValue(PDFDictionaryElement.ATT_ID); + if (id != null) { + layer.setProperty(PDFDictionaryExtension.PROPERTY_ID, id); + } + collections.push(layer); + } else if (PDFDictionaryType.Navigator.elementName().equals(localName)) { + PDFNavigatorExtension navigator = new PDFNavigatorExtension(); + String id = attributes.getValue(PDFDictionaryElement.ATT_ID); + if (id != null) { + navigator.setProperty(PDFDictionaryExtension.PROPERTY_ID, id); + } + collections.push(navigator); + } else if (PDFDictionaryType.Page.elementName().equals(localName)) { + PDFPageExtension page = new PDFPageExtension(); + String pageNumbers = attributes.getValue(PDFPageElement.ATT_PAGE_NUMBERS); + if (pageNumbers != null) { + page.setProperty(PDFPageExtension.PROPERTY_PAGE_NUMBERS, pageNumbers); + } + collections.push(page); + } else if (PDFObjectType.hasValueOfElementName(localName)) { + PDFCollectionEntryExtension entry; + if (PDFObjectType.Reference.elementName().equals(localName)) { + entry = new PDFReferenceExtension(); + } else { + entry = new PDFCollectionEntryExtension(PDFObjectType.valueOfElementName(localName)); } - dictionaries.push(dictionary); - } else if (PDFDictionaryEntryType.hasValueOfElementName(localName)) { - PDFDictionaryEntryExtension entry = new PDFDictionaryEntryExtension(PDFDictionaryEntryType.valueOfElementName(localName)); - String key = attributes.getValue(PDFDictionaryEntryElement.ATT_KEY); + String key = attributes.getValue(PDFCollectionEntryElement.ATT_KEY); if (key != null) { entry.setKey(key); } - if (!dictionaries.empty()) { - PDFDictionaryExtension dictionary = dictionaries.peek(); - dictionary.addEntry(entry); - captureContent = true; + if (entry instanceof PDFReferenceExtension) { + String refid = attributes.getValue(PDFReferenceElement.ATT_REFID); + if (refid != null) { + ((PDFReferenceExtension) entry).setReferenceId(refid); + } + } + if (!collections.empty()) { + PDFCollectionExtension collection = collections.peek(); + collection.addEntry(entry); + if (!(entry instanceof PDFReferenceExtension)) { + captureContent = true; + } } } else { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); @@ -107,33 +156,48 @@ public class PDFExtensionHandler extends DefaultHandler implements ContentHandle String name = lastAttributes.getValue("name"); String src = lastAttributes.getValue("src"); String desc = lastAttributes.getValue("description"); + this.lastAttributes = null; this.returnedObject = new PDFEmbeddedFileAttachment(name, src, desc); } else if (PDFDictionaryType.hasValueOfElementName(localName)) { - if (!dictionaries.empty()) { - PDFDictionaryExtension dictionary = dictionaries.pop(); - if ((dictionary.getDictionaryType() == PDFDictionaryType.Catalog) || (dictionary.getDictionaryType() == PDFDictionaryType.Page)) { + if (!collections.empty() && (collections.peek() instanceof PDFDictionaryExtension)) { + PDFDictionaryExtension dictionary = (PDFDictionaryExtension) collections.pop(); + if (!collections.empty()) { + PDFCollectionExtension collectionOuter = collections.peek(); + collectionOuter.addEntry(dictionary); + } else if (dictionary.getDictionaryType() != PDFDictionaryType.Dictionary) { this.returnedObject = new PDFDictionaryAttachment(dictionary); - } else if (!dictionaries.empty()) { - PDFDictionaryExtension dictionaryOuter = dictionaries.peek(); - dictionaryOuter.addEntry(dictionary); + } else { + throw new SAXException(new IllegalStateException("generic dictionary not permitted at outer level")); + } + } else { + throw new SAXException(new IllegalStateException("collections stack is empty or not a dictionary")); + } + } else if (PDFObjectType.Array.elementName().equals(localName)) { + if (!collections.empty() && (collections.peek() instanceof PDFArrayExtension)) { + PDFArrayExtension array = (PDFArrayExtension) collections.pop(); + if (!collections.empty()) { + PDFCollectionExtension collectionOuter = collections.peek(); + collectionOuter.addEntry(array); + } else { + throw new SAXException(new IllegalStateException("array not permitted at outer level")); } } else { - throw new SAXException(new IllegalStateException("no active dictionary")); + throw new SAXException(new IllegalStateException("collections stack is empty or not an array")); } - } else if (PDFDictionaryEntryType.hasValueOfElementName(localName)) { - if (!dictionaries.empty()) { - PDFDictionaryExtension dictionary = dictionaries.peek(); - PDFDictionaryEntryExtension entry = dictionary.getLastEntry(); + } else if (PDFObjectType.hasValueOfElementName(localName)) { + if (!collections.empty()) { + PDFCollectionExtension collection = collections.peek(); + PDFCollectionEntryExtension entry = collection.getLastEntry(); if (entry != null) { if (characters != null) { entry.setValue(characters.toString()); characters = null; } } else { - throw new SAXException(new IllegalStateException("no active entry")); + throw new SAXException(new IllegalStateException("no current entry")); } } else { - throw new SAXException(new IllegalStateException("no active dictionary")); + throw new SAXException(new IllegalStateException("entry not permitted at outer level")); } } } diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFLayerElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFLayerElement.java new file mode 100644 index 000000000..dab0ecf78 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFLayerElement.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.fo.Constants; +import org.apache.fop.fo.FONode; + +// CSOFF: LineLengthCheck + +/** + * Extension element for pdf:layer. + */ +public class PDFLayerElement extends PDFDictionaryElement { + + PDFLayerElement(FONode parent) { + super(parent, PDFDictionaryType.Layer); + } + + @Override + public void startOfNode() throws FOPException { + super.startOfNode(); + if (parent.getNameId() != Constants.FO_DECLARATIONS) { + invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); + } + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFLayerExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFLayerExtension.java new file mode 100644 index 000000000..d6cc27ab8 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFLayerExtension.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +// CSOFF: LineLengthCheck + +public class PDFLayerExtension extends PDFDictionaryExtension { + + PDFLayerExtension() { + super(PDFDictionaryType.Layer); + } +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFNavigatorElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFNavigatorElement.java new file mode 100644 index 000000000..5c5b779b5 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFNavigatorElement.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.fo.Constants; +import org.apache.fop.fo.FONode; + +// CSOFF: LineLengthCheck + +/** + * Extension element for pdf:navigator. + */ +public class PDFNavigatorElement extends PDFDictionaryElement { + + PDFNavigatorElement(FONode parent) { + super(parent, PDFDictionaryType.Navigator); + } + + @Override + public void startOfNode() throws FOPException { + super.startOfNode(); + if (parent.getNameId() != Constants.FO_DECLARATIONS) { + invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); + } + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFNavigatorExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFNavigatorExtension.java new file mode 100644 index 000000000..ee9dfa7c8 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFNavigatorExtension.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +// CSOFF: LineLengthCheck + +public class PDFNavigatorExtension extends PDFDictionaryExtension { + + PDFNavigatorExtension() { + super(PDFDictionaryType.Navigator); + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryEntryExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFObjectExtension.java index 94d6b5dbf..5447d87f2 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryEntryExtension.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFObjectExtension.java @@ -23,34 +23,20 @@ import org.apache.fop.util.XMLUtil; // CSOFF: LineLengthCheck -public class PDFDictionaryEntryExtension { +public class PDFObjectExtension { - public static final String PROPERTY_KEY = "key"; - - private PDFDictionaryEntryType type; - private String key = ""; + private PDFObjectType type; private Object value; - PDFDictionaryEntryExtension() { - } - - PDFDictionaryEntryExtension(PDFDictionaryEntryType type) { + PDFObjectExtension(PDFObjectType type) { this.type = type; } - public PDFDictionaryEntryType getType() { + public PDFObjectType getType() { return type; } - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public void setValue(String value) { + public void setValue(Object value) { this.value = value; } @@ -63,7 +49,10 @@ public class PDFDictionaryEntryExtension { * @return entry value */ public Boolean getValueAsBoolean() { - if (value instanceof String) { + Object value = getValue(); + if (value instanceof Boolean) { + return (Boolean) value; + } else if (value instanceof String) { return Boolean.valueOf((String)value); } else { return false; @@ -75,9 +64,12 @@ public class PDFDictionaryEntryExtension { * @return entry value */ public Number getValueAsNumber() { - if (value instanceof String) { + Object value = getValue(); + if (value instanceof Number) { + return (Number) value; + } else if (value instanceof String) { double d = Double.parseDouble((String) value); - if (Math.floor(d) == d) { + if (Math.abs(Math.floor(d) - d) < 1E-10) { return Long.valueOf((long) d); } else { return Double.valueOf(d); @@ -88,10 +80,13 @@ public class PDFDictionaryEntryExtension { } public String getValueAsString() { - if (value instanceof String) { + Object value = getValue(); + if (value == null) { + return null; + } else if (value instanceof String) { return (String) value; } else { - return ""; + return value.toString(); } } @@ -99,10 +94,6 @@ public class PDFDictionaryEntryExtension { return XMLUtil.escape(getValueAsString()); } - public void setValue(Object value) { - this.value = value; - } - public String getElementName() { return type.elementName(); } diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryEntryType.java b/src/java/org/apache/fop/render/pdf/extensions/PDFObjectType.java index e4b25819a..c193a3b7b 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFDictionaryEntryType.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFObjectType.java @@ -22,24 +22,27 @@ package org.apache.fop.render.pdf.extensions; // CSOFF: LineLengthCheck /** - * Enumeration type for leaf PDF dictionary entry extension elements. + * Enumeration type for leaf PDF object extension types used as singletons, + * dictionary entries, or array entries. */ -public enum PDFDictionaryEntryType { - Boolean("boolean"), // boolean valued entry - Dictionary("dictionary"), // dictionary valued entry - Name("name"), // name valued entry - Number("number"), // number valued entry - String("string"); // string valued entry +public enum PDFObjectType { + Array("array"), // array valued entry + Boolean("boolean"), // boolean valued entry + Dictionary("dictionary"), // dictionary valued entry + Name("name"), // name valued entry + Number("number"), // number valued entry + Reference("reference"), // indirect object reference entry + String("string"); // string valued entry private String elementName; - PDFDictionaryEntryType(String elementName) { + PDFObjectType(String elementName) { this.elementName = elementName; } public String elementName() { return elementName; } - static PDFDictionaryEntryType valueOfElementName(String elementName) { - for (PDFDictionaryEntryType type : values()) { + static PDFObjectType valueOfElementName(String elementName) { + for (PDFObjectType type : values()) { if (type.elementName.equals(elementName)) { return type; } @@ -48,7 +51,8 @@ public enum PDFDictionaryEntryType { } static boolean hasValueOfElementName(String elementName) { try { - return valueOfElementName(elementName) != null; + valueOfElementName(elementName); + return true; } catch (Exception e) { return false; } diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFPageElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFPageElement.java new file mode 100644 index 000000000..28a966ead --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFPageElement.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +import org.xml.sax.Attributes; +import org.xml.sax.Locator; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.fo.Constants; +import org.apache.fop.fo.FONode; +import org.apache.fop.fo.PropertyList; + +// CSOFF: LineLengthCheck + +/** + * Extension element for pdf:page. + */ +public class PDFPageElement extends PDFDictionaryElement { + + public static final String ATT_PAGE_NUMBERS = PDFDictionaryExtension.PROPERTY_PAGE_NUMBERS; + + /** + * Main constructor + * @param parent parent FO node + */ + PDFPageElement(FONode parent) { + super(parent, PDFDictionaryType.Page); + } + + @Override + public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { + super.processNode(elementName, locator, attlist, propertyList); + String pageNumbers = attlist.getValue(ATT_PAGE_NUMBERS); + if (pageNumbers != null) { + getDictionaryExtension().setProperty(PDFDictionaryExtension.PROPERTY_PAGE_NUMBERS, pageNumbers); + } + } + + @Override + public void startOfNode() throws FOPException { + super.startOfNode(); + if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { + invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPM"); + } + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFPageExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFPageExtension.java new file mode 100644 index 000000000..0726a4e55 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFPageExtension.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +// CSOFF: LineLengthCheck + +public class PDFPageExtension extends PDFDictionaryExtension { + + public static final String PROPERTY_PAGE_NUMBERS = "page-numbers"; + + PDFPageExtension() { + super(PDFDictionaryType.Page); + } + + /** + * Determine if page dictionary and page number matches. + * @param pageNumber page number, where first page number is 1 + * @return true if this dictionary is a page dictionary and specified page number matches specified page-number property + */ + public boolean matchesPageNumber(int pageNumber) { + String pageNumbers = getProperty(PROPERTY_PAGE_NUMBERS); + if ((pageNumbers == null) || (pageNumbers.length() == 0)) { + return false; + } else if (pageNumbers.equals("*")) { + return true; + } else { + for (String interval : pageNumbers.split("\\s*,\\s*")) { + String[] components = interval.split("\\s*-\\s*"); + if (components.length < 1) { + continue; + } else { + try { + int start = Integer.parseInt(components[0]); + int end = 0; + if (components.length > 1) { + if (!components[1].equals("LAST")) { + end = Integer.parseInt(components[1]); + } + } + if ((end == 0) && (pageNumber == start)) { + return true; + } else if ((end > start) && (pageNumber >= start) && (pageNumber < end)) { + return true; + } else { + continue; + } + } catch (NumberFormatException e) { + continue; + } + } + } + } + return false; + } + +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFReferenceElement.java b/src/java/org/apache/fop/render/pdf/extensions/PDFReferenceElement.java new file mode 100644 index 000000000..37aeeb890 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFReferenceElement.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +import org.xml.sax.Attributes; +import org.xml.sax.Locator; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.fo.FONode; +import org.apache.fop.fo.PropertyList; + +// CSOFF: LineLengthCheck + +/** + * Extension element for pdf:reference. + */ +public class PDFReferenceElement extends PDFCollectionEntryElement { + + public static final String ATT_REFID = PDFReferenceExtension.PROPERTY_REFID; + + /** + * Main constructor + * @param parent parent FO node + */ + PDFReferenceElement(FONode parent) { + super(parent, PDFObjectType.Reference); + } + + @Override + public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { + super.processNode(elementName, locator, attlist, propertyList); + String refid = attlist.getValue(ATT_REFID); + if (refid == null) { + missingPropertyError(ATT_REFID); + } else if (refid.length() == 0) { + invalidPropertyValueError(ATT_REFID, refid, null); + } else { + ((PDFReferenceExtension) getExtension()).setReferenceId(refid); + } + } +} diff --git a/src/java/org/apache/fop/render/pdf/extensions/PDFReferenceExtension.java b/src/java/org/apache/fop/render/pdf/extensions/PDFReferenceExtension.java new file mode 100644 index 000000000..09621c01c --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFReferenceExtension.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.pdf.extensions; + +// CSOFF: LineLengthCheck + +public class PDFReferenceExtension extends PDFCollectionEntryExtension { + + public static final String PROPERTY_REFID = "refid"; + + private String refid; + private Object resolvedReference; + + PDFReferenceExtension() { + super(PDFObjectType.Reference); + } + + @Override + public void setValue(Object value) { + throw new UnsupportedOperationException(); + } + + @Override + public Object getValue() { + return this; + } + + public String getReferenceId() { + return refid; + } + + public void setReferenceId(String refid) { + this.refid = refid; + } + + public Object getResolvedReference() { + return resolvedReference; + } + + public void setResolvedReference(Object resolvedReference) { + this.resolvedReference = resolvedReference; + } + +} diff --git a/src/java/org/apache/fop/render/ps/PSFontUtils.java b/src/java/org/apache/fop/render/ps/PSFontUtils.java index c22a3ba28..06191f84d 100644 --- a/src/java/org/apache/fop/render/ps/PSFontUtils.java +++ b/src/java/org/apache/fop/render/ps/PSFontUtils.java @@ -175,6 +175,15 @@ public class PSFontUtils extends org.apache.xmlgraphics.ps.PSFontUtils { if (!tracker.isResourceSupplied(WINANSI_ENCODING_RESOURCE)) { //Only out Base 14 fonts still use that + for (Typeface tf : fonts.values()) { + if (tf instanceof LazyFont) { + tf = ((LazyFont)tf).getRealFont(); + if (tf instanceof SingleByteFont + && ((SingleByteFont) tf).getEncoding().getName().equals("custom")) { + defineEncoding(gen, ((SingleByteFont) tf).getEncoding()); + } + } + } defineWinAnsiEncoding(gen); } gen.commentln("%FOPBeginFontReencode"); diff --git a/src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java b/src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java index 3ade34522..cadc28267 100644 --- a/src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java +++ b/src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java @@ -19,26 +19,50 @@ package org.apache.fop.render.ps; +import java.awt.Color; +import java.awt.Dimension; import java.awt.Rectangle; import java.awt.geom.AffineTransform; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.imageio.ImageIO; import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; import org.apache.batik.bridge.BridgeContext; import org.apache.batik.bridge.GVTBuilder; import org.apache.batik.gvt.GraphicsNode; +import org.apache.batik.transcoder.SVGAbstractTranscoder; +import org.apache.batik.transcoder.TranscoderException; +import org.apache.batik.transcoder.TranscoderInput; +import org.apache.batik.transcoder.TranscoderOutput; +import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.xmlgraphics.image.loader.Image; import org.apache.xmlgraphics.image.loader.ImageFlavor; import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM; -import org.apache.xmlgraphics.java2d.ps.PSGraphics2D; +import org.apache.xmlgraphics.ps.ImageEncoder; +import org.apache.xmlgraphics.ps.ImageEncodingHelper; import org.apache.xmlgraphics.ps.PSGenerator; import org.apache.fop.image.loader.batik.BatikImageFlavors; import org.apache.fop.image.loader.batik.BatikUtil; import org.apache.fop.render.ImageHandler; import org.apache.fop.render.RenderingContext; +import org.apache.fop.render.ps.svg.PSSVGGraphics2D; import org.apache.fop.svg.SVGEventProducer; import org.apache.fop.svg.SVGUserAgent; @@ -47,6 +71,9 @@ import org.apache.fop.svg.SVGUserAgent; */ public class PSImageHandlerSVG implements ImageHandler { + private static final Color FALLBACK_COLOR = new Color(255, 33, 117); + private HashMap<String, String> gradientsFound = new HashMap<String, String>(); + private static final ImageFlavor[] FLAVORS = new ImageFlavor[] { BatikImageFlavors.SVG_DOM }; @@ -58,78 +85,262 @@ public class PSImageHandlerSVG implements ImageHandler { PSGenerator gen = psContext.getGenerator(); ImageXMLDOM imageSVG = (ImageXMLDOM)image; - //Controls whether text painted by Batik is generated using text or path operations - boolean strokeText = false; - //TODO Configure text stroking + if (shouldRaster(imageSVG)) { + InputStream is = renderSVGToInputStream(context, imageSVG); + + float x = (float) pos.getX() / 1000f; + float y = (float) pos.getY() / 1000f; + float w = (float) pos.getWidth() / 1000f; + float h = (float) pos.getHeight() / 1000f; + Rectangle2D targetRect = new Rectangle2D.Double(x, y, w, h); + + MaskedImage mi = convertToRGB(ImageIO.read(is)); + BufferedImage ri = mi.getImage(); + ImageEncoder encoder = ImageEncodingHelper.createRenderedImageEncoder(ri); + Dimension imgDim = new Dimension(ri.getWidth(), ri.getHeight()); + String imgDescription = ri.getClass().getName(); + ImageEncodingHelper helper = new ImageEncodingHelper(ri); + ColorModel cm = helper.getEncodedColorModel(); + PSImageUtils.writeImage(encoder, imgDim, imgDescription, targetRect, cm, gen, ri, mi.getMaskColor()); + } else { + //Controls whether text painted by Batik is generated using text or path operations + boolean strokeText = false; + //TODO Configure text stroking + + SVGUserAgent ua + = new SVGUserAgent(context.getUserAgent(), new AffineTransform()); + + PSSVGGraphics2D graphics = new PSSVGGraphics2D(strokeText, gen); + graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); + + BridgeContext ctx = new PSBridgeContext(ua, + (strokeText ? null : psContext.getFontInfo()), + context.getUserAgent().getImageManager(), + context.getUserAgent().getImageSessionContext()); + + //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) + //to it. + Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument()); + + GraphicsNode root; + try { + GVTBuilder builder = new GVTBuilder(); + root = builder.build(ctx, clonedDoc); + } catch (Exception e) { + SVGEventProducer eventProducer = SVGEventProducer.Provider.get( + context.getUserAgent().getEventBroadcaster()); + eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); + return; + } + // get the 'width' and 'height' attributes of the SVG document + float w = (float)ctx.getDocumentSize().getWidth() * 1000f; + float h = (float)ctx.getDocumentSize().getHeight() * 1000f; - SVGUserAgent ua - = new SVGUserAgent(context.getUserAgent(), new AffineTransform()); + float sx = pos.width / w; + float sy = pos.height / h; - PSGraphics2D graphics = new PSGraphics2D(strokeText, gen); - graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); + ctx = null; - BridgeContext ctx = new PSBridgeContext(ua, - (strokeText ? null : psContext.getFontInfo()), - context.getUserAgent().getImageManager(), - context.getUserAgent().getImageSessionContext()); + gen.commentln("%FOPBeginSVG"); + gen.saveGraphicsState(); + final boolean clip = false; + if (clip) { + /* + * Clip to the svg area. + * Note: To have the svg overlay (under) a text area then use + * an fo:block-container + */ + gen.writeln("newpath"); + gen.defineRect(pos.getMinX() / 1000f, pos.getMinY() / 1000f, + pos.width / 1000f, pos.height / 1000f); + gen.writeln("clip"); + } - //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) - //to it. - Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument()); + // transform so that the coordinates (0,0) is from the top left + // and positive is down and to the right. (0,0) is where the + // viewBox puts it. + gen.concatMatrix(sx, 0, 0, sy, pos.getMinX() / 1000f, pos.getMinY() / 1000f); - GraphicsNode root; + AffineTransform transform = new AffineTransform(); + // scale to viewbox + transform.translate(pos.getMinX(), pos.getMinY()); + gen.getCurrentState().concatMatrix(transform); + try { + root.paint(graphics); + } catch (Exception e) { + SVGEventProducer eventProducer = SVGEventProducer.Provider.get( + context.getUserAgent().getEventBroadcaster()); + eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); + } + + gen.restoreGraphicsState(); + gen.commentln("%FOPEndSVG"); + } + } + + private InputStream renderSVGToInputStream(RenderingContext context, ImageXMLDOM imageSVG) throws IOException { + PNGTranscoder png = new PNGTranscoder(); + Float width = getDimension(imageSVG.getDocument(), "width") * 8; + png.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, width); + Float height = getDimension(imageSVG.getDocument(), "height") * 8; + png.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, height); + TranscoderInput input = new TranscoderInput(imageSVG.getDocument()); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + TranscoderOutput output = new TranscoderOutput(os); try { - GVTBuilder builder = new GVTBuilder(); - root = builder.build(ctx, clonedDoc); - } catch (Exception e) { + png.transcode(input, output); + } catch (TranscoderException ex) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); - eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); - return; + eventProducer.svgRenderingError(this, ex, imageSVG.getInfo().getOriginalURI()); + } finally { + os.flush(); + os.close(); + } + return new ByteArrayInputStream(os.toByteArray()); + } + + private MaskedImage convertToRGB(BufferedImage alphaImage) { + int[] red = new int[256]; + int[] green = new int[256]; + int[] blue = new int[256]; + BufferedImage rgbImage = new BufferedImage(alphaImage.getWidth(), + alphaImage.getHeight(), BufferedImage.TYPE_INT_RGB); + //Count occurances of each colour in image + for (int cx = 0; cx < alphaImage.getWidth(); cx++) { + for (int cy = 0; cy < alphaImage.getHeight(); cy++) { + int pixelValue = alphaImage.getRGB(cx, cy); + Color pixelColor = new Color(pixelValue); + red[pixelColor.getRed()]++; + green[pixelColor.getGreen()]++; + blue[pixelColor.getBlue()]++; + } + } + //Find colour not in image + Color alphaSwap = null; + for (int i = 0; i < 256; i++) { + if (red[i] == 0) { + alphaSwap = new Color(i, 0, 0); + break; + } else if (green[i] == 0) { + alphaSwap = new Color(0, i, 0); + break; + } else if (blue[i] == 0) { + alphaSwap = new Color(0, 0, i); + break; + } } - // get the 'width' and 'height' attributes of the SVG document - float w = (float)ctx.getDocumentSize().getWidth() * 1000f; - float h = (float)ctx.getDocumentSize().getHeight() * 1000f; - - float sx = pos.width / w; - float sy = pos.height / h; - - ctx = null; - - gen.commentln("%FOPBeginSVG"); - gen.saveGraphicsState(); - final boolean clip = false; - if (clip) { - /* - * Clip to the svg area. - * Note: To have the svg overlay (under) a text area then use - * an fo:block-container - */ - gen.writeln("newpath"); - gen.defineRect(pos.getMinX() / 1000f, pos.getMinY() / 1000f, - pos.width / 1000f, pos.height / 1000f); - gen.writeln("clip"); + //Check if all variations are used in all three colours + if (alphaSwap == null) { + //Fallback colour is no unique colour channel can be found + alphaSwap = FALLBACK_COLOR; } + //Replace alpha channel with the new mask colour + for (int cx = 0; cx < alphaImage.getWidth(); cx++) { + for (int cy = 0; cy < alphaImage.getHeight(); cy++) { + int pixelValue = alphaImage.getRGB(cx, cy); + if (pixelValue == 0) { + rgbImage.setRGB(cx, cy, alphaSwap.getRGB()); + } else { + rgbImage.setRGB(cx, cy, alphaImage.getRGB(cx, cy)); + } + } + } + return new MaskedImage(rgbImage, alphaSwap); + } + + private static class MaskedImage { + private Color maskColor = new Color(0, 0, 0); + private BufferedImage image; + + public MaskedImage(BufferedImage image, Color maskColor) { + this.image = image; + this.maskColor = maskColor; + } + + public Color getMaskColor() { + return maskColor; + } + + public BufferedImage getImage() { + return image; + } + } - // transform so that the coordinates (0,0) is from the top left - // and positive is down and to the right. (0,0) is where the - // viewBox puts it. - gen.concatMatrix(sx, 0, 0, sy, pos.getMinX() / 1000f, pos.getMinY() / 1000f); + private Float getDimension(Document document, String dimension) { + if (document.getFirstChild().getAttributes().getNamedItem(dimension) != null) { + String width = document.getFirstChild().getAttributes().getNamedItem(dimension).getNodeValue(); + width = width.replaceAll("[^\\d.]", ""); + return Float.parseFloat(width); + } + return null; + } - AffineTransform transform = new AffineTransform(); - // scale to viewbox - transform.translate(pos.getMinX(), pos.getMinY()); - gen.getCurrentState().concatMatrix(transform); + private boolean shouldRaster(ImageXMLDOM image) { + //A list of objects on which to check opacity try { - root.paint(graphics); - } catch (Exception e) { - SVGEventProducer eventProducer = SVGEventProducer.Provider.get( - context.getUserAgent().getEventBroadcaster()); - eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); + List<String> gradMatches = new ArrayList<String>(); + gradMatches.add("radialGradient"); + gradMatches.add("linearGradient"); + return recurseSVGElements(image.getDocument().getChildNodes(), gradMatches, false); + } finally { + gradientsFound.clear(); } + } - gen.restoreGraphicsState(); - gen.commentln("%FOPEndSVG"); + private boolean recurseSVGElements(NodeList childNodes, List<String> gradMatches, boolean isMatched) { + boolean opacityFound = false; + for (int i = 0; i < childNodes.getLength(); i++) { + Node curNode = childNodes.item(i); + if (isMatched && curNode.getLocalName() != null && curNode.getLocalName().equals("stop")) { + if (curNode.getAttributes().getNamedItem("style") != null) { + String[] stylePairs = curNode.getAttributes().getNamedItem("style").getNodeValue() + .split(";"); + for (int styleAtt = 0; styleAtt < stylePairs.length; styleAtt++) { + String[] style = stylePairs[styleAtt].split(":"); + if (style[0].equalsIgnoreCase("stop-opacity")) { + if (Double.parseDouble(style[1]) < 1) { + return true; + } + } + } + } + if (curNode.getAttributes().getNamedItem("stop-opacity") != null) { + String opacityValue = curNode.getAttributes().getNamedItem("stop-opacity").getNodeValue(); + if (Double.parseDouble(opacityValue) < 1) { + return true; + } + } + } + String nodeName = curNode.getLocalName(); + //Special case where rasterization needed for radial gradients + if (nodeName != null && nodeName.equals("ellipse")) { + String found = ""; + String ellipseFill = curNode.getAttributes().getNamedItem("fill").getNodeValue(); + Pattern pattern = Pattern.compile("#(.*?)\\)"); + Matcher matcher = pattern.matcher(ellipseFill); + if (matcher.find()) { + found = matcher.group(1); + } + if (gradientsFound.get(found) != null) { + return true; + } + } + boolean inMatch = false; + if (!isMatched) { + inMatch = nodeName != null && gradMatches.contains(nodeName); + if (inMatch) { + gradientsFound.put(curNode.getAttributes().getNamedItem("id").getNodeValue(), nodeName); + } + } else { + inMatch = true; + } + opacityFound = recurseSVGElements(curNode.getChildNodes(), gradMatches, inMatch); + if (opacityFound) { + return true; + } + } + return opacityFound; } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/ps/PSPainter.java b/src/java/org/apache/fop/render/ps/PSPainter.java index 3d1887f2d..547662c47 100644 --- a/src/java/org/apache/fop/render/ps/PSPainter.java +++ b/src/java/org/apache/fop/render/ps/PSPainter.java @@ -116,7 +116,7 @@ public class PSPainter extends AbstractIFPainter<PSDocumentHandler> { } /** {@inheritDoc} */ - public void startGroup(AffineTransform transform) throws IFException { + public void startGroup(AffineTransform transform, String layer) throws IFException { try { PSGenerator generator = getGenerator(); saveGraphicsState(); diff --git a/src/java/org/apache/fop/render/ps/svg/PSFunction.java b/src/java/org/apache/fop/render/ps/svg/PSFunction.java new file mode 100644 index 000000000..b03e0b590 --- /dev/null +++ b/src/java/org/apache/fop/render/ps/svg/PSFunction.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.ps.svg; + +import java.io.UnsupportedEncodingException; +import java.util.List; + +import org.apache.fop.render.shading.Function; +import org.apache.fop.render.shading.FunctionDelegate; +import org.apache.fop.render.shading.FunctionPattern; + +public class PSFunction implements Function { + + private FunctionDelegate delegate; + + /** + * Creates a Postscript function dictionary + * @param theFunctionType The function type (0 = Sampled, 2 = Exponential + * Interpolation, 3 = Stitching) + * @param theDomain The function domain + * @param theRange Range used for clipping + * @param theFunctions An array of sub-functions such as determining the + * colour values used in a gradient. + * @param theBounds Bounds determines where each boundary exists for whatever + * the function is mean't. In a gradient case, it would be the point between + * colours. + * @param theEncode The function encoding + */ + public PSFunction(int theFunctionType, List<Double> theDomain, + List<Double> theRange, List<Function> theFunctions, + List<Double> theBounds, List<Double> theEncode) { + delegate = new FunctionDelegate(this, theFunctionType, theDomain, theRange, theFunctions, + theBounds, theEncode); + } + + /** + * Creates a Postscript function dictionary + * @param theFunctionType The function type (0 = Sampled, 2 = Exponential + * Interpolation, 3 = Stitching) + * @param theDomain The function domain + * @param theRange Range used for clipping + * @param theCZero In a gradient, this would be the first colour + * @param theCOne In a gradient, this would be the second colour + * @param theInterpolationExponentN Determines the number of values + * the function returns. + */ + public PSFunction(int theFunctionType, List<Double> theDomain, + List<Double> theRange, List<Double> theCZero, List<Double> theCOne, + double theInterpolationExponentN) { + delegate = new FunctionDelegate(this, theFunctionType, theDomain, theRange, theCZero, + theCOne, theInterpolationExponentN); + } + + /** + * Outputs the function to a byte array + */ + public byte[] toByteString() { + FunctionPattern pattern = new FunctionPattern(this); + try { + return pattern.toWriteableString().getBytes("UTF-8"); + } catch (UnsupportedEncodingException ex) { + //This should have been made an enum type to avoid throwing exceptions. + return new byte[0]; + } + } + + public int getFunctionType() { + return delegate.getFunctionType(); + } + + public List<Double> getBounds() { + return delegate.getBounds(); + } + + public List<Double> getDomain() { + return delegate.getDomain(); + } + + public List<Double> getSize() { + return delegate.getSize(); + } + + public List<String> getFilter() { + return delegate.getFilter(); + } + + public List<Double> getEncode() { + return delegate.getEncode(); + } + + public List<Function> getFunctions() { + return delegate.getFunctions(); + } + + public int getBitsPerSample() { + return delegate.getBitsPerSample(); + } + + public double getInterpolationExponentN() { + return delegate.getInterpolationExponentN(); + } + + public int getOrder() { + return delegate.getOrder(); + } + + public List<Double> getRange() { + return delegate.getRange(); + } + + public List<Double> getDecode() { + return delegate.getDecode(); + } + + public StringBuffer getDataStream() { + return delegate.getDataStream(); + } + + public List<Double> getCZero() { + return delegate.getCZero(); + } + + public List<Double> getCOne() { + return delegate.getCOne(); + } +} diff --git a/src/java/org/apache/fop/render/ps/svg/PSPattern.java b/src/java/org/apache/fop/render/ps/svg/PSPattern.java new file mode 100644 index 000000000..46f976672 --- /dev/null +++ b/src/java/org/apache/fop/render/ps/svg/PSPattern.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.ps.svg; + +import java.util.List; + +import org.apache.fop.render.shading.Pattern; +import org.apache.fop.render.shading.Shading; + +public class PSPattern implements Pattern { + + /** + * Either one (1) for tiling, or two (2) for shading. + */ + protected int patternType = 2; // Default + + /** + * The Shading object comprising the Type 2 pattern + */ + protected PSShading shading = null; + + /** + * List of Integers represetning the Extended unique Identifier + */ + protected List xUID = null; + + /** + * TODO use PDFGState + * String representing the extended Graphics state. + * Probably will never be used like this. + */ + protected StringBuffer extGState = null; + + /** + * Creates a radial or axial shading pattern + * @param thePatternType The pattern type which will be 3 for radial and 2 for axial + * @param theShading The shading object to determine how the gradient + * is drawn + * @param theXUID The XUID + * @param theExtGState The exit state + */ + public PSPattern(int thePatternType, Shading theShading, List theXUID, + StringBuffer theExtGState) { + this.patternType = 2; // thePatternType; + assert theShading instanceof PSShading; + this.shading = (PSShading)theShading; + this.xUID = theXUID; + this.extGState = theExtGState; // always null + } + + /** + * Outputs the radial or axial pattern as a string dictionary to insert + * into a postscript document. + */ + public String toString() { + int vectorSize = 0; + int tempInt = 0; + StringBuffer p = new StringBuffer(64); + p.append("/Pattern setcolorspace\n"); + p.append("<< \n/Type /Pattern \n"); + + p.append("/PatternType " + this.patternType + " \n"); + + if (this.shading != null) { + p.append("/Shading " + this.shading.toString() + " \n"); + } + + if (this.xUID != null) { + vectorSize = this.xUID.size(); + p.append("/XUID [ "); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append((this.xUID.get(tempInt)) + " "); + } + p.append("] \n"); + } + + if (this.extGState != null) { + p.append("/ExtGState " + this.extGState + " \n"); + } + + p.append(">> \n"); + p.append("matrix makepattern setcolor\n"); + + return p.toString(); + } +} diff --git a/src/java/org/apache/fop/render/ps/svg/PSSVGGraphics2D.java b/src/java/org/apache/fop/render/ps/svg/PSSVGGraphics2D.java new file mode 100644 index 000000000..1c15e569b --- /dev/null +++ b/src/java/org/apache/fop/render/ps/svg/PSSVGGraphics2D.java @@ -0,0 +1,294 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.ps.svg; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Paint; +import java.awt.geom.AffineTransform; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.batik.ext.awt.LinearGradientPaint; +import org.apache.batik.ext.awt.MultipleGradientPaint; +import org.apache.batik.ext.awt.RadialGradientPaint; + +import org.apache.xmlgraphics.java2d.ps.PSGraphics2D; +import org.apache.xmlgraphics.ps.PSGenerator; + +import org.apache.fop.pdf.PDFDeviceColorSpace; +import org.apache.fop.render.shading.Function; +import org.apache.fop.render.shading.GradientFactory; +import org.apache.fop.render.shading.GradientRegistrar; +import org.apache.fop.render.shading.PSGradientFactory; +import org.apache.fop.render.shading.Pattern; +import org.apache.fop.render.shading.Shading; + + +public class PSSVGGraphics2D extends PSGraphics2D implements GradientRegistrar { + + private static final Log LOG = LogFactory.getLog(PSSVGGraphics2D.class); + + /** + * Create a new Graphics2D that generates PostScript code. + * @param textAsShapes True if text should be rendered as graphics + * @see org.apache.xmlgraphics.java2d.AbstractGraphics2D#AbstractGraphics2D(boolean) + */ + public PSSVGGraphics2D(boolean textAsShapes) { + super(textAsShapes); + } + + /** + * Create a new Graphics2D that generates PostScript code. + * @param textAsShapes True if text should be rendered as graphics + * @param gen PostScript generator to use for output + * @see org.apache.xmlgraphics.java2d.AbstractGraphics2D#AbstractGraphics2D(boolean) + */ + public PSSVGGraphics2D(boolean textAsShapes, PSGenerator gen) { + super(textAsShapes, gen); + } + + /** + * Constructor for creating copies + * @param g parent PostScript Graphics2D + */ + public PSSVGGraphics2D(PSGraphics2D g) { + super(g); + } + + protected void applyPaint(Paint paint, boolean fill) { + super.applyPaint(paint, fill); + if (paint instanceof RadialGradientPaint) { + RadialGradientPaint rgp = (RadialGradientPaint)paint; + try { + handleRadialGradient(rgp, gen); + } catch (IOException ioe) { + handleIOException(ioe); + } + } else if (paint instanceof LinearGradientPaint) { + LinearGradientPaint lgp = (LinearGradientPaint)paint; + try { + handleLinearGradient(lgp, gen); + } catch (IOException ioe) { + handleIOException(ioe); + } + } + } + + private void handleLinearGradient(LinearGradientPaint lgp, PSGenerator gen) throws IOException { + MultipleGradientPaint.CycleMethodEnum cycle = lgp.getCycleMethod(); + if (cycle != MultipleGradientPaint.NO_CYCLE) { + return; + } + float[] fractions = lgp.getFractions(); + Color[] cols = lgp.getColors(); + + AffineTransform transform = new AffineTransform(getBaseTransform()); + transform.concatenate(getTransform()); + transform.concatenate(lgp.getTransform()); + + List theMatrix = new ArrayList(); + double [] mat = new double[6]; + transform.getMatrix(mat); + for (int idx = 0; idx < mat.length; idx++) { + theMatrix.add(Double.valueOf(mat[idx])); + } + + + List<Double> theCoords = new java.util.ArrayList<Double>(); + + + AffineTransform start = applyTransform(lgp.getTransform(), + lgp.getStartPoint().getX(), lgp.getStartPoint().getY()); + AffineTransform end = applyTransform(lgp.getTransform(), lgp.getEndPoint().getX(), lgp.getEndPoint().getY()); + double startX = start.getTranslateX(); + double startY = start.getTranslateY(); + double endX = end.getTranslateX(); + double endY = end.getTranslateY(); + + double width = endX - startX; + double height = endY - startY; + + startX = startX + width * fractions[0]; + endX = endX - width * (1 - fractions[fractions.length - 1]); + startY = startY + (height * fractions[0]); + endY = endY - height * (1 - fractions[fractions.length - 1]); + + theCoords.add(startX); + theCoords.add(startY); + theCoords.add(endX); + theCoords.add(endY); + + + List<Color> someColors = new java.util.ArrayList<Color>(); + for (int count = 0; count < cols.length; count++) { + Color c1 = cols[count]; + if (c1.getAlpha() != 255) { + LOG.warn("Opacity is not currently supported for Postscript output"); + } + someColors.add(c1); + } + List<Double> theBounds = new java.util.ArrayList<Double>(); + for (int count = 1; count < fractions.length - 1; count++) { + float offset = fractions[count]; + theBounds.add(Double.valueOf(offset)); + } + PDFDeviceColorSpace colSpace; + colSpace = new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_RGB); + + PSGradientFactory gradientFactory = (PSGradientFactory)GradientFactory.newInstance(this); + PSPattern myPattern = gradientFactory.createGradient(false, colSpace, + someColors, theBounds, theCoords, theMatrix); + + gen.write(myPattern.toString()); + + } + + + + private void handleRadialGradient(RadialGradientPaint rgp, PSGenerator gen) throws IOException { + MultipleGradientPaint.CycleMethodEnum cycle = rgp.getCycleMethod(); + if (cycle != MultipleGradientPaint.NO_CYCLE) { + return; + } + + AffineTransform transform; + transform = new AffineTransform(getBaseTransform()); + transform.concatenate(getTransform()); + transform.concatenate(rgp.getTransform()); + + AffineTransform resultCentre = applyTransform(rgp.getTransform(), + rgp.getCenterPoint().getX(), rgp.getCenterPoint().getY()); + AffineTransform resultFocus = applyTransform(rgp.getTransform(), + rgp.getFocusPoint().getX(), rgp.getFocusPoint().getY()); + double scale = Math.sqrt(rgp.getTransform().getDeterminant()); + double radius = rgp.getRadius() * scale; + double centreX = resultCentre.getTranslateX(); + double centreY = resultCentre.getTranslateY(); + double focusX = resultFocus.getTranslateX(); + double focusY = resultFocus.getTranslateY(); + + List<Double> theMatrix = new java.util.ArrayList<Double>(); + double [] mat = new double[6]; + transform.getMatrix(mat); + for (int idx = 0; idx < mat.length; idx++) { + theMatrix.add(Double.valueOf(mat[idx])); + } + + List<Double> theCoords = new java.util.ArrayList<Double>(); + float[] fractions = rgp.getFractions(); + + theCoords.add(centreX); + theCoords.add(centreY); + theCoords.add(radius * rgp.getFractions()[0]); + theCoords.add(focusX); + theCoords.add(focusY); + theCoords.add(radius * fractions[fractions.length - 1]); + + Color[] cols = rgp.getColors(); + List<Color> someColors = new java.util.ArrayList<Color>(); + for (int count = 0; count < cols.length; count++) { + Color cc = cols[count]; + if (cc.getAlpha() != 255) { + /* This should never happen because radial gradients with opacity should now + * be rasterized in the PSImageHandlerSVG class. Please see the shouldRaster() + * method for more information. */ + LOG.warn("Opacity is not currently supported for Postscript output"); + } + + someColors.add(cc); + } + + List<Double> theBounds = new java.util.ArrayList<Double>(); + for (int count = 1; count < fractions.length - 1; count++) { + float offset = fractions[count]; + theBounds.add(Double.valueOf(offset)); + } + PDFDeviceColorSpace colSpace; + colSpace = new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_RGB); + + PSGradientFactory gradientFactory = (PSGradientFactory)GradientFactory.newInstance(this); + PSPattern myPattern = gradientFactory.createGradient(true, colSpace, + someColors, theBounds, theCoords, theMatrix); + + gen.write(myPattern.toString()); + } + + private AffineTransform applyTransform(AffineTransform base, double posX, double posY) { + AffineTransform result = AffineTransform.getTranslateInstance(posX, posY); + AffineTransform orig = base; + orig.concatenate(result); + return orig; + } + + protected AffineTransform getBaseTransform() { + AffineTransform at = new AffineTransform(this.getTransform()); + return at; + } + + /** + * Creates a new <code>Graphics</code> object that is + * a copy of this <code>Graphics</code> object. + * @return a new graphics context that is a copy of + * this graphics context. + */ + @Override + public Graphics create() { + preparePainting(); + return new PSSVGGraphics2D(this); + } + + /** + * Registers a function object against the output format document + * @param function The function object to register + * @return Returns either the function which has already been registered + * or the current new registered object. + */ + public Function registerFunction(Function function) { + //Objects aren't needed to be registered in Postscript + return function; + } + + /** + * Registers a shading object against the otuput format document + * @param shading The shading object to register + * @return Returs either the shading which has already been registered + * or the current new registered object + */ + public Shading registerShading(Shading shading) { + //Objects aren't needed to be registered in Postscript + return shading; + } + + /** + * Registers a pattern object against the output format document + * @param pattern The pattern object to register + * @return Returns either the pattern which has already been registered + * or the current new registered object + */ + public Pattern registerPattern(Pattern pattern) { + // TODO Auto-generated method stub + return pattern; + } +} diff --git a/src/java/org/apache/fop/render/ps/svg/PSShading.java b/src/java/org/apache/fop/render/ps/svg/PSShading.java new file mode 100644 index 000000000..7465fcadb --- /dev/null +++ b/src/java/org/apache/fop/render/ps/svg/PSShading.java @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.ps.svg; + +import java.io.UnsupportedEncodingException; +import java.util.List; + +import org.apache.fop.pdf.PDFDeviceColorSpace; +import org.apache.fop.pdf.PDFNumber; +import org.apache.fop.render.shading.Function; +import org.apache.fop.render.shading.Shading; +import org.apache.fop.render.shading.ShadingPattern; + +public class PSShading implements Shading { + + /** + * Required: The Type of shading (1,2,3,4,5,6,7) + */ + protected int shadingType = 3; // Default + + /** + * A ColorSpace representing the colorspace. "DeviceRGB" is an example. + */ + protected PDFDeviceColorSpace colorSpace = null; + + /** + * The background color. Since shading is opaque, + * this is very rarely used. + */ + protected List background = null; + + /** + * Optional: A List specifying the clipping rectangle + */ + protected List bBox = null; + + /** + * Optional: A flag whether or not to filter the shading function + * to prevent aliasing artifacts. Default is false. + */ + protected boolean antiAlias = false; + + /** + * Optional for Type 1: Array of four numbers, xmin, xmax, ymin, ymax. + * Default is [0 1 0 1] + * Optional for Type 2: An array of two numbers between which the blend + * varies between start and end points. Default is 0, 1. + * Optional for Type 3: An array of two numbers between which the blend + * varies between start and end points. Default is 0, 1. + */ + protected List domain = null; + + /** + * Required for Type 1, 2, and 3: + * The object of the color mapping function (usually type 2 or 3). + * Optional for Type 4,5,6, and 7: When it's nearly the same thing. + */ + protected PSFunction function = null; + + /** + * Required for Type 2: An Array of four numbers specifying + * the starting and ending coordinate pairs + * Required for Type 3: An Array of six numbers [x0,y0,r0,x1,y1,r1] + * specifying the centers and radii of + * the starting and ending circles. + */ + protected List coords = null; + + /** + * Required for Type 2+3: An Array of two boolean values specifying + * whether to extend the start and end colors past the start + * and end points, respectively. + * Default is false, false. + */ + protected List extend = null; + + /** + * Constructor for Type 2 and 3 + * + * @param theShadingType 2 or 3 for axial or radial shading + * @param theColorSpace "DeviceRGB" or similar. + * @param theBackground theBackground An array of color components appropriate to the + * colorspace key specifying a single color value. + * This key is used by the f operator buy ignored by the sh operator. + * @param theBBox List of double's representing a rectangle + * in the coordinate space that is current at the + * time of shading is imaged. Temporary clipping + * boundary. + * @param theAntiAlias Default is false + * @param theCoords List of four (type 2) or 6 (type 3) Double + * @param theDomain List of Doubles specifying the domain + * @param theFunction the Stitching (PDFfunction type 3) function, + * even if it's stitching a single function + * @param theExtend List of Booleans of whether to extend the start + * and end colors past the start and end points + * The default is [false, false] + */ + public PSShading(int theShadingType, PDFDeviceColorSpace theColorSpace, + List<Double> theBackground, List<Double> theBBox, + boolean theAntiAlias, List<Double> theCoords, + List<Double> theDomain, Function theFunction, + List<Integer> theExtend) { + this.shadingType = theShadingType; // 2 or 3 + this.colorSpace = theColorSpace; + this.background = theBackground; + this.bBox = theBBox; + this.antiAlias = theAntiAlias; + + this.coords = theCoords; + this.domain = theDomain; + assert theFunction instanceof PSFunction; + this.function = (PSFunction)theFunction; + this.extend = theExtend; + } + + /** + * represent as PS. Whatever the shadingType is, the correct + * representation spits out. The sets of required and optional + * attributes are different for each type, but if a required + * attribute's object was constructed as null, then no error + * is raised. Instead, the malformed PS that was requested + * by the construction is dutifully output. + * This policy should be reviewed. + * + * @return the PDF string. + */ + public String toString() { + ShadingPattern pattern = new ShadingPattern(this); + return pattern.toString(colorSpace, shadingType, background, bBox, antiAlias); + } + + /** + * A method to write a type 2 or 3 shading object + * @param p The StringBuffer to write the shading object + * @return Returns the StringBuffer to which the shading object was written + */ + public StringBuffer handleShadingType2or3(StringBuffer p) { + if (this.coords != null) { + p.append("\t/Coords [ "); + for (int coordIndex = 0; coordIndex < coords.size(); coordIndex++) { + p.append(PDFNumber.doubleOut((Double)this.coords.get(coordIndex)) + + " "); + } + p.append("] \n"); + } + + // DOMAIN + if (this.domain != null) { + p.append("\t/Domain [ "); + for (int domainIndex = 0; domainIndex < domain.size(); domainIndex++) { + p.append(PDFNumber.doubleOut((Double)this.domain.get(domainIndex)) + + " "); + } + p.append("] \n"); + } else { + p.append("\t/Domain [ 0 1 ] \n"); + } + + if (this.extend != null) { + p.append("\t/Extend [ "); + for (int extendIndex = 0; extendIndex < extend.size(); extendIndex++) { + p.append((this.extend.get(extendIndex)) + " "); + } + + p.append("] \n"); + } else { + p.append("\t/Extend [ true true ] \n"); + } + + + if (this.function != null) { + p.append("\t/Function "); + try { + p.append(new String(this.function.toByteString(), "UTF-8") + " \n"); + } catch (UnsupportedEncodingException ex) { + //This should have been made an enum type to avoid throwing exceptions. + } + } + return p; + } + + /** + * A method to write a type 1 shading object + * @param p The StringBuffer to write the shading object + * @return Returns the StringBuffer to which the shading object was written + */ + public StringBuffer handleShadingType1(StringBuffer p) { + // TODO Auto-generated method stub + return null; + } + + /** + * A method to write a type 4, 6 or 7 shading object + * @param p The StringBuffer to write the shading object + * @return Returns the StringBuffer to which the shading object was written + */ + public StringBuffer handleShadingType4or6or7(StringBuffer p) { + // TODO Auto-generated method stub + return null; + } + + /** + * A method to write a type 5 shading object + * @param p The StringBuffer to write the shading object + * @return Returns the StringBuffer to which the shading object was written + */ + public StringBuffer handleShadingType5(StringBuffer p) { + // TODO Auto-generated method stub + return null; + } +} diff --git a/src/java/org/apache/fop/render/rtf/RTFHandler.java b/src/java/org/apache/fop/render/rtf/RTFHandler.java index dfeff65f1..73fa3504c 100644 --- a/src/java/org/apache/fop/render/rtf/RTFHandler.java +++ b/src/java/org/apache/fop/render/rtf/RTFHandler.java @@ -157,6 +157,7 @@ public class RTFHandler extends FOEventHandler { private PercentContext percentManager = new PercentContext(); + /** * Creates a new RTF structure handler. * @param userAgent the FOUserAgent for this process @@ -270,7 +271,7 @@ public class RTFHandler extends FOEventHandler { return; } else { - builderContext.popContainer(); + builderContext.popContainer(RtfSection.class, this); this.pagemaster = null; } } @@ -377,10 +378,10 @@ public class RTFHandler extends FOEventHandler { //just do nothing } else if (regionBefore != null && fl.getFlowName().equals(regionBefore.getRegionName())) { - builderContext.popContainer(); + builderContext.popContainer(RtfBefore.class, this); } else if (regionAfter != null && fl.getFlowName().equals(regionAfter.getRegionName())) { - builderContext.popContainer(); + builderContext.popContainer(RtfAfter.class, this); } } catch (Exception e) { log.error("endFlow: " + e.getMessage()); @@ -571,7 +572,7 @@ public class RTFHandler extends FOEventHandler { nestedTableDepth--; builderContext.popTableContext(); - builderContext.popContainer(); + builderContext.popContainer(RtfTable.class, this); } /** {@inheritDoc} */ @@ -605,21 +606,25 @@ public class RTFHandler extends FOEventHandler { /** {@inheritDoc} */ public void startHeader(TableHeader header) { + builderContext.pushPart(header); startPart(header); } /** {@inheritDoc} */ public void endHeader(TableHeader header) { + builderContext.popPart(header.getClass(), this); endPart(header); } /** {@inheritDoc} */ public void startFooter(TableFooter footer) { + builderContext.pushPart(footer); startPart(footer); } /** {@inheritDoc} */ public void endFooter(TableFooter footer) { + builderContext.popPart(footer.getClass(), this); endPart(footer); } @@ -711,11 +716,13 @@ public class RTFHandler extends FOEventHandler { * {@inheritDoc} */ public void startBody(TableBody body) { + builderContext.pushPart(body); startPart(body); } /** {@inheritDoc} */ public void endBody(TableBody body) { + builderContext.popPart(TableBody.class, this); endPart(body); } @@ -784,7 +791,7 @@ public class RTFHandler extends FOEventHandler { } - builderContext.popContainer(); + builderContext.popContainer(RtfTableRow.class, this); builderContext.getTableContext().decreaseRowSpannings(); } @@ -893,7 +900,7 @@ public class RTFHandler extends FOEventHandler { throw new RuntimeException(e.getMessage()); } - builderContext.popContainer(); + builderContext.popContainer(RtfTableCell.class, this); builderContext.getTableContext().selectNextColumn(); } @@ -929,7 +936,7 @@ public class RTFHandler extends FOEventHandler { return; } - builderContext.popContainer(); + builderContext.popContainer(RtfList.class, this); } /** {@inheritDoc} */ @@ -976,7 +983,7 @@ public class RTFHandler extends FOEventHandler { return; } - builderContext.popContainer(); + builderContext.popContainer(RtfListItem.class, this); } /** {@inheritDoc} */ @@ -1005,7 +1012,7 @@ public class RTFHandler extends FOEventHandler { return; } - builderContext.popContainer(); + builderContext.popContainer(RtfListItemLabel.class, this); } /** {@inheritDoc} */ @@ -1070,7 +1077,7 @@ public class RTFHandler extends FOEventHandler { return; } - builderContext.popContainer(); + builderContext.popContainer(RtfHyperLink.class, this); } /** {@inheritDoc} */ @@ -1306,7 +1313,7 @@ public class RTFHandler extends FOEventHandler { return; } - builderContext.popContainer(); + builderContext.popContainer(RtfFootnote.class, this); } /** {@inheritDoc} */ @@ -1688,6 +1695,19 @@ public class RTFHandler extends FOEventHandler { } /** + * Closes any mismatched tags that are detected in the RTF structure. + * @param containerClass The class representing the tag to close. + * @return Determines whether the tag mismatch has been handled. + */ + public boolean endContainer(Class containerClass) { + if (containerClass == RtfTableRow.class) { + endRow(null); + return true; + } + return false; + } + + /** * Calls the event handlers for the passed FONode and all its elements. * * @param foNode FONode object which shall be recursed diff --git a/src/java/org/apache/fop/render/rtf/RTFPlaceHolderHelper.java b/src/java/org/apache/fop/render/rtf/RTFPlaceHolderHelper.java new file mode 100644 index 000000000..e3278ad95 --- /dev/null +++ b/src/java/org/apache/fop/render/rtf/RTFPlaceHolderHelper.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.rtf; + +import org.apache.fop.render.rtf.rtflib.exceptions.RtfException; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfAttributes; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfContainer; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; +import org.apache.fop.render.rtf.rtflib.tools.BuilderContext; + +/** + * This class creates objects which are missing from the XSL:FO but are required + * by the RTF format. + */ +public class RTFPlaceHolderHelper { + /** The context object for building the RTF */ + private BuilderContext builderContext; + + /** + * Creates a new instance for the RTF place holder which attempts to resolve + * mismatches in structure between XSL:FO and RTF. + * @param builderContext The builder context + */ + public RTFPlaceHolderHelper(BuilderContext builderContext) { + this.builderContext = builderContext; + } + + /** + * A method to create an object which is missing and required from the + * RTF structure. + * @param containerClass The class which is missing + * @throws Exception + */ + public void createRTFPlaceholder(Class containerClass) throws RtfException { + if (containerClass == RtfTableRow.class) { + createRtfTableRow(); + } + } + + private void createRtfTableRow() throws RtfException { + try { + RtfContainer element = builderContext.getContainer(RtfTable.class, true, null); + if (element != null && element instanceof RtfTable) { + RtfTable table = (RtfTable)element; + RtfAttributes attribs = new RtfAttributes(); + RtfTableRow newRow = table.newTableRow(attribs); + builderContext.pushContainer(newRow); + builderContext.getTableContext().selectFirstColumn(); + } + } catch (org.apache.fop.apps.FOPException e) { + throw new RtfException(e.getMessage()); + } catch (java.io.IOException e) { + throw new RtfException(e.getMessage()); + } + } +} diff --git a/src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java b/src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java index f0a29a0ab..4b3f8bd4a 100644 --- a/src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java +++ b/src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java @@ -21,6 +21,12 @@ package org.apache.fop.render.rtf.rtflib.tools; import java.util.Stack; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.fop.fo.FObj; +import org.apache.fop.render.rtf.RTFHandler; +import org.apache.fop.render.rtf.RTFPlaceHolderHelper; import org.apache.fop.render.rtf.rtflib.exceptions.RtfException; import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfOptions; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfContainer; @@ -38,6 +44,10 @@ import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfContainer; */ public class BuilderContext { + + /** Static logging instance */ + protected static final Log LOG = LogFactory.getLog(BuilderContext.class.getName()); + /** stack of RtfContainers */ private final Stack containers = new Stack(); @@ -96,17 +106,22 @@ public class BuilderContext { * @throws RtfException if not caught */ public RtfContainer getContainer(Class containerClass, boolean required, - Object /*IBuilder*/ forWhichBuilder) throws RtfException { + Object forWhichBuilder) throws RtfException { // TODO what to do if the desired container is not at the top of the stack? // close top-of-stack container? - final RtfContainer result = (RtfContainer)getObjectFromStack(containers, + RtfContainer result = (RtfContainer)getObjectFromStack(containers, containerClass); if (result == null && required) { - throw new RtfException( - "No RtfContainer of class '" + containerClass.getName() - + "' available for '" + forWhichBuilder.getClass().getName() + "' builder" - ); + RTFPlaceHolderHelper placeHolderHelper = new RTFPlaceHolderHelper(this); + placeHolderHelper.createRTFPlaceholder(containerClass); + result = getContainer(containerClass, required, forWhichBuilder); + if (result == null) { + throw new RtfException( + "No RtfContainer of class '" + containerClass.getName() + + "' available for '" + forWhichBuilder.getClass().getName() + "' builder" + ); + } } return result; @@ -121,6 +136,14 @@ public class BuilderContext { } /** + * Push a Class representing a non-writeable section of the FO tree + * @param part the part + */ + public void pushPart(FObj part) { + containers.push(part); + } + + /** * In some cases an RtfContainer must be replaced by another one on the * stack. This happens when handling nested fo:blocks for example: after * handling a nested block the enclosing block must switch to a new @@ -142,8 +165,40 @@ public class BuilderContext { } /** pop the topmost RtfContainer from our stack */ - public void popContainer() { - containers.pop(); + public void popContainer(Class containerClass, RTFHandler handler) { + handlePop(containerClass, handler); + } + + /** pop the topmost part class from our stack */ + public void popPart(Class part, RTFHandler handler) { + handlePop(part, handler); + } + + /** + * This method checks for any tag mismatches between what is being closed + * and what exists on the stack. If a mismatch is found, then it will push + * the object back onto the stack and attempt to close the given section + * before retrying with the current pop task. + * @param aClass The class to be popped from the stack + * @param handler The RTF handler class to fix any mismatches + */ + private void handlePop(Class aClass, RTFHandler handler) { + Object object = containers.pop(); + if (object.getClass() != aClass) { + pushAndClose(aClass, object, handler); + } + } + + private void pushAndClose(Class aClass, Object object, RTFHandler handler) { + containers.push(object); + if (handler.endContainer(object.getClass())) { + popContainer(aClass, handler); + } else { + /* This should never happen unless a placeholder is not catered for + * in the RTFHandler.endContainer method. */ + LOG.warn("Unhandled RTF structure tag mismatch detected between " + + aClass.getSimpleName() + " and " + object.getClass().getSimpleName()); + } } /* push an IBuilder to our stack / diff --git a/src/java/org/apache/fop/render/shading/Function.java b/src/java/org/apache/fop/render/shading/Function.java new file mode 100644 index 000000000..5bd44087e --- /dev/null +++ b/src/java/org/apache/fop/render/shading/Function.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.shading; + +import java.util.List; + +public interface Function { + int getFunctionType(); + List<Double> getBounds(); + List<Double> getDomain(); + List<Double> getSize(); + List<String> getFilter(); + List<Double> getEncode(); + List<Function> getFunctions(); + int getBitsPerSample(); + double getInterpolationExponentN(); + int getOrder(); + List<Double> getRange(); + List<Double> getDecode(); + StringBuffer getDataStream(); + List<Double> getCZero(); + List<Double> getCOne(); + byte[] toByteString(); +} diff --git a/src/java/org/apache/fop/render/shading/FunctionDelegate.java b/src/java/org/apache/fop/render/shading/FunctionDelegate.java new file mode 100644 index 000000000..eea24e0db --- /dev/null +++ b/src/java/org/apache/fop/render/shading/FunctionDelegate.java @@ -0,0 +1,451 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.shading; + +import java.util.List; + +public class FunctionDelegate implements Function { + + private Function parentFunction; + + /** + * Required: The Type of function (0,2,3,4) default is 0. + */ + protected int functionType = 0; // Default + + /** + * Required: 2 * m Array of Double numbers which are possible inputs to the function + */ + protected List<Double> domain = null; + + /** + * Required: 2 * n Array of Double numbers which are possible outputs to the function + */ + protected List<Double> range = null; + + /* ********************TYPE 0***************************** */ + // FunctionType 0 specific function guts + + /** + * Required: Array containing the Integer size of the Domain and Range, respectively. + * Note: This is really more like two seperate integers, sizeDomain, and sizeRange, + * but since they're expressed as an array in PDF, my implementation reflects that. + */ + protected List<Double> size = null; + + /** + * Required for Type 0: Number of Bits used to represent each sample value. + * Limited to 1,2,4,8,12,16,24, or 32 + */ + protected int bitsPerSample = 1; + + /** + * Optional for Type 0: order of interpolation between samples. + * Limited to linear (1) or cubic (3). Default is 1 + */ + protected int order = 1; + + /** + * Optional for Type 0: A 2 * m array of Doubles which provides a + * linear mapping of input values to the domain. + * + * Required for Type 3: A 2 * k array of Doubles that, taken + * in pairs, map each subset of the domain defined by Domain + * and the Bounds array to the domain of the corresponding function. + * Should be two values per function, usually (0,1), + * as in [0 1 0 1] for 2 functions. + */ + protected List<Double> encode = null; + + /** + * Optional for Type 0: A 2 * n array of Doubles which provides + * a linear mapping of sample values to the range. Defaults to Range. + */ + protected List<Double> decode = null; + + /** + * Optional For Type 0: A stream of sample values + */ + + /** + * Required For Type 4: Postscript Calculator function + * composed of arithmetic, boolean, and stack operators + boolean constants + */ + protected StringBuffer functionDataStream = null; + + /** + * Required (possibly) For Type 0: A vector of Strings for the + * various filters to be used to decode the stream. + * These are how the string is compressed. Flate, LZW, etc. + */ + protected List<String> filter = null; + /* *************************TYPE 2************************** */ + + /** + * Required For Type 2: An Array of n Doubles defining + * the function result when x=0. Default is [0]. + */ + protected List<Double> cZero = null; + + /** + * Required For Type 2: An Array of n Doubles defining + * the function result when x=1. Default is [1]. + */ + protected List<Double> cOne = null; + + /** + * Required for Type 2: The interpolation exponent. + * Each value x will return n results. + * Must be greater than 0. + */ + protected double interpolationExponentN = 1; + + /* *************************TYPE 3************************** */ + + /** + * Required for Type 3: An vector of PDFFunctions which + * form an array of k single input functions making up + * the stitching function. + */ + protected List<Function> functions = null; + + /** + * Optional for Type 3: An array of (k-1) Doubles that, + * in combination with Domain, define the intervals to which + * each function from the Functions array apply. Bounds + * elements must be in order of increasing magnitude, + * and each value must be within the value of Domain. + * k is the number of functions. + * If you pass null, it will output (1/k) in an array of k-1 elements. + * This makes each function responsible for an equal amount of the stitching function. + * It makes the gradient even. + */ + protected List<Double> bounds = null; + + /** + * create an complete Function object of Type 0, A Sampled function. + * + * Use null for an optional object parameter if you choose not to use it. + * For optional int parameters, pass the default. + * + * @param theDomain List objects of Double objects. + * This is the domain of the function. + * See page 264 of the PDF 1.3 Spec. + * @param theRange List objects of Double objects. + * This is the Range of the function. + * See page 264 of the PDF 1.3 Spec. + * @param theSize A List object of Integer objects. + * This is the number of samples in each input dimension. + * I can't imagine there being more or less than two input dimensions, + * so maybe this should be an array of length 2. + * + * See page 265 of the PDF 1.3 Spec. + * @param theBitsPerSample An int specifying the number of bits + used to represent each sample value. + * Limited to 1,2,4,8,12,16,24 or 32. + * See page 265 of the 1.3 PDF Spec. + * @param theOrder The order of interpolation between samples. Default is 1 (one). Limited + * to 1 (one) or 3, which means linear or cubic-spline interpolation. + * + * This attribute is optional. + * + * See page 265 in the PDF 1.3 spec. + * @param theEncode List objects of Double objects. + * This is the linear mapping of input values intop the domain + * of the function's sample table. Default is hard to represent in + * ascii, but basically [0 (Size0 1) 0 (Size1 1)...]. + * This attribute is optional. + * + * See page 265 in the PDF 1.3 spec. + * @param theDecode List objects of Double objects. + * This is a linear mapping of sample values into the range. + * The default is just the range. + * + * This attribute is optional. + * Read about it on page 265 of the PDF 1.3 spec. + * @param theFunctionDataStream The sample values that specify + * the function are provided in a stream. + * + * This is optional, but is almost always used. + * + * Page 265 of the PDF 1.3 spec has more. + * @param theFilter This is a vector of String objects which are the various filters that + * have are to be applied to the stream to make sense of it. Order matters, + * so watch out. + * + * This is not documented in the Function section of the PDF 1.3 spec, + * it was deduced from samples that this is sometimes used, even if we may never + * use it in FOP. It is added for completeness sake. + * @param theFunctionType This is the type of function (0,2,3, or 4). + * It should be 0 as this is the constructor for sampled functions. + */ + public FunctionDelegate(Function parentFunction, int theFunctionType, List<Double> theDomain, + List<Double> theRange, List<Double> theSize, int theBitsPerSample, + int theOrder, List<Double> theEncode, List<Double> theDecode, + StringBuffer theFunctionDataStream, List<String> theFilter) { + this.parentFunction = parentFunction; + this.functionType = 0; // dang well better be 0; + this.size = theSize; + this.bitsPerSample = theBitsPerSample; + this.order = theOrder; // int + this.encode = theEncode; // vector of int + this.decode = theDecode; // vector of int + this.functionDataStream = theFunctionDataStream; + this.filter = theFilter; // vector of Strings + + // the domain and range are actually two dimensional arrays. + // so if there's not an even number of items, bad stuff + // happens. + this.domain = theDomain; + this.range = theRange; + } + + /** + * create an complete Function object of Type 2, an Exponential Interpolation function. + * + * Use null for an optional object parameter if you choose not to use it. + * For optional int parameters, pass the default. + * + * @param theDomain List objects of Double objects. + * This is the domain of the function. + * See page 264 of the PDF 1.3 Spec. + * @param theRange List of Doubles that is the Range of the function. + * See page 264 of the PDF 1.3 Spec. + * @param theCZero This is a vector of Double objects which defines the function result + * when x=0. + * + * This attribute is optional. + * It's described on page 268 of the PDF 1.3 spec. + * @param theCOne This is a vector of Double objects which defines the function result + * when x=1. + * + * This attribute is optional. + * It's described on page 268 of the PDF 1.3 spec. + * @param theInterpolationExponentN This is the inerpolation exponent. + * + * This attribute is required. + * PDF Spec page 268 + * @param theFunctionType The type of the function, which should be 2. + */ + public FunctionDelegate(Function parentFunction, int theFunctionType, List<Double> theDomain, + List<Double> theRange, List<Double> theCZero, List<Double> theCOne, + double theInterpolationExponentN) { + this.parentFunction = parentFunction; + this.functionType = 2; // dang well better be 2; + + this.cZero = theCZero; + this.cOne = theCOne; + this.interpolationExponentN = theInterpolationExponentN; + + this.domain = theDomain; + this.range = theRange; + + } + + /** + * create an complete Function object of Type 3, a Stitching function. + * + * Use null for an optional object parameter if you choose not to use it. + * For optional int parameters, pass the default. + * + * @param theDomain List objects of Double objects. + * This is the domain of the function. + * See page 264 of the PDF 1.3 Spec. + * @param theRange List objects of Double objects. + * This is the Range of the function. + * See page 264 of the PDF 1.3 Spec. + * @param theFunctions A List of the PDFFunction objects that the stitching function stitches. + * + * This attributed is required. + * It is described on page 269 of the PDF spec. + * @param theBounds This is a vector of Doubles representing the numbers that, + * in conjunction with Domain define the intervals to which each function from + * the 'functions' object applies. It must be in order of increasing magnitude, + * and each must be within Domain. + * + * It basically sets how much of the gradient each function handles. + * + * This attributed is required. + * It's described on page 269 of the PDF 1.3 spec. + * @param theEncode List objects of Double objects. + * This is the linear mapping of input values intop the domain + * of the function's sample table. Default is hard to represent in + * ascii, but basically [0 (Size0 1) 0 (Size1 1)...]. + * This attribute is required. + * + * See page 270 in the PDF 1.3 spec. + * @param theFunctionType This is the function type. It should be 3, + * for a stitching function. + */ + public FunctionDelegate(Function parentFunction, int theFunctionType, List<Double> theDomain, + List<Double> theRange, List<Function> theFunctions, + List<Double> theBounds, List<Double> theEncode) { + this.parentFunction = parentFunction; + this.functionType = 3; // dang well better be 3; + + this.functions = theFunctions; + this.bounds = theBounds; + this.encode = theEncode; + this.domain = theDomain; + this.range = theRange; + + } + + /** + * create an complete Function object of Type 4, a postscript calculator function. + * + * Use null for an optional object parameter if you choose not to use it. + * For optional int parameters, pass the default. + * + * @param theDomain List object of Double objects. + * This is the domain of the function. + * See page 264 of the PDF 1.3 Spec. + * @param theRange List object of Double objects. + * This is the Range of the function. + * See page 264 of the PDF 1.3 Spec. + * @param theFunctionDataStream This is a stream of arithmetic, + * boolean, and stack operators and boolean constants. + * I end up enclosing it in the '{' and '}' braces for you, so don't do it + * yourself. + * + * This attribute is required. + * It's described on page 269 of the PDF 1.3 spec. + * @param theFunctionType The type of function which should be 4, as this is + * a Postscript calculator function + */ + public FunctionDelegate(Function parentFunction, int theFunctionType, List<Double> theDomain, + List<Double> theRange, StringBuffer theFunctionDataStream) { + this.parentFunction = parentFunction; + this.functionType = 4; // dang well better be 4; + this.functionDataStream = theFunctionDataStream; + + this.domain = theDomain; + + this.range = theRange; + + } + + /** + * Gets the function type + */ + public int getFunctionType() { + return functionType; + } + + /** + * Gets the function bounds + */ + public List<Double> getBounds() { + return bounds; + } + + /** + * The function domain + */ + public List<Double> getDomain() { + return domain; + } + + /** + * The function size + */ + public List<Double> getSize() { + return size; + } + + /** + * Gets the function encoding + */ + public List<Double> getEncode() { + return encode; + } + + /** + * Gets the sub-functions + */ + public List<Function> getFunctions() { + return functions; + } + + /** + * Gets the function filter + */ + public List<String> getFilter() { + return filter; + } + + /** + * Gets the bits per sample of the function + */ + public int getBitsPerSample() { + return bitsPerSample; + } + + /** + * Gets the interpolation exponent of the function + */ + public double getInterpolationExponentN() { + return interpolationExponentN; + } + + /** + * Gets the function order + */ + public int getOrder() { + return order; + } + + /** + * Gets the function range + */ + public List<Double> getRange() { + return range; + } + + /** + * Gets the function decoding + */ + public List<Double> getDecode() { + return decode; + } + + /** + * Gets the function data stream + */ + public StringBuffer getDataStream() { + return functionDataStream; + } + + /** + * Gets the function C0 value (color for gradient) + */ + public List<Double> getCZero() { + return cZero; + } + + /** + * Gets the function C1 value (color for gradient) + */ + public List<Double> getCOne() { + return cOne; + } + + public byte[] toByteString() { + return parentFunction.toByteString(); + } +} diff --git a/src/java/org/apache/fop/render/shading/FunctionPattern.java b/src/java/org/apache/fop/render/shading/FunctionPattern.java new file mode 100644 index 000000000..044053a8b --- /dev/null +++ b/src/java/org/apache/fop/render/shading/FunctionPattern.java @@ -0,0 +1,363 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.shading; + +import java.io.UnsupportedEncodingException; + +import org.apache.fop.pdf.PDFFunction; +import org.apache.fop.pdf.PDFNumber; +import org.apache.fop.render.ps.svg.PSFunction; + +/** + * A class for writing function objects for different output formats + */ +public class FunctionPattern { + + private Function function; + + /** + * Constructor + * @param function The function from which to write the output + */ + public FunctionPattern(Function function) { + this.function = function; + } + + /** + * Outputs the function to a byte array + */ + public String toWriteableString() { + int vectorSize = 0; + int numberOfFunctions = 0; + int tempInt = 0; + StringBuffer p = new StringBuffer(256); + p.append("<< \n/FunctionType " + function.getFunctionType() + " \n"); + + // FunctionType 0 + if (this.function.getFunctionType() == 0) { + if (function.getDomain() != null) { + // DOMAIN + p.append("/Domain [ "); + vectorSize = function.getDomain().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getDomain().get(tempInt)) + + " "); + } + + p.append("] \n"); + } else { + p.append("/Domain [ 0 1 ] \n"); + } + + // SIZE + if (function.getSize() != null) { + p.append("/Size [ "); + vectorSize = function.getSize().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getSize().get(tempInt)) + + " "); + } + p.append("] \n"); + } + // ENCODE + if (function.getEncode() != null) { + p.append("/Encode [ "); + vectorSize = function.getEncode().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getEncode().get(tempInt)) + + " "); + } + p.append("] \n"); + } else { + p.append("/Encode [ "); + vectorSize = function.getFunctions().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append("0 1 "); + } + p.append("] \n"); + + } + + // BITSPERSAMPLE + p.append("/BitsPerSample " + function.getBitsPerSample()); + + // ORDER (optional) + if (function.getOrder() == 1 || function.getOrder() == 3) { + p.append(" \n/Order " + function.getOrder() + " \n"); + } + + // RANGE + if (function.getRange() != null) { + p.append("/Range [ "); + vectorSize = function.getRange().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getRange().get(tempInt)) + + " "); + } + + p.append("] \n"); + } + + // DECODE + if (function.getDecode() != null) { + p.append("/Decode [ "); + vectorSize = function.getDecode().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getDecode().get(tempInt)) + + " "); + } + + p.append("] \n"); + } + + // LENGTH + if (function.getDataStream() != null) { + p.append("/Length " + (function.getDataStream().length() + 1) + + " \n"); + } + + // FILTER? + if (function.getFilter() != null) { // if there's a filter + vectorSize = function.getFilter().size(); + p.append("/Filter "); + if (vectorSize == 1) { + p.append("/" + (function.getFilter().get(0)) + + " \n"); + } else { + p.append("[ "); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append("/" + (function.getFilter().get(0)) + + " "); + } + p.append("] \n"); + } + } + p.append(">>"); + + // stream representing the function + if (function.getDataStream() != null) { + p.append("\nstream\n" + function.getDataStream() + + "\nendstream"); + } + + // end of if FunctionType 0 + + } else if (function.getFunctionType() == 2) { + // DOMAIN + if (function.getDomain() != null) { + p.append("/Domain [ "); + vectorSize = function.getDomain().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getDomain().get(tempInt)) + + " "); + } + + p.append("] \n"); + } else { + p.append("/Domain [ 0 1 ] \n"); + } + + + // RANGE + if (function.getRange() != null) { + p.append("/Range [ "); + vectorSize = function.getRange().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getRange().get(tempInt)) + + " "); + } + + p.append("] \n"); + } + + // FunctionType, C0, C1, N are required in PDF + + // C0 + if (function.getCZero() != null) { + p.append("/C0 [ "); + vectorSize = function.getCZero().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getCZero().get(tempInt)) + + " "); + } + p.append("] \n"); + } + + // C1 + if (function.getCOne() != null) { + p.append("/C1 [ "); + vectorSize = function.getCOne().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getCOne().get(tempInt)) + + " "); + } + p.append("] \n"); + } + + // N: The interpolation Exponent + p.append("/N " + + PDFNumber.doubleOut(Double.valueOf(function.getInterpolationExponentN())) + + " \n"); + + p.append(">>"); + + } else if (function.getFunctionType() + == 3) { // fix this up when my eyes uncross + // DOMAIN + if (function.getDomain() != null) { + p.append("/Domain [ "); + vectorSize = function.getDomain().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getDomain().get(tempInt)) + + " "); + } + p.append("] \n"); + } else { + p.append("/Domain [ 0 1 ] \n"); + } + + // RANGE + if (function.getRange() != null) { + p.append("/Range [ "); + vectorSize = function.getRange().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getRange().get(tempInt)) + + " "); + } + + p.append("] \n"); + } + + // FUNCTIONS + if (function.getFunctions() != null) { + p.append("/Functions [ "); + numberOfFunctions = function.getFunctions().size(); + for (tempInt = 0; tempInt < numberOfFunctions; tempInt++) { + try { + if (function instanceof PSFunction) { + p.append(new String(function.getFunctions().get(tempInt).toByteString(), "UTF-8") + + " "); + } else { + p.append(((PDFFunction)function.getFunctions().get(tempInt)).referencePDF() + + " "); + } + } catch (UnsupportedEncodingException ex) { + //This should have been made an enum type to avoid throwing exceptions. + } + } + p.append("] \n"); + } + + + // ENCODE + if (function.getEncode() != null) { + p.append("/Encode [ "); + vectorSize = function.getEncode().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getEncode().get(tempInt)) + + " "); + } + + p.append("] \n"); + } else { + p.append("/Encode [ "); + vectorSize = function.getFunctions().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append("0 1 "); + } + p.append("] \n"); + + } + + + // BOUNDS, required, but can be empty + p.append("/Bounds [ "); + if (function.getBounds() != null) { + + vectorSize = function.getBounds().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getBounds().get(tempInt)) + + " "); + } + + } else { + if (function.getFunctions() != null) { + // if there are n functions, + // there must be n-1 bounds. + // so let each function handle an equal portion + // of the whole. e.g. if there are 4, then [ 0.25 0.25 0.25 ] + + String functionsFraction = PDFNumber.doubleOut(Double.valueOf(1.0 + / (numberOfFunctions))); + + for (tempInt = 0; tempInt + 1 < numberOfFunctions; + tempInt++) { + + p.append(functionsFraction + " "); + } + } + + } + p.append("]\n>>"); + } else if (function.getFunctionType() + == 4) { // fix this up when my eyes uncross + // DOMAIN + if (function.getDomain() != null) { + p.append("/Domain [ "); + vectorSize = function.getDomain().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getDomain().get(tempInt)) + + " "); + } + + p.append("] \n"); + } else { + p.append("/Domain [ 0 1 ] \n"); + } + + // RANGE + if (function.getRange() != null) { + p.append("/Range [ "); + vectorSize = function.getRange().size(); + for (tempInt = 0; tempInt < vectorSize; tempInt++) { + p.append(PDFNumber.doubleOut(function.getRange().get(tempInt)) + + " "); + } + + p.append("] \n"); + } + + // LENGTH + if (function.getDataStream() != null) { + p.append("/Length " + (function.getDataStream().length() + 1) + + " \n"); + } + + p.append(">>"); + + // stream representing the function + if (function.getDataStream() != null) { + p.append("\nstream\n{ " + function.getDataStream() + + " }\nendstream"); + } + } + return p.toString(); + } +} diff --git a/src/java/org/apache/fop/render/shading/GradientFactory.java b/src/java/org/apache/fop/render/shading/GradientFactory.java new file mode 100644 index 000000000..87ac11c83 --- /dev/null +++ b/src/java/org/apache/fop/render/shading/GradientFactory.java @@ -0,0 +1,162 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.shading; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +import org.apache.xmlgraphics.java2d.color.ColorUtil; + +import org.apache.fop.pdf.PDFDeviceColorSpace; +import org.apache.fop.render.ps.svg.PSSVGGraphics2D; + +public abstract class GradientFactory { + + static GradientRegistrar registrar; + + /** + * Constructor + * @param registrar The object used to register new embedded objects in the + * output format. + */ + public static GradientFactory newInstance(GradientRegistrar theRegistrar) { + registrar = theRegistrar; + if (registrar instanceof PSSVGGraphics2D) { + return new PSGradientFactory(); + } else { + return new PDFGradientFactory(); + } + } + + /** + * Creates a new gradient + * @param radial Determines whether the gradient is radial + * @param theColorspace The colorspace used in PDF and Postscript + * @param theColors The colors to be used in the gradient + * @param theBounds The bounds of each color + * @param theCoords The co-ordinates of the gradient + * @param theMatrix The matrix for any transformations + * @return Returns the Pattern object of the gradient + */ + public abstract Pattern createGradient(boolean radial, + PDFDeviceColorSpace theColorspace, List<Color> theColors, List<Double> theBounds, + List<Double> theCoords, List<Double> theMatrix); + + protected Pattern makeGradient(boolean radial, PDFDeviceColorSpace theColorspace, + List<Color> theColors, List<Double> theBounds, + List<Double> theCoords, List<Double> theMatrix) { + Shading myShad; + Function myfunky; + Function myfunc; + List<Double> theCzero; + List<Double> theCone; + double interpolation = 1.000; + List<Function> theFunctions = new ArrayList<Function>(); + + int currentPosition; + int lastPosition = theColors.size() - 1; + + + // if 5 elements, the penultimate element is 3. + // do not go beyond that, because you always need + // to have a next color when creating the function. + + for (currentPosition = 0; currentPosition < lastPosition; + currentPosition++) { // for every consecutive color pair + Color currentColor = theColors.get(currentPosition); + Color nextColor = theColors.get(currentPosition + 1); + + // colorspace must be consistent, so we simply convert to sRGB where necessary + if (!currentColor.getColorSpace().isCS_sRGB()) { + //Convert to sRGB + currentColor = ColorUtil.toSRGBColor(currentColor); + theColors.set(currentPosition, currentColor); + } + if (!nextColor.getColorSpace().isCS_sRGB()) { + //Convert to sRGB + nextColor = ColorUtil.toSRGBColor(nextColor); + theColors.set(currentPosition + 1, nextColor); + } + + theCzero = toColorVector(currentColor); + theCone = toColorVector(nextColor); + + myfunc = makeFunction(2, null, null, theCzero, theCone, + interpolation); + + theFunctions.add(myfunc); + + } // end of for every consecutive color pair + + myfunky = makeFunction(3, null, null, theFunctions, theBounds, + null); + + if (radial) { + if (theCoords.size() == 6) { + // make Shading of Type 2 or 3 + myShad = makeShading(3, theColorspace, null, null, false, theCoords, + null, myfunky, null); + } else { // if the center x, center y, and radius specifiy + // the gradient, then assume the same center x, center y, + // and radius of zero for the other necessary component + List<Double> newCoords = new ArrayList<Double>(); + newCoords.add(theCoords.get(0)); + newCoords.add(theCoords.get(1)); + newCoords.add(theCoords.get(2)); + newCoords.add(theCoords.get(0)); + newCoords.add(theCoords.get(1)); + newCoords.add(Double.valueOf(0.0)); + + myShad = makeShading(3, theColorspace, null, null, false, newCoords, + null, myfunky, null); + } + } else { + myShad = makeShading(2, theColorspace, null, null, false, theCoords, + null, myfunky, null); + } + return makePattern(2, myShad, null, null, theMatrix); + } + + public abstract Function makeFunction(int functionType, List<Double> theDomain, + List<Double> theRange, List<Function> theFunctions, + List<Double> theBounds, List<Double> theEncode); + + public abstract Function makeFunction(int functionType, List<Double> theDomain, + List<Double> theRange, List<Double> theCZero, List<Double> theCOne, + double theInterpolationExponentN); + + public abstract Shading makeShading(int theShadingType, + PDFDeviceColorSpace theColorSpace, List<Double> theBackground, List<Double> theBBox, + boolean theAntiAlias, List<Double> theCoords, List<Double> theDomain, + Function theFunction, List<Integer> theExtend); + + public abstract Pattern makePattern(int thePatternType, Shading theShading, List theXUID, + StringBuffer theExtGState, List<Double> theMatrix); + + private List<Double> toColorVector(Color nextColor) { + List<Double> vector = new java.util.ArrayList<Double>(); + float[] comps = nextColor.getColorComponents(null); + for (int i = 0, c = comps.length; i < c; i++) { + vector.add(Double.valueOf(comps[i])); + } + return vector; + } +} diff --git a/src/java/org/apache/fop/render/shading/GradientRegistrar.java b/src/java/org/apache/fop/render/shading/GradientRegistrar.java new file mode 100644 index 000000000..617fcd4fb --- /dev/null +++ b/src/java/org/apache/fop/render/shading/GradientRegistrar.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.shading; + +public interface GradientRegistrar { + + /** + * Registers a function object against the output format document + * @param function The function object to register + * @return Returns either the function which has already been registered + * or the current new registered object. + */ + Function registerFunction(Function function); + + /** + * Registers a shading object against the output format document + * @param shading The shading object to register + * @return Returns either the shading which has already been registered + * or the current new registered object + */ + Shading registerShading(Shading shading); + + /** + * Registers a pattern object against the output format document + * @param pattern The pattern object to register + * @return Returns either the pattern which has already been registered + * or the current new registered object + */ + Pattern registerPattern(Pattern pattern); +} diff --git a/src/java/org/apache/fop/render/shading/PDFGradientFactory.java b/src/java/org/apache/fop/render/shading/PDFGradientFactory.java new file mode 100644 index 000000000..3b3dcab75 --- /dev/null +++ b/src/java/org/apache/fop/render/shading/PDFGradientFactory.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.shading; + +import java.awt.Color; +import java.util.List; + +import org.apache.fop.pdf.PDFDeviceColorSpace; +import org.apache.fop.pdf.PDFFunction; +import org.apache.fop.pdf.PDFPattern; +import org.apache.fop.pdf.PDFShading; + +public class PDFGradientFactory extends GradientFactory { + + @Override + public PDFPattern createGradient(boolean radial, PDFDeviceColorSpace theColorspace, List<Color> theColors, + List<Double> theBounds, List<Double> theCoords, List<Double> theMatrix) { + return (PDFPattern)makeGradient(radial, theColorspace, theColors, theBounds, + theCoords, theMatrix); + } + + @Override + public Function makeFunction(int functionType, List<Double> theDomain, + List<Double> theRange, List<Function> theFunctions, + List<Double> theBounds, List<Double> theEncode) { + Function newFunction = new PDFFunction(functionType, theDomain, theRange, theFunctions, + theBounds, theEncode); + newFunction = registrar.registerFunction(newFunction); + return newFunction; + } + + public Function makeFunction(int functionType, List<Double> theDomain, + List<Double> theRange, List<Double> theCZero, List<Double> theCOne, + double theInterpolationExponentN) { + Function newFunction = new PDFFunction(functionType, theDomain, theRange, theCZero, + theCOne, theInterpolationExponentN); + newFunction = registrar.registerFunction(newFunction); + return newFunction; + } + + @Override + public Shading makeShading(int theShadingType, + PDFDeviceColorSpace theColorSpace, List<Double> theBackground, List<Double> theBBox, + boolean theAntiAlias, List<Double> theCoords, List<Double> theDomain, + Function theFunction, List<Integer> theExtend) { + Shading newShading = new PDFShading(theShadingType, theColorSpace, theBackground, + theBBox, theAntiAlias, theCoords, theDomain, theFunction, theExtend); + newShading = registrar.registerShading(newShading); + return newShading; + } + + @Override + public Pattern makePattern(int thePatternType, Shading theShading, List theXUID, + StringBuffer theExtGState, List<Double> theMatrix) { + Pattern newPattern = new PDFPattern(thePatternType, theShading, theXUID, theExtGState, + theMatrix); + newPattern = registrar.registerPattern(newPattern); + return newPattern; + } + +} diff --git a/src/java/org/apache/fop/render/shading/PSGradientFactory.java b/src/java/org/apache/fop/render/shading/PSGradientFactory.java new file mode 100644 index 000000000..cd47de93a --- /dev/null +++ b/src/java/org/apache/fop/render/shading/PSGradientFactory.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.shading; + +import java.awt.Color; +import java.util.List; + +import org.apache.fop.pdf.PDFDeviceColorSpace; +import org.apache.fop.render.ps.svg.PSFunction; +import org.apache.fop.render.ps.svg.PSPattern; +import org.apache.fop.render.ps.svg.PSShading; + +public class PSGradientFactory extends GradientFactory { + + @Override + public PSPattern createGradient(boolean radial, PDFDeviceColorSpace theColorspace, + List<Color> theColors, List<Double> theBounds, List<Double> theCoords, + List<Double> theMatrix) { + return (PSPattern)makeGradient(radial, theColorspace, theColors, theBounds, + theCoords, theMatrix); + } + + public Function makeFunction(int functionType, List<Double> theDomain, + List<Double> theRange, List<Function> theFunctions, + List<Double> theBounds, List<Double> theEncode) { + Function newFunction = new PSFunction(functionType, theDomain, theRange, theFunctions, + theBounds, theEncode); + return newFunction; + } + + @Override + public Function makeFunction(int functionType, List<Double> theDomain, + List<Double> theRange, List<Double> theCZero, List<Double> theCOne, + double theInterpolationExponentN) { + Function newFunction = new PSFunction(functionType, theDomain, theRange, theCZero, + theCOne, theInterpolationExponentN); + return newFunction; + } + + @Override + public Shading makeShading(int theShadingType, + PDFDeviceColorSpace theColorSpace, List<Double> theBackground, List<Double> theBBox, + boolean theAntiAlias, List<Double> theCoords, List<Double> theDomain, + Function theFunction, List<Integer> theExtend) { + Shading newShading = new PSShading(theShadingType, theColorSpace, theBackground, theBBox, + theAntiAlias, theCoords, theDomain, theFunction, theExtend); + return newShading; + } + + @Override + public Pattern makePattern(int thePatternType, Shading theShading, List theXUID, + StringBuffer theExtGState, List<Double> theMatrix) { + return new PSPattern(thePatternType, theShading, theXUID, theExtGState); + } +} diff --git a/src/java/org/apache/fop/render/shading/Pattern.java b/src/java/org/apache/fop/render/shading/Pattern.java new file mode 100644 index 000000000..b66926e53 --- /dev/null +++ b/src/java/org/apache/fop/render/shading/Pattern.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.shading; + +public interface Pattern { + +} diff --git a/src/java/org/apache/fop/render/shading/Shading.java b/src/java/org/apache/fop/render/shading/Shading.java new file mode 100644 index 000000000..385cb112b --- /dev/null +++ b/src/java/org/apache/fop/render/shading/Shading.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.shading; + + +public interface Shading { + StringBuffer handleShadingType1(StringBuffer p); + StringBuffer handleShadingType2or3(StringBuffer p); + StringBuffer handleShadingType4or6or7(StringBuffer p); + StringBuffer handleShadingType5(StringBuffer p); +} diff --git a/src/java/org/apache/fop/render/shading/ShadingPattern.java b/src/java/org/apache/fop/render/shading/ShadingPattern.java new file mode 100644 index 000000000..6dac65f55 --- /dev/null +++ b/src/java/org/apache/fop/render/shading/ShadingPattern.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.shading; + +import java.util.List; + +import org.apache.fop.pdf.PDFDeviceColorSpace; +import org.apache.fop.pdf.PDFNumber; + +/** + * A class for writing shading objects for different output formats + */ +public class ShadingPattern { + + private Shading shading; + + /** + * Constructor + * @param shading The shading object from which to write the output + */ + public ShadingPattern(Shading shading) { + this.shading = shading; + } + + /** + * Outputs the given shading object to a String + * @param colorSpace The Colospace (PDF and Postscript) + * @param shadingType The shading type + * @param background The background + * @param bBox The bounding box + * @param antiAlias Anti-aliasing + * @return Returns the output string + */ + public String toString(PDFDeviceColorSpace colorSpace, int shadingType, List background, + List bBox, boolean antiAlias) { + StringBuffer p = new StringBuffer(128); + p.append("<<\n/ShadingType " + shadingType + " \n"); + if (colorSpace != null) { + p.append("/ColorSpace /" + + colorSpace.getName() + " \n"); + } + + if (background != null) { + p.append("/Background [ "); + for (int bgIndex = 0; bgIndex < background.size(); bgIndex++) { + p.append(PDFNumber.doubleOut((Double)background.get(bgIndex)) + + " "); + } + p.append("] \n"); + } + + if (bBox + != null) { // I've never seen an example, so I guess this is right. + p.append("/BBox [ "); + for (int bboxIndex = 0; bboxIndex < bBox.size(); bboxIndex++) { + p.append(PDFNumber.doubleOut((Double)bBox.get(bboxIndex)) + + " "); + } + p.append("] \n"); + } + + if (antiAlias) { + p.append("/AntiAlias " + antiAlias + " \n"); + } + + // Here's where we differentiate based on what type it is. + switch (shadingType) { + //Function based shading + case 1: p = shading.handleShadingType1(p); break; + //Axial shading + case 2: + //Radial shading + case 3: p = shading.handleShadingType2or3(p); break; + //Free-form Gouraud-shaded triangle meshes + case 4: + //Coons patch meshes + case 6: + //Tensor product patch meshes + case 7: p = shading.handleShadingType4or6or7(p); break; + //Lattice Free form gouraud-shaded triangle mesh + case 5: p = shading.handleShadingType5(p); break; + default: //Shading pattern outside expecting values + break; + } + + p.append(">>"); + + return (p.toString()); + } +} diff --git a/src/java/org/apache/fop/render/txt/TXTRenderer.java b/src/java/org/apache/fop/render/txt/TXTRenderer.java index bf4a46e19..5b398711f 100644 --- a/src/java/org/apache/fop/render/txt/TXTRenderer.java +++ b/src/java/org/apache/fop/render/txt/TXTRenderer.java @@ -583,6 +583,14 @@ public class TXTRenderer extends AbstractPathOrientedRenderer { } /** {@inheritDoc} */ + protected void startLayer(String layer) { + } + + /** {@inheritDoc} */ + protected void endLayer() { + } + + /** {@inheritDoc} */ protected void concatenateTransformationMatrix(AffineTransform at) { currentState.push(new CTM(UnitConv.ptToMpt(at))); } diff --git a/src/java/org/apache/fop/render/xml/XMLRenderer.java b/src/java/org/apache/fop/render/xml/XMLRenderer.java index 2212da434..68e2e3c62 100644 --- a/src/java/org/apache/fop/render/xml/XMLRenderer.java +++ b/src/java/org/apache/fop/render/xml/XMLRenderer.java @@ -545,6 +545,16 @@ public class XMLRenderer extends AbstractXMLRenderer { //only necessary for graphical output } + /** {@inheritDoc} */ + protected void startLayer(String layer) { + //only necessary for graphical output + } + + /** {@inheritDoc} */ + protected void endLayer() { + //only necessary for graphical output + } + /** * {@inheritDoc} * org.apache.fop.area.inline.InlineArea) diff --git a/src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java b/src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java index e91e2231c..cb2b58c40 100644 --- a/src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java +++ b/src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java @@ -278,7 +278,6 @@ public class PDFDocumentGraphics2D extends PDFGraphics2D { PDFStream pdfStream = this.pdfDoc.getFactory().makeStream( PDFFilterList.CONTENT_FILTER, false); pdfStream.add(getString()); - currentStream = null; this.pdfDoc.registerObject(pdfStream); pdfContext.getCurrentPage().setContents(pdfStream); PDFAnnotList annots = pdfContext.getCurrentPage().getAnnotations(); diff --git a/src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java b/src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java index 0c0335a8b..6f2d4429d 100644 --- a/src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java +++ b/src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java @@ -88,7 +88,8 @@ public class PDFDocumentGraphics2DConfigurator { final boolean strict = false; if (cfg != null) { URI thisUri = new File(".").getAbsoluteFile().toURI(); - InternalResourceResolver resourceResolver = ResourceResolverFactory.createDefaultInternalResourceResolver(thisUri); + InternalResourceResolver resourceResolver + = ResourceResolverFactory.createDefaultInternalResourceResolver(thisUri); //TODO The following could be optimized by retaining the FontManager somewhere FontManager fontManager = new FontManager(resourceResolver, FontDetectorFactory.createDefault(), FontCacheManagerFactory.createDefault()); diff --git a/src/java/org/apache/fop/svg/PDFGraphics2D.java b/src/java/org/apache/fop/svg/PDFGraphics2D.java index efa71a225..1fcf9f870 100644 --- a/src/java/org/apache/fop/svg/PDFGraphics2D.java +++ b/src/java/org/apache/fop/svg/PDFGraphics2D.java @@ -80,6 +80,7 @@ import org.apache.fop.pdf.PDFColorHandler; import org.apache.fop.pdf.PDFConformanceException; import org.apache.fop.pdf.PDFDeviceColorSpace; import org.apache.fop.pdf.PDFDocument; +import org.apache.fop.pdf.PDFFunction; import org.apache.fop.pdf.PDFGState; import org.apache.fop.pdf.PDFImage; import org.apache.fop.pdf.PDFImageXObject; @@ -89,11 +90,18 @@ import org.apache.fop.pdf.PDFPaintingState; import org.apache.fop.pdf.PDFPattern; import org.apache.fop.pdf.PDFResourceContext; import org.apache.fop.pdf.PDFResources; +import org.apache.fop.pdf.PDFShading; import org.apache.fop.pdf.PDFText; import org.apache.fop.pdf.PDFXObject; import org.apache.fop.render.pdf.ImageRawCCITTFaxAdapter; import org.apache.fop.render.pdf.ImageRawJPEGAdapter; import org.apache.fop.render.pdf.ImageRenderedAdapter; +import org.apache.fop.render.shading.Function; +import org.apache.fop.render.shading.GradientFactory; +import org.apache.fop.render.shading.GradientRegistrar; +import org.apache.fop.render.shading.PDFGradientFactory; +import org.apache.fop.render.shading.Pattern; +import org.apache.fop.render.shading.Shading; /** * <p>PDF Graphics 2D. @@ -104,7 +112,7 @@ import org.apache.fop.render.pdf.ImageRenderedAdapter; * * @see org.apache.batik.ext.awt.g2d.AbstractGraphics2D */ -public class PDFGraphics2D extends AbstractGraphics2D implements NativeImageHandler { +public class PDFGraphics2D extends AbstractGraphics2D implements NativeImageHandler, GradientRegistrar { private static final AffineTransform IDENTITY_TRANSFORM = new AffineTransform(); /** The number of decimal places. */ @@ -868,11 +876,10 @@ public class PDFGraphics2D extends AbstractGraphics2D implements NativeImageHand } //Gradients are currently restricted to sRGB - PDFDeviceColorSpace aColorSpace; - aColorSpace = new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_RGB); - PDFPattern myPat = pdfDoc.getFactory().makeGradient( - resourceContext, false, aColorSpace, - someColors, theBounds, theCoords, theMatrix); + PDFDeviceColorSpace colSpace = new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_RGB); + PDFGradientFactory gradientFactory = (PDFGradientFactory)GradientFactory.newInstance(this); + PDFPattern myPat = gradientFactory.createGradient(false, colSpace, someColors, theBounds, + theCoords, theMatrix); currentStream.write(myPat.getColorSpaceOut(fill)); return true; @@ -944,13 +951,10 @@ public class PDFGraphics2D extends AbstractGraphics2D implements NativeImageHand float offset = fractions[count]; theBounds.add(new Double(offset)); } - PDFDeviceColorSpace colSpace; - colSpace = new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_RGB); - - PDFPattern myPat = pdfDoc.getFactory().makeGradient( - resourceContext, true, colSpace, - someColors, theBounds, theCoords, theMatrix); - + PDFDeviceColorSpace colSpace = new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_RGB); + PDFGradientFactory gradientFactory = (PDFGradientFactory) GradientFactory.newInstance(this); + PDFPattern myPat = gradientFactory.createGradient(true, colSpace, someColors, theBounds, + theCoords, theMatrix); currentStream.write(myPat.getColorSpaceOut(fill)); return true; @@ -1856,4 +1860,36 @@ public class PDFGraphics2D extends AbstractGraphics2D implements NativeImageHand //NYI } + /** + * Registers a function object against the output format document + * @param function The function object to register + * @return Returns either the function which has already been registered + * or the current new registered object. + */ + public Function registerFunction(Function function) { + return pdfDoc.getFactory().registerFunction((PDFFunction)function); + } + + /** + * Registers a shading object against the otuput format document + * @param shading The shading object to register + * @return Returs either the shading which has already been registered + * or the current new registered object + */ + public Shading registerShading(Shading shading) { + assert shading instanceof PDFShading; + return pdfDoc.getFactory().registerShading(resourceContext, (PDFShading)shading); + } + + /** + * Registers a pattern object against the output format document + * @param pattern The pattern object to register + * @return Returns either the pattern which has already been registered + * or the current new registered object + */ + public Pattern registerPattern(Pattern pattern) { + assert pattern instanceof PDFPattern; + return pdfDoc.getFactory().registerPattern(resourceContext, (PDFPattern)pattern); + } + } diff --git a/src/java/org/apache/fop/svg/SimpleSVGUserAgent.java b/src/java/org/apache/fop/svg/SimpleSVGUserAgent.java index 2b27945a4..132c633dc 100644 --- a/src/java/org/apache/fop/svg/SimpleSVGUserAgent.java +++ b/src/java/org/apache/fop/svg/SimpleSVGUserAgent.java @@ -23,8 +23,11 @@ import java.awt.Dimension; import java.awt.geom.AffineTransform; import java.awt.geom.Dimension2D; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; +import org.xml.sax.SAXException; + import org.apache.batik.bridge.UserAgentAdapter; /** @@ -79,17 +82,28 @@ public class SimpleSVGUserAgent extends UserAgentAdapter { return null; // userStyleSheetURI; } + + private static final String XML_PARSER_CLASS_NAME; + + static { + String result; + try { + SAXParserFactory factory = SAXParserFactory.newInstance(); + result = factory.newSAXParser().getXMLReader().getClass().getName(); + } catch (SAXException e) { + result = null; + } catch (ParserConfigurationException e) { + result = null; + } + XML_PARSER_CLASS_NAME = result; + } + /** * Returns the class name of the XML parser. * @return the XML parser class name */ public String getXMLParserClassName() { - try { - SAXParserFactory factory = SAXParserFactory.newInstance(); - return factory.newSAXParser().getXMLReader().getClass().getName(); - } catch (Exception e) { - return null; - } + return XML_PARSER_CLASS_NAME; } /** diff --git a/src/java/org/apache/fop/text/linebreak/LineBreakUtils.java b/src/java/org/apache/fop/text/linebreak/LineBreakUtils.java index d6e19a97a..6598d1b85 100644 --- a/src/java/org/apache/fop/text/linebreak/LineBreakUtils.java +++ b/src/java/org/apache/fop/text/linebreak/LineBreakUtils.java @@ -29,7 +29,6 @@ package org.apache.fop.text.linebreak; * - commit BOTH changed files */ -// CSOFF: WhitespaceAfterCheck // CSOFF: LineLengthCheck /** Line breaking utilities. */ @@ -694,11 +693,11 @@ public final class LineBreakUtils { "CP", "CR", "EX", "GL", "H2", "H3", "HY", "ID", "IN", "IS", "JL", "JT", "JV", "LF", "NL", "NS", "NU", "OP", "PO", "PR", "QU", "SA", "SG", "SP", "SY", "WJ", "XX", "ZW"}; - private static String[] lineBreakPropertyLongNames = {"Ambiguous","Alphabetic","Break_Both","Break_After","Break_Before", - "Mandatory_Break","Contingent_Break","Close_Punctuation","Combining_Mark","Close_Parenthesis","Carriage_Return", - "Exclamation","Glue","H2","H3","Hyphen","Ideographic","Inseparable","Infix_Numeric","JL","JT","JV","Line_Feed", - "Next_Line","Nonstarter","Numeric","Open_Punctuation","Postfix_Numeric","Prefix_Numeric","Quotation","Complex_Context", - "Surrogate","Space","Break_Symbols","Word_Joiner","Unknown","ZWSpace"}; + private static String[] lineBreakPropertyLongNames = {"Ambiguous", "Alphabetic", "Break_Both", "Break_After", "Break_Before", + "Mandatory_Break", "Contingent_Break", "Close_Punctuation", "Combining_Mark", "Close_Parenthesis", "Carriage_Return", + "Exclamation", "Glue", "H2", "H3", "Hyphen", "Ideographic", "Inseparable", "Infix_Numeric", "JL", "JT", "JV", "Line_Feed", + "Next_Line", "Nonstarter", "Numeric", "Open_Punctuation", "Postfix_Numeric", "Prefix_Numeric", "Quotation", "Complex_Context", + "Surrogate", "Space", "Break_Symbols", "Word_Joiner", "Unknown", "ZWSpace"}; /** * Return the short name for the linebreak property corresponding diff --git a/src/java/org/apache/fop/traits/WritingMode.java b/src/java/org/apache/fop/traits/WritingMode.java index 8718118ef..f8c784941 100644 --- a/src/java/org/apache/fop/traits/WritingMode.java +++ b/src/java/org/apache/fop/traits/WritingMode.java @@ -54,8 +54,9 @@ public final class WritingMode extends TraitEnum { * Assign writing mode traits from this trait to the specified * writing mode traits setter. * @param wms a writing mode traits setter + * @param explicit true if writing mode property explicitly specified */ - public void assignWritingModeTraits(WritingModeTraitsSetter wms) { + public void assignWritingModeTraits(WritingModeTraitsSetter wms, boolean explicit) { Direction inlineProgressionDirection; Direction blockProgressionDirection; Direction columnProgressionDirection; @@ -97,7 +98,7 @@ public final class WritingMode extends TraitEnum { wms.setColumnProgressionDirection(columnProgressionDirection); wms.setRowProgressionDirection(rowProgressionDirection); wms.setShiftDirection(shiftDirection); - wms.setWritingMode(this); + wms.setWritingMode(this, explicit); } /** diff --git a/src/java/org/apache/fop/traits/WritingModeTraits.java b/src/java/org/apache/fop/traits/WritingModeTraits.java index 279326afa..fbd150ca9 100644 --- a/src/java/org/apache/fop/traits/WritingModeTraits.java +++ b/src/java/org/apache/fop/traits/WritingModeTraits.java @@ -31,20 +31,21 @@ public class WritingModeTraits implements WritingModeTraitsSetter { private Direction rowProgressionDirection; private Direction shiftDirection; private WritingMode writingMode; + private boolean explicit; /** * Default writing mode traits constructor. */ public WritingModeTraits() { - this (WritingMode.LR_TB); + this (WritingMode.LR_TB, false); } /** * Construct writing mode traits using the specified writing mode. * @param writingMode a writing mode traits object */ - public WritingModeTraits(WritingMode writingMode) { - assignWritingModeTraits(writingMode); + public WritingModeTraits(WritingMode writingMode, boolean explicit) { + assignWritingModeTraits(writingMode, explicit); } /** @@ -125,17 +126,25 @@ public class WritingModeTraits implements WritingModeTraitsSetter { } /** + * @return the "explicit-writing-mode" trait. + */ + public boolean getExplicitWritingMode() { + return explicit; + } + + /** * @param writingMode the "writing-mode" trait. */ - public void setWritingMode(WritingMode writingMode) { + public void setWritingMode(WritingMode writingMode, boolean explicit) { this.writingMode = writingMode; + this.explicit = explicit; } /** * @param writingMode the "writing-mode" trait. */ - public void assignWritingModeTraits(WritingMode writingMode) { - writingMode.assignWritingModeTraits(this); + public void assignWritingModeTraits(WritingMode writingMode, boolean explicit) { + writingMode.assignWritingModeTraits(this, explicit); } /** diff --git a/src/java/org/apache/fop/traits/WritingModeTraitsGetter.java b/src/java/org/apache/fop/traits/WritingModeTraitsGetter.java index a67e437c9..7340b3e8c 100644 --- a/src/java/org/apache/fop/traits/WritingModeTraitsGetter.java +++ b/src/java/org/apache/fop/traits/WritingModeTraitsGetter.java @@ -55,4 +55,9 @@ public interface WritingModeTraitsGetter { */ WritingMode getWritingMode(); + /** + * @return the "explicit-writing-mode" trait + */ + boolean getExplicitWritingMode(); + } diff --git a/src/java/org/apache/fop/traits/WritingModeTraitsSetter.java b/src/java/org/apache/fop/traits/WritingModeTraitsSetter.java index 6dcf0fb12..b70f73954 100644 --- a/src/java/org/apache/fop/traits/WritingModeTraitsSetter.java +++ b/src/java/org/apache/fop/traits/WritingModeTraitsSetter.java @@ -58,13 +58,14 @@ public interface WritingModeTraitsSetter extends WritingModeTraitsGetter { * Set value of writing-mode trait. * @param writingMode the "writing-mode" trait */ - void setWritingMode(WritingMode writingMode); + void setWritingMode(WritingMode writingMode, boolean explicit); /** * Collectivelly assign values to all writing mode traits based upon a specific * writing mode. * @param writingMode the "writing-mode" trait + * @param explicit true if writing mode explicitly specified */ - void assignWritingModeTraits(WritingMode writingMode); + void assignWritingModeTraits(WritingMode writingMode, boolean explicit); } diff --git a/src/java/org/apache/fop/util/AbstractPaintingState.java b/src/java/org/apache/fop/util/AbstractPaintingState.java index 96c3633e6..3e966d202 100644 --- a/src/java/org/apache/fop/util/AbstractPaintingState.java +++ b/src/java/org/apache/fop/util/AbstractPaintingState.java @@ -24,7 +24,6 @@ import java.awt.geom.AffineTransform; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; -import java.util.Iterator; import java.util.List; import java.util.Stack; @@ -36,10 +35,10 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { private static final long serialVersionUID = 5998356138437094188L; /** current state data */ - private AbstractData data = null; + private AbstractData data; /** the state stack */ - private StateStack/*<AbstractData>*/ stateStack = new StateStack/*<AbstractData>*/(); + private StateStack<AbstractData> stateStack = new StateStack<AbstractData>(); /** * Instantiates a new state data object @@ -216,8 +215,7 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { */ public AffineTransform getTransform() { AffineTransform at = new AffineTransform(); - for (Iterator iter = stateStack.iterator(); iter.hasNext();) { - AbstractData data = (AbstractData)iter.next(); + for (AbstractData data : stateStack) { AffineTransform stackTrans = data.getTransform(); at.concatenate(stackTrans); } @@ -249,7 +247,7 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { if (stateStack.isEmpty()) { return null; } else { - AbstractData baseData = (AbstractData)stateStack.get(0); + AbstractData baseData = stateStack.get(0); return (AffineTransform) baseData.getTransform().clone(); } } @@ -297,7 +295,7 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { */ public AbstractData restore() { if (!stateStack.isEmpty()) { - setData((AbstractData)stateStack.pop()); + setData(stateStack.pop()); return this.data; } else { return null; @@ -310,12 +308,11 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { * * @param dataList a state data list */ - public void saveAll(List/*<AbstractData>*/ dataList) { - Iterator it = dataList.iterator(); - while (it.hasNext()) { + public void saveAll(List<AbstractData> dataList) { + for (AbstractData data : dataList) { // save current data on stack save(); - setData((AbstractData)it.next()); + setData(data); } } @@ -325,8 +322,8 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { * * @return a list of state data popped from the stack */ - public List/*<AbstractData>*/ restoreAll() { - List/*<AbstractData>*/ dataList = new java.util.ArrayList/*<AbstractData>*/(); + public List<AbstractData> restoreAll() { + List<AbstractData> dataList = new java.util.ArrayList<AbstractData>(); AbstractData data; while (true) { data = getData(); @@ -361,7 +358,7 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { * * @return the state stack */ - protected Stack/*<AbstractData>*/ getStateStack() { + protected Stack<AbstractData> getStateStack() { return this.stateStack; } @@ -369,8 +366,10 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { @Override public Object clone() { AbstractPaintingState state = instantiate(); - state.stateStack = new StateStack(this.stateStack); - state.data = (AbstractData)this.data.clone(); + state.stateStack = new StateStack<AbstractData>(this.stateStack); + if (this.data != null) { + state.data = (AbstractData)this.data.clone(); + } return state; } @@ -385,7 +384,7 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { /** * A stack implementation which holds state objects */ - public class StateStack extends java.util.Stack { + public class StateStack<E> extends java.util.Stack<E> { private static final long serialVersionUID = 4897178211223823041L; @@ -393,7 +392,6 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { * Default constructor */ public StateStack() { - super(); } /** @@ -419,25 +417,28 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { private static final long serialVersionUID = 5208418041189828624L; /** The current color */ - protected Color color = null; + protected Color color; /** The current background color */ - protected Color backColor = null; + protected Color backColor; /** The current font name */ - protected String fontName = null; + protected String fontName; /** The current font size */ - protected int fontSize = 0; + protected int fontSize; /** The current line width */ - protected float lineWidth = 0; + protected float lineWidth; /** The dash array for the current basic stroke (line type) */ - protected float[] dashArray = null; + protected float[] dashArray; /** The current transform */ - protected AffineTransform transform = null; + protected AffineTransform transform; + + /** The current (optional content group) layer. */ + protected String layer; /** * Returns a newly create data object @@ -485,6 +486,18 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { transform = new AffineTransform(); } + public void setLayer(String layer) { + if (layer != null) { + this.layer = layer; + } else { + throw new IllegalArgumentException(); + } + } + + public String getLayer() { + return this.layer; + } + /** * Returns the derived rotation from the current transform * @@ -523,6 +536,7 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { this.transform = new AffineTransform(); } data.transform = new AffineTransform(this.transform); + data.layer = this.layer; return data; } @@ -535,7 +549,8 @@ public abstract class AbstractPaintingState implements Cloneable, Serializable { + ", fontSize=" + fontSize + ", lineWidth=" + lineWidth + ", dashArray=" + dashArray - + ", transform=" + transform; + + ", transform=" + transform + + ", layer=" + layer; } } } diff --git a/src/sandbox/org/apache/fop/render/svg/SVGPainter.java b/src/sandbox/org/apache/fop/render/svg/SVGPainter.java index ebd143a69..fb7ce2677 100644 --- a/src/sandbox/org/apache/fop/render/svg/SVGPainter.java +++ b/src/sandbox/org/apache/fop/render/svg/SVGPainter.java @@ -146,16 +146,16 @@ public class SVGPainter extends AbstractIFPainter<AbstractSVGDocumentHandler> } /** {@inheritDoc} */ - public void startGroup(AffineTransform[] transforms) throws IFException { - startGroup(SVGUtil.formatAffineTransformsMptToPt(transforms)); + public void startGroup(AffineTransform[] transforms, String layer) throws IFException { + startGroup(SVGUtil.formatAffineTransformsMptToPt(transforms), layer); } /** {@inheritDoc} */ - public void startGroup(AffineTransform transform) throws IFException { - startGroup(SVGUtil.formatAffineTransformMptToPt(transform)); + public void startGroup(AffineTransform transform, String layer) throws IFException { + startGroup(SVGUtil.formatAffineTransformMptToPt(transform), layer); } - private void startGroup(String transform) throws IFException { + private void startGroup(String transform, String layer) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { diff --git a/status.xml b/status.xml index 5f29deefb..a54bab8e6 100644 --- a/status.xml +++ b/status.xml @@ -58,7 +58,16 @@ users, i.e. when the behaviour changes and could affect the layout of existing documents. Example: the fix of marks layering will be such a case when it's done. --> - <release version="FOP Trunk" date="TBD"> + <release version="FOP Trunk" date="01 November 2013"> + <action context="Code" dev="GA" type="fix" fixes-bug="FOP-2311"> + Eliminate regression to shorthand properties from Bugzilla 37114 (FOP-1069). + </action> + <action context="Renderers" dev="GA" type="add" fixes-bug="FOP-2301"> + Enable support for PDF sub-page transitions. + </action> + <action context="Layout" dev="GA" type="fix" fixes-bug="FOP-2310"> + Fix misplaced table cell border in WM RTL context. + </action> <action context="Renderers" dev="GA" type="add" fixes-bug="FOP-2298"> Enable support for PDF page transitions. </action> diff --git a/test/config/relative-uri/base_font.xconf b/test/config/relative-uri/base_font.xconf new file mode 100644 index 000000000..872c102e7 --- /dev/null +++ b/test/config/relative-uri/base_font.xconf @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="UTF-8"?> +<fop version="1.0"> + <base>relative/</base> + <font-base>fonts/</font-base> +</fop> diff --git a/test/config/relative-uri/base_no-font.xconf b/test/config/relative-uri/base_no-font.xconf new file mode 100644 index 000000000..97d378511 --- /dev/null +++ b/test/config/relative-uri/base_no-font.xconf @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="UTF-8"?> +<fop version="1.0"> + <base>relative/</base> +</fop> diff --git a/test/config/relative-uri/no-base_font.xconf b/test/config/relative-uri/no-base_font.xconf new file mode 100644 index 000000000..165cc1231 --- /dev/null +++ b/test/config/relative-uri/no-base_font.xconf @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="UTF-8"?> +<fop version="1.0"> + <font-base>fonts/</font-base> +</fop> diff --git a/test/config/relative-uri/no-base_no-font.xconf b/test/config/relative-uri/no-base_no-font.xconf new file mode 100644 index 000000000..211d94212 --- /dev/null +++ b/test/config/relative-uri/no-base_no-font.xconf @@ -0,0 +1,3 @@ +<?xml version="1.0" encoding="UTF-8"?> +<fop version="1.0"> +</fop> diff --git a/test/java/org/apache/fop/AbstractBasicTranscoderTest.java b/test/java/org/apache/fop/AbstractBasicTranscoderTest.java index 2087c8df2..7a40b353a 100644 --- a/test/java/org/apache/fop/AbstractBasicTranscoderTest.java +++ b/test/java/org/apache/fop/AbstractBasicTranscoderTest.java @@ -24,13 +24,15 @@ import java.io.InputStream; import org.junit.Test; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.io.output.ByteArrayOutputStream; + import org.apache.batik.transcoder.Transcoder; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; -import org.apache.commons.io.output.ByteArrayOutputStream; import static org.apache.fop.FOPTestUtils.getBaseDir; -import static org.junit.Assert.assertTrue; /** * Basic runtime test for FOP's transcoders. It is used to verify that diff --git a/test/java/org/apache/fop/BasicDriverTestCase.java b/test/java/org/apache/fop/BasicDriverTestCase.java index f149b451e..e89a1c558 100644 --- a/test/java/org/apache/fop/BasicDriverTestCase.java +++ b/test/java/org/apache/fop/BasicDriverTestCase.java @@ -28,11 +28,13 @@ import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamSource; -import org.apache.fop.apps.FOPException; import org.junit.Test; +import static org.junit.Assert.assertTrue; + import org.apache.commons.io.output.ByteArrayOutputStream; +import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; @@ -40,7 +42,6 @@ import org.apache.fop.apps.MimeConstants; import org.apache.fop.cli.InputHandler; import static org.apache.fop.FOPTestUtils.getBaseDir; -import static org.junit.Assert.assertTrue; /** * Basic runtime test for the old Fop class. It is used to verify that @@ -136,7 +137,7 @@ public class BasicDriverTestCase { InputHandler handler = new InputHandler(xmlFile, xsltFile, null); try { handler.renderTo(foUserAgent, MimeConstants.MIME_PDF, baout); - } catch (FOPException e) {} + } catch (FOPException e) { /* NOP */ } } } diff --git a/test/java/org/apache/fop/BasicDriverTestSuite.java b/test/java/org/apache/fop/BasicDriverTestSuite.java index 8330a5f7f..68619926a 100644 --- a/test/java/org/apache/fop/BasicDriverTestSuite.java +++ b/test/java/org/apache/fop/BasicDriverTestSuite.java @@ -27,6 +27,6 @@ import org.junit.runners.Suite.SuiteClasses; * Test suite for basic functionality of FOP's Driver API. */ @RunWith(Suite.class) -@SuiteClasses({ BasicDriverTestCase.class }) +@SuiteClasses(BasicDriverTestCase.class) public class BasicDriverTestSuite { } diff --git a/test/java/org/apache/fop/BasicPSTranscoderTestCase.java b/test/java/org/apache/fop/BasicPSTranscoderTestCase.java index f2f233a5a..2d6fc0d81 100644 --- a/test/java/org/apache/fop/BasicPSTranscoderTestCase.java +++ b/test/java/org/apache/fop/BasicPSTranscoderTestCase.java @@ -20,6 +20,7 @@ package org.apache.fop; import org.apache.batik.transcoder.Transcoder; + import org.apache.fop.render.ps.PSTranscoder; /** diff --git a/test/java/org/apache/fop/DebugHelper.java b/test/java/org/apache/fop/DebugHelper.java index 6705d2f56..9ee7de072 100644 --- a/test/java/org/apache/fop/DebugHelper.java +++ b/test/java/org/apache/fop/DebugHelper.java @@ -25,7 +25,10 @@ import org.apache.fop.logging.LoggingElementListObserver; /** * Handles some standard tasks for debugging. */ -public class DebugHelper { +public final class DebugHelper { + + private DebugHelper() { + } private static boolean elObserversRegistered = false; diff --git a/test/java/org/apache/fop/DigestFilterTestCase.java b/test/java/org/apache/fop/DigestFilterTestCase.java index 5606c2b66..679b65aee 100644 --- a/test/java/org/apache/fop/DigestFilterTestCase.java +++ b/test/java/org/apache/fop/DigestFilterTestCase.java @@ -19,8 +19,6 @@ package org.apache.fop; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.StringReader; import java.security.NoSuchAlgorithmException; @@ -28,13 +26,16 @@ import java.security.NoSuchAlgorithmException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; -import org.apache.fop.util.DigestFilter; import org.junit.Before; import org.junit.Test; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; +import static org.junit.Assert.assertTrue; + +import org.apache.fop.util.DigestFilter; + /** * Test case for digesting SAX filter. * diff --git a/test/java/org/apache/fop/KnuthAlgorithmTestCase.java b/test/java/org/apache/fop/KnuthAlgorithmTestCase.java index 18176117c..8f44864e0 100644 --- a/test/java/org/apache/fop/KnuthAlgorithmTestCase.java +++ b/test/java/org/apache/fop/KnuthAlgorithmTestCase.java @@ -19,10 +19,13 @@ package org.apache.fop; -import static org.junit.Assert.assertEquals; - import java.util.List; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + import org.apache.fop.layoutmgr.BlockKnuthSequence; import org.apache.fop.layoutmgr.BreakingAlgorithm; import org.apache.fop.layoutmgr.ElementListObserver; @@ -30,8 +33,6 @@ import org.apache.fop.layoutmgr.KnuthBox; import org.apache.fop.layoutmgr.KnuthGlue; import org.apache.fop.layoutmgr.KnuthPenalty; import org.apache.fop.layoutmgr.KnuthSequence; -import org.junit.Before; -import org.junit.Test; /** * Tests the Knuth algorithm implementation. diff --git a/test/java/org/apache/fop/URIResolutionTestCase.java b/test/java/org/apache/fop/URIResolutionTestCase.java index e1015306e..e01271f2b 100644 --- a/test/java/org/apache/fop/URIResolutionTestCase.java +++ b/test/java/org/apache/fop/URIResolutionTestCase.java @@ -41,6 +41,9 @@ import org.junit.BeforeClass; import org.junit.Test; import org.w3c.dom.Document; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.xpath.XPathAPI; @@ -59,8 +62,6 @@ import org.apache.fop.apps.io.ResourceResolverFactory; import org.apache.fop.render.xml.XMLRenderer; import static org.apache.fop.FOPTestUtils.getBaseDir; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Tests URI resolution facilities. diff --git a/test/java/org/apache/fop/afp/AFPObjectAreaInfoTestCase.java b/test/java/org/apache/fop/afp/AFPObjectAreaInfoTestCase.java index fc5f1825c..e9134a90b 100644 --- a/test/java/org/apache/fop/afp/AFPObjectAreaInfoTestCase.java +++ b/test/java/org/apache/fop/afp/AFPObjectAreaInfoTestCase.java @@ -19,11 +19,11 @@ package org.apache.fop.afp; -import static org.junit.Assert.assertEquals; - import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** * Test case for {@link AFPObjectAreaInfo}. */ diff --git a/test/java/org/apache/fop/afp/AFPPaintingStateTestCase.java b/test/java/org/apache/fop/afp/AFPPaintingStateTestCase.java index 47c93064c..e9806f944 100644 --- a/test/java/org/apache/fop/afp/AFPPaintingStateTestCase.java +++ b/test/java/org/apache/fop/afp/AFPPaintingStateTestCase.java @@ -19,11 +19,11 @@ package org.apache.fop.afp; -import static org.junit.Assert.assertEquals; - import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** * Test case for {@link AFPPaintingState}. */ diff --git a/test/java/org/apache/fop/afp/AFPResourceManagerTestCase.java b/test/java/org/apache/fop/afp/AFPResourceManagerTestCase.java index 21540221f..9d805a7da 100644 --- a/test/java/org/apache/fop/afp/AFPResourceManagerTestCase.java +++ b/test/java/org/apache/fop/afp/AFPResourceManagerTestCase.java @@ -26,13 +26,13 @@ import java.io.IOException; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.apache.xmlgraphics.util.MimeConstants; import org.apache.fop.apps.io.ResourceResolverFactory; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - /** * Test case for {@link AFPResourceManager}. */ diff --git a/test/java/org/apache/fop/afp/AFPResourceUtilTestCase.java b/test/java/org/apache/fop/afp/AFPResourceUtilTestCase.java index a7cf57ebe..178e5c6ad 100644 --- a/test/java/org/apache/fop/afp/AFPResourceUtilTestCase.java +++ b/test/java/org/apache/fop/afp/AFPResourceUtilTestCase.java @@ -19,8 +19,6 @@ package org.apache.fop.afp; -import static org.junit.Assert.assertTrue; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -29,11 +27,11 @@ import java.util.Arrays; import org.junit.Test; +import static org.junit.Assert.assertTrue; + import org.apache.commons.io.IOUtils; -import org.apache.fop.afp.util.AFPResourceUtil; -import org.junit.Test; -import static org.junit.Assert.assertTrue; +import org.apache.fop.afp.util.AFPResourceUtil; /** * Tests the {@link AFPResourceUtil} class. @@ -133,7 +131,7 @@ public class AFPResourceUtilTestCase { * names fails. * @throws Exception - */ - @Test(expected=Exception.class) + @Test(expected = Exception.class) public void testResourceNameMismatch() throws Exception { testResource(RESOURCE_NAME_MISMATCH, PSEG_B); } @@ -156,6 +154,6 @@ public class AFPResourceUtilTestCase { } private interface ResourceCopier { - public void copy(InputStream in, OutputStream out) throws IOException; + void copy(InputStream in, OutputStream out) throws IOException; } } diff --git a/test/java/org/apache/fop/afp/goca/GraphicsCharacterStringTestCase.java b/test/java/org/apache/fop/afp/goca/GraphicsCharacterStringTestCase.java index b77ef6e12..17c47743c 100644 --- a/test/java/org/apache/fop/afp/goca/GraphicsCharacterStringTestCase.java +++ b/test/java/org/apache/fop/afp/goca/GraphicsCharacterStringTestCase.java @@ -16,16 +16,17 @@ */ package org.apache.fop.afp.goca; -import static org.junit.Assert.assertEquals; - import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + import org.apache.fop.afp.fonts.CharacterSet; import org.apache.fop.afp.fonts.CharacterSetBuilder; import org.apache.fop.fonts.Typeface; -import org.junit.Before; -import org.junit.Test; public class GraphicsCharacterStringTestCase { private GraphicsCharacterString gcsCp500; diff --git a/test/java/org/apache/fop/afp/modca/AbstractAFPObjectTest.java b/test/java/org/apache/fop/afp/modca/AbstractAFPObjectTest.java index 65c0224c2..a4c80cc65 100644 --- a/test/java/org/apache/fop/afp/modca/AbstractAFPObjectTest.java +++ b/test/java/org/apache/fop/afp/modca/AbstractAFPObjectTest.java @@ -19,10 +19,6 @@ package org.apache.fop.afp.modca; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -30,9 +26,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.apache.fop.afp.Streamable; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.apache.fop.afp.Streamable; + /** * Tests the {@link AbstractAFPObject} class. */ diff --git a/test/java/org/apache/fop/afp/modca/AbstractNamedAFPObjectTest.java b/test/java/org/apache/fop/afp/modca/AbstractNamedAFPObjectTest.java index 5c863b6e4..0593ae637 100644 --- a/test/java/org/apache/fop/afp/modca/AbstractNamedAFPObjectTest.java +++ b/test/java/org/apache/fop/afp/modca/AbstractNamedAFPObjectTest.java @@ -19,12 +19,12 @@ package org.apache.fop.afp.modca; -import static org.junit.Assert.assertTrue; - import java.util.Arrays; import org.junit.Test; +import static org.junit.Assert.assertTrue; + /** * Tests the {@linkplain AbstractAFPObject} class. */ diff --git a/test/java/org/apache/fop/afp/modca/AbstractStructuredObjectTest.java b/test/java/org/apache/fop/afp/modca/AbstractStructuredObjectTest.java index faef0a4f6..d0a543087 100644 --- a/test/java/org/apache/fop/afp/modca/AbstractStructuredObjectTest.java +++ b/test/java/org/apache/fop/afp/modca/AbstractStructuredObjectTest.java @@ -21,7 +21,8 @@ package org.apache.fop.afp.modca; import java.io.IOException; -public abstract class AbstractStructuredObjectTest<S extends AbstractStructuredObject> extends AbstractAFPObjectTest<S> { +public abstract class AbstractStructuredObjectTest<S extends AbstractStructuredObject> + extends AbstractAFPObjectTest<S> { /** * Test writeStart() - test that the contract is maintained with diff --git a/test/java/org/apache/fop/afp/modca/AbstractTripletStructuredObjectTest.java b/test/java/org/apache/fop/afp/modca/AbstractTripletStructuredObjectTest.java index 10c154550..fe25996bb 100644 --- a/test/java/org/apache/fop/afp/modca/AbstractTripletStructuredObjectTest.java +++ b/test/java/org/apache/fop/afp/modca/AbstractTripletStructuredObjectTest.java @@ -19,10 +19,6 @@ package org.apache.fop.afp.modca; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; @@ -33,6 +29,10 @@ import java.util.List; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.apache.fop.afp.modca.triplets.AbstractTriplet; import org.apache.fop.afp.modca.triplets.AttributeQualifierTriplet; import org.apache.fop.afp.modca.triplets.CommentTriplet; diff --git a/test/java/org/apache/fop/afp/modca/IncludeObjectTestCase.java b/test/java/org/apache/fop/afp/modca/IncludeObjectTestCase.java index 0449f2599..7e096f98b 100644 --- a/test/java/org/apache/fop/afp/modca/IncludeObjectTestCase.java +++ b/test/java/org/apache/fop/afp/modca/IncludeObjectTestCase.java @@ -19,16 +19,17 @@ package org.apache.fop.afp.modca; -import static org.junit.Assert.assertTrue; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; -import org.apache.fop.afp.util.BinaryUtils; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; + +import org.apache.fop.afp.util.BinaryUtils; + /** * Test {@link IncludeObject} */ diff --git a/test/java/org/apache/fop/afp/parser/MODCAParserTestCase.java b/test/java/org/apache/fop/afp/parser/MODCAParserTestCase.java index c80ef086c..176344618 100644 --- a/test/java/org/apache/fop/afp/parser/MODCAParserTestCase.java +++ b/test/java/org/apache/fop/afp/parser/MODCAParserTestCase.java @@ -19,11 +19,6 @@ package org.apache.fop.afp.parser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; @@ -32,6 +27,11 @@ import java.util.Arrays; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * MODCAParser and MODCAParser.UnparsedStructuredField Unit tests */ diff --git a/test/java/org/apache/fop/afp/ptoca/TransparentDataControlSequenceTestCase.java b/test/java/org/apache/fop/afp/ptoca/TransparentDataControlSequenceTestCase.java index 338c5e6f4..8d6c79d05 100644 --- a/test/java/org/apache/fop/afp/ptoca/TransparentDataControlSequenceTestCase.java +++ b/test/java/org/apache/fop/afp/ptoca/TransparentDataControlSequenceTestCase.java @@ -24,15 +24,16 @@ import java.io.OutputStream; import org.junit.Test; -import org.apache.fop.afp.fonts.CharactersetEncoder.EncodedChars; -import org.apache.fop.afp.ptoca.TransparentDataControlSequence.TransparentData; - -import static org.apache.fop.afp.ptoca.PtocaConstants.TRANSPARENT_DATA_MAX_SIZE; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import org.apache.fop.afp.fonts.CharactersetEncoder.EncodedChars; +import org.apache.fop.afp.ptoca.TransparentDataControlSequence.TransparentData; + +import static org.apache.fop.afp.ptoca.PtocaConstants.TRANSPARENT_DATA_MAX_SIZE; + public class TransparentDataControlSequenceTestCase { private EncodedChars encodedChars; diff --git a/test/java/org/apache/fop/apps/AbstractRendererConfigParserTester.java b/test/java/org/apache/fop/apps/AbstractRendererConfigParserTester.java index 9739db2f3..e4c9ceb44 100644 --- a/test/java/org/apache/fop/apps/AbstractRendererConfigParserTester.java +++ b/test/java/org/apache/fop/apps/AbstractRendererConfigParserTester.java @@ -19,6 +19,9 @@ package org.apache.fop.apps; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; @@ -28,9 +31,6 @@ import org.apache.fop.fonts.FontManager; import org.apache.fop.render.RendererConfig; import org.apache.fop.render.RendererConfig.RendererConfigParser; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public abstract class AbstractRendererConfigParserTester<B extends RendererConfBuilder, C extends RendererConfig> { diff --git a/test/java/org/apache/fop/apps/AbstractRendererConfiguratorTest.java b/test/java/org/apache/fop/apps/AbstractRendererConfiguratorTest.java index 58c14f5df..2487c0a63 100644 --- a/test/java/org/apache/fop/apps/AbstractRendererConfiguratorTest.java +++ b/test/java/org/apache/fop/apps/AbstractRendererConfiguratorTest.java @@ -24,16 +24,17 @@ import java.io.IOException; import org.xml.sax.SAXException; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.fop.apps.FopConfBuilder.RendererConfBuilder; import org.apache.fop.render.PrintRendererConfigurator; import org.apache.fop.render.intermediate.IFDocumentHandler; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public abstract class AbstractRendererConfiguratorTest<T extends PrintRendererConfigurator, B extends RendererConfBuilder> { +public abstract class AbstractRendererConfiguratorTest<T extends PrintRendererConfigurator, + B extends RendererConfBuilder> { protected final String mimeType; protected FOUserAgent userAgent; diff --git a/test/java/org/apache/fop/apps/EnvironmentalProfileFactoryTestCase.java b/test/java/org/apache/fop/apps/EnvironmentalProfileFactoryTestCase.java index e94403e71..83bfd2076 100644 --- a/test/java/org/apache/fop/apps/EnvironmentalProfileFactoryTestCase.java +++ b/test/java/org/apache/fop/apps/EnvironmentalProfileFactoryTestCase.java @@ -21,7 +21,6 @@ import java.net.URI; import org.junit.Test; - import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; diff --git a/test/java/org/apache/fop/apps/FopConfParserTestCase.java b/test/java/org/apache/fop/apps/FopConfParserTestCase.java index 3c2930942..dc794fdb8 100644 --- a/test/java/org/apache/fop/apps/FopConfParserTestCase.java +++ b/test/java/org/apache/fop/apps/FopConfParserTestCase.java @@ -19,6 +19,7 @@ package org.apache.fop.apps; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -127,4 +128,41 @@ public class FopConfParserTestCase { builder.setPreferRenderer(true); assertTrue(buildFactory().getRendererFactory().isRendererPreferred()); } + + @Test + public void testRelativeURINoBaseNoFont() throws Exception { + checkRelativeURIs("test/config/relative-uri/no-base_no-font.xconf", + "", ""); + } + + @Test + public void testRelativeURINoBaseFont() throws Exception { + checkRelativeURIs("test/config/relative-uri/no-base_font.xconf", + "", "test/config/relative-uri/fonts/"); + } + + @Test + public void testRelativeURIBaseNoFont() throws Exception { + checkRelativeURIs("test/config/relative-uri/base_no-font.xconf", + "test/config/relative-uri/relative/", "test/config/relative-uri/relative/"); + } + + @Test + public void testRelativeURIBaseFont() throws Exception { + checkRelativeURIs("test/config/relative-uri/base_font.xconf", + "test/config/relative-uri/relative/", "test/config/relative-uri/fonts/"); + } + + private void checkRelativeURIs(String conf, String expectedBase, String expectedFontBase) + throws SAXException, IOException { + File configFile = new File(conf); + URI currentDir = new File(".").getCanonicalFile().toURI(); + FopConfParser parser = new FopConfParser(configFile, currentDir); + FopFactoryBuilder fopFactoryBuilder = parser.getFopFactoryBuilder(); + assertEquals("base URI", currentDir.resolve(expectedBase), + fopFactoryBuilder.getBaseURI()); + assertEquals("font base", currentDir.resolve(expectedFontBase), + fopFactoryBuilder.getFontManager().getResourceResolver().getBaseURI()); + } + } diff --git a/test/java/org/apache/fop/apps/FopFactoryBuilderTestCase.java b/test/java/org/apache/fop/apps/FopFactoryBuilderTestCase.java index e504c4bc4..86b4e7c04 100644 --- a/test/java/org/apache/fop/apps/FopFactoryBuilderTestCase.java +++ b/test/java/org/apache/fop/apps/FopFactoryBuilderTestCase.java @@ -27,6 +27,12 @@ import java.util.List; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import org.apache.fop.apps.io.ResourceResolverFactory; import org.apache.fop.area.AreaTreeHandler; import org.apache.fop.area.Block; @@ -45,12 +51,6 @@ import org.apache.fop.layoutmgr.PageSequenceLayoutManager; import org.apache.fop.layoutmgr.StaticContentLayoutManager; import org.apache.fop.layoutmgr.inline.ContentLayoutManager; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - /** * Test case for {@link FopFactoryBuilder}. */ diff --git a/test/java/org/apache/fop/apps/FopFactoryTestCase.java b/test/java/org/apache/fop/apps/FopFactoryTestCase.java index 8ac21c994..439ffa44e 100644 --- a/test/java/org/apache/fop/apps/FopFactoryTestCase.java +++ b/test/java/org/apache/fop/apps/FopFactoryTestCase.java @@ -24,16 +24,15 @@ import java.io.IOException; import org.junit.Test; import org.xml.sax.SAXException; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.config.BaseConstructiveUserConfigTest; -import org.apache.fop.render.RendererConfig.RendererConfigParser; -import org.apache.fop.render.pdf.PDFRendererConfig; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import org.apache.fop.config.BaseConstructiveUserConfigTest; +import org.apache.fop.render.RendererConfig.RendererConfigParser; +import org.apache.fop.render.pdf.PDFRendererConfig; + public class FopFactoryTestCase extends BaseConstructiveUserConfigTest { public FopFactoryTestCase() throws SAXException, IOException { diff --git a/test/java/org/apache/fop/apps/PDFRendererConfBuilder.java b/test/java/org/apache/fop/apps/PDFRendererConfBuilder.java index 13ca3df6b..3da4e1daf 100644 --- a/test/java/org/apache/fop/apps/PDFRendererConfBuilder.java +++ b/test/java/org/apache/fop/apps/PDFRendererConfBuilder.java @@ -22,10 +22,8 @@ package org.apache.fop.apps; import org.w3c.dom.Element; import org.apache.fop.apps.FopConfBuilder.RendererConfBuilder; -import org.apache.fop.pdf.PDFEncryptionParams; import org.apache.fop.render.RendererConfigOption; import org.apache.fop.render.pdf.PDFEncryptionOption; -import org.apache.fop.render.pdf.PDFRendererOption; import static org.apache.fop.render.pdf.PDFEncryptionOption.ENCRYPTION_LENGTH; import static org.apache.fop.render.pdf.PDFEncryptionOption.ENCRYPTION_PARAMS; diff --git a/test/java/org/apache/fop/apps/io/BaseURIResolutionTest.java b/test/java/org/apache/fop/apps/io/BaseURIResolutionTest.java index 2131407c1..e04283718 100644 --- a/test/java/org/apache/fop/apps/io/BaseURIResolutionTest.java +++ b/test/java/org/apache/fop/apps/io/BaseURIResolutionTest.java @@ -34,6 +34,8 @@ import javax.xml.transform.stream.StreamSource; import org.xml.sax.SAXException; +import static org.junit.Assert.assertTrue; + import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; @@ -48,7 +50,6 @@ import org.apache.fop.apps.FopFactoryBuilder; import org.apache.fop.apps.MimeConstants; import static org.apache.fop.FOPTestUtils.getBaseDir; -import static org.junit.Assert.assertTrue; public abstract class BaseURIResolutionTest { diff --git a/test/java/org/apache/fop/apps/io/FontURIResolver.java b/test/java/org/apache/fop/apps/io/FontURIResolver.java index 40d6c7402..781aca368 100644 --- a/test/java/org/apache/fop/apps/io/FontURIResolver.java +++ b/test/java/org/apache/fop/apps/io/FontURIResolver.java @@ -33,14 +33,13 @@ import javax.xml.transform.TransformerException; import org.junit.Test; import org.xml.sax.SAXException; -import org.apache.fop.apps.FopConfBuilder; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.apps.PDFRendererConfBuilder; - import static org.junit.Assert.assertTrue; import org.apache.xmlgraphics.io.Resource; +import org.apache.fop.apps.FopConfBuilder; +import org.apache.fop.apps.PDFRendererConfBuilder; + public class FontURIResolver extends BaseURIResolutionTest { public enum Event { diff --git a/test/java/org/apache/fop/area/ViewportTest.java b/test/java/org/apache/fop/area/ViewportTest.java index cb2282071..46412c83d 100644 --- a/test/java/org/apache/fop/area/ViewportTest.java +++ b/test/java/org/apache/fop/area/ViewportTest.java @@ -19,13 +19,13 @@ package org.apache.fop.area; +import java.awt.Rectangle; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import java.awt.Rectangle; - /** * Tests implementations of the {@linkplain Viewport} interface. */ diff --git a/test/java/org/apache/fop/area/ViewportTestSuite.java b/test/java/org/apache/fop/area/ViewportTestSuite.java index 065e07bf9..891f1d081 100644 --- a/test/java/org/apache/fop/area/ViewportTestSuite.java +++ b/test/java/org/apache/fop/area/ViewportTestSuite.java @@ -19,11 +19,12 @@ package org.apache.fop.area; -import org.apache.fop.area.inline.InlineViewportTestCase; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import org.apache.fop.area.inline.InlineViewportTestCase; + /** * A suite of all the tests relating to the {@linkplain Viewport} interface. */ diff --git a/test/java/org/apache/fop/area/inline/InlineViewportTestCase.java b/test/java/org/apache/fop/area/inline/InlineViewportTestCase.java index edcf99d14..cba5759cf 100644 --- a/test/java/org/apache/fop/area/inline/InlineViewportTestCase.java +++ b/test/java/org/apache/fop/area/inline/InlineViewportTestCase.java @@ -19,9 +19,10 @@ package org.apache.fop.area.inline; -import org.apache.fop.area.ViewportTest; import org.junit.Test; +import org.apache.fop.area.ViewportTest; + /** * Tests the {@linkplain InlineViewport} class. */ diff --git a/test/java/org/apache/fop/check/ChecksFactory.java b/test/java/org/apache/fop/check/ChecksFactory.java index a493c09f2..d77ce422d 100644 --- a/test/java/org/apache/fop/check/ChecksFactory.java +++ b/test/java/org/apache/fop/check/ChecksFactory.java @@ -37,7 +37,7 @@ public abstract class ChecksFactory<C extends Check> { /** * A factory to create a particular kind of check. */ - protected static interface CheckFactory<C> { + protected interface CheckFactory<C> { /** * Creates a {@link Check} instance from the given XML element. diff --git a/test/java/org/apache/fop/cli/CommandLineOptionsTestCase.java b/test/java/org/apache/fop/cli/CommandLineOptionsTestCase.java index 9a80fd964..1be3daa84 100644 --- a/test/java/org/apache/fop/cli/CommandLineOptionsTestCase.java +++ b/test/java/org/apache/fop/cli/CommandLineOptionsTestCase.java @@ -19,15 +19,16 @@ package org.apache.fop.cli; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; -import org.apache.fop.apps.FOPException; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.apache.fop.apps.FOPException; + public class CommandLineOptionsTestCase { private final CommandLineOptions clo = new CommandLineOptions(); diff --git a/test/java/org/apache/fop/complexscripts/bidi/BidiAlgorithmTestCase.java b/test/java/org/apache/fop/complexscripts/bidi/BidiAlgorithmTestCase.java index f20e113c1..8ed1af217 100644 --- a/test/java/org/apache/fop/complexscripts/bidi/BidiAlgorithmTestCase.java +++ b/test/java/org/apache/fop/complexscripts/bidi/BidiAlgorithmTestCase.java @@ -19,26 +19,23 @@ package org.apache.fop.complexscripts.bidi; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.apache.fop.complexscripts.bidi.UnicodeBidiAlgorithm; - import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + /** * <p>Test case for Unicode Bidi Algorithm.</p> - * @author Glenn Adams */ public class BidiAlgorithmTestCase { /** * logging instance */ - private static final Log log = LogFactory.getLog(BidiAlgorithmTestCase.class); // CSOK: ConstantNameCheck + private static final Log log = LogFactory.getLog(BidiAlgorithmTestCase.class); /** * Concatenated array of <test-set,test-sequence> tuples @@ -122,7 +119,7 @@ public class BidiAlgorithmTestCase { } if (includeSequence(testSet, testSequence)) { includedSequences++; - if (! excludeSequence(testSet, testSequence)) { + if (!excludeSequence(testSet, testSequence)) { if (testBidiAlgorithm(testSet, testSequence, la, ra, ta, bs)) { passedSequences++; } @@ -151,7 +148,7 @@ public class BidiAlgorithmTestCase { } private boolean includeSequence(int testSet, int testSequence) { - if (! includeTestSet(testSet)) { + if (!includeTestSet(testSet)) { return false; } else { for (int i = 0, n = INCLUSIONS.length / 2; i < n; i++) { @@ -196,7 +193,8 @@ public class BidiAlgorithmTestCase { return false; } - private boolean testBidiAlgorithm(int testSet, int testSequence, int[] la, int[] ra, int[] ta, int bs) throws Exception { + private boolean testBidiAlgorithm(int testSet, int testSequence, int[] la, int[] ra, int[] ta, int bs) + throws Exception { boolean passed = true; int n = la.length; if (ra.length != n) { @@ -211,14 +209,14 @@ public class BidiAlgorithmTestCase { // LTR if ((bs & 2) != 0) { int[] levels = UnicodeBidiAlgorithm.resolveLevels(null, ta, 0, new int [ n ], true); - if (! verifyResults(la, levels, ta, 0, testSet, testSequence)) { + if (!verifyResults(la, levels, ta, 0, testSet, testSequence)) { passed = false; } } // RTL if ((bs & 4) != 0) { int[] levels = UnicodeBidiAlgorithm.resolveLevels(null, ta, 1, new int [ n ], true); - if (! verifyResults(la, levels, ta, 1, testSet, testSequence)) { + if (!verifyResults(la, levels, ta, 1, testSet, testSequence)) { passed = false; } } diff --git a/test/java/org/apache/fop/complexscripts/bidi/BidiClassTestCase.java b/test/java/org/apache/fop/complexscripts/bidi/BidiClassTestCase.java index 10a84b856..f393e5b70 100644 --- a/test/java/org/apache/fop/complexscripts/bidi/BidiClassTestCase.java +++ b/test/java/org/apache/fop/complexscripts/bidi/BidiClassTestCase.java @@ -19,14 +19,13 @@ package org.apache.fop.complexscripts.bidi; -import org.apache.fop.complexscripts.bidi.BidiClass; -import org.apache.fop.util.CharUtilities; - import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import org.apache.fop.util.CharUtilities; + public class BidiClassTestCase { @Test @@ -46,8 +45,8 @@ public class BidiClassTestCase { private void testBidiClass(int[] da) throws Exception { int bc = da[0]; for (int i = 1, n = da.length; i < n; i += 2) { - int s = da[i+0]; - int e = da[i+1]; + int s = da[i + 0]; + int e = da[i + 1]; for (int c = s; c < e; c++) { int cbc = BidiClass.getBidiClass(c); assertEquals("bad bidi class for CH(" + CharUtilities.format(c) + ")", bc, cbc); diff --git a/test/java/org/apache/fop/complexscripts/bidi/BidiTestData.java b/test/java/org/apache/fop/complexscripts/bidi/BidiTestData.java index 726682ce0..49a5c9455 100644 --- a/test/java/org/apache/fop/complexscripts/bidi/BidiTestData.java +++ b/test/java/org/apache/fop/complexscripts/bidi/BidiTestData.java @@ -23,7 +23,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; -// CSOFF: WhitespaceAfterCheck /* * !!! THIS IS A GENERATED FILE !!! @@ -66,7 +65,7 @@ public final class BidiTestData { data = null; } finally { if (is != null) { - try { is.close(); } catch (Exception e) {} + try { is.close(); } catch (Exception e) { /* NOP */ } } } return data; diff --git a/test/java/org/apache/fop/complexscripts/fonts/GDEFTestCase.java b/test/java/org/apache/fop/complexscripts/fonts/GDEFTestCase.java index af929d3a1..f1512903c 100644 --- a/test/java/org/apache/fop/complexscripts/fonts/GDEFTestCase.java +++ b/test/java/org/apache/fop/complexscripts/fonts/GDEFTestCase.java @@ -21,21 +21,14 @@ package org.apache.fop.complexscripts.fonts; import java.io.File; -import org.apache.fop.complexscripts.fonts.GlyphSubtable; -import org.apache.fop.complexscripts.fonts.GlyphDefinitionSubtable; -import org.apache.fop.complexscripts.fonts.GlyphDefinitionTable; -import org.apache.fop.complexscripts.fonts.GlyphTable.LookupSpec; -import org.apache.fop.complexscripts.fonts.GlyphTable.LookupTable; -import org.apache.fop.complexscripts.fonts.ttx.TTXFile; -import org.apache.fop.complexscripts.util.GlyphContextTester; -import org.apache.fop.complexscripts.util.GlyphSequence; - import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import org.apache.fop.complexscripts.fonts.ttx.TTXFile; + public class GDEFTestCase { private static String ttxFilesRoot = "test/resources/complexscripts"; diff --git a/test/java/org/apache/fop/complexscripts/fonts/GPOSTestCase.java b/test/java/org/apache/fop/complexscripts/fonts/GPOSTestCase.java index 270b56797..cf63b4eff 100644 --- a/test/java/org/apache/fop/complexscripts/fonts/GPOSTestCase.java +++ b/test/java/org/apache/fop/complexscripts/fonts/GPOSTestCase.java @@ -20,18 +20,6 @@ package org.apache.fop.complexscripts.fonts; import java.io.File; -import java.util.List; -import java.util.Map; - -import org.apache.fop.complexscripts.fonts.GlyphSubtable; -import org.apache.fop.complexscripts.fonts.GlyphPositioningSubtable; -import org.apache.fop.complexscripts.fonts.GlyphPositioningTable; -import org.apache.fop.complexscripts.fonts.GlyphTable.LookupSpec; -import org.apache.fop.complexscripts.fonts.GlyphTable.LookupTable; -import org.apache.fop.complexscripts.fonts.ttx.TTXFile; -import org.apache.fop.complexscripts.util.GlyphContextTester; -import org.apache.fop.complexscripts.util.GlyphSequence; -import org.apache.fop.complexscripts.util.ScriptContextTester; import org.junit.Test; @@ -40,6 +28,14 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import org.apache.fop.complexscripts.fonts.GlyphTable.LookupTable; +import org.apache.fop.complexscripts.fonts.ttx.TTXFile; +import org.apache.fop.complexscripts.util.GlyphContextTester; +import org.apache.fop.complexscripts.util.GlyphSequence; +import org.apache.fop.complexscripts.util.ScriptContextTester; + +// CSOFF: LineLength + public class GPOSTestCase implements ScriptContextTester, GlyphContextTester { private static String ttxFilesRoot = "test/resources/complexscripts"; diff --git a/test/java/org/apache/fop/complexscripts/fonts/GSUBTestCase.java b/test/java/org/apache/fop/complexscripts/fonts/GSUBTestCase.java index b235fa58c..3f23d9ab3 100644 --- a/test/java/org/apache/fop/complexscripts/fonts/GSUBTestCase.java +++ b/test/java/org/apache/fop/complexscripts/fonts/GSUBTestCase.java @@ -21,18 +21,6 @@ package org.apache.fop.complexscripts.fonts; import java.io.File; import java.nio.IntBuffer; -import java.util.List; -import java.util.Map; - -import org.apache.fop.complexscripts.fonts.GlyphSubtable; -import org.apache.fop.complexscripts.fonts.GlyphSubstitutionSubtable; -import org.apache.fop.complexscripts.fonts.GlyphSubstitutionTable; -import org.apache.fop.complexscripts.fonts.GlyphTable.LookupSpec; -import org.apache.fop.complexscripts.fonts.GlyphTable.LookupTable; -import org.apache.fop.complexscripts.fonts.ttx.TTXFile; -import org.apache.fop.complexscripts.util.GlyphContextTester; -import org.apache.fop.complexscripts.util.GlyphSequence; -import org.apache.fop.complexscripts.util.ScriptContextTester; import org.junit.Test; @@ -41,6 +29,14 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import org.apache.fop.complexscripts.fonts.GlyphTable.LookupTable; +import org.apache.fop.complexscripts.fonts.ttx.TTXFile; +import org.apache.fop.complexscripts.util.GlyphContextTester; +import org.apache.fop.complexscripts.util.GlyphSequence; +import org.apache.fop.complexscripts.util.ScriptContextTester; + +// CSOFF: LineLength + public class GSUBTestCase implements ScriptContextTester, GlyphContextTester { private static String ttxFilesRoot = "test/resources/complexscripts"; diff --git a/test/java/org/apache/fop/complexscripts/fonts/ttx/TTXFile.java b/test/java/org/apache/fop/complexscripts/fonts/ttx/TTXFile.java index b3e080d50..178203ff6 100644 --- a/test/java/org/apache/fop/complexscripts/fonts/ttx/TTXFile.java +++ b/test/java/org/apache/fop/complexscripts/fonts/ttx/TTXFile.java @@ -21,11 +21,9 @@ package org.apache.fop.complexscripts.fonts.ttx; import java.io.File; import java.io.IOException; - import java.nio.IntBuffer; - -import java.util.Arrays; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; @@ -41,21 +39,23 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import org.xml.sax.Attributes; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.fop.complexscripts.fonts.GlyphClassTable; import org.apache.fop.complexscripts.fonts.GlyphCoverageTable; -import org.apache.fop.complexscripts.fonts.GlyphDefinitionSubtable; import org.apache.fop.complexscripts.fonts.GlyphDefinitionTable; import org.apache.fop.complexscripts.fonts.GlyphMappingTable; -import org.apache.fop.complexscripts.fonts.GlyphPositioningSubtable; import org.apache.fop.complexscripts.fonts.GlyphPositioningTable; import org.apache.fop.complexscripts.fonts.GlyphPositioningTable.Anchor; import org.apache.fop.complexscripts.fonts.GlyphPositioningTable.MarkAnchor; import org.apache.fop.complexscripts.fonts.GlyphPositioningTable.PairValues; import org.apache.fop.complexscripts.fonts.GlyphPositioningTable.Value; -import org.apache.fop.complexscripts.fonts.GlyphSubstitutionSubtable; import org.apache.fop.complexscripts.fonts.GlyphSubstitutionTable; import org.apache.fop.complexscripts.fonts.GlyphSubstitutionTable.Ligature; import org.apache.fop.complexscripts.fonts.GlyphSubstitutionTable.LigatureSet; @@ -66,15 +66,8 @@ import org.apache.fop.complexscripts.util.GlyphSequence; import org.apache.fop.complexscripts.util.UTF32; import org.apache.fop.util.CharUtilities; -import org.xml.sax.Attributes; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -// CSOFF: InnerAssignmentCheck // CSOFF: LineLengthCheck -// CSOFF: NoWhitespaceAfterCheck /** * This class supports a subset of the <code>TTX</code> file as produced by the Adobe FLEX @@ -89,8 +82,6 @@ import org.xml.sax.helpers.DefaultHandler; * files directly in the FOP distribution. In such cases, <code>TTX</code> files are used * to distribute a subset of the complex script advanced table information contained in * certain font files to facilitate testing. - * - * @author Glenn Adams */ public class TTXFile { @@ -102,22 +93,22 @@ public class TTXFile { private static final String DEFAULT_LANGUAGE_TAG = "dflt"; /** ttxfile cache */ - private static Map<String,TTXFile> cache = new HashMap<String,TTXFile>(); + private static Map<String, TTXFile> cache = new HashMap<String, TTXFile>(); // transient parsing state private Locator locator; // current document locator private Stack<String[]> elements; // stack of ttx elements being parsed - private Map<String,Integer> glyphIds; // map of glyph names to glyph identifiers + private Map<String, Integer> glyphIds; // map of glyph names to glyph identifiers private List<int[]> cmapEntries; // list of <charCode,glyphCode> pairs private Vector<int[]> hmtxEntries; // vector of <width,lsb> pairs - private Map<String,Integer> glyphClasses; // map of glyph names to glyph classes - private Map<String,Map<String,List<String>>> scripts; // map of script tag to Map<language-tag,List<features-id>>> - private Map<String,List<String>> languages; // map of language tag to List<feature-id> - private Map<String,Object[]> features; // map of feature id to Object[2] : { feature-tag, List<lookup-id> } + private Map<String, Integer> glyphClasses; // map of glyph names to glyph classes + private Map<String, Map<String, List<String>>> scripts; // map of script tag to Map<language-tag,List<features-id>>> + private Map<String, List<String>> languages; // map of language tag to List<feature-id> + private Map<String, Object[]> features; // map of feature id to Object[2] : { feature-tag, List<lookup-id> } private List<String> languageFeatures; // list of language system feature ids, where first is (possibly null) required feature id private List<String> featureLookups; // list of lookup ids for feature being constructed private List<Integer> coverageEntries; // list of entries for coverage table being constructed - private Map<String,GlyphCoverageTable> coverages; // map of coverage table keys to coverage tables + private Map<String, GlyphCoverageTable> coverages; // map of coverage table keys to coverage tables private List subtableEntries; // list of lookup subtable entries private List<GlyphSubtable> subtables; // list of constructed subtables private List<Integer> alternates; // list of alternates in alternate set being constructed @@ -164,8 +155,8 @@ public class TTXFile { // resultant state private int upem; // units per em - private Map<Integer,Integer> cmap; // constructed character map - private Map<Integer,Integer> gmap; // constructed glyph map + private Map<Integer, Integer> cmap; // constructed character map + private Map<Integer, Integer> gmap; // constructed glyph map private int[][] hmtx; // constructed horizontal metrics - array of design { width, lsb } pairs, indexed by glyph code private int[] widths; // pdf normalized widths (millipoints) private GlyphDefinitionTable gdef; // constructed glyph definition table @@ -174,17 +165,17 @@ public class TTXFile { public TTXFile() { elements = new Stack<String[]>(); - glyphIds = new HashMap<String,Integer>(); + glyphIds = new HashMap<String, Integer>(); cmapEntries = new ArrayList<int[]>(); hmtxEntries = new Vector<int[]>(); - glyphClasses = new HashMap<String,Integer>(); - scripts = new HashMap<String,Map<String,List<String>>>(); - languages = new HashMap<String,List<String>>(); - features = new HashMap<String,Object[]>(); + glyphClasses = new HashMap<String, Integer>(); + scripts = new HashMap<String, Map<String, List<String>>>(); + languages = new HashMap<String, List<String>>(); + features = new HashMap<String, Object[]>(); languageFeatures = new ArrayList<String>(); featureLookups = new ArrayList<String>(); coverageEntries = new ArrayList<Integer>(); - coverages = new HashMap<String,GlyphCoverageTable>(); + coverages = new HashMap<String, GlyphCoverageTable>(); subtableEntries = new ArrayList(); subtables = new ArrayList<GlyphSubtable>(); alternates = new ArrayList<Integer>(); @@ -344,7 +335,7 @@ public class TTXFile { long rest1 = tw % upem; long storrest = 1000 * rest1; long ledd2 = (storrest != 0) ? (rest1 / storrest) : 0; - pw = - ((-1000 * tw) / upem - (int) ledd2); + pw = -((-1000 * tw) / upem - (int) ledd2); } else { pw = (tw / upem) * 1000 + ((tw % upem) * 1000) / upem; } @@ -372,7 +363,7 @@ public class TTXFile { public static synchronized void clearCache() { cache.clear(); } - private class Handler extends DefaultHandler { + private final class Handler extends DefaultHandler { private Handler() { } @Override @@ -495,7 +486,7 @@ public class TTXFile { } } else if (en[1].equals("BaseArray")) { String[] pn = new String[] { null, "MarkBasePos" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } } else if (en[1].equals("BaseCoverage")) { @@ -589,7 +580,7 @@ public class TTXFile { if (glyphClass == null) { missingRequiredAttribute(en, "class"); } - if (! glyphIds.containsKey(glyph)) { + if (!glyphIds.containsKey(glyph)) { unsupportedGlyph(en, glyph); } else if (isParent(pn1)) { if (glyphClasses.containsKey(glyph)) { @@ -677,7 +668,7 @@ public class TTXFile { } } else if (en[1].equals("DefaultLangSys")) { String[] pn = new String[] { null, "Script" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } else { assertLanguageFeaturesClear(); @@ -720,7 +711,7 @@ public class TTXFile { } } else if (en[1].equals("Feature")) { String[] pn = new String[] { null, "FeatureRecord" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } else { assertFeatureLookupsClear(); @@ -754,7 +745,7 @@ public class TTXFile { String[] pn1 = new String[] { null, "GSUB" }; String[] pn2 = new String[] { null, "GPOS" }; String[][] pnx = new String[][] { pn1, pn2 }; - if (! isParent(pnx)) { + if (!isParent(pnx)) { notPermittedInElementContext(en, getParent(), pnx); } } else if (en[1].equals("FeatureRecord")) { @@ -887,7 +878,7 @@ public class TTXFile { } } else if (en[1].equals("GlyphOrder")) { String[] pn = new String[] { null, "ttFont" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } } else if (en[1].equals("InputCoverage")) { @@ -925,7 +916,7 @@ public class TTXFile { } } else if (en[1].equals("LangSys")) { String[] pn = new String[] { null, "LangSysRecord" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } else { assertLanguageFeaturesClear(); @@ -955,7 +946,7 @@ public class TTXFile { } } else if (en[1].equals("LigCaretList")) { String[] pn = new String[] { null, "GDEF" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } } else if (en[1].equals("Ligature")) { @@ -993,7 +984,7 @@ public class TTXFile { } } else if (en[1].equals("LigatureArray")) { String[] pn = new String[] { null, "MarkLigPos" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } } else if (en[1].equals("LigatureAttach")) { @@ -1141,7 +1132,7 @@ public class TTXFile { String[] pn1 = new String[] { null, "GSUB" }; String[] pn2 = new String[] { null, "GPOS" }; String[][] pnx = new String[][] { pn1, pn2 }; - if (! isParent(pnx)) { + if (!isParent(pnx)) { notPermittedInElementContext(en, getParent(), pnx); } } else if (en[1].equals("LookupListIndex")) { @@ -1181,7 +1172,7 @@ public class TTXFile { } } else if (en[1].equals("Mark1Array")) { String[] pn = new String[] { null, "MarkMarkPos" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } } else if (en[1].equals("Mark1Coverage")) { @@ -1222,7 +1213,7 @@ public class TTXFile { } } else if (en[1].equals("Mark2Array")) { String[] pn = new String[] { null, "MarkMarkPos" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } } else if (en[1].equals("Mark2Coverage")) { @@ -1275,7 +1266,7 @@ public class TTXFile { String[] pn1 = new String[] { null, "MarkBasePos" }; String[] pn2 = new String[] { null, "MarkLigPos" }; String[][] pnx = new String[][] { pn1, pn2 }; - if (! isParent(pnx)) { + if (!isParent(pnx)) { notPermittedInElementContext(en, getParent(), pnx); } } else if (en[1].equals("MarkAttachClassDef")) { @@ -1551,14 +1542,14 @@ public class TTXFile { } } else if (en[1].equals("Script")) { String[] pn = new String[] { null, "ScriptRecord" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } } else if (en[1].equals("ScriptList")) { String[] pn1 = new String[] { null, "GSUB" }; String[] pn2 = new String[] { null, "GPOS" }; String[][] pnx = new String[][] { pn1, pn2 }; - if (! isParent(pnx)) { + if (!isParent(pnx)) { notPermittedInElementContext(en, getParent(), pnx); } } else if (en[1].equals("ScriptRecord")) { @@ -1892,7 +1883,7 @@ public class TTXFile { } } else if (en[1].equals("cmap")) { String[] pn = new String[] { null, "ttFont" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } } else if (en[1].equals("cmap_format_0")) { @@ -1999,12 +1990,12 @@ public class TTXFile { } } else if (en[1].equals("head")) { String[] pn = new String[] { null, "ttFont" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } } else if (en[1].equals("hmtx")) { String[] pn = new String[] { null, "ttFont" }; - if (! isParent(pn)) { + if (!isParent(pn)) { notPermittedInElementContext(en, getParent(), pn); } else if (glyphIdMax > 0) { hmtxEntries.setSize(glyphIdMax + 1); @@ -2218,7 +2209,7 @@ public class TTXFile { throw new SAXException("element stack is empty, elements are not balanced"); } String[] en = makeExpandedName(uri, localName, qName); - if (! sameExpandedName(enParent, en)) { + if (!sameExpandedName(enParent, en)) { throw new SAXException("element stack is unbalanced, expanded name mismatch"); } if (en[0] != null) { @@ -2246,7 +2237,7 @@ public class TTXFile { } else if (en[1].equals("AlternateSet")) { subtableEntries.add(extractAlternates()); } else if (en[1].equals("AlternateSubst")) { - if (! sortEntries(coverageEntries, subtableEntries)) { + if (!sortEntries(coverageEntries, subtableEntries)) { mismatchedEntries(en, coverageEntries.size(), subtableEntries.size()); } addGSUBSubtable(GlyphSubstitutionTable.GSUB_LOOKUP_TYPE_ALTERNATE, extractCoverage()); @@ -2264,9 +2255,9 @@ public class TTXFile { } else if (en[1].equals("ChainContextPos") || en[1].equals("ChainContextSubst")) { GlyphCoverageTable coverage = null; if (stFormat == 3) { - GlyphCoverageTable igca[] = getCoveragesWithPrefix("in"); - GlyphCoverageTable bgca[] = getCoveragesWithPrefix("bk"); - GlyphCoverageTable lgca[] = getCoveragesWithPrefix("la"); + GlyphCoverageTable[] igca = getCoveragesWithPrefix("in"); + GlyphCoverageTable[] bgca = getCoveragesWithPrefix("bk"); + GlyphCoverageTable[] lgca = getCoveragesWithPrefix("la"); if ((igca.length == 0) || hasMissingCoverage(igca)) { missingCoverage(en, "input", igca.length); } else if (hasMissingCoverage(bgca)) { @@ -2365,7 +2356,7 @@ public class TTXFile { } else if (en[1].equals("LigatureSet")) { subtableEntries.add(extractLigatures()); } else if (en[1].equals("LigatureSubst")) { - if (! sortEntries(coverageEntries, subtableEntries)) { + if (!sortEntries(coverageEntries, subtableEntries)) { mismatchedEntries(en, coverageEntries.size(), subtableEntries.size()); } GlyphCoverageTable coverage = extractCoverage(); @@ -2477,7 +2468,8 @@ public class TTXFile { } GlyphCoverageTable coverage = coverages.get("main"); addGPOSSubtable(GlyphPositioningTable.GPOS_LOOKUP_TYPE_PAIR, coverage); - vf1 = vf2 = -1; psIndex = -1; + vf1 = vf2 = -1; + psIndex = -1; } else if (en[1].equals("PairSet")) { if (psIndex != pairSets.size()) { invalidIndex(en, psIndex, pairSets.size()); @@ -2530,7 +2522,7 @@ public class TTXFile { addGPOSSubtable(GlyphPositioningTable.GPOS_LOOKUP_TYPE_SINGLE, coverage); vf1 = -1; } else if (en[1].equals("SingleSubst")) { - if (! sortEntries(coverageEntries, subtableEntries)) { + if (!sortEntries(coverageEntries, subtableEntries)) { mismatchedEntries(en, coverageEntries.size(), subtableEntries.size()); } GlyphCoverageTable coverage = extractCoverage(); @@ -2558,7 +2550,7 @@ public class TTXFile { public void characters(char[] chars, int start, int length) { } private String[] getParent() { - if (! elements.empty()) { + if (!elements.empty()) { return elements.peek(); } else { return new String[] { null, null }; @@ -2574,13 +2566,11 @@ public class TTXFile { return false; } else if (enx instanceof String[]) { String[] en = (String[]) enx; - if (! elements.empty()) { + if (!elements.empty()) { String[] pn = elements.peek(); return (pn != null) && sameExpandedName(en, pn); - } else if ((en[0] == null) && (en[1] == null)) { - return true; } else { - return false; + return ((en[0] == null) && (en[1] == null)); } } else { return false; @@ -2597,14 +2587,12 @@ public class TTXFile { return true; } else if (ln.equals("MarkAnchor")) { return true; - } else if (ln.equals("Mark2Anchor")) { - return true; } else { - return false; + return ln.equals("Mark2Anchor"); } } - private Map<Integer,Integer> getCMAP() { - Map<Integer,Integer> cmap = new TreeMap(); + private Map<Integer, Integer> getCMAP() { + Map<Integer, Integer> cmap = new TreeMap(); for (int[] cme : cmapEntries) { Integer c = Integer.valueOf(cme[0]); Integer g = Integer.valueOf(cme[1]); @@ -2612,8 +2600,8 @@ public class TTXFile { } return cmap; } - private Map<Integer,Integer> getGMAP() { - Map<Integer,Integer> gmap = new TreeMap(); + private Map<Integer, Integer> getGMAP() { + Map<Integer, Integer> gmap = new TreeMap(); for (int[] cme : cmapEntries) { Integer c = Integer.valueOf(cme[0]); Integer g = Integer.valueOf(cme[1]); @@ -2633,7 +2621,7 @@ public class TTXFile { } return hmtx; } - private GlyphClassTable extractClassDefMapping(Map<String,Integer> glyphClasses, int format, boolean clearSourceMap) { + private GlyphClassTable extractClassDefMapping(Map<String, Integer> glyphClasses, int format, boolean clearSourceMap) { GlyphClassTable ct; if (format == 1) { ct = extractClassDefMapping1(extractClassMappings(glyphClasses, clearSourceMap)); @@ -2687,11 +2675,11 @@ public class TTXFile { } return GlyphClassTable.createClassTable(entries); } - private int[][] extractClassMappings(Map<String,Integer> glyphClasses, boolean clearSourceMap) { + private int[][] extractClassMappings(Map<String, Integer> glyphClasses, boolean clearSourceMap) { int nc = glyphClasses.size(); int i = 0; int[][] cma = new int [ nc ] [ 2 ]; - for (Map.Entry<String,Integer> e : glyphClasses.entrySet()) { + for (Map.Entry<String, Integer> e : glyphClasses.entrySet()) { Integer gid = glyphIds.get(e.getKey()); assert gid != null; int[] m = cma [ i ]; @@ -2858,8 +2846,8 @@ public class TTXFile { private void clearLanguageFeatures() { languageFeatures.clear(); } - private Map<String,List<String>> extractLanguages() { - Map<String,List<String>> lm = new HashMap(languages); + private Map<String, List<String>> extractLanguages() { + Map<String, List<String>> lm = new HashMap(languages); clearLanguages(); return lm; } @@ -2925,10 +2913,10 @@ public class TTXFile { ltFlags = 0; clearSubtablesInLookup(); } - private Map<GlyphTable.LookupSpec,List<String>> extractLookups() { - Map<GlyphTable.LookupSpec,List<String>> lookups = new LinkedHashMap<GlyphTable.LookupSpec,List<String>>(); + private Map<GlyphTable.LookupSpec, List<String>> extractLookups() { + Map<GlyphTable.LookupSpec, List<String>> lookups = new LinkedHashMap<GlyphTable.LookupSpec, List<String>>(); for (String st : scripts.keySet()) { - Map<String,List<String>> lm = scripts.get(st); + Map<String, List<String>> lm = scripts.get(st); if (lm != null) { for (String lt : lm.keySet()) { List<String> fids = lm.get(lt); @@ -3064,7 +3052,7 @@ public class TTXFile { missingParameter(en, "xAdvance"); } String yAdvance = attrs.getValue("YAdvance"); - int ya = 0;; + int ya = 0; if (yAdvance != null) { ya = Integer.parseInt(yAdvance); } else if ((format & GlyphPositioningTable.Value.Y_ADVANCE) != 0) { @@ -3209,7 +3197,7 @@ public class TTXFile { if (cm != null) { for (Anchor[] aa : cm) { if (aa != null) { - int nc = aa.length;; + int nc = aa.length; if (nc > ncMax) { ncMax = nc; } @@ -3225,7 +3213,7 @@ public class TTXFile { if (lam != null) { for (Anchor[][] cm : lam) { if (cm != null) { - int nx = cm.length;; + int nx = cm.length; if (nx > nxMax) { nxMax = nx; } @@ -3426,7 +3414,7 @@ public class TTXFile { return false; } if ((u1 != null) && (u2 != null)) { - if (! u1.equals(u2)) { + if (!u1.equals(u2)) { return false; } } @@ -3436,7 +3424,7 @@ public class TTXFile { return false; } if ((l1 != null) && (l2 != null)) { - if (! l1.equals(l2)) { + if (!l1.equals(l2)) { return false; } } diff --git a/test/java/org/apache/fop/complexscripts/scripts/ScriptsTestSuite.java b/test/java/org/apache/fop/complexscripts/scripts/ScriptsTestSuite.java index cf5d846b4..c48be5220 100644 --- a/test/java/org/apache/fop/complexscripts/scripts/ScriptsTestSuite.java +++ b/test/java/org/apache/fop/complexscripts/scripts/ScriptsTestSuite.java @@ -29,8 +29,6 @@ import org.apache.fop.complexscripts.scripts.arabic.ArabicTestCase; * Test suite for script specific functionality related to complex scripts. */ @RunWith(Suite.class) -@SuiteClasses({ - ArabicTestCase.class -}) +@SuiteClasses(ArabicTestCase.class) public class ScriptsTestSuite { } diff --git a/test/java/org/apache/fop/complexscripts/scripts/arabic/ArabicTestCase.java b/test/java/org/apache/fop/complexscripts/scripts/arabic/ArabicTestCase.java index d34e88a03..8542faae9 100644 --- a/test/java/org/apache/fop/complexscripts/scripts/arabic/ArabicTestCase.java +++ b/test/java/org/apache/fop/complexscripts/scripts/arabic/ArabicTestCase.java @@ -21,30 +21,26 @@ package org.apache.fop.complexscripts.scripts.arabic; import java.io.File; import java.io.FileInputStream; -import java.io.FilenameFilter; import java.io.FileNotFoundException; -import java.io.FileOutputStream; +import java.io.FilenameFilter; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.LineNumberReader; import java.io.ObjectInputStream; import java.nio.IntBuffer; -import java.nio.charset.Charset; -import java.util.ArrayList; import java.util.List; -import org.apache.fop.complexscripts.fonts.GlyphPositioningTable; -import org.apache.fop.complexscripts.fonts.GlyphSubstitutionTable; -import org.apache.fop.complexscripts.fonts.ttx.TTXFile; -import org.apache.fop.complexscripts.util.GlyphSequence; - -import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import org.apache.fop.complexscripts.fonts.GlyphPositioningTable; +import org.apache.fop.complexscripts.fonts.GlyphSubstitutionTable; +import org.apache.fop.complexscripts.fonts.ttx.TTXFile; +import org.apache.fop.complexscripts.util.GlyphSequence; + +// CSOFF: LineLength + /** * Tests for functionality related to the arabic script. */ @@ -52,9 +48,9 @@ public class ArabicTestCase implements ArabicTestConstants { @Test public void testArabicWordForms() { - for (String sfn : srcFiles) { + for (String sfn : SRC_FILES) { try { - processWordForms(new File(datFilesDir)); + processWordForms(new File(DAT_FILES_DIR)); } catch (Exception e) { fail(e.getMessage()); } @@ -72,7 +68,7 @@ public class ArabicTestCase implements ArabicTestConstants { private String[] listWordFormFiles(File dfd) { return dfd.list(new FilenameFilter() { public boolean accept(File f, String name) { - return hasPrefixFrom(name, srcFiles) && hasExtension(name, WF_FILE_DAT_EXT); + return hasPrefixFrom(name, SRC_FILES) && hasExtension(name, WF_FILE_DAT_EXT); } private boolean hasPrefixFrom(String name, String[] prefixes) { for (String p : prefixes) { @@ -108,7 +104,7 @@ public class ArabicTestCase implements ArabicTestConstants { throw new RuntimeException(e.getMessage(), e); } finally { if (fis != null) { - try { fis.close(); } catch (Exception e) {} + try { fis.close(); } catch (Exception e) { /* NOP */ } } } } @@ -129,7 +125,7 @@ public class ArabicTestCase implements ArabicTestConstants { script = (String) d[0]; language = (String) d[1]; tfn = (String) d[3]; - tf = TTXFile.getFromCache(ttxFontsDir + File.separator + tfn); + tf = TTXFile.getFromCache(TTX_FONTS_DIR + File.separator + tfn); assertTrue(tf != null); gsub = tf.getGSUB(); assertTrue(gsub != null); diff --git a/test/java/org/apache/fop/complexscripts/scripts/arabic/ArabicTestConstants.java b/test/java/org/apache/fop/complexscripts/scripts/arabic/ArabicTestConstants.java index 0669ff137..cc9167553 100644 --- a/test/java/org/apache/fop/complexscripts/scripts/arabic/ArabicTestConstants.java +++ b/test/java/org/apache/fop/complexscripts/scripts/arabic/ArabicTestConstants.java @@ -24,22 +24,22 @@ package org.apache.fop.complexscripts.scripts.arabic; */ public interface ArabicTestConstants { - final String WF_FILE_SCRIPT = "arab"; - final String WF_FILE_LANGUAGE = "dflt"; + String WF_FILE_SCRIPT = "arab"; + String WF_FILE_LANGUAGE = "dflt"; - String srcFilesDir = "test/resources/complexscripts/arab/data"; - String datFilesDir = "test/resources/complexscripts/arab/data"; + String SRC_FILES_DIR = "test/resources/complexscripts/arab/data"; + String DAT_FILES_DIR = "test/resources/complexscripts/arab/data"; - String[] srcFiles = { + String[] SRC_FILES = { "arab-001", // unpointed word forms }; - final String WF_FILE_SRC_EXT = "txt"; - final String WF_FILE_DAT_EXT = "ser"; + String WF_FILE_SRC_EXT = "txt"; + String WF_FILE_DAT_EXT = "ser"; - String ttxFontsDir = "test/resources/complexscripts/arab/ttx"; + String TTX_FONTS_DIR = "test/resources/complexscripts/arab/ttx"; - String[] ttxFonts = { + String[] TTX_FONTS = { "arab-001.ttx", // simplified arabic "arab-002.ttx", // traditional arabic "arab-003.ttx", // lateef diff --git a/test/java/org/apache/fop/complexscripts/scripts/arabic/GenerateArabicTestData.java b/test/java/org/apache/fop/complexscripts/scripts/arabic/GenerateArabicTestData.java index a4f876dd8..9ca16a164 100644 --- a/test/java/org/apache/fop/complexscripts/scripts/arabic/GenerateArabicTestData.java +++ b/test/java/org/apache/fop/complexscripts/scripts/arabic/GenerateArabicTestData.java @@ -40,7 +40,10 @@ import org.apache.fop.complexscripts.util.GlyphSequence; /** * Tests for functionality related to the arabic script. */ -public class GenerateArabicTestData implements ArabicTestConstants { +public final class GenerateArabicTestData implements ArabicTestConstants { + + private GenerateArabicTestData() { + } public static void main(String[] args) { boolean compile = false; @@ -69,9 +72,9 @@ public class GenerateArabicTestData implements ArabicTestConstants { } private static void compile() { - for (String sfn : srcFiles) { + for (String sfn : SRC_FILES) { try { - String spn = srcFilesDir + File.separator + sfn + "." + WF_FILE_SRC_EXT; + String spn = SRC_FILES_DIR + File.separator + sfn + "." + WF_FILE_SRC_EXT; compile(WF_FILE_SCRIPT, WF_FILE_LANGUAGE, spn); } catch (Exception e) { System.err.println(e.getMessage()); @@ -81,8 +84,8 @@ public class GenerateArabicTestData implements ArabicTestConstants { private static void compile(String script, String language, String spn) { int fno = 0; - for (String tfn : ttxFonts) { - TTXFile tf = TTXFile.getFromCache(ttxFontsDir + File.separator + tfn); + for (String tfn : TTX_FONTS) { + TTXFile tf = TTXFile.getFromCache(TTX_FONTS_DIR + File.separator + tfn); assert tf != null; List data = compile(script, language, spn, tfn, tf); output(makeDataPathName(spn, fno++), data); @@ -106,7 +109,7 @@ public class GenerateArabicTestData implements ArabicTestConstants { GlyphSequence igs = tf.mapCharsToGlyphs(wf); GlyphSequence ogs = gsub.substitute(igs, script, language); int[][] paa = new int [ ogs.getGlyphCount() ] [ 4 ]; - if (! gpos.position(ogs, script, language, 1000, widths, paa)) { + if (!gpos.position(ogs, script, language, 1000, widths, paa)) { paa = null; } data.add(new Object[] { wf, getGlyphs(igs), getGlyphs(ogs), paa }); @@ -121,7 +124,7 @@ public class GenerateArabicTestData implements ArabicTestConstants { throw new RuntimeException(e.getMessage(), e); } finally { if (fis != null) { - try { fis.close(); } catch (Exception e) {} + try { fis.close(); } catch (Exception e) { /* NOP */ } } } } else { @@ -142,7 +145,7 @@ public class GenerateArabicTestData implements ArabicTestConstants { private static String makeDataPathName(String spn, int fno) { File f = new File(spn); - return datFilesDir + File.separator + stripExtension(f.getName()) + "-f" + fno + "." + WF_FILE_DAT_EXT; + return DAT_FILES_DIR + File.separator + stripExtension(f.getName()) + "-f" + fno + "." + WF_FILE_DAT_EXT; } private static String stripExtension(String s) { @@ -171,7 +174,7 @@ public class GenerateArabicTestData implements ArabicTestConstants { throw new RuntimeException(e.getMessage(), e); } finally { if (fos != null) { - try { fos.close(); } catch (Exception e) {} + try { fos.close(); } catch (Exception e) { /* NOP */ } } } } diff --git a/test/java/org/apache/fop/complexscripts/util/NumberConverterTestCase.java b/test/java/org/apache/fop/complexscripts/util/NumberConverterTestCase.java index ea885b6c5..4e1db5fb3 100644 --- a/test/java/org/apache/fop/complexscripts/util/NumberConverterTestCase.java +++ b/test/java/org/apache/fop/complexscripts/util/NumberConverterTestCase.java @@ -30,12 +30,10 @@ import static org.junit.Assert.assertEquals; /** * Test number converter functionality. - * - * @author Glenn Adams */ public class NumberConverterTestCase { - static private String[][] formatDecimal = + private static String[][] formatDecimal = { { "1" }, { "0", "0" }, @@ -45,7 +43,7 @@ public class NumberConverterTestCase { { "1000000000", "1000000000" }, }; - static private String[][] formatDecimalPadded = + private static String[][] formatDecimalPadded = { { "001" }, { "0", "000" }, @@ -58,7 +56,7 @@ public class NumberConverterTestCase { { "1000", "1000" }, }; - static private String[][] formatDecimalGrouped = + private static String[][] formatDecimalGrouped = { { "1", ",", "1" }, { "0", "0" }, @@ -68,7 +66,7 @@ public class NumberConverterTestCase { { "1000000000", "1,0,0,0,0,0,0,0,0,0" }, }; - static private String[][] formatDecimalGroupedPadded = + private static String[][] formatDecimalGroupedPadded = { { "001", ",", "2" }, { "0", "0,00" }, @@ -81,7 +79,7 @@ public class NumberConverterTestCase { { "1000", "10,00" }, }; - static private String[][] formatDecimalArabic = + private static String[][] formatDecimalArabic = { { "\u0661" }, { "0", "\u0660" }, @@ -100,7 +98,7 @@ public class NumberConverterTestCase { { "1000000000", "\u0661\u0660\u0660\u0660\u0660\u0660\u0660\u0660\u0660\u0660" }, }; - static private String[][] formatDecimalArabicPadded = + private static String[][] formatDecimalArabicPadded = { { "\u0660\u0660\u0661" }, { "0", "\u0660\u0660\u0660" }, @@ -113,7 +111,7 @@ public class NumberConverterTestCase { { "1000", "\u0661\u0660\u0660\u0660" }, }; - static private String[][] formatDecimalArabicGrouped = + private static String[][] formatDecimalArabicGrouped = { { "\u0661", "\u066c", "1" }, { "0", "\u0660" }, @@ -123,7 +121,7 @@ public class NumberConverterTestCase { { "1000000000", "\u0661\u066c\u0660\u066c\u0660\u066c\u0660\u066c\u0660\u066c\u0660\u066c\u0660\u066c\u0660\u066c\u0660\u066c\u0660" }, }; - static private String[][] formatDecimalArabicGroupedPadded = + private static String[][] formatDecimalArabicGroupedPadded = { { "\u0660\u0660\u0661", "\u066c", "2" }, { "0", "\u0660\u066c\u0660\u0660" }, @@ -136,7 +134,7 @@ public class NumberConverterTestCase { { "1000", "\u0661\u0660\u066c\u0660\u0660" }, }; - static private String[][] formatDecimalThai = + private static String[][] formatDecimalThai = { { "\u0E51" }, { "0", "\u0E50" }, @@ -155,7 +153,7 @@ public class NumberConverterTestCase { { "1000000000", "\u0E51\u0E50\u0E50\u0E50\u0E50\u0E50\u0E50\u0E50\u0E50\u0E50" }, }; - static private String[][] formatDecimalThaiPadded = + private static String[][] formatDecimalThaiPadded = { { "\u0E50\u0E50\u0E51" }, { "0", "\u0E50\u0E50\u0E50" }, @@ -168,7 +166,7 @@ public class NumberConverterTestCase { { "1000", "\u0E51\u0E50\u0E50\u0E50" }, }; - static private String[][] formatRomanLower = + private static String[][] formatRomanLower = { { "i" }, { "0", "0" }, @@ -206,7 +204,7 @@ public class NumberConverterTestCase { { "5000", "5000" }, }; - static private String[][] formatRomanUpper = + private static String[][] formatRomanUpper = { { "I" }, @@ -245,7 +243,7 @@ public class NumberConverterTestCase { { "5000", "5000" }, }; - static private String[][] formatRomanLargeLower = + private static String[][] formatRomanLargeLower = { { "i", null, null, null, "large" }, { "0", "0" }, @@ -293,7 +291,7 @@ public class NumberConverterTestCase { { "200000", "200000" }, }; - static private String[][] formatRomanLargeUpper = + private static String[][] formatRomanLargeUpper = { { "I", null, null, null, "large" }, { "0", "0" }, @@ -341,7 +339,7 @@ public class NumberConverterTestCase { { "200000", "200000" }, }; - static private String[][] formatRomanNumberFormsLower = + private static String[][] formatRomanNumberFormsLower = { { "i", null, null, null, "unicode-number-forms" }, { "0", "0" }, @@ -399,7 +397,7 @@ public class NumberConverterTestCase { { "200000", "200000" }, }; - static private String[][] formatRomanNumberFormsUpper = + private static String[][] formatRomanNumberFormsUpper = { { "I", null, null, null, "unicode-number-forms" }, { "0", "0" }, @@ -457,7 +455,7 @@ public class NumberConverterTestCase { { "200000", "200000" }, }; - static private String[][] formatAlphabeticLatinLower = + private static String[][] formatAlphabeticLatinLower = { { "a" }, { "0", "0" }, @@ -478,7 +476,7 @@ public class NumberConverterTestCase { { "1000000", "bdwgn" }, }; - static private String[][] formatAlphabeticLatinUpper = + private static String[][] formatAlphabeticLatinUpper = { { "A" }, { "0", "0" }, @@ -499,7 +497,7 @@ public class NumberConverterTestCase { { "1000000", "BDWGN" }, }; - static private String[][] formatAlphabeticArabicHijai = + private static String[][] formatAlphabeticArabicHijai = { { "\u0627", null, null, "alphabetic" }, { "0", "0" }, @@ -540,7 +538,7 @@ public class NumberConverterTestCase { { "1000000", "\u0623\u0638\u0636\u0635\u062F" }, }; - static private String[][] formatAlphabeticArabicAbjadi = + private static String[][] formatAlphabeticArabicAbjadi = { { "\u0627", null, null, "traditional" }, { "0", "0" }, @@ -581,7 +579,7 @@ public class NumberConverterTestCase { { "1000000", "\u0623\u0641\u0633\u0646\u062D" }, }; - static private String[][] formatNumeralArabicAbjadi = + private static String[][] formatNumeralArabicAbjadi = { { "\u0623", null, null, "traditional" }, { "0", "0" }, @@ -629,7 +627,7 @@ public class NumberConverterTestCase { { "2000", "2000" }, }; - static private String[][] formatAlphabeticHebrew = + private static String[][] formatAlphabeticHebrew = { { "\u05D0", null, null, "alphabetic" }, { "0", "0" }, @@ -669,7 +667,7 @@ public class NumberConverterTestCase { { "1000000", "\u05D0\u05DA\u05E9\u05E8\u05D0" }, }; - static private String[][] formatNumeralHebrewGematria = + private static String[][] formatNumeralHebrewGematria = { { "\u05D0", null, null, "traditional" }, { "0", "0" }, @@ -717,7 +715,7 @@ public class NumberConverterTestCase { { "2000", "2000" }, }; - static private String[][] formatAlphabeticThai = + private static String[][] formatAlphabeticThai = { { "\u0E01", null, null, "alphabetic" }, { "0", "0" }, @@ -738,7 +736,7 @@ public class NumberConverterTestCase { { "1000000", "\u0E0B\u0E20\u0E17\u0E0C" }, }; - static private String[][] formatWordEnglishLower = + private static String[][] formatWordEnglishLower = { { "w", null, null, null, null, "eng" }, { "0", "zero" }, @@ -762,7 +760,7 @@ public class NumberConverterTestCase { { "1000000000", "one billion" } }; - static private String[][] formatWordEnglishUpper = + private static String[][] formatWordEnglishUpper = { { "W", null, null, null, null, "eng" }, { "0", "ZERO" }, @@ -786,7 +784,7 @@ public class NumberConverterTestCase { { "1000000000", "ONE BILLION" } }; - static private String[][] formatWordEnglishTitle = + private static String[][] formatWordEnglishTitle = { { "Ww", null, null, null, null, "eng" }, { "0", "Zero" }, @@ -810,7 +808,7 @@ public class NumberConverterTestCase { { "1000000000", "One Billion" } }; - static private String[][] formatWordSpanishLower = + private static String[][] formatWordSpanishLower = { { "w", null, null, null, null, "spa" }, { "0", "cero" }, @@ -890,7 +888,7 @@ public class NumberConverterTestCase { { "1000000000", "mil millones" } }; - static private String[][] formatWordSpanishUpper = + private static String[][] formatWordSpanishUpper = { { "W", null, null, null, null, "spa" }, { "0", "CERO" }, @@ -970,7 +968,7 @@ public class NumberConverterTestCase { { "1000000000", "MIL MILLONES" } }; - static private String[][] formatWordSpanishTitle = + private static String[][] formatWordSpanishTitle = { { "Ww", null, null, null, null, "spa" }, { "0", "Cero" }, @@ -1050,7 +1048,7 @@ public class NumberConverterTestCase { { "1000000000", "Mil Millones" } }; - static private String[][] formatWordFrenchLower = + private static String[][] formatWordFrenchLower = { { "w", null, null, null, null, "fra" }, { "0", "z\u00e9ro" }, @@ -1141,7 +1139,7 @@ public class NumberConverterTestCase { { "1000000000", "un milliard" } }; - static private String[][] formatWordFrenchUpper = + private static String[][] formatWordFrenchUpper = { { "W", null, null, null, null, "fra" }, { "0", "Z\u00c9RO" }, @@ -1232,7 +1230,7 @@ public class NumberConverterTestCase { { "1000000000", "UN MILLIARD" } }; - static private String[][] formatWordFrenchTitle = + private static String[][] formatWordFrenchTitle = { { "Ww", null, null, null, null, "fra" }, { "0", "Z\u00e9ro" }, diff --git a/test/java/org/apache/fop/complexscripts/util/UtilTestSuite.java b/test/java/org/apache/fop/complexscripts/util/UtilTestSuite.java index 70bd568af..4407254a8 100644 --- a/test/java/org/apache/fop/complexscripts/util/UtilTestSuite.java +++ b/test/java/org/apache/fop/complexscripts/util/UtilTestSuite.java @@ -27,8 +27,6 @@ import org.junit.runners.Suite.SuiteClasses; * Test suite for bidirectional functionality. */ @RunWith(Suite.class) -@SuiteClasses({ - NumberConverterTestCase.class -}) +@SuiteClasses(NumberConverterTestCase.class) public class UtilTestSuite { } diff --git a/test/java/org/apache/fop/config/FontAttributesMissingTestCase.java b/test/java/org/apache/fop/config/FontAttributesMissingTestCase.java index 8d7d46928..fa4babfa2 100644 --- a/test/java/org/apache/fop/config/FontAttributesMissingTestCase.java +++ b/test/java/org/apache/fop/config/FontAttributesMissingTestCase.java @@ -24,7 +24,6 @@ import java.io.IOException; import org.xml.sax.SAXException; import org.apache.fop.apps.FopConfBuilder; -import org.apache.fop.apps.MimeConstants; import org.apache.fop.apps.PDFRendererConfBuilder; /** diff --git a/test/java/org/apache/fop/config/FontMetricsUrlBadTestCase.java b/test/java/org/apache/fop/config/FontMetricsUrlBadTestCase.java index 84e8ee804..591104412 100644 --- a/test/java/org/apache/fop/config/FontMetricsUrlBadTestCase.java +++ b/test/java/org/apache/fop/config/FontMetricsUrlBadTestCase.java @@ -24,7 +24,6 @@ import java.io.IOException; import org.xml.sax.SAXException; import org.apache.fop.apps.FopConfBuilder; -import org.apache.fop.apps.MimeConstants; import org.apache.fop.apps.PDFRendererConfBuilder; /** diff --git a/test/java/org/apache/fop/config/FontMetricsUrlMalformedTestCase.java b/test/java/org/apache/fop/config/FontMetricsUrlMalformedTestCase.java index 3479c3794..11538dc33 100644 --- a/test/java/org/apache/fop/config/FontMetricsUrlMalformedTestCase.java +++ b/test/java/org/apache/fop/config/FontMetricsUrlMalformedTestCase.java @@ -24,7 +24,6 @@ import java.io.IOException; import org.xml.sax.SAXException; import org.apache.fop.apps.FopConfBuilder; -import org.apache.fop.apps.MimeConstants; import org.apache.fop.apps.PDFRendererConfBuilder; /** diff --git a/test/java/org/apache/fop/config/FontTripletAttributeMissingTestCase.java b/test/java/org/apache/fop/config/FontTripletAttributeMissingTestCase.java index 800e06d32..4bacc180c 100644 --- a/test/java/org/apache/fop/config/FontTripletAttributeMissingTestCase.java +++ b/test/java/org/apache/fop/config/FontTripletAttributeMissingTestCase.java @@ -24,7 +24,6 @@ import java.io.IOException; import org.xml.sax.SAXException; import org.apache.fop.apps.FopConfBuilder; -import org.apache.fop.apps.MimeConstants; import org.apache.fop.apps.PDFRendererConfBuilder; /** diff --git a/test/java/org/apache/fop/config/FontsAutoDetectTestCase.java b/test/java/org/apache/fop/config/FontsAutoDetectTestCase.java index c9f6d98ff..e05e44ab1 100644 --- a/test/java/org/apache/fop/config/FontsAutoDetectTestCase.java +++ b/test/java/org/apache/fop/config/FontsAutoDetectTestCase.java @@ -24,7 +24,6 @@ import java.io.IOException; import org.xml.sax.SAXException; import org.apache.fop.apps.FopConfBuilder; -import org.apache.fop.apps.MimeConstants; import org.apache.fop.apps.PDFRendererConfBuilder; public class FontsAutoDetectTestCase extends BaseConstructiveUserConfigTest { diff --git a/test/java/org/apache/fop/config/FontsDirectoryRecursiveTestCase.java b/test/java/org/apache/fop/config/FontsDirectoryRecursiveTestCase.java index 2776c2cce..aab7a2e7c 100644 --- a/test/java/org/apache/fop/config/FontsDirectoryRecursiveTestCase.java +++ b/test/java/org/apache/fop/config/FontsDirectoryRecursiveTestCase.java @@ -24,7 +24,6 @@ import java.io.IOException; import org.xml.sax.SAXException; import org.apache.fop.apps.FopConfBuilder; -import org.apache.fop.apps.MimeConstants; import org.apache.fop.apps.PDFRendererConfBuilder; /** diff --git a/test/java/org/apache/fop/datatypes/URISpecificationTestCase.java b/test/java/org/apache/fop/datatypes/URISpecificationTestCase.java index 23af20a1a..f6e2b02ba 100644 --- a/test/java/org/apache/fop/datatypes/URISpecificationTestCase.java +++ b/test/java/org/apache/fop/datatypes/URISpecificationTestCase.java @@ -19,10 +19,10 @@ package org.apache.fop.datatypes; -import static org.junit.Assert.assertEquals; - import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** * Tests for URISpecification. */ diff --git a/test/java/org/apache/fop/events/BasicEventTestCase.java b/test/java/org/apache/fop/events/BasicEventTestCase.java index 87fc04329..39e3fec98 100644 --- a/test/java/org/apache/fop/events/BasicEventTestCase.java +++ b/test/java/org/apache/fop/events/BasicEventTestCase.java @@ -19,6 +19,8 @@ package org.apache.fop.events; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -26,7 +28,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.apache.fop.events.model.EventSeverity; -import org.junit.Test; public class BasicEventTestCase { diff --git a/test/java/org/apache/fop/events/TestEventProducer.java b/test/java/org/apache/fop/events/TestEventProducer.java index ff0bc2a81..ff19c7ea6 100644 --- a/test/java/org/apache/fop/events/TestEventProducer.java +++ b/test/java/org/apache/fop/events/TestEventProducer.java @@ -38,7 +38,10 @@ public interface TestEventProducer extends EventProducer { */ void enjoy(Object source, String what); - public class Provider { + public static final class Provider { + + private Provider() { + } public static TestEventProducer get(EventBroadcaster broadcaster) { return (TestEventProducer)broadcaster.getEventProducerFor(TestEventProducer.class); diff --git a/test/java/org/apache/fop/fo/DelegatingFOEventHandlerTestCase.java b/test/java/org/apache/fop/fo/DelegatingFOEventHandlerTestCase.java index 313379e02..226c551fb 100644 --- a/test/java/org/apache/fop/fo/DelegatingFOEventHandlerTestCase.java +++ b/test/java/org/apache/fop/fo/DelegatingFOEventHandlerTestCase.java @@ -19,8 +19,6 @@ package org.apache.fop.fo; -import static org.junit.Assert.assertArrayEquals; - import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -42,6 +40,8 @@ import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; +import static org.junit.Assert.assertArrayEquals; + import org.apache.fop.apps.FOUserAgent; import org.apache.fop.fo.FODocumentParser.FOEventHandlerFactory; import org.apache.fop.fo.flow.BasicLink; diff --git a/test/java/org/apache/fop/fo/FODocumentParser.java b/test/java/org/apache/fop/fo/FODocumentParser.java index 7d03e38a6..2e691519b 100644 --- a/test/java/org/apache/fop/fo/FODocumentParser.java +++ b/test/java/org/apache/fop/fo/FODocumentParser.java @@ -64,7 +64,7 @@ public final class FODocumentParser { /** * A factory to create custom instances of {@link FOEventHandler}. */ - public static interface FOEventHandlerFactory { + public interface FOEventHandlerFactory { /** * Creates a new {@code FOEventHandler} instance parameterized with the given FO user agent. diff --git a/test/java/org/apache/fop/fo/FONodeMocks.java b/test/java/org/apache/fop/fo/FONodeMocks.java index ba969b9fa..97889c177 100644 --- a/test/java/org/apache/fop/fo/FONodeMocks.java +++ b/test/java/org/apache/fop/fo/FONodeMocks.java @@ -31,7 +31,6 @@ import org.apache.xmlgraphics.image.loader.ImageManager; import org.apache.xmlgraphics.image.loader.ImageSessionContext; import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.FopFactory; import org.apache.fop.events.EventBroadcaster; import org.apache.fop.fo.flow.table.ColumnNumberManager; import org.apache.fop.fo.flow.table.ColumnNumberManagerHolder; @@ -46,7 +45,7 @@ public final class FONodeMocks { /** * Creates and returns a mock {@link FONode} configured with a mock * {@link FOEventHandler}. The FO event handler returns a mock {@link FOUserAgent}, - * which in turn returns a mock {@link FopFactory}, which returns a mock + * which in turn returns a mock {@link org.apache.fop.apps.FopFactory}, which returns a mock * {@link ImageManager}. * * @return a mock FO node diff --git a/test/java/org/apache/fop/fo/flow/MarkersTestCase.java b/test/java/org/apache/fop/fo/flow/MarkersTestCase.java index 983a531b0..09a4e129c 100644 --- a/test/java/org/apache/fop/fo/flow/MarkersTestCase.java +++ b/test/java/org/apache/fop/fo/flow/MarkersTestCase.java @@ -30,10 +30,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.apache.fop.fo.Constants; -import org.apache.fop.fo.flow.Marker; -import org.apache.fop.fo.flow.Markers; -import org.apache.fop.fo.flow.RetrieveMarker; -import org.apache.fop.fo.flow.RetrieveTableMarker; public class MarkersTestCase { diff --git a/test/java/org/apache/fop/fo/flow/table/AbstractTableTest.java b/test/java/org/apache/fop/fo/flow/table/AbstractTableTest.java index fb6ec6a25..0f0e347d3 100644 --- a/test/java/org/apache/fop/fo/flow/table/AbstractTableTest.java +++ b/test/java/org/apache/fop/fo/flow/table/AbstractTableTest.java @@ -24,8 +24,8 @@ import java.util.Iterator; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.fo.FODocumentParser; -import org.apache.fop.fo.FOEventHandler; import org.apache.fop.fo.FODocumentParser.FOEventHandlerFactory; +import org.apache.fop.fo.FOEventHandler; import org.apache.fop.util.ConsoleEventListenerForTests; /** diff --git a/test/java/org/apache/fop/fo/flow/table/CollapsedConditionalBorderTestCase.java b/test/java/org/apache/fop/fo/flow/table/CollapsedConditionalBorderTestCase.java index 7c0301ca7..75ba53525 100644 --- a/test/java/org/apache/fop/fo/flow/table/CollapsedConditionalBorderTestCase.java +++ b/test/java/org/apache/fop/fo/flow/table/CollapsedConditionalBorderTestCase.java @@ -19,18 +19,20 @@ package org.apache.fop.fo.flow.table; -import static org.junit.Assert.assertEquals; - import java.awt.Color; import java.util.Iterator; import java.util.List; import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.apache.fop.fo.Constants; import org.apache.fop.fo.FONode.FONodeIterator; import org.apache.fop.fo.properties.CommonBorderPaddingBackground.BorderInfo; +// CSOFF: LineLength + /** * A testcase for the resolution of collapsed borders in the FO tree, taking * conditionality into account. The resolved borders are generated by the diff --git a/test/java/org/apache/fop/fo/flow/table/RowGroupBuilderTestCase.java b/test/java/org/apache/fop/fo/flow/table/RowGroupBuilderTestCase.java index 361517a66..884116441 100644 --- a/test/java/org/apache/fop/fo/flow/table/RowGroupBuilderTestCase.java +++ b/test/java/org/apache/fop/fo/flow/table/RowGroupBuilderTestCase.java @@ -19,16 +19,16 @@ package org.apache.fop.fo.flow.table; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - import java.util.Iterator; import java.util.List; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + /** * Tests that RowGroupBuilder returns, for each part of a table, the expected number of * row-groups with the expected number or rows in each. diff --git a/test/java/org/apache/fop/fo/flow/table/TableColumnColumnNumberTestCase.java b/test/java/org/apache/fop/fo/flow/table/TableColumnColumnNumberTestCase.java index a21806559..2df0cac2a 100644 --- a/test/java/org/apache/fop/fo/flow/table/TableColumnColumnNumberTestCase.java +++ b/test/java/org/apache/fop/fo/flow/table/TableColumnColumnNumberTestCase.java @@ -19,12 +19,12 @@ package org.apache.fop.fo.flow.table; -import static org.junit.Assert.assertEquals; - import java.util.Iterator; import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.apache.fop.datatypes.PercentBaseContext; import org.apache.fop.fo.FObj; diff --git a/test/java/org/apache/fop/fo/flow/table/TableHandler.java b/test/java/org/apache/fop/fo/flow/table/TableHandler.java index 11f24b99b..04da32b47 100644 --- a/test/java/org/apache/fop/fo/flow/table/TableHandler.java +++ b/test/java/org/apache/fop/fo/flow/table/TableHandler.java @@ -24,7 +24,6 @@ import java.util.List; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.fo.FOEventHandler; -import org.apache.fop.fo.flow.table.Table; public class TableHandler extends FOEventHandler { diff --git a/test/java/org/apache/fop/fo/pagination/AllTests.java b/test/java/org/apache/fop/fo/pagination/AllTests.java index 40990cb06..bd5b21c14 100644 --- a/test/java/org/apache/fop/fo/pagination/AllTests.java +++ b/test/java/org/apache/fop/fo/pagination/AllTests.java @@ -19,8 +19,8 @@ package org.apache.fop.fo.pagination; -import org.junit.runners.Suite; import org.junit.runner.RunWith; +import org.junit.runners.Suite; /** * All test to be added in FOTreeTestSuite @@ -28,6 +28,6 @@ import org.junit.runner.RunWith; */ @RunWith(Suite.class) @Suite.SuiteClasses({ PageSequenceMasterTestCase.class, - RepeatablePageMasterAlternativesTestCase.class}) + RepeatablePageMasterAlternativesTestCase.class }) public final class AllTests { } diff --git a/test/java/org/apache/fop/fo/pagination/PageSequenceMasterTestCase.java b/test/java/org/apache/fop/fo/pagination/PageSequenceMasterTestCase.java index ad4f991ac..d7bc2e11c 100644 --- a/test/java/org/apache/fop/fo/pagination/PageSequenceMasterTestCase.java +++ b/test/java/org/apache/fop/fo/pagination/PageSequenceMasterTestCase.java @@ -19,8 +19,10 @@ package org.apache.fop.fo.pagination; -import static org.junit.Assert.fail; +import org.junit.Test; +import org.xml.sax.Locator; +import static org.junit.Assert.fail; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyObject; @@ -33,8 +35,6 @@ import static org.mockito.Mockito.when; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.FONode; import org.apache.fop.layoutmgr.BlockLevelEventProducer; -import org.junit.Test; -import org.xml.sax.Locator; /** diff --git a/test/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternativesTestCase.java b/test/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternativesTestCase.java index 5ac4860dc..ce1a97638 100644 --- a/test/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternativesTestCase.java +++ b/test/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternativesTestCase.java @@ -19,6 +19,8 @@ package org.apache.fop.fo.pagination; +import org.junit.Test; + import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; @@ -30,8 +32,6 @@ import org.apache.fop.fo.PropertyList; import org.apache.fop.fo.expr.NumericProperty; import org.apache.fop.fo.properties.Property; -import org.junit.Test; - /** * Unit Test for RepeatablePageMasterAlternatives * diff --git a/test/java/org/apache/fop/fo/properties/AltTextHolderTestCase.java b/test/java/org/apache/fop/fo/properties/AltTextHolderTestCase.java index cd5d545ff..89ed2733d 100644 --- a/test/java/org/apache/fop/fo/properties/AltTextHolderTestCase.java +++ b/test/java/org/apache/fop/fo/properties/AltTextHolderTestCase.java @@ -19,12 +19,12 @@ package org.apache.fop.fo.properties; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.junit.Test; - import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.fo.Constants; diff --git a/test/java/org/apache/fop/fo/properties/CommonAccessibilityHolderTestCase.java b/test/java/org/apache/fop/fo/properties/CommonAccessibilityHolderTestCase.java index 352a39713..81ebc2f41 100644 --- a/test/java/org/apache/fop/fo/properties/CommonAccessibilityHolderTestCase.java +++ b/test/java/org/apache/fop/fo/properties/CommonAccessibilityHolderTestCase.java @@ -19,16 +19,16 @@ package org.apache.fop.fo.properties; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.apache.fop.fo.Constants; import org.apache.fop.fo.FONode; import org.apache.fop.fo.FONodeMocks; diff --git a/test/java/org/apache/fop/fonts/DejaVuLGCSerifTestCase.java b/test/java/org/apache/fop/fonts/DejaVuLGCSerifTestCase.java index 20212b002..8c2621b51 100644 --- a/test/java/org/apache/fop/fonts/DejaVuLGCSerifTestCase.java +++ b/test/java/org/apache/fop/fonts/DejaVuLGCSerifTestCase.java @@ -24,11 +24,11 @@ import java.io.File; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.apache.fop.apps.io.InternalResourceResolver; import org.apache.fop.apps.io.ResourceResolverFactory; -import static org.junit.Assert.assertEquals; - /** * */ diff --git a/test/java/org/apache/fop/fonts/EmbedFontInfoTestCase.java b/test/java/org/apache/fop/fonts/EmbedFontInfoTestCase.java index d156b908c..c8099f860 100644 --- a/test/java/org/apache/fop/fonts/EmbedFontInfoTestCase.java +++ b/test/java/org/apache/fop/fonts/EmbedFontInfoTestCase.java @@ -35,6 +35,8 @@ import static org.junit.Assert.assertTrue; */ public class EmbedFontInfoTestCase { + public EmbedFontInfoTestCase() { } + private EmbedFontInfo sut; private final URI metricsURI = URI.create("test/resources/fonts/ttf/glb12.ttf.xml"); diff --git a/test/java/org/apache/fop/fonts/FontManagerConfiguratorTestCase.java b/test/java/org/apache/fop/fonts/FontManagerConfiguratorTestCase.java index 073743c13..d653171b7 100644 --- a/test/java/org/apache/fop/fonts/FontManagerConfiguratorTestCase.java +++ b/test/java/org/apache/fop/fonts/FontManagerConfiguratorTestCase.java @@ -20,7 +20,6 @@ package org.apache.fop.fonts; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; @@ -28,13 +27,14 @@ import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; +import static org.junit.Assert.assertEquals; + import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FopConfBuilder; import org.apache.fop.apps.FopConfParser; import org.apache.fop.apps.FopFactory; import static org.apache.fop.apps.FopConfParserTestCase.getFopFactory; -import static org.junit.Assert.assertEquals; /** * A test case for {@link FontManagerConfigurator}. @@ -84,7 +84,7 @@ public class FontManagerConfiguratorTestCase { /** * This test is an interesting one; it's basically testing that if a base URI pointing to a * directory that doesn't exist is used, an error is not thrown. The URI resolver should handle - * any {@link FileNotFoundException}s, not the configuration. We're NOT testing whether a font + * any {@link java.io.FileNotFoundException}s, not the configuration. We're NOT testing whether a font * can be resolved here, just that the URI resolver accepts it as its base URI. */ @Test diff --git a/test/java/org/apache/fop/fonts/FontsTestSuite.java b/test/java/org/apache/fop/fonts/FontsTestSuite.java index ad48c46c4..1baba49df 100644 --- a/test/java/org/apache/fop/fonts/FontsTestSuite.java +++ b/test/java/org/apache/fop/fonts/FontsTestSuite.java @@ -29,7 +29,7 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ FontManagerConfiguratorTestCase.class, - EmbedFontInfo.class, + EmbedFontInfoTestCase.class, FontEventProcessingTestCase.class, FontManagerConfiguratorTestCase.class }) diff --git a/test/java/org/apache/fop/fonts/cff/CFFDataReaderTestCase.java b/test/java/org/apache/fop/fonts/cff/CFFDataReaderTestCase.java index 64c7642eb..97ea5c52b 100644 --- a/test/java/org/apache/fop/fonts/cff/CFFDataReaderTestCase.java +++ b/test/java/org/apache/fop/fonts/cff/CFFDataReaderTestCase.java @@ -26,14 +26,14 @@ import java.util.Random; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.apache.fontbox.cff.CFFDataInput; import org.apache.fop.fonts.cff.CFFDataReader.CFFIndexData; import org.apache.fop.fonts.cff.CFFDataReader.DICTEntry; import org.apache.fop.fonts.truetype.OTFSubSetFile; -import static org.junit.Assert.assertEquals; - public class CFFDataReaderTestCase { private CFFDataReader cffReader; @@ -113,7 +113,7 @@ public class CFFDataReaderTestCase { //Array comparison int[] fontBBox = { -50, -40, 100, 120 }; DICTEntry fontBBoxEntry = dictMap.get("FontBBox"); - for (int i = 0;i < fontBBoxEntry.getOperands().size();i++) { + for (int i = 0; i < fontBBoxEntry.getOperands().size(); i++) { assertEquals(fontBBoxEntry.getOperands().get(i).intValue(), fontBBox[i]); } //Multi-byte offset (number) @@ -141,7 +141,7 @@ public class CFFDataReaderTestCase { }; Random randGen = new Random(); byte[] data = new byte[31]; - for (int i = 0;i < data.length;i++) { + for (int i = 0; i < data.length; i++) { data[i] = (byte)randGen.nextInt(255); } testIndex = OTFSubSetFile.concatArray(testIndex, data); diff --git a/test/java/org/apache/fop/fonts/truetype/GlyfTableTestCase.java b/test/java/org/apache/fop/fonts/truetype/GlyfTableTestCase.java index e794ab1a8..952c3ec1f 100644 --- a/test/java/org/apache/fop/fonts/truetype/GlyfTableTestCase.java +++ b/test/java/org/apache/fop/fonts/truetype/GlyfTableTestCase.java @@ -37,7 +37,7 @@ import static org.junit.Assert.assertTrue; */ public class GlyfTableTestCase { - private final static class DirData { + private static final class DirData { final long offset; final long length; diff --git a/test/java/org/apache/fop/fonts/truetype/OTFFileTestCase.java b/test/java/org/apache/fop/fonts/truetype/OTFFileTestCase.java index 737c2e05e..b4e2cee2e 100644 --- a/test/java/org/apache/fop/fonts/truetype/OTFFileTestCase.java +++ b/test/java/org/apache/fop/fonts/truetype/OTFFileTestCase.java @@ -20,7 +20,6 @@ package org.apache.fop.fonts.truetype; import java.io.FileInputStream; -import java.io.IOException; import java.io.InputStream; import org.junit.Before; @@ -37,7 +36,7 @@ public class OTFFileTestCase { /** * Initializes fonts used for the testing of reading OTF CFF - * @throws IOException + * @throws java.io.IOException */ @Before public void setUp() throws Exception { @@ -75,11 +74,11 @@ public class OTFFileTestCase { int[] gids = {32, 42, 44, 47}; int[] sourceSansWidths = {516, 555, 572, 383}; - for (int i = 0;i < gids.length;i++) { + for (int i = 0; i < gids.length; i++) { assertEquals(sourceSansWidths[i], sourceSansProBold.getWidths()[gids[i]]); } int[] carolynaWidths = {842, 822, 658, 784}; - for (int i = 0;i < gids.length;i++) { + for (int i = 0; i < gids.length; i++) { assertEquals(carolynaWidths[i], alexBrush.getWidths()[gids[i]]); } } diff --git a/test/java/org/apache/fop/fonts/truetype/OTFSubSetFileTestCase.java b/test/java/org/apache/fop/fonts/truetype/OTFSubSetFileTestCase.java index 604cca3a8..c555ebc20 100644 --- a/test/java/org/apache/fop/fonts/truetype/OTFSubSetFileTestCase.java +++ b/test/java/org/apache/fop/fonts/truetype/OTFSubSetFileTestCase.java @@ -27,6 +27,9 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import org.apache.fontbox.cff.CFFDataInput; import org.apache.fontbox.cff.CFFFont; import org.apache.fontbox.cff.CFFParser; @@ -37,9 +40,6 @@ import org.apache.fop.fonts.cff.CFFDataReader; import org.apache.fop.fonts.cff.CFFDataReader.CFFIndexData; import org.apache.fop.fonts.cff.CFFDataReader.DICTEntry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - public class OTFSubSetFileTestCase extends OTFFileTestCase { CFFDataReader cffReaderSourceSans; @@ -85,7 +85,7 @@ public class OTFSubSetFileTestCase extends OTFFileTestCase { private boolean checkCorrectOffsets(CFFIndexData indexData) { int last = 0; - for (int i = 0;i < indexData.getOffsets().length;i++) { + for (int i = 0; i < indexData.getOffsets().length; i++) { if (indexData.getOffsets()[i] < last) { return false; } @@ -107,7 +107,7 @@ public class OTFSubSetFileTestCase extends OTFFileTestCase { IndexData localIndexData = CFFParser.readIndexData(localSubrs); CFFIndexData charStrings = cffReader.getCharStringIndex(); - for (int i = 0;i < charStrings.getNumObjects();i++) { + for (int i = 0; i < charStrings.getNumObjects(); i++) { byte[] charData = charStrings.getValue(i); Type2CharStringParser parser = new Type2CharStringParser(); diff --git a/test/java/org/apache/fop/fonts/truetype/TTFFileTestCase.java b/test/java/org/apache/fop/fonts/truetype/TTFFileTestCase.java index a390bef0f..32e527f9d 100644 --- a/test/java/org/apache/fop/fonts/truetype/TTFFileTestCase.java +++ b/test/java/org/apache/fop/fonts/truetype/TTFFileTestCase.java @@ -26,12 +26,12 @@ import java.util.Map; import org.junit.Test; -import org.apache.fop.fonts.truetype.OpenFont.PostScriptVersion; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import org.apache.fop.fonts.truetype.OpenFont.PostScriptVersion; + /** * Class for testing org.apache.fop.fonts.truetype.TTFFile */ diff --git a/test/java/org/apache/fop/fonts/truetype/TTFFontLoaderTestCase.java b/test/java/org/apache/fop/fonts/truetype/TTFFontLoaderTestCase.java index f50b116ac..899fe1d73 100644 --- a/test/java/org/apache/fop/fonts/truetype/TTFFontLoaderTestCase.java +++ b/test/java/org/apache/fop/fonts/truetype/TTFFontLoaderTestCase.java @@ -25,14 +25,14 @@ import java.net.URI; import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.apache.fop.apps.io.InternalResourceResolver; import org.apache.fop.apps.io.ResourceResolverFactory; import org.apache.fop.fonts.EmbeddingMode; import org.apache.fop.fonts.EncodingMode; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - /** * Test case for {@link OFFontLoader}. */ diff --git a/test/java/org/apache/fop/fonts/type1/AFMParserTestCase.java b/test/java/org/apache/fop/fonts/type1/AFMParserTestCase.java index 93443a0d9..5e31054b5 100644 --- a/test/java/org/apache/fop/fonts/type1/AFMParserTestCase.java +++ b/test/java/org/apache/fop/fonts/type1/AFMParserTestCase.java @@ -19,9 +19,6 @@ package org.apache.fop.fonts.type1; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.awt.Rectangle; import java.io.IOException; import java.io.InputStream; @@ -29,6 +26,9 @@ import java.util.List; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * Test case for {@link AFMParser}. */ diff --git a/test/java/org/apache/fop/fonts/type1/AdobeStandardEncodingTestCase.java b/test/java/org/apache/fop/fonts/type1/AdobeStandardEncodingTestCase.java index 10ba42119..a3a3e1c40 100644 --- a/test/java/org/apache/fop/fonts/type1/AdobeStandardEncodingTestCase.java +++ b/test/java/org/apache/fop/fonts/type1/AdobeStandardEncodingTestCase.java @@ -19,8 +19,6 @@ package org.apache.fop.fonts.type1; -import static org.junit.Assert.assertEquals; - import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; @@ -30,6 +28,8 @@ import java.io.InputStreamReader; import org.junit.BeforeClass; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** * Test case for {@link AdobeStandardEncoding}. */ diff --git a/test/java/org/apache/fop/fonts/type1/CharMetricsHandlerTestCase.java b/test/java/org/apache/fop/fonts/type1/CharMetricsHandlerTestCase.java index de9af2d33..c3e9334dd 100644 --- a/test/java/org/apache/fop/fonts/type1/CharMetricsHandlerTestCase.java +++ b/test/java/org/apache/fop/fonts/type1/CharMetricsHandlerTestCase.java @@ -19,10 +19,6 @@ package org.apache.fop.fonts.type1; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - import java.awt.Rectangle; import java.io.IOException; import java.util.HashMap; @@ -31,6 +27,10 @@ import java.util.Stack; import org.junit.Test; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.fop.fonts.NamedCharacter; import org.apache.fop.fonts.type1.AFMParser.ValueHandler; diff --git a/test/java/org/apache/fop/fotreetest/ext/AssertElement.java b/test/java/org/apache/fop/fotreetest/ext/AssertElement.java index 5070984d1..955644ae4 100644 --- a/test/java/org/apache/fop/fotreetest/ext/AssertElement.java +++ b/test/java/org/apache/fop/fotreetest/ext/AssertElement.java @@ -20,6 +20,9 @@ package org.apache.fop.fotreetest.ext; +import org.xml.sax.Attributes; +import org.xml.sax.Locator; + import org.apache.fop.apps.FOPException; import org.apache.fop.fo.FONode; import org.apache.fop.fo.FOPropertyMapping; @@ -32,9 +35,6 @@ import org.apache.fop.fo.properties.Property; import org.apache.fop.fo.properties.SpaceProperty; import org.apache.fop.fotreetest.ResultCollector; -import org.xml.sax.Attributes; -import org.xml.sax.Locator; - /** * Defines the assert element for the FOP Test extension. */ diff --git a/test/java/org/apache/fop/fotreetest/ext/TestElementMapping.java b/test/java/org/apache/fop/fotreetest/ext/TestElementMapping.java index eee0efac4..b61944eae 100644 --- a/test/java/org/apache/fop/fotreetest/ext/TestElementMapping.java +++ b/test/java/org/apache/fop/fotreetest/ext/TestElementMapping.java @@ -19,8 +19,8 @@ package org.apache.fop.fotreetest.ext; -import org.apache.fop.fo.FONode; import org.apache.fop.fo.ElementMapping; +import org.apache.fop.fo.FONode; /** * This class provides the element mapping for FOP. diff --git a/test/java/org/apache/fop/image/loader/batik/ImageLoaderTestCase.java b/test/java/org/apache/fop/image/loader/batik/ImageLoaderTestCase.java index f4763512a..7f3036c24 100644 --- a/test/java/org/apache/fop/image/loader/batik/ImageLoaderTestCase.java +++ b/test/java/org/apache/fop/image/loader/batik/ImageLoaderTestCase.java @@ -19,10 +19,6 @@ package org.apache.fop.image.loader.batik; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.io.File; @@ -30,6 +26,10 @@ import java.io.File; import org.junit.Ignore; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + import org.apache.xmlgraphics.image.loader.Image; import org.apache.xmlgraphics.image.loader.ImageFlavor; import org.apache.xmlgraphics.image.loader.ImageInfo; diff --git a/test/java/org/apache/fop/image/loader/batik/ImagePreloaderTestCase.java b/test/java/org/apache/fop/image/loader/batik/ImagePreloaderTestCase.java index efc5df1f7..3d690b67c 100644 --- a/test/java/org/apache/fop/image/loader/batik/ImagePreloaderTestCase.java +++ b/test/java/org/apache/fop/image/loader/batik/ImagePreloaderTestCase.java @@ -19,15 +19,15 @@ package org.apache.fop.image.loader.batik; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - import java.io.File; import java.io.IOException; import org.junit.Ignore; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import org.apache.xmlgraphics.image.loader.ImageException; import org.apache.xmlgraphics.image.loader.ImageInfo; import org.apache.xmlgraphics.image.loader.ImageManager; diff --git a/test/java/org/apache/fop/intermediate/AbstractIFTest.java b/test/java/org/apache/fop/intermediate/AbstractIFTest.java index 419db2c47..48c3f335b 100644 --- a/test/java/org/apache/fop/intermediate/AbstractIFTest.java +++ b/test/java/org/apache/fop/intermediate/AbstractIFTest.java @@ -34,7 +34,6 @@ import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.w3c.dom.Document; - import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; diff --git a/test/java/org/apache/fop/intermediate/AreaTreeXMLFormatTestSuite.java b/test/java/org/apache/fop/intermediate/AreaTreeXMLFormatTestSuite.java index 3fc855cef..2003958c8 100644 --- a/test/java/org/apache/fop/intermediate/AreaTreeXMLFormatTestSuite.java +++ b/test/java/org/apache/fop/intermediate/AreaTreeXMLFormatTestSuite.java @@ -27,6 +27,6 @@ import org.junit.runners.Suite.SuiteClasses; * JUnit test suite for the area tree XML format */ @RunWith(Suite.class) -@SuiteClasses({ AreaTreeParserTestCase.class }) +@SuiteClasses(AreaTreeParserTestCase.class) public class AreaTreeXMLFormatTestSuite { } diff --git a/test/java/org/apache/fop/intermediate/IFMimickingTestCase.java b/test/java/org/apache/fop/intermediate/IFMimickingTestCase.java index 58281fc10..83dd88661 100644 --- a/test/java/org/apache/fop/intermediate/IFMimickingTestCase.java +++ b/test/java/org/apache/fop/intermediate/IFMimickingTestCase.java @@ -19,8 +19,6 @@ package org.apache.fop.intermediate; -import static org.junit.Assert.fail; - import java.io.File; import javax.xml.transform.ErrorListener; @@ -34,6 +32,8 @@ import javax.xml.transform.stream.StreamSource; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.fail; + import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.Fop; diff --git a/test/java/org/apache/fop/intermediate/IntermediateFormatTestSuite.java b/test/java/org/apache/fop/intermediate/IntermediateFormatTestSuite.java index f960990b2..71b26cb9b 100644 --- a/test/java/org/apache/fop/intermediate/IntermediateFormatTestSuite.java +++ b/test/java/org/apache/fop/intermediate/IntermediateFormatTestSuite.java @@ -27,6 +27,6 @@ import org.junit.runners.Suite.SuiteClasses; * A test suite for testing the Intermediate Format output. */ @RunWith(Suite.class) -@SuiteClasses({ IFTestCase.class }) +@SuiteClasses(IFTestCase.class) public final class IntermediateFormatTestSuite { } diff --git a/test/java/org/apache/fop/intermediate/LayoutIFTestSuite.java b/test/java/org/apache/fop/intermediate/LayoutIFTestSuite.java index 5d87df1a5..ea60f2ff4 100644 --- a/test/java/org/apache/fop/intermediate/LayoutIFTestSuite.java +++ b/test/java/org/apache/fop/intermediate/LayoutIFTestSuite.java @@ -27,6 +27,6 @@ import org.junit.runners.Suite.SuiteClasses; * JUnit test suite for the intermediate format */ @RunWith(Suite.class) -@SuiteClasses({ IFParserTestCase.class }) +@SuiteClasses(IFParserTestCase.class) public final class LayoutIFTestSuite { } diff --git a/test/java/org/apache/fop/layoutengine/ElementListCheck.java b/test/java/org/apache/fop/layoutengine/ElementListCheck.java index e63fc3291..4d33d670b 100644 --- a/test/java/org/apache/fop/layoutengine/ElementListCheck.java +++ b/test/java/org/apache/fop/layoutengine/ElementListCheck.java @@ -22,16 +22,17 @@ package org.apache.fop.layoutengine; import java.util.Iterator; import java.util.List; -import org.apache.fop.layoutmgr.KnuthBox; -import org.apache.fop.layoutmgr.KnuthElement; -import org.apache.fop.layoutmgr.KnuthGlue; -import org.apache.fop.layoutmgr.KnuthPenalty; import org.w3c.dom.CDATASection; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; +import org.apache.fop.layoutmgr.KnuthBox; +import org.apache.fop.layoutmgr.KnuthElement; +import org.apache.fop.layoutmgr.KnuthGlue; +import org.apache.fop.layoutmgr.KnuthPenalty; + /** * Check implementation that checks a Knuth element list. */ diff --git a/test/java/org/apache/fop/layoutengine/LayoutEngineTestSuite.java b/test/java/org/apache/fop/layoutengine/LayoutEngineTestSuite.java index 2a70f255d..89bf28a55 100644 --- a/test/java/org/apache/fop/layoutengine/LayoutEngineTestSuite.java +++ b/test/java/org/apache/fop/layoutengine/LayoutEngineTestSuite.java @@ -27,6 +27,6 @@ import org.junit.runners.Suite.SuiteClasses; * JUnit test suit for running layout engine test under JUnit control. */ @RunWith(Suite.class) -@SuiteClasses({ LayoutEngineTestCase.class }) +@SuiteClasses(LayoutEngineTestCase.class) public class LayoutEngineTestSuite { } diff --git a/test/java/org/apache/fop/layoutengine/LayoutResult.java b/test/java/org/apache/fop/layoutengine/LayoutResult.java index 52c83daa8..92c459234 100644 --- a/test/java/org/apache/fop/layoutengine/LayoutResult.java +++ b/test/java/org/apache/fop/layoutengine/LayoutResult.java @@ -19,9 +19,10 @@ package org.apache.fop.layoutengine; -import org.apache.fop.apps.FormattingResults; import org.w3c.dom.Document; +import org.apache.fop.apps.FormattingResults; + /** * This class holds references to all the results from the FOP processing run. */ diff --git a/test/java/org/apache/fop/layoutmgr/table/TableCellLayoutManagerTestCase.java b/test/java/org/apache/fop/layoutmgr/table/TableCellLayoutManagerTestCase.java index c2fc84551..629e5f1c6 100644 --- a/test/java/org/apache/fop/layoutmgr/table/TableCellLayoutManagerTestCase.java +++ b/test/java/org/apache/fop/layoutmgr/table/TableCellLayoutManagerTestCase.java @@ -23,6 +23,10 @@ import java.awt.Color; import org.junit.Test; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import org.apache.fop.fo.flow.table.PrimaryGridUnit; import org.apache.fop.fo.flow.table.Table; import org.apache.fop.fo.flow.table.TableCell; @@ -37,10 +41,6 @@ import org.apache.fop.layoutmgr.PageSequenceLayoutManager; import org.apache.fop.layoutmgr.PositionIterator; import org.apache.fop.layoutmgr.RetrieveTableMarkerLayoutManager; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class TableCellLayoutManagerTestCase { // this test aims to check that the first call to addAreas() calls diff --git a/test/java/org/apache/fop/logging/LoggingElementListObserver.java b/test/java/org/apache/fop/logging/LoggingElementListObserver.java index 26c4db00e..7824a6b8b 100644 --- a/test/java/org/apache/fop/logging/LoggingElementListObserver.java +++ b/test/java/org/apache/fop/logging/LoggingElementListObserver.java @@ -24,9 +24,10 @@ import java.util.ListIterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import org.apache.fop.layoutmgr.ElementListObserver.Observer; import org.apache.fop.layoutmgr.ElementListUtils; import org.apache.fop.layoutmgr.ListElement; -import org.apache.fop.layoutmgr.ElementListObserver.Observer; /** * <p>Logs all observed element lists. diff --git a/test/java/org/apache/fop/memory/MemoryEater.java b/test/java/org/apache/fop/memory/MemoryEater.java index 7afb80476..efe0cc489 100644 --- a/test/java/org/apache/fop/memory/MemoryEater.java +++ b/test/java/org/apache/fop/memory/MemoryEater.java @@ -45,7 +45,7 @@ import org.apache.fop.apps.MimeConstants; /** * Debug tool to create and process large FO files by replicating them a specified number of times. */ -public class MemoryEater { +public final class MemoryEater { private SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); @@ -53,7 +53,7 @@ public class MemoryEater { private Stats stats; - public MemoryEater() throws TransformerConfigurationException, MalformedURLException { + private MemoryEater() throws TransformerConfigurationException, MalformedURLException { File xsltFile = new File("test/xsl/fo-replicator.xsl"); Source xslt = new StreamSource(xsltFile); replicatorTemplates = tFactory.newTemplates(xslt); diff --git a/test/java/org/apache/fop/pdf/AbstractPDFStreamTestCase.java b/test/java/org/apache/fop/pdf/AbstractPDFStreamTestCase.java index 95d5c0a1d..dec62c0a4 100644 --- a/test/java/org/apache/fop/pdf/AbstractPDFStreamTestCase.java +++ b/test/java/org/apache/fop/pdf/AbstractPDFStreamTestCase.java @@ -23,10 +23,11 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; -import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** * Test case for {@link AbstractPDFStream}. */ diff --git a/test/java/org/apache/fop/pdf/FileIDGeneratorTestCase.java b/test/java/org/apache/fop/pdf/FileIDGeneratorTestCase.java index a9d7bf4f6..3301fff9e 100644 --- a/test/java/org/apache/fop/pdf/FileIDGeneratorTestCase.java +++ b/test/java/org/apache/fop/pdf/FileIDGeneratorTestCase.java @@ -19,10 +19,6 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -33,6 +29,10 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + /** * Tests the {@link FileIDGenerator} class. */ @@ -96,7 +96,7 @@ public class FileIDGeneratorTestCase { assertTrue(Arrays.equals(originalFileID, updatedFileID)); } - private static interface TestGetter { + private interface TestGetter { FileIDGenerator getSut() throws Exception; } diff --git a/test/java/org/apache/fop/pdf/ObjectStreamManagerTestCase.java b/test/java/org/apache/fop/pdf/ObjectStreamManagerTestCase.java index 89d980029..21eb6088f 100644 --- a/test/java/org/apache/fop/pdf/ObjectStreamManagerTestCase.java +++ b/test/java/org/apache/fop/pdf/ObjectStreamManagerTestCase.java @@ -19,15 +19,15 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.OutputStream; import java.util.List; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import org.apache.fop.pdf.xref.CompressedObjectReference; public class ObjectStreamManagerTestCase { diff --git a/test/java/org/apache/fop/pdf/ObjectStreamTestCase.java b/test/java/org/apache/fop/pdf/ObjectStreamTestCase.java index 317828e4b..3512e1147 100644 --- a/test/java/org/apache/fop/pdf/ObjectStreamTestCase.java +++ b/test/java/org/apache/fop/pdf/ObjectStreamTestCase.java @@ -19,8 +19,6 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; @@ -29,6 +27,8 @@ import java.util.List; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class ObjectStreamTestCase { private static final String OBJECT_CONTENT = "<<\n /Foo True\n /Bar False\n>>\n"; diff --git a/test/java/org/apache/fop/pdf/PDFAModeTestCase.java b/test/java/org/apache/fop/pdf/PDFAModeTestCase.java index 352e0710e..68609575a 100644 --- a/test/java/org/apache/fop/pdf/PDFAModeTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFAModeTestCase.java @@ -97,7 +97,7 @@ public class PDFAModeTestCase { } @Test - public void checkPDFA_1a() { + public void checkPDFA1a() { new PDFAModeChecker(PDFAMode.PDFA_1A) .isEnabled() .isPart1() @@ -106,7 +106,7 @@ public class PDFAModeTestCase { } @Test - public void checkPDFA_1b() { + public void checkPDFA1b() { new PDFAModeChecker(PDFAMode.PDFA_1B) .isEnabled() .isPart1() @@ -115,7 +115,7 @@ public class PDFAModeTestCase { } @Test - public void checkPDFA_2a() { + public void checkPDFA2a() { new PDFAModeChecker(PDFAMode.PDFA_2A) .isEnabled() .isNotPart1() @@ -124,7 +124,7 @@ public class PDFAModeTestCase { } @Test - public void checkPDFA_2b() { + public void checkPDFA2b() { new PDFAModeChecker(PDFAMode.PDFA_2B) .isEnabled() .isNotPart1() @@ -133,7 +133,7 @@ public class PDFAModeTestCase { } @Test - public void checkPDFA_2u() { + public void checkPDFA2u() { new PDFAModeChecker(PDFAMode.PDFA_2U) .isEnabled() .isNotPart1() diff --git a/test/java/org/apache/fop/pdf/PDFArrayTestCase.java b/test/java/org/apache/fop/pdf/PDFArrayTestCase.java index 418b2f1a9..53e9bdba0 100644 --- a/test/java/org/apache/fop/pdf/PDFArrayTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFArrayTestCase.java @@ -19,17 +19,17 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import org.junit.Before; import org.junit.Test; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; /** * Test case for {@link PDFArray}. diff --git a/test/java/org/apache/fop/pdf/PDFDestsTestCase.java b/test/java/org/apache/fop/pdf/PDFDestsTestCase.java index 08d841ede..4655b258d 100644 --- a/test/java/org/apache/fop/pdf/PDFDestsTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFDestsTestCase.java @@ -19,20 +19,20 @@ package org.apache.fop.pdf; -import org.junit.Before; -import org.junit.Test; - import java.io.IOException; import java.util.ArrayList; import java.util.List; +import org.junit.Before; +import org.junit.Test; + /** * Test case for {@link PDFDests}. */ public class PDFDestsTestCase extends PDFObjectTestCase { private PDFDests dests = new PDFDests(); - private String expectedString = "<< /Names [(number) 10 (name) /Test#20name] >>\n"; + private String expectedString = "<< /Names [(number) 10 (name) /Test#20name] >>"; @Before public void setUp() { diff --git a/test/java/org/apache/fop/pdf/PDFDictionaryTestCase.java b/test/java/org/apache/fop/pdf/PDFDictionaryTestCase.java index 3f84fac2e..267e05c2c 100644 --- a/test/java/org/apache/fop/pdf/PDFDictionaryTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFDictionaryTestCase.java @@ -19,17 +19,18 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - import java.io.ByteArrayOutputStream; import java.io.IOException; -import org.apache.commons.io.output.CountingOutputStream; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import org.apache.commons.io.output.CountingOutputStream; + /** * Test case for {@link PDFDictionary}. @@ -47,7 +48,7 @@ public class PDFDictionaryTestCase extends PDFObjectTestCase { + " /array [1 (two) 20]\n" + " /number 20\n" + " /null null\n" - + ">>\n"; + + ">>"; @Before public void setUp() { diff --git a/test/java/org/apache/fop/pdf/PDFDocumentGraphics2DTestCase.java b/test/java/org/apache/fop/pdf/PDFDocumentGraphics2DTestCase.java index c7eff506e..880613a78 100644 --- a/test/java/org/apache/fop/pdf/PDFDocumentGraphics2DTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFDocumentGraphics2DTestCase.java @@ -24,8 +24,6 @@ import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; -import junit.framework.Assert; - import org.junit.Test; import org.apache.commons.io.output.ByteArrayOutputStream; @@ -34,6 +32,8 @@ import org.apache.xmlgraphics.util.UnitConv; import org.apache.fop.svg.PDFDocumentGraphics2D; +import junit.framework.Assert; + /** * Tests for {@link PDFDocumentGraphics2D}. */ diff --git a/test/java/org/apache/fop/pdf/PDFDocumentTestCase.java b/test/java/org/apache/fop/pdf/PDFDocumentTestCase.java index 8965635b9..e58201f13 100644 --- a/test/java/org/apache/fop/pdf/PDFDocumentTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFDocumentTestCase.java @@ -19,12 +19,12 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; +import java.io.ByteArrayOutputStream; +import java.io.IOException; import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.IOException; +import static org.junit.Assert.assertEquals; /** * Test case for {@link PDFDocument} diff --git a/test/java/org/apache/fop/pdf/PDFEncodingTestCase.java b/test/java/org/apache/fop/pdf/PDFEncodingTestCase.java index 34e48f1a6..2f80b077c 100644 --- a/test/java/org/apache/fop/pdf/PDFEncodingTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFEncodingTestCase.java @@ -19,11 +19,11 @@ package org.apache.fop.pdf; import org.junit.Test; -import org.apache.fop.fonts.CodePointMapping; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import org.apache.fop.fonts.CodePointMapping; + public class PDFEncodingTestCase { /** diff --git a/test/java/org/apache/fop/pdf/PDFEncryptionJCETestCase.java b/test/java/org/apache/fop/pdf/PDFEncryptionJCETestCase.java index ea3b011c7..e3f8344e0 100644 --- a/test/java/org/apache/fop/pdf/PDFEncryptionJCETestCase.java +++ b/test/java/org/apache/fop/pdf/PDFEncryptionJCETestCase.java @@ -19,10 +19,6 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -43,6 +39,10 @@ import javax.crypto.spec.SecretKeySpec; import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * Tests the {@link PDFEncryptionJCE} class. */ diff --git a/test/java/org/apache/fop/pdf/PDFFilterListTestCase.java b/test/java/org/apache/fop/pdf/PDFFilterListTestCase.java index 2504d871a..d1cc6273d 100644 --- a/test/java/org/apache/fop/pdf/PDFFilterListTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFFilterListTestCase.java @@ -19,10 +19,10 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertFalse; - import org.junit.Test; +import static org.junit.Assert.assertFalse; + public class PDFFilterListTestCase { @Test diff --git a/test/java/org/apache/fop/pdf/PDFNameTestCase.java b/test/java/org/apache/fop/pdf/PDFNameTestCase.java index 80917f416..8d7321496 100644 --- a/test/java/org/apache/fop/pdf/PDFNameTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFNameTestCase.java @@ -22,11 +22,13 @@ package org.apache.fop.pdf; import java.io.ByteArrayOutputStream; import java.io.IOException; -import org.apache.commons.io.output.CountingOutputStream; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.fail; + import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.apache.commons.io.output.CountingOutputStream; /** * Test class for {@link PDFName}. diff --git a/test/java/org/apache/fop/pdf/PDFNullTestCase.java b/test/java/org/apache/fop/pdf/PDFNullTestCase.java index 98427cd20..87dacc7f6 100644 --- a/test/java/org/apache/fop/pdf/PDFNullTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFNullTestCase.java @@ -19,12 +19,12 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; +import java.io.ByteArrayOutputStream; +import java.io.IOException; import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.IOException; +import static org.junit.Assert.assertEquals; /** * Test case for {@link PDFNull}. diff --git a/test/java/org/apache/fop/pdf/PDFNumberTestCase.java b/test/java/org/apache/fop/pdf/PDFNumberTestCase.java index ed660af8d..65f484dc7 100644 --- a/test/java/org/apache/fop/pdf/PDFNumberTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFNumberTestCase.java @@ -19,13 +19,13 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import java.io.IOException; import org.junit.Before; import org.junit.Test; -import java.io.IOException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; /** * This test tests PDFNumber's doubleOut() methods. diff --git a/test/java/org/apache/fop/pdf/PDFNumsArrayTestCase.java b/test/java/org/apache/fop/pdf/PDFNumsArrayTestCase.java index e0dca33bf..d36775cda 100644 --- a/test/java/org/apache/fop/pdf/PDFNumsArrayTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFNumsArrayTestCase.java @@ -19,11 +19,11 @@ package org.apache.fop.pdf; +import java.io.IOException; + import org.junit.Before; import org.junit.Test; -import java.io.IOException; - /** * Test case for {@link PDFNumsArray}. */ diff --git a/test/java/org/apache/fop/pdf/PDFObjectTestCase.java b/test/java/org/apache/fop/pdf/PDFObjectTestCase.java index 10ffa3b27..f35d2a15c 100644 --- a/test/java/org/apache/fop/pdf/PDFObjectTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFObjectTestCase.java @@ -19,17 +19,17 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * Tests the PDFObject class. */ diff --git a/test/java/org/apache/fop/pdf/PDFPageLabelsTestCase.java b/test/java/org/apache/fop/pdf/PDFPageLabelsTestCase.java index e982bf246..a8be7ee74 100644 --- a/test/java/org/apache/fop/pdf/PDFPageLabelsTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFPageLabelsTestCase.java @@ -37,11 +37,11 @@ public class PDFPageLabelsTestCase { int index = 0; StringBuilder expected = new StringBuilder(); expected.append("["); - expected.append(index + " << /S /r >>\n"); + expected.append(index + " << /S /r >>"); pageLabels.addPageLabel(index++, "i"); pageLabels.addPageLabel(index++, "ii"); pageLabels.addPageLabel(index++, "iii"); - expected.append(" " + index + " << /S /D >>\n"); + expected.append(" " + index + " << /S /D >>"); pageLabels.addPageLabel(index++, "1"); pageLabels.addPageLabel(index++, "2"); pageLabels.addPageLabel(index++, "3"); @@ -52,33 +52,33 @@ public class PDFPageLabelsTestCase { pageLabels.addPageLabel(index++, "8"); pageLabels.addPageLabel(index++, "9"); pageLabels.addPageLabel(index++, "10"); - expected.append(" " + index + " << /S /A >>\n"); + expected.append(" " + index + " << /S /A >>"); pageLabels.addPageLabel(index++, "A"); pageLabels.addPageLabel(index++, "B"); - expected.append(" " + index + " << /S /R /St 100 >>\n"); + expected.append(" " + index + " << /S /R /St 100 >>"); pageLabels.addPageLabel(index++, "C"); - expected.append(" " + index + " << /S /R /St 500 >>\n"); + expected.append(" " + index + " << /S /R /St 500 >>"); pageLabels.addPageLabel(index++, "D"); - expected.append(" " + index + " << /S /A /St 5 >>\n"); + expected.append(" " + index + " << /S /A /St 5 >>"); pageLabels.addPageLabel(index++, "E"); pageLabels.addPageLabel(index++, "F"); pageLabels.addPageLabel(index++, "G"); - expected.append(" " + index + " << /P (aa) >>\n"); + expected.append(" " + index + " << /P (aa) >>"); pageLabels.addPageLabel(index++, "aa"); - expected.append(" " + index + " << /P (ab) >>\n"); + expected.append(" " + index + " << /P (ab) >>"); pageLabels.addPageLabel(index++, "ab"); - expected.append(" " + index + " << /P (ac) >>\n"); + expected.append(" " + index + " << /P (ac) >>"); pageLabels.addPageLabel(index++, "ac"); - expected.append(" " + index + " << /S /a >>\n"); + expected.append(" " + index + " << /S /a >>"); pageLabels.addPageLabel(index++, "a"); pageLabels.addPageLabel(index++, "b"); - expected.append(" " + index + " << /S /R /St 2 >>\n"); + expected.append(" " + index + " << /S /R /St 2 >>"); pageLabels.addPageLabel(index++, "II"); - expected.append(" " + index + " << /S /R /St 12 >>\n"); + expected.append(" " + index + " << /S /R /St 12 >>"); pageLabels.addPageLabel(index++, "XII"); - expected.append(" " + index + " <<\n /P (00)\n /S /D\n /St 9\n>>\n"); + expected.append(" " + index + " <<\n /P (00)\n /S /D\n /St 9\n>>"); pageLabels.addPageLabel(index++, "009"); - expected.append(" " + index + " <<\n /P (0)\n /S /D\n /St 10\n>>\n"); + expected.append(" " + index + " <<\n /P (0)\n /S /D\n /St 10\n>>"); pageLabels.addPageLabel(index++, "010"); pageLabels.addPageLabel(index++, "011"); expected.append("]"); diff --git a/test/java/org/apache/fop/pdf/PDFRectangleTestCase.java b/test/java/org/apache/fop/pdf/PDFRectangleTestCase.java index 24b6a1c71..ed87cd23e 100644 --- a/test/java/org/apache/fop/pdf/PDFRectangleTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFRectangleTestCase.java @@ -19,14 +19,14 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + /** * Test case for {@link PDFRectangle}. */ diff --git a/test/java/org/apache/fop/pdf/PDFReferenceTestCase.java b/test/java/org/apache/fop/pdf/PDFReferenceTestCase.java index a2c6193cf..4e0e8814d 100644 --- a/test/java/org/apache/fop/pdf/PDFReferenceTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFReferenceTestCase.java @@ -19,12 +19,12 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertEquals; +import java.io.ByteArrayOutputStream; +import java.io.IOException; import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.IOException; +import static org.junit.Assert.assertEquals; /** * Test case for {@link PDFReference}. diff --git a/test/java/org/apache/fop/pdf/PDFStreamTestCase.java b/test/java/org/apache/fop/pdf/PDFStreamTestCase.java index 93dcea511..b5fb66e00 100644 --- a/test/java/org/apache/fop/pdf/PDFStreamTestCase.java +++ b/test/java/org/apache/fop/pdf/PDFStreamTestCase.java @@ -19,17 +19,17 @@ package org.apache.fop.pdf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class PDFStreamTestCase { private PDFStream stream; @@ -118,7 +118,7 @@ public class PDFStreamTestCase { private byte[] createSampleStreamData() throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); - stream.write("stream\n".getBytes("US-ASCII")); + stream.write("\nstream\n".getBytes("US-ASCII")); stream.write(createSampleData()); stream.write("\nendstream".getBytes("US-ASCII")); return stream.toByteArray(); diff --git a/test/java/org/apache/fop/pdf/TableHeaderScopeTestCase.java b/test/java/org/apache/fop/pdf/TableHeaderScopeTestCase.java index a1d581402..2fa5008ed 100644 --- a/test/java/org/apache/fop/pdf/TableHeaderScopeTestCase.java +++ b/test/java/org/apache/fop/pdf/TableHeaderScopeTestCase.java @@ -109,14 +109,14 @@ public class TableHeaderScopeTestCase { } private PDFDictionary scopeAttribute(Scope scope) { - return argThat(new isScopeAttribute(scope)); + return argThat(new IsScopeAttribute(scope)); } - private static class isScopeAttribute extends ArgumentMatcher<PDFDictionary> { + private static class IsScopeAttribute extends ArgumentMatcher<PDFDictionary> { private final Scope expectedScope; - public isScopeAttribute(Scope expectedScope) { + public IsScopeAttribute(Scope expectedScope) { this.expectedScope = expectedScope; } diff --git a/test/java/org/apache/fop/pdf/VersionControllerTestCase.java b/test/java/org/apache/fop/pdf/VersionControllerTestCase.java index 74637c91f..e14fc9502 100644 --- a/test/java/org/apache/fop/pdf/VersionControllerTestCase.java +++ b/test/java/org/apache/fop/pdf/VersionControllerTestCase.java @@ -19,13 +19,13 @@ package org.apache.fop.pdf; +import org.junit.Before; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; -import org.junit.Before; -import org.junit.Test; - /** * A test class for {@link VersionController}. diff --git a/test/java/org/apache/fop/pdf/VersionTestCase.java b/test/java/org/apache/fop/pdf/VersionTestCase.java index 9c90f0966..dd2731d8b 100644 --- a/test/java/org/apache/fop/pdf/VersionTestCase.java +++ b/test/java/org/apache/fop/pdf/VersionTestCase.java @@ -19,11 +19,11 @@ package org.apache.fop.pdf; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.junit.Test; - /** * This is a test case for ({@link Version}. */ diff --git a/test/java/org/apache/fop/pdf/xref/CompressedObjectReferenceTestCase.java b/test/java/org/apache/fop/pdf/xref/CompressedObjectReferenceTestCase.java index 8b103d277..b7a326c64 100644 --- a/test/java/org/apache/fop/pdf/xref/CompressedObjectReferenceTestCase.java +++ b/test/java/org/apache/fop/pdf/xref/CompressedObjectReferenceTestCase.java @@ -19,14 +19,14 @@ package org.apache.fop.pdf.xref; -import static org.junit.Assert.assertArrayEquals; - import java.io.IOException; import java.util.Arrays; import java.util.List; import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; + public class CompressedObjectReferenceTestCase extends ObjectReferenceTest { @Test diff --git a/test/java/org/apache/fop/pdf/xref/CrossReferenceObjectTest.java b/test/java/org/apache/fop/pdf/xref/CrossReferenceObjectTest.java index df1b86e53..cd55577cd 100644 --- a/test/java/org/apache/fop/pdf/xref/CrossReferenceObjectTest.java +++ b/test/java/org/apache/fop/pdf/xref/CrossReferenceObjectTest.java @@ -19,8 +19,6 @@ package org.apache.fop.pdf.xref; -import static org.junit.Assert.assertArrayEquals; - import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; @@ -32,6 +30,8 @@ import java.util.Map; import org.junit.Before; +import static org.junit.Assert.assertArrayEquals; + import org.apache.fop.pdf.PDFDocument; import org.apache.fop.pdf.PDFInfo; import org.apache.fop.pdf.PDFPages; diff --git a/test/java/org/apache/fop/pdf/xref/CrossReferenceTableTestCase.java b/test/java/org/apache/fop/pdf/xref/CrossReferenceTableTestCase.java index ceff96a91..12f6e3c1b 100644 --- a/test/java/org/apache/fop/pdf/xref/CrossReferenceTableTestCase.java +++ b/test/java/org/apache/fop/pdf/xref/CrossReferenceTableTestCase.java @@ -73,7 +73,7 @@ public class CrossReferenceTableTestCase extends CrossReferenceObjectTest { .append(" /Info 2 0 R\n") .append(" /ID [<0123456789ABCDEF> <0123456789ABCDEF>]\n") .append(" /Size ").append(Integer.toString(offsets.size() + 1)).append('\n') - .append(">>\n"); + .append(">>"); return getBytes(expected); } diff --git a/test/java/org/apache/fop/pdf/xref/UncompressedObjectReferenceTestCase.java b/test/java/org/apache/fop/pdf/xref/UncompressedObjectReferenceTestCase.java index b147084e8..a9f506aaa 100644 --- a/test/java/org/apache/fop/pdf/xref/UncompressedObjectReferenceTestCase.java +++ b/test/java/org/apache/fop/pdf/xref/UncompressedObjectReferenceTestCase.java @@ -19,8 +19,6 @@ package org.apache.fop.pdf.xref; -import static org.junit.Assert.assertArrayEquals; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -28,6 +26,8 @@ import java.util.List; import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; + public class UncompressedObjectReferenceTestCase extends ObjectReferenceTest { @Test diff --git a/test/java/org/apache/fop/render/AbstractRenderingTest.java b/test/java/org/apache/fop/render/AbstractRenderingTest.java index 9d196e71d..297a9ba05 100644 --- a/test/java/org/apache/fop/render/AbstractRenderingTest.java +++ b/test/java/org/apache/fop/render/AbstractRenderingTest.java @@ -33,6 +33,7 @@ import javax.xml.transform.stream.StreamSource; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; + import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; diff --git a/test/java/org/apache/fop/render/RawPNGTestUtil.java b/test/java/org/apache/fop/render/RawPNGTestUtil.java index e6660bb42..506556c66 100644 --- a/test/java/org/apache/fop/render/RawPNGTestUtil.java +++ b/test/java/org/apache/fop/render/RawPNGTestUtil.java @@ -28,9 +28,9 @@ import org.apache.xmlgraphics.image.loader.ImageSize; public final class RawPNGTestUtil { - private static int NUM_ROWS = 32; - private static int NUM_COLUMNS = 32; - private static int DPI = 72; + private static final int NUM_ROWS = 32; + private static final int NUM_COLUMNS = 32; + private static final int DPI = 72; private RawPNGTestUtil() { @@ -83,7 +83,7 @@ public final class RawPNGTestUtil { } /** - * + * * @return a default ImageSize */ public static ImageSize getImageSize() { diff --git a/test/java/org/apache/fop/render/RendererFactoryTestCase.java b/test/java/org/apache/fop/render/RendererFactoryTestCase.java index 4bed835ec..1fa4ae0fa 100644 --- a/test/java/org/apache/fop/render/RendererFactoryTestCase.java +++ b/test/java/org/apache/fop/render/RendererFactoryTestCase.java @@ -19,13 +19,13 @@ package org.apache.fop.render; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.File; import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import org.apache.commons.io.output.NullOutputStream; import org.apache.fop.apps.FOPException; diff --git a/test/java/org/apache/fop/render/afp/AFPBorderPainterTestCase.java b/test/java/org/apache/fop/render/afp/AFPBorderPainterTestCase.java index 691d75f3f..dfe956d90 100644 --- a/test/java/org/apache/fop/render/afp/AFPBorderPainterTestCase.java +++ b/test/java/org/apache/fop/render/afp/AFPBorderPainterTestCase.java @@ -19,12 +19,15 @@ package org.apache.fop.render.afp; -import static org.junit.Assert.assertTrue; - import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.OutputStream; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + import org.apache.fop.afp.AFPBorderPainter; import org.apache.fop.afp.AFPLineDataInfo; import org.apache.fop.afp.AFPPaintingState; @@ -32,8 +35,6 @@ import org.apache.fop.afp.BorderPaintingInfo; import org.apache.fop.afp.DataStream; import org.apache.fop.afp.Factory; import org.apache.fop.fo.Constants; -import org.junit.Before; -import org.junit.Test; public class AFPBorderPainterTestCase { private ByteArrayOutputStream outStream; @@ -63,12 +64,12 @@ public class AFPBorderPainterTestCase { ds.endDocument(); assertTrue(line.getX1() == 4999 && line.getX2() == 8332); } - + class MyDataStream extends DataStream { public MyDataStream(Factory factory, AFPPaintingState paintingState, OutputStream outputStream) { super(factory, paintingState, outputStream); } - + public void createLine(AFPLineDataInfo lineDataInfo) { line = lineDataInfo; } diff --git a/test/java/org/apache/fop/render/afp/AFPRendererConfigParserTestCase.java b/test/java/org/apache/fop/render/afp/AFPRendererConfigParserTestCase.java index 799045872..8ed54049f 100644 --- a/test/java/org/apache/fop/render/afp/AFPRendererConfigParserTestCase.java +++ b/test/java/org/apache/fop/render/afp/AFPRendererConfigParserTestCase.java @@ -25,6 +25,10 @@ import java.util.Map; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + import org.apache.fop.afp.AFPConstants; import org.apache.fop.apps.AFPRendererConfBuilder; import org.apache.fop.apps.AbstractRendererConfigParserTester; @@ -33,9 +37,6 @@ import org.apache.fop.render.afp.AFPRendererConfig.ImagesModeOptions; import static org.apache.fop.render.afp.AFPRendererConfig.ImagesModeOptions.MODE_COLOR; import static org.apache.fop.render.afp.AFPRendererConfig.ImagesModeOptions.MODE_GRAYSCALE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; public class AFPRendererConfigParserTestCase extends AbstractRendererConfigParserTester<AFPRendererConfBuilder, AFPRendererConfig> { diff --git a/test/java/org/apache/fop/render/afp/AFPRendererConfiguratorTestCase.java b/test/java/org/apache/fop/render/afp/AFPRendererConfiguratorTestCase.java index 115b3149a..48cf89240 100644 --- a/test/java/org/apache/fop/render/afp/AFPRendererConfiguratorTestCase.java +++ b/test/java/org/apache/fop/render/afp/AFPRendererConfiguratorTestCase.java @@ -24,6 +24,9 @@ import java.util.Map; import org.junit.Test; import org.mockito.ArgumentCaptor; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; + import org.apache.fop.afp.AFPResourceLevel; import org.apache.fop.afp.AFPResourceLevel.ResourceType; import org.apache.fop.afp.AFPResourceLevelDefaults; @@ -33,9 +36,6 @@ import org.apache.fop.apps.MimeConstants; import org.apache.fop.render.afp.AFPRendererConfig.AFPRendererConfigParser; import org.apache.fop.render.afp.AFPRendererConfig.ImagesModeOptions; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; - public class AFPRendererConfiguratorTestCase extends AbstractRendererConfiguratorTest<AFPRendererConfigurator, AFPRendererConfBuilder> { diff --git a/test/java/org/apache/fop/render/afp/NoOperationTestCase.java b/test/java/org/apache/fop/render/afp/NoOperationTestCase.java index 78578a2b6..9e83829f8 100644 --- a/test/java/org/apache/fop/render/afp/NoOperationTestCase.java +++ b/test/java/org/apache/fop/render/afp/NoOperationTestCase.java @@ -19,20 +19,22 @@ package org.apache.fop.render.afp; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + import org.apache.commons.io.IOUtils; + import org.apache.fop.afp.AFPConstants; import org.apache.fop.afp.parser.MODCAParser; import org.apache.fop.afp.parser.UnparsedStructuredField; import org.apache.fop.apps.FOUserAgent; -import org.junit.Test; /** * Tests generation of afp:no-operation (NOPs). diff --git a/test/java/org/apache/fop/render/bitmap/AbstractBitmapRendererConfigParserTester.java b/test/java/org/apache/fop/render/bitmap/AbstractBitmapRendererConfigParserTester.java index 04f872a84..cae184d51 100644 --- a/test/java/org/apache/fop/render/bitmap/AbstractBitmapRendererConfigParserTester.java +++ b/test/java/org/apache/fop/render/bitmap/AbstractBitmapRendererConfigParserTester.java @@ -24,6 +24,11 @@ import java.awt.image.BufferedImage; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import org.apache.fop.apps.AbstractRendererConfigParserTester; import org.apache.fop.apps.BitmapRendererConfBuilder; import org.apache.fop.render.bitmap.BitmapRendererConfig.BitmapRendererConfigParser; @@ -36,10 +41,6 @@ import static org.apache.fop.render.bitmap.BitmapRendererOption.COLOR_MODE_RGBA; import static org.apache.fop.render.bitmap.BitmapRendererOption.JAVA2D_TRANSPARENT_PAGE_BACKGROUND; import static org.apache.fop.render.bitmap.BitmapRendererOption.RENDERING_QUALITY; import static org.apache.fop.render.bitmap.BitmapRendererOption.RENDERING_SPEED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; public class AbstractBitmapRendererConfigParserTester extends AbstractRendererConfigParserTester<BitmapRendererConfBuilder, BitmapRendererConfig> { diff --git a/test/java/org/apache/fop/render/bitmap/AbstractBitmapRendererConfiguratorTest.java b/test/java/org/apache/fop/render/bitmap/AbstractBitmapRendererConfiguratorTest.java index 3e0c8c203..dcbb27754 100644 --- a/test/java/org/apache/fop/render/bitmap/AbstractBitmapRendererConfiguratorTest.java +++ b/test/java/org/apache/fop/render/bitmap/AbstractBitmapRendererConfiguratorTest.java @@ -23,6 +23,11 @@ import java.awt.image.BufferedImage; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + import org.apache.fop.apps.AbstractRendererConfiguratorTest; import org.apache.fop.apps.BitmapRendererConfBuilder; import org.apache.fop.render.intermediate.IFDocumentHandler; @@ -35,10 +40,6 @@ import static org.apache.fop.render.bitmap.BitmapRendererOption.COLOR_MODE_RGB; import static org.apache.fop.render.bitmap.BitmapRendererOption.COLOR_MODE_RGBA; import static org.apache.fop.render.bitmap.BitmapRendererOption.RENDERING_QUALITY; import static org.apache.fop.render.bitmap.BitmapRendererOption.RENDERING_SPEED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; public abstract class AbstractBitmapRendererConfiguratorTest extends AbstractRendererConfiguratorTest<BitmapRendererConfigurator, BitmapRendererConfBuilder> { diff --git a/test/java/org/apache/fop/render/bitmap/TIFFRendererConfigParserTestCase.java b/test/java/org/apache/fop/render/bitmap/TIFFRendererConfigParserTestCase.java index d33076983..8a5c2a72d 100644 --- a/test/java/org/apache/fop/render/bitmap/TIFFRendererConfigParserTestCase.java +++ b/test/java/org/apache/fop/render/bitmap/TIFFRendererConfigParserTestCase.java @@ -21,16 +21,16 @@ package org.apache.fop.render.bitmap; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.apache.xmlgraphics.image.writer.Endianness; import org.apache.fop.apps.FopConfBuilder; import org.apache.fop.apps.TIFFRendererConfBuilder; import org.apache.fop.render.bitmap.TIFFRendererConfig.TIFFRendererConfigParser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class TIFFRendererConfigParserTestCase extends AbstractBitmapRendererConfigParserTester { diff --git a/test/java/org/apache/fop/render/bitmap/TIFFRendererConfiguratorTestCase.java b/test/java/org/apache/fop/render/bitmap/TIFFRendererConfiguratorTestCase.java index b5e6318ce..e340830f4 100644 --- a/test/java/org/apache/fop/render/bitmap/TIFFRendererConfiguratorTestCase.java +++ b/test/java/org/apache/fop/render/bitmap/TIFFRendererConfiguratorTestCase.java @@ -23,6 +23,10 @@ import java.awt.image.BufferedImage; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.apache.xmlgraphics.image.writer.Endianness; import org.apache.fop.apps.FopConfBuilder; @@ -32,9 +36,6 @@ import org.apache.fop.render.bitmap.TIFFRendererConfig.TIFFRendererConfigParser; import static org.apache.fop.render.bitmap.TIFFCompressionValue.CCITT_T4; import static org.apache.fop.render.bitmap.TIFFCompressionValue.CCITT_T6; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; public class TIFFRendererConfiguratorTestCase extends AbstractBitmapRendererConfiguratorTest { diff --git a/test/java/org/apache/fop/render/extensions/prepress/PageBoundariesTestCase.java b/test/java/org/apache/fop/render/extensions/prepress/PageBoundariesTestCase.java index 6e48845c1..e3f892e7c 100644 --- a/test/java/org/apache/fop/render/extensions/prepress/PageBoundariesTestCase.java +++ b/test/java/org/apache/fop/render/extensions/prepress/PageBoundariesTestCase.java @@ -19,15 +19,15 @@ package org.apache.fop.render.extensions.prepress; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - import java.awt.Dimension; import java.awt.Rectangle; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + /** * Tests for the fox:bleed, fox:crop-offset, fox:crop-box extension properties. */ diff --git a/test/java/org/apache/fop/render/extensions/prepress/PageScaleTestCase.java b/test/java/org/apache/fop/render/extensions/prepress/PageScaleTestCase.java index ff07e63ce..9de045cf7 100644 --- a/test/java/org/apache/fop/render/extensions/prepress/PageScaleTestCase.java +++ b/test/java/org/apache/fop/render/extensions/prepress/PageScaleTestCase.java @@ -19,14 +19,14 @@ package org.apache.fop.render.extensions.prepress; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - import java.awt.geom.Point2D; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + /** * Tests for the fox:scale extension property. */ diff --git a/test/java/org/apache/fop/render/intermediate/AbstractIFPainterTestCase.java b/test/java/org/apache/fop/render/intermediate/AbstractIFPainterTestCase.java index 592335648..ec0f35737 100644 --- a/test/java/org/apache/fop/render/intermediate/AbstractIFPainterTestCase.java +++ b/test/java/org/apache/fop/render/intermediate/AbstractIFPainterTestCase.java @@ -26,15 +26,15 @@ import org.junit.Before; import org.junit.Test; import org.w3c.dom.Document; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.apache.fop.fonts.FontInfo; import org.apache.fop.fonts.FontTriplet; import org.apache.fop.render.RenderingContext; import org.apache.fop.traits.BorderProps; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class AbstractIFPainterTestCase { private AbstractIFPainter<?> sut; @@ -51,7 +51,7 @@ public class AbstractIFPainterTestCase { public void endViewport() throws IFException { } - public void startGroup(AffineTransform transform) throws IFException { + public void startGroup(AffineTransform transform, String layer) throws IFException { } public void endGroup() throws IFException { diff --git a/test/java/org/apache/fop/render/intermediate/ArcToBezierCurveTransformerTestCase.java b/test/java/org/apache/fop/render/intermediate/ArcToBezierCurveTransformerTestCase.java index 61093c629..039ddcf90 100644 --- a/test/java/org/apache/fop/render/intermediate/ArcToBezierCurveTransformerTestCase.java +++ b/test/java/org/apache/fop/render/intermediate/ArcToBezierCurveTransformerTestCase.java @@ -76,4 +76,4 @@ public class ArcToBezierCurveTransformerTestCase { fail("Angle " + angle + " is in (0, " + Math.PI / 2 + ")"); } } -}
\ No newline at end of file +} diff --git a/test/java/org/apache/fop/render/intermediate/BorderPainterTestCase.java b/test/java/org/apache/fop/render/intermediate/BorderPainterTestCase.java index f0e9522d9..4a89b3ac6 100644 --- a/test/java/org/apache/fop/render/intermediate/BorderPainterTestCase.java +++ b/test/java/org/apache/fop/render/intermediate/BorderPainterTestCase.java @@ -575,4 +575,4 @@ public class BorderPainterTestCase { } -}
\ No newline at end of file +} diff --git a/test/java/org/apache/fop/render/intermediate/IFStructureTreeBuilderTestCase.java b/test/java/org/apache/fop/render/intermediate/IFStructureTreeBuilderTestCase.java index 4df3fe278..5546e5905 100644 --- a/test/java/org/apache/fop/render/intermediate/IFStructureTreeBuilderTestCase.java +++ b/test/java/org/apache/fop/render/intermediate/IFStructureTreeBuilderTestCase.java @@ -19,14 +19,6 @@ package org.apache.fop.render.intermediate; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; @@ -36,6 +28,14 @@ import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import org.apache.fop.fo.FOElementMapping; import org.apache.fop.fo.extensions.ExtensionElementMapping; import org.apache.fop.fo.extensions.InternalElementMapping; diff --git a/test/java/org/apache/fop/render/intermediate/SAXEventRecorderTestCase.java b/test/java/org/apache/fop/render/intermediate/SAXEventRecorderTestCase.java index c5aad66d0..757d6620b 100644 --- a/test/java/org/apache/fop/render/intermediate/SAXEventRecorderTestCase.java +++ b/test/java/org/apache/fop/render/intermediate/SAXEventRecorderTestCase.java @@ -20,10 +20,6 @@ package org.apache.fop.render.intermediate; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; @@ -32,6 +28,10 @@ import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import org.apache.fop.render.intermediate.IFStructureTreeBuilder.SAXEventRecorder; import org.apache.fop.util.XMLUtil; diff --git a/test/java/org/apache/fop/render/java2d/Java2DRendererConfigParserTestcase.java b/test/java/org/apache/fop/render/java2d/Java2DRendererConfigParserTestcase.java index 00631af4b..e87c8713d 100644 --- a/test/java/org/apache/fop/render/java2d/Java2DRendererConfigParserTestcase.java +++ b/test/java/org/apache/fop/render/java2d/Java2DRendererConfigParserTestcase.java @@ -21,17 +21,14 @@ package org.apache.fop.render.java2d; import org.junit.Test; -import org.apache.avalon.framework.configuration.Configuration; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import org.apache.fop.apps.AbstractRendererConfigParserTester; -import org.apache.fop.apps.FOPException; import org.apache.fop.apps.Java2DRendererConfBuilder; import org.apache.fop.render.java2d.Java2DRendererConfig.Java2DRendererConfigParser; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - public class Java2DRendererConfigParserTestcase extends AbstractRendererConfigParserTester<Java2DRendererConfBuilder, Java2DRendererConfig> { diff --git a/test/java/org/apache/fop/render/pcl/PCLRendererConfigParserTestCase.java b/test/java/org/apache/fop/render/pcl/PCLRendererConfigParserTestCase.java index 113c3e2bd..caf534854 100644 --- a/test/java/org/apache/fop/render/pcl/PCLRendererConfigParserTestCase.java +++ b/test/java/org/apache/fop/render/pcl/PCLRendererConfigParserTestCase.java @@ -21,13 +21,13 @@ package org.apache.fop.render.pcl; import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.apache.fop.apps.AbstractRendererConfigParserTester; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.MimeConstants; import org.apache.fop.render.pcl.PCLRendererConfig.PCLRendererConfigParser; -import static org.junit.Assert.assertEquals; - public class PCLRendererConfigParserTestCase extends AbstractRendererConfigParserTester<PCLRendererConfBuilder, PCLRendererConfig> { diff --git a/test/java/org/apache/fop/render/pcl/PCLRendererConfiguratorTestCase.java b/test/java/org/apache/fop/render/pcl/PCLRendererConfiguratorTestCase.java index 024104179..fc7175ad6 100644 --- a/test/java/org/apache/fop/render/pcl/PCLRendererConfiguratorTestCase.java +++ b/test/java/org/apache/fop/render/pcl/PCLRendererConfiguratorTestCase.java @@ -19,16 +19,16 @@ package org.apache.fop.render.pcl; import org.junit.Test; -import org.apache.fop.apps.AbstractRendererConfiguratorTest; -import org.apache.fop.apps.FOPException; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.render.pcl.PCLRendererConfig.PCLRendererConfigParser; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; +import org.apache.fop.apps.AbstractRendererConfiguratorTest; +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.MimeConstants; +import org.apache.fop.render.pcl.PCLRendererConfig.PCLRendererConfigParser; + public class PCLRendererConfiguratorTestCase extends AbstractRendererConfiguratorTest<PCLRendererConfigurator, PCLRendererConfBuilder> { diff --git a/test/java/org/apache/fop/render/pdf/PDFAConformanceTestCase.java b/test/java/org/apache/fop/render/pdf/PDFAConformanceTestCase.java index 94c842e68..6aad0320e 100644 --- a/test/java/org/apache/fop/render/pdf/PDFAConformanceTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFAConformanceTestCase.java @@ -25,11 +25,11 @@ import java.io.IOException; import org.junit.Test; import org.xml.sax.SAXException; +import static org.junit.Assert.fail; + import org.apache.fop.apps.FOUserAgent; import org.apache.fop.pdf.PDFConformanceException; -import static org.junit.Assert.fail; - /** * Tests PDF/A-1 functionality. */ diff --git a/test/java/org/apache/fop/render/pdf/PDFAMetadataTestCase.java b/test/java/org/apache/fop/render/pdf/PDFAMetadataTestCase.java index 1606bf073..6ff40b3c3 100644 --- a/test/java/org/apache/fop/render/pdf/PDFAMetadataTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFAMetadataTestCase.java @@ -19,15 +19,14 @@ package org.apache.fop.render.pdf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - import java.util.Calendar; import java.util.TimeZone; -import org.apache.fop.pdf.PDFDocument; -import org.apache.fop.pdf.PDFInfo; -import org.apache.fop.pdf.PDFMetadata; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + import org.apache.xmlgraphics.xmp.Metadata; import org.apache.xmlgraphics.xmp.schemas.DublinCoreAdapter; import org.apache.xmlgraphics.xmp.schemas.DublinCoreSchema; @@ -35,7 +34,10 @@ import org.apache.xmlgraphics.xmp.schemas.XMPBasicAdapter; import org.apache.xmlgraphics.xmp.schemas.XMPBasicSchema; import org.apache.xmlgraphics.xmp.schemas.pdf.AdobePDFAdapter; import org.apache.xmlgraphics.xmp.schemas.pdf.AdobePDFSchema; -import org.junit.Test; + +import org.apache.fop.pdf.PDFDocument; +import org.apache.fop.pdf.PDFInfo; +import org.apache.fop.pdf.PDFMetadata; /** * Test case for PDF/A metadata handling. diff --git a/test/java/org/apache/fop/render/pdf/PDFCMapTestCase.java b/test/java/org/apache/fop/render/pdf/PDFCMapTestCase.java index fee2c07aa..bb0f2f92e 100644 --- a/test/java/org/apache/fop/render/pdf/PDFCMapTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFCMapTestCase.java @@ -19,13 +19,14 @@ package org.apache.fop.render.pdf; -import static org.junit.Assert.assertEquals; - import java.io.StringWriter; -import org.apache.fop.pdf.CMapBuilder; import org.junit.Test; +import static org.junit.Assert.assertEquals; + +import org.apache.fop.pdf.CMapBuilder; + /** Simple sanity test of the PDFCmap class */ public class PDFCMapTestCase { private static final String EOL = "\n"; @@ -60,8 +61,7 @@ public class PDFCMapTestCase { + "end" + EOL + "end" + EOL + "%%EndResource" + EOL - + "%%EOF" + EOL - ; + + "%%EOF" + EOL; final StringWriter w = new StringWriter(); final CMapBuilder builder = new CMapBuilder(w, "test"); diff --git a/test/java/org/apache/fop/render/pdf/PDFEncodingTestCase.java b/test/java/org/apache/fop/render/pdf/PDFEncodingTestCase.java index 34647818a..fc6212dcd 100644 --- a/test/java/org/apache/fop/render/pdf/PDFEncodingTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFEncodingTestCase.java @@ -19,9 +19,6 @@ package org.apache.fop.render.pdf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.File; import java.io.IOException; import java.util.StringTokenizer; @@ -30,6 +27,9 @@ import org.junit.Ignore; import org.junit.Test; import org.xml.sax.SAXException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import org.apache.fop.apps.FOUserAgent; /** Test that characters are correctly encoded in a generated PDF file */ diff --git a/test/java/org/apache/fop/render/pdf/PDFGraphicsPainterTestCase.java b/test/java/org/apache/fop/render/pdf/PDFGraphicsPainterTestCase.java index 4f3a5e628..3130a73e7 100644 --- a/test/java/org/apache/fop/render/pdf/PDFGraphicsPainterTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFGraphicsPainterTestCase.java @@ -24,12 +24,12 @@ import java.io.IOException; import org.junit.Before; import org.junit.Test; -import org.apache.fop.pdf.PDFNumber; - import static org.mockito.Matchers.endsWith; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import org.apache.fop.pdf.PDFNumber; + public class PDFGraphicsPainterTestCase { private PDFGraphicsPainter sut; diff --git a/test/java/org/apache/fop/render/pdf/PDFPainterTestCase.java b/test/java/org/apache/fop/render/pdf/PDFPainterTestCase.java index f431b3ee9..db1757847 100644 --- a/test/java/org/apache/fop/render/pdf/PDFPainterTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFPainterTestCase.java @@ -24,17 +24,17 @@ import java.awt.Rectangle; import org.junit.Test; -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.fo.Constants; -import org.apache.fop.render.intermediate.IFContext; -import org.apache.fop.traits.BorderProps; - import static org.mockito.Matchers.endsWith; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.fo.Constants; +import org.apache.fop.render.intermediate.IFContext; +import org.apache.fop.traits.BorderProps; + public class PDFPainterTestCase { @Test diff --git a/test/java/org/apache/fop/render/pdf/PDFRendererConfigParserTestCase.java b/test/java/org/apache/fop/render/pdf/PDFRendererConfigParserTestCase.java index 2d3dfb760..4dd3a6610 100644 --- a/test/java/org/apache/fop/render/pdf/PDFRendererConfigParserTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFRendererConfigParserTestCase.java @@ -21,6 +21,10 @@ package org.apache.fop.render.pdf; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.apache.fop.apps.AbstractRendererConfigParserTester; import org.apache.fop.apps.PDFRendererConfBuilder; import org.apache.fop.pdf.PDFAMode; @@ -28,10 +32,6 @@ import org.apache.fop.pdf.PDFXMode; import org.apache.fop.pdf.Version; import org.apache.fop.render.pdf.PDFRendererConfig.PDFRendererConfigParser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class PDFRendererConfigParserTestCase extends AbstractRendererConfigParserTester<PDFRendererConfBuilder, PDFRendererConfig> { diff --git a/test/java/org/apache/fop/render/pdf/PDFRendererOptionsConfigTestCase.java b/test/java/org/apache/fop/render/pdf/PDFRendererOptionsConfigTestCase.java index 489d4dc96..699a8a186 100644 --- a/test/java/org/apache/fop/render/pdf/PDFRendererOptionsConfigTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFRendererOptionsConfigTestCase.java @@ -29,6 +29,8 @@ import java.util.Map; import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.apache.fop.pdf.PDFAMode; import org.apache.fop.pdf.PDFEncryptionParams; import org.apache.fop.pdf.PDFXMode; @@ -40,7 +42,6 @@ import static org.apache.fop.render.pdf.PDFRendererOption.OUTPUT_PROFILE; import static org.apache.fop.render.pdf.PDFRendererOption.PDF_A_MODE; import static org.apache.fop.render.pdf.PDFRendererOption.PDF_X_MODE; import static org.apache.fop.render.pdf.PDFRendererOption.VERSION; -import static org.junit.Assert.assertEquals; public class PDFRendererOptionsConfigTestCase { @@ -51,7 +52,7 @@ public class PDFRendererOptionsConfigTestCase { static { final EnumMap<PDFRendererOption, Object> props = new EnumMap<PDFRendererOption, Object>(PDFRendererOption.class); - for(PDFRendererOption option : PDFRendererOption.values()) { + for (PDFRendererOption option : PDFRendererOption.values()) { props.put(option, option.getDefaultValue()); } DEFAULT_OPTIONS = Collections.unmodifiableMap(props); @@ -102,7 +103,7 @@ public class PDFRendererOptionsConfigTestCase { assertEncryptionParamsEquals(expectedEncryptionParams, actual.getEncryptionParameters()); } - private static void assertEncryptionParamsEquals(PDFEncryptionParams expected, + private static void assertEncryptionParamsEquals(PDFEncryptionParams expected, PDFEncryptionParams actual) { assertEquals(expected == null, actual == null); if (actual != null) { diff --git a/test/java/org/apache/fop/render/pdf/PDFsRGBSettingsTestCase.java b/test/java/org/apache/fop/render/pdf/PDFsRGBSettingsTestCase.java index d084aa618..965a8e30e 100644 --- a/test/java/org/apache/fop/render/pdf/PDFsRGBSettingsTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFsRGBSettingsTestCase.java @@ -19,14 +19,14 @@ package org.apache.fop.render.pdf; -import static org.junit.Assert.fail; - import java.io.File; import java.io.IOException; import org.junit.Test; import org.xml.sax.SAXException; +import static org.junit.Assert.fail; + import org.apache.fop.apps.FOUserAgent; /** diff --git a/test/java/org/apache/fop/render/pdf/RenderPDFTestSuite.java b/test/java/org/apache/fop/render/pdf/RenderPDFTestSuite.java index f41520bf3..e74251be1 100644 --- a/test/java/org/apache/fop/render/pdf/RenderPDFTestSuite.java +++ b/test/java/org/apache/fop/render/pdf/RenderPDFTestSuite.java @@ -28,8 +28,6 @@ import org.junit.runners.Suite.SuiteClasses; * A test suite for org.apache.fop.render.pdf.* */ @RunWith(Suite.class) -@SuiteClasses({ - PDFRendererConfigParserTestCase.class -}) +@SuiteClasses(PDFRendererConfigParserTestCase.class) public final class RenderPDFTestSuite { } diff --git a/test/java/org/apache/fop/render/ps/AbstractPostScriptTest.java b/test/java/org/apache/fop/render/ps/AbstractPostScriptTest.java index dcbc2d757..eb25c3f94 100644 --- a/test/java/org/apache/fop/render/ps/AbstractPostScriptTest.java +++ b/test/java/org/apache/fop/render/ps/AbstractPostScriptTest.java @@ -19,11 +19,11 @@ package org.apache.fop.render.ps; -import static org.junit.Assert.assertEquals; - import java.io.File; import java.io.IOException; +import static org.junit.Assert.assertEquals; + import org.apache.xmlgraphics.ps.PSResource; import org.apache.xmlgraphics.ps.dsc.DSCException; import org.apache.xmlgraphics.ps.dsc.DSCParser; diff --git a/test/java/org/apache/fop/render/ps/ImageEncoderPNGTestCase.java b/test/java/org/apache/fop/render/ps/ImageEncoderPNGTestCase.java index 458033dad..53654d76a 100644 --- a/test/java/org/apache/fop/render/ps/ImageEncoderPNGTestCase.java +++ b/test/java/org/apache/fop/render/ps/ImageEncoderPNGTestCase.java @@ -27,17 +27,16 @@ import java.io.IOException; import org.junit.Test; -import org.apache.xmlgraphics.image.loader.ImageSize; -import org.apache.xmlgraphics.image.loader.impl.ImageRawPNG; - -import org.apache.fop.render.RawPNGTestUtil; - import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import org.apache.xmlgraphics.image.loader.ImageSize; +import org.apache.xmlgraphics.image.loader.impl.ImageRawPNG; + +import org.apache.fop.render.RawPNGTestUtil; + public class ImageEncoderPNGTestCase { @Test diff --git a/test/java/org/apache/fop/render/ps/ImageHandlingTestCase.java b/test/java/org/apache/fop/render/ps/ImageHandlingTestCase.java index ba0598b52..02e96806f 100644 --- a/test/java/org/apache/fop/render/ps/ImageHandlingTestCase.java +++ b/test/java/org/apache/fop/render/ps/ImageHandlingTestCase.java @@ -18,15 +18,15 @@ /* $Id$ */ package org.apache.fop.render.ps; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.File; import java.io.IOException; import java.io.InputStream; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import org.apache.commons.io.IOUtils; import org.apache.xmlgraphics.ps.DSCConstants; diff --git a/test/java/org/apache/fop/render/ps/PSPainterTestCase.java b/test/java/org/apache/fop/render/ps/PSPainterTestCase.java index 79e5bd9b6..b678fdb4b 100644 --- a/test/java/org/apache/fop/render/ps/PSPainterTestCase.java +++ b/test/java/org/apache/fop/render/ps/PSPainterTestCase.java @@ -146,11 +146,11 @@ public class PSPainterTestCase { int y = 100000; int letterSpacing = 0; int wordSpacing = 0; - int dp[][] = {{100, 100, 0, 0}, null, null, {200, 200, -100, -100}}; - double X = (x + dp[0][0]) / 1000.0; - double Y = (y - dp[0][1]) / 1000.0; - when(psGenerator.formatDouble(X)).thenReturn("100.100"); - when(psGenerator.formatDouble(Y)).thenReturn("99.900"); + int[][] dp = {{100, 100, 0, 0}, null, null, {200, 200, -100, -100}}; + double xAsDouble = (x + dp[0][0]) / 1000.0; + double yAsDouble = (y - dp[0][1]) / 1000.0; + when(psGenerator.formatDouble(xAsDouble)).thenReturn("100.100"); + when(psGenerator.formatDouble(yAsDouble)).thenReturn("99.900"); String text = "Hello Mock!"; try { psPainter.drawText(x, y, letterSpacing, wordSpacing, dp, text); diff --git a/test/java/org/apache/fop/render/ps/PSRendererConfigParserTestCase.java b/test/java/org/apache/fop/render/ps/PSRendererConfigParserTestCase.java index fe59143b4..45642764c 100644 --- a/test/java/org/apache/fop/render/ps/PSRendererConfigParserTestCase.java +++ b/test/java/org/apache/fop/render/ps/PSRendererConfigParserTestCase.java @@ -21,14 +21,14 @@ package org.apache.fop.render.ps; import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.apache.xmlgraphics.ps.PSGenerator; import org.apache.fop.apps.AbstractRendererConfigParserTester; import org.apache.fop.apps.PSRendererConfBuilder; import org.apache.fop.render.ps.PSRendererConfig.PSRendererConfigParser; -import static org.junit.Assert.assertEquals; - public class PSRendererConfigParserTestCase extends AbstractRendererConfigParserTester<PSRendererConfBuilder, PSRendererConfig> { diff --git a/test/java/org/apache/fop/render/ps/PSRendererConfiguratorTestCase.java b/test/java/org/apache/fop/render/ps/PSRendererConfiguratorTestCase.java index 4d42a0aab..67ba24763 100644 --- a/test/java/org/apache/fop/render/ps/PSRendererConfiguratorTestCase.java +++ b/test/java/org/apache/fop/render/ps/PSRendererConfiguratorTestCase.java @@ -19,16 +19,16 @@ package org.apache.fop.render.ps; import org.junit.Test; -import org.apache.fop.apps.AbstractRendererConfiguratorTest; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.apps.PSRendererConfBuilder; -import org.apache.fop.render.ps.PSRendererConfig.PSRendererConfigParser; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; +import org.apache.fop.apps.AbstractRendererConfiguratorTest; +import org.apache.fop.apps.MimeConstants; +import org.apache.fop.apps.PSRendererConfBuilder; +import org.apache.fop.render.ps.PSRendererConfig.PSRendererConfigParser; + public class PSRendererConfiguratorTestCase extends AbstractRendererConfiguratorTest<PSRendererConfigurator, PSRendererConfBuilder> { private PSRenderingUtil psUtil; diff --git a/test/java/org/apache/fop/render/ps/PSRenderingUtilTestCase.java b/test/java/org/apache/fop/render/ps/PSRenderingUtilTestCase.java index 3f1088fe1..0a2c895be 100644 --- a/test/java/org/apache/fop/render/ps/PSRenderingUtilTestCase.java +++ b/test/java/org/apache/fop/render/ps/PSRenderingUtilTestCase.java @@ -23,13 +23,13 @@ import java.io.IOException; import org.junit.Test; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import org.apache.xmlgraphics.ps.PSGenerator; import org.apache.fop.render.ps.extensions.PSPageTrailerCodeBefore; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - public class PSRenderingUtilTestCase { private final String content = "<< /MyEntry 0 >> command"; diff --git a/test/java/org/apache/fop/render/ps/ResourceOptimizationTestCase.java b/test/java/org/apache/fop/render/ps/ResourceOptimizationTestCase.java index bfdb5f968..4f06938d2 100644 --- a/test/java/org/apache/fop/render/ps/ResourceOptimizationTestCase.java +++ b/test/java/org/apache/fop/render/ps/ResourceOptimizationTestCase.java @@ -19,11 +19,6 @@ package org.apache.fop.render.ps; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -33,6 +28,11 @@ import java.util.Set; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import org.apache.commons.io.IOUtils; import org.apache.xmlgraphics.ps.DSCConstants; diff --git a/test/java/org/apache/fop/render/ps/svg/PSSVGGraphics2DTestCase.java b/test/java/org/apache/fop/render/ps/svg/PSSVGGraphics2DTestCase.java new file mode 100644 index 000000000..29a3a7bd3 --- /dev/null +++ b/test/java/org/apache/fop/render/ps/svg/PSSVGGraphics2DTestCase.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.ps.svg; + +import java.awt.Color; +import java.awt.geom.AffineTransform; +import java.awt.geom.Rectangle2D; +import java.awt.geom.Rectangle2D.Float; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +import org.apache.commons.io.FileUtils; + +import org.apache.batik.ext.awt.RadialGradientPaint; + +import org.apache.xmlgraphics.java2d.GraphicContext; +import org.apache.xmlgraphics.ps.PSGenerator; + +public class PSSVGGraphics2DTestCase { + + float cx = 841.891f; + float cy = 178.583f; + float r = 16.4331f; + float[] fractions = {0.2f, 0.6012f, 0.8094f, 1.0f}; + + /** + * Tests a radial gradient generated pattern with certain inputs against + * an expected output. + * @throws IOException + */ + @Test + public void testApplyPaint() throws IOException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PSGenerator gen = new PSGenerator(os); + PSSVGGraphics2D svgGraphics2D = new PSSVGGraphics2D(false, gen); + svgGraphics2D.setGraphicContext(new GraphicContext()); + svgGraphics2D.setTransform(new AffineTransform()); + Color[] colors = {new Color(255, 255, 255), new Color(200, 200, 200), + new Color(170, 170, 170), new Color(140, 140, 140)}; + RadialGradientPaint paint = new RadialGradientPaint(cx, cy, r, fractions, colors); + Float s = new Rectangle2D.Float(7.0f, 3.0f, 841.891f, 178.583f); + svgGraphics2D.applyPaint(paint, true); + byte[] test = os.toByteArray(); + + byte[] expected = FileUtils.readFileToByteArray( + new File("test/java/org/apache/fop/render/ps/svg/expected.ps")); + assertEquals(new String(test), new String(expected)); + } +} diff --git a/test/java/org/apache/fop/render/ps/svg/PSSVGLinearGraphics2DTestCase.java b/test/java/org/apache/fop/render/ps/svg/PSSVGLinearGraphics2DTestCase.java new file mode 100644 index 000000000..3a6db4396 --- /dev/null +++ b/test/java/org/apache/fop/render/ps/svg/PSSVGLinearGraphics2DTestCase.java @@ -0,0 +1,70 @@ + /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.ps.svg; + +import java.awt.Color; +import java.awt.geom.AffineTransform; +import java.awt.geom.Rectangle2D; +import java.awt.geom.Rectangle2D.Float; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +import org.apache.commons.io.FileUtils; + +import org.apache.batik.ext.awt.LinearGradientPaint; + +import org.apache.xmlgraphics.java2d.GraphicContext; +import org.apache.xmlgraphics.ps.PSGenerator; + +public class PSSVGLinearGraphics2DTestCase { + float startX = 115f; + float endX = 15f; + float startY = 285f; + float endY = 15f; + float[] fractions = {0.0f, 1.0f}; + + /** + * Tests a linear gradient generated pattern with certain inputs against + * an expected output. + * @throws IOException + */ + @Test + public void testApplyPaint() throws IOException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PSGenerator gen = new PSGenerator(os); + PSSVGGraphics2D svgGraphics2D = new PSSVGGraphics2D(false, gen); + svgGraphics2D.setGraphicContext(new GraphicContext()); + svgGraphics2D.setTransform(new AffineTransform()); + Color[] colors = {new Color(255, 255, 0), new Color(255, 0, 0)}; + LinearGradientPaint paint = new LinearGradientPaint(startX, startY, endX, endY, fractions, colors); + Float s = new Rectangle2D.Float(115.0f, 15.0f, 170f, 110f); + svgGraphics2D.applyPaint(paint, true); + byte[] test = os.toByteArray(); + + byte[] expected = FileUtils.readFileToByteArray( + new File("test/java/org/apache/fop/render/ps/svg/axial-shading-expected.dat")); + assertEquals(new String(test), new String(expected)); + } +} diff --git a/test/java/org/apache/fop/render/ps/svg/axial-shading-expected.dat b/test/java/org/apache/fop/render/ps/svg/axial-shading-expected.dat new file mode 100644 index 000000000..fdf92cda5 --- /dev/null +++ b/test/java/org/apache/fop/render/ps/svg/axial-shading-expected.dat @@ -0,0 +1,26 @@ +/Pattern setcolorspace +<< +/Type /Pattern +/PatternType 2 +/Shading << +/ShadingType 2 +/ColorSpace /DeviceRGB + /Coords [ 115 285 15 15 ] + /Domain [ 0 1 ] + /Extend [ true true ] + /Function << +/FunctionType 3 +/Domain [ 0 1 ] +/Functions [ << +/FunctionType 2 +/Domain [ 0 1 ] +/C0 [ 1 1 0 ] +/C1 [ 1 0 0 ] +/N 1 +>> ] +/Encode [ 0 1 ] +/Bounds [ ] +>> +>> +>> +matrix makepattern setcolor diff --git a/test/java/org/apache/fop/render/ps/svg/expected.ps b/test/java/org/apache/fop/render/ps/svg/expected.ps new file mode 100644 index 000000000..9977070c3 --- /dev/null +++ b/test/java/org/apache/fop/render/ps/svg/expected.ps @@ -0,0 +1,38 @@ +/Pattern setcolorspace +<< +/Type /Pattern +/PatternType 2 +/Shading << +/ShadingType 3 +/ColorSpace /DeviceRGB + /Coords [ 841.890991 178.582993 3.28662 841.890991 178.582993 16.4331 ] + /Domain [ 0 1 ] + /Extend [ true true ] + /Function << +/FunctionType 3 +/Domain [ 0 1 ] +/Functions [ << +/FunctionType 2 +/Domain [ 0 1 ] +/C0 [ 1 1 1 ] +/C1 [ 0.784314 0.784314 0.784314 ] +/N 1 +>> << +/FunctionType 2 +/Domain [ 0 1 ] +/C0 [ 0.784314 0.784314 0.784314 ] +/C1 [ 0.666667 0.666667 0.666667 ] +/N 1 +>> << +/FunctionType 2 +/Domain [ 0 1 ] +/C0 [ 0.666667 0.666667 0.666667 ] +/C1 [ 0.54902 0.54902 0.54902 ] +/N 1 +>> ] +/Encode [ 0 1 0 1 0 1 ] +/Bounds [ 0.6012 0.8094 ] +>> +>> +>> +matrix makepattern setcolor diff --git a/test/java/org/apache/fop/render/rtf/Bug39607TestCase.java b/test/java/org/apache/fop/render/rtf/Bug39607TestCase.java index c5821fff1..4c3c8446e 100644 --- a/test/java/org/apache/fop/render/rtf/Bug39607TestCase.java +++ b/test/java/org/apache/fop/render/rtf/Bug39607TestCase.java @@ -21,13 +21,14 @@ package org.apache.fop.render.rtf; import java.io.StringWriter; +import org.junit.Test; + import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfFile; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; -import org.junit.Test; /** * Test for http://issues.apache.org/bugzilla/show_bug.cgi?id=39607 diff --git a/test/java/org/apache/fop/render/rtf/RichTextFormatTestSuite.java b/test/java/org/apache/fop/render/rtf/RichTextFormatTestSuite.java index d8296fc33..5b294bd9b 100644 --- a/test/java/org/apache/fop/render/rtf/RichTextFormatTestSuite.java +++ b/test/java/org/apache/fop/render/rtf/RichTextFormatTestSuite.java @@ -27,6 +27,6 @@ import org.junit.runners.Suite.SuiteClasses; * Test suite for FOP's RTF library. */ @RunWith(Suite.class) -@SuiteClasses({ Bug39607TestCase.class }) +@SuiteClasses(Bug39607TestCase.class) public class RichTextFormatTestSuite { } diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/BasicLink.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/BasicLink.java index 07085059d..9df1c26ef 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/BasicLink.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/BasicLink.java @@ -27,17 +27,15 @@ package org.apache.fop.render.rtf.rtflib.testdocs; +import java.io.IOException; + import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfHyperLink; - -import java.io.IOException; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; /** * Class <code>BasicLink</code> here. - * - * @author <a href="mailto:mks@ANDREAS">Andreas Putz</a> */ public class BasicLink extends TestDocument { diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/CreateTestDocuments.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/CreateTestDocuments.java index 16460cd1c..7f17514ef 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/CreateTestDocuments.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/CreateTestDocuments.java @@ -29,11 +29,8 @@ package org.apache.fop.render.rtf.rtflib.testdocs; import java.io.File; import java.io.IOException; -//import org.apache.fop.render.rtf.rtflib.jfor.main.JForVersionInfo; /** Create test RTF documents from classes found in this package. - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch - * @author Andreas Putz a.putz@skynamics.com */ public class CreateTestDocuments { diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/DummyTableColumnsInfo.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/DummyTableColumnsInfo.java index 3329b26b9..1af4c7bed 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/DummyTableColumnsInfo.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/DummyTableColumnsInfo.java @@ -33,8 +33,6 @@ import org.apache.fop.render.rtf.rtflib.rtfdoc.ITableColumnsInfo; * to create documents without worrying about nested tables handling. * Might need to be replaced by more complete version in some sample * documents created by this package. - * - * @author bdelacretaz@codeconsult.ch */ class DummyTableColumnsInfo implements ITableColumnsInfo { diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ExternalGraphic.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ExternalGraphic.java index b957bc1fa..1127f3e72 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ExternalGraphic.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ExternalGraphic.java @@ -27,16 +27,14 @@ package org.apache.fop.render.rtf.rtflib.testdocs; +import java.io.IOException; + import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfExternalGraphic; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; - -import java.io.IOException; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; /** * Generate a test document containing external graphics. - * - * @author <a href="mailto:a.putz@skynamics.com">Andreas Putz</a> */ class ExternalGraphic extends TestDocument { private String file = "file:///tmp/jfor-images/logo."; diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ListInTable.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ListInTable.java index 3ce05c606..6f4e27a59 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ListInTable.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ListInTable.java @@ -30,13 +30,13 @@ package org.apache.fop.render.rtf.rtflib.testdocs; import java.io.IOException; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfList; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableCell; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListItem; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableCell; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; /** Generates a simple RTF test document for the jfor rtflib package. */ diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/MergedTableCells.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/MergedTableCells.java index f1817bf03..9be5e899a 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/MergedTableCells.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/MergedTableCells.java @@ -32,11 +32,10 @@ import java.io.IOException; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableCell; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; /** Generates an RTF test document containing merged table cells - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch */ class MergedTableCells extends TestDocument { diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/NestedTable.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/NestedTable.java index 72dad7e98..c11fbc334 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/NestedTable.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/NestedTable.java @@ -30,14 +30,13 @@ package org.apache.fop.render.rtf.rtflib.testdocs; import java.io.IOException; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableCell; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; /** Generates an RTF document to test nested tables with the jfor rtflib package. - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch */ class NestedTable extends TestDocument { diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ParagraphAlignment.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ParagraphAlignment.java index 2b38aa789..edce3264a 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ParagraphAlignment.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/ParagraphAlignment.java @@ -27,14 +27,13 @@ package org.apache.fop.render.rtf.rtflib.testdocs; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfAttributes; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfText; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfAttributes; /** Generates a simple RTF test document for the jfor rtflib package. - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch */ public class ParagraphAlignment extends TestDocument { diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleDocument.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleDocument.java index 2ca16c0e5..ca6ce79bc 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleDocument.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleDocument.java @@ -30,11 +30,10 @@ package org.apache.fop.render.rtf.rtflib.testdocs; import java.io.IOException; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; /** Generates a simple RTF test document for the jfor rtflib package. - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch */ class SimpleDocument diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleLists.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleLists.java index eff3aa7ff..e817f6a13 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleLists.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleLists.java @@ -30,15 +30,14 @@ package org.apache.fop.render.rtf.rtflib.testdocs; import java.io.IOException; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfList; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListItem; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListStyle; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListStyleNumber; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; /** Generates a simple RTF test document for the jfor rtflib package. - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch */ class SimpleLists extends TestDocument { diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleTable.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleTable.java index cf84b3ec4..10ddc11e7 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleTable.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/SimpleTable.java @@ -32,11 +32,10 @@ import java.io.IOException; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableCell; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; /** Generates a simple RTF test document for the jfor rtflib package. - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch */ class SimpleTable extends TestDocument { /** generate the body of the test document */ diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/TestDocument.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/TestDocument.java index 5274dc32e..266903766 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/TestDocument.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/TestDocument.java @@ -27,19 +27,17 @@ package org.apache.fop.render.rtf.rtflib.testdocs; -import java.util.Date; import java.io.File; -import java.io.IOException; import java.io.FileWriter; +import java.io.IOException; +import java.util.Date; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfFile; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; -//import org.apache.fop.render.rtf.rtflib.jfor.main.JForVersionInfo; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; /** Base class for generating RTF documents used to test the jfor rtflib package. - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch */ abstract class TestDocument { diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/TextAttributes.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/TextAttributes.java index 4ab48acb0..bb0614cee 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/TextAttributes.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/TextAttributes.java @@ -29,14 +29,13 @@ package org.apache.fop.render.rtf.rtflib.testdocs; import java.io.IOException; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfAttributes; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfText; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfAttributes; /** Generates a simple RTF test document for the jfor rtflib package. - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch */ class TextAttributes extends TestDocument { diff --git a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/Whitespace.java b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/Whitespace.java index 4359822f6..a206e014f 100644 --- a/test/java/org/apache/fop/render/rtf/rtflib/testdocs/Whitespace.java +++ b/test/java/org/apache/fop/render/rtf/rtflib/testdocs/Whitespace.java @@ -30,11 +30,10 @@ package org.apache.fop.render.rtf.rtflib.testdocs; import java.io.IOException; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; -import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfParagraph; +import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; /** Generates an RTF document to test the WhitespaceCollapser - * @author Bertrand Delacretaz bdelacretaz@codeconsult.ch */ class Whitespace extends TestDocument { diff --git a/test/java/org/apache/fop/render/txt/TxtRendererConfigParserTestCase.java b/test/java/org/apache/fop/render/txt/TxtRendererConfigParserTestCase.java index a7ae52c65..30fed05ea 100644 --- a/test/java/org/apache/fop/render/txt/TxtRendererConfigParserTestCase.java +++ b/test/java/org/apache/fop/render/txt/TxtRendererConfigParserTestCase.java @@ -21,13 +21,12 @@ package org.apache.fop.render.txt; import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.apache.fop.apps.AbstractRendererConfigParserTester; import org.apache.fop.apps.TxtRendererConfBuilder; -import org.apache.fop.render.RendererConfig.RendererConfigParser; -import org.apache.fop.render.txt.TxtRendererConfig.TxtRendererOption; import org.apache.fop.render.txt.TxtRendererConfig.TxtRendererConfigParser; - -import static org.junit.Assert.assertEquals; +import org.apache.fop.render.txt.TxtRendererConfig.TxtRendererOption; public class TxtRendererConfigParserTestCase extends AbstractRendererConfigParserTester<TxtRendererConfBuilder, TxtRendererConfig> { diff --git a/test/java/org/apache/fop/text/linebreak/LineBreakStatusTestCase.java b/test/java/org/apache/fop/text/linebreak/LineBreakStatusTestCase.java index 42ca8dee6..d8813c3bc 100644 --- a/test/java/org/apache/fop/text/linebreak/LineBreakStatusTestCase.java +++ b/test/java/org/apache/fop/text/linebreak/LineBreakStatusTestCase.java @@ -19,10 +19,10 @@ package org.apache.fop.text.linebreak; -import static org.junit.Assert.assertTrue; - import org.junit.Test; +import static org.junit.Assert.assertTrue; + /** * JUnit test case for the LineBreakStatus class diff --git a/test/java/org/apache/fop/text/linebreak/LineBreakUtilsTestCase.java b/test/java/org/apache/fop/text/linebreak/LineBreakUtilsTestCase.java index 015c1846f..5fc5c7d50 100644 --- a/test/java/org/apache/fop/text/linebreak/LineBreakUtilsTestCase.java +++ b/test/java/org/apache/fop/text/linebreak/LineBreakUtilsTestCase.java @@ -19,10 +19,10 @@ package org.apache.fop.text.linebreak; -import static org.junit.Assert.assertEquals; - import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** * TODO add javadoc * diff --git a/test/java/org/apache/fop/threading/FOProcessorImpl.java b/test/java/org/apache/fop/threading/FOProcessorImpl.java index 04fed19ba..721830aee 100644 --- a/test/java/org/apache/fop/threading/FOProcessorImpl.java +++ b/test/java/org/apache/fop/threading/FOProcessorImpl.java @@ -81,8 +81,8 @@ public class FOProcessorImpl extends AbstractLogEnabled } } - /** {@inheritDoc} - * @throws URISyntaxException + /** {@inheritDoc} + * @throws URISyntaxException * @throws SAXException */ public void process(Source src, Templates templates, OutputStream out) throws java.io.IOException, URISyntaxException, SAXException { diff --git a/test/java/org/apache/fop/threading/Main.java b/test/java/org/apache/fop/threading/Main.java index 7ff0cec4f..d18ae405a 100644 --- a/test/java/org/apache/fop/threading/Main.java +++ b/test/java/org/apache/fop/threading/Main.java @@ -32,7 +32,10 @@ import org.apache.avalon.framework.logger.ConsoleLogger; /** * Starter class for the multi-threading testbed. */ -public class Main { +public final class Main { + + private Main() { + } private static void prompt() throws IOException { BufferedReader in = new BufferedReader(new java.io.InputStreamReader(System.in)); diff --git a/test/java/org/apache/fop/traits/BorderPropsTestCase.java b/test/java/org/apache/fop/traits/BorderPropsTestCase.java index ec93d708e..692e3059f 100644 --- a/test/java/org/apache/fop/traits/BorderPropsTestCase.java +++ b/test/java/org/apache/fop/traits/BorderPropsTestCase.java @@ -23,14 +23,14 @@ import java.awt.Color; import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.apache.xmlgraphics.java2d.color.ColorWithAlternatives; import org.apache.xmlgraphics.java2d.color.DeviceCMYKColorSpace; import org.apache.fop.fo.Constants; import org.apache.fop.util.ColorUtil; -import static org.junit.Assert.assertEquals; - /** * Tests the BorderProps class. */ @@ -67,7 +67,7 @@ public class BorderPropsTestCase { Color col = new Color(1.0f, 1.0f, 0.5f, 1.0f); //Normalize: Avoid false alarms due to color conversion (rounding) col = ColorUtil.parseColorString(null, ColorUtil.colorToString(col)); - for(BorderProps.Mode mode : BorderProps.Mode.values()) { + for (BorderProps.Mode mode : BorderProps.Mode.values()) { BorderProps sut = BorderProps.makeRectangular(Constants.EN_SOLID, 10, col, mode); testSerialization(sut); sut = new BorderProps(Constants.EN_SOLID, 10, 4, 3, col, mode); diff --git a/test/java/org/apache/fop/traits/MinOptMaxTestCase.java b/test/java/org/apache/fop/traits/MinOptMaxTestCase.java index 73465fdcc..ba6862785 100644 --- a/test/java/org/apache/fop/traits/MinOptMaxTestCase.java +++ b/test/java/org/apache/fop/traits/MinOptMaxTestCase.java @@ -19,13 +19,13 @@ package org.apache.fop.traits; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import org.junit.Test; - /** * Tests the {@link MinOptMax} class. */ diff --git a/test/java/org/apache/fop/util/AdvancedMessageFormatTestCase.java b/test/java/org/apache/fop/util/AdvancedMessageFormatTestCase.java index c4b9446ac..5e75f2563 100644 --- a/test/java/org/apache/fop/util/AdvancedMessageFormatTestCase.java +++ b/test/java/org/apache/fop/util/AdvancedMessageFormatTestCase.java @@ -19,15 +19,16 @@ package org.apache.fop.util; -import static org.junit.Assert.assertEquals; - import java.util.Map; -import org.apache.fop.events.model.EventSeverity; -import org.apache.fop.util.text.AdvancedMessageFormat; import org.junit.Test; import org.xml.sax.helpers.LocatorImpl; +import static org.junit.Assert.assertEquals; + +import org.apache.fop.events.model.EventSeverity; +import org.apache.fop.util.text.AdvancedMessageFormat; + /** * Tests for EventFormatter. */ diff --git a/test/java/org/apache/fop/util/BitmapImageUtilTestCase.java b/test/java/org/apache/fop/util/BitmapImageUtilTestCase.java index 3afcc3a2e..8bda99785 100644 --- a/test/java/org/apache/fop/util/BitmapImageUtilTestCase.java +++ b/test/java/org/apache/fop/util/BitmapImageUtilTestCase.java @@ -19,8 +19,6 @@ package org.apache.fop.util; -import static org.junit.Assert.assertEquals; - import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; @@ -31,13 +29,18 @@ import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + import org.apache.commons.io.IOUtils; -import org.apache.fop.util.bitmap.BitmapImageUtil; -import org.apache.fop.util.bitmap.MonochromeBitmapConverter; + import org.apache.xmlgraphics.image.writer.ImageWriterUtil; import org.apache.xmlgraphics.util.WriterOutputStream; import org.apache.xmlgraphics.util.io.ASCIIHexOutputStream; -import org.junit.Test; + +import org.apache.fop.util.bitmap.BitmapImageUtil; +import org.apache.fop.util.bitmap.MonochromeBitmapConverter; /** * Tests {@link BitmapImageUtil}. diff --git a/test/java/org/apache/fop/util/ColorUtilTestCase.java b/test/java/org/apache/fop/util/ColorUtilTestCase.java index 6e65004a3..c86ebbeac 100644 --- a/test/java/org/apache/fop/util/ColorUtilTestCase.java +++ b/test/java/org/apache/fop/util/ColorUtilTestCase.java @@ -26,6 +26,11 @@ import java.net.URI; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import org.apache.xmlgraphics.java2d.color.ColorSpaces; import org.apache.xmlgraphics.java2d.color.ColorWithAlternatives; import org.apache.xmlgraphics.java2d.color.NamedColorSpace; @@ -34,11 +39,6 @@ import org.apache.xmlgraphics.java2d.color.RenderingIntent; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.FopFactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - /** * Tests the ColorUtil class. */ diff --git a/test/java/org/apache/fop/util/DigestFilter.java b/test/java/org/apache/fop/util/DigestFilter.java index 94e8d67d2..9e62fdc1c 100644 --- a/test/java/org/apache/fop/util/DigestFilter.java +++ b/test/java/org/apache/fop/util/DigestFilter.java @@ -95,9 +95,6 @@ public class DigestFilter extends XMLFilterImpl { super.endDocument(); } - /* (non-Javadoc) - * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) - */ public void startElement( String url, String localName, diff --git a/test/java/org/apache/fop/util/ElementListUtilsTestCase.java b/test/java/org/apache/fop/util/ElementListUtilsTestCase.java index 342488a93..5e4f38b0b 100644 --- a/test/java/org/apache/fop/util/ElementListUtilsTestCase.java +++ b/test/java/org/apache/fop/util/ElementListUtilsTestCase.java @@ -19,17 +19,18 @@ package org.apache.fop.util; +import java.util.LinkedList; + +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import java.util.LinkedList; - import org.apache.fop.layoutmgr.ElementListUtils; import org.apache.fop.layoutmgr.KnuthBox; import org.apache.fop.layoutmgr.KnuthElement; import org.apache.fop.layoutmgr.KnuthGlue; import org.apache.fop.layoutmgr.KnuthPenalty; -import org.junit.Test; /** * Test class for ElementListUtils. diff --git a/test/java/org/apache/fop/util/LanguageTagsTestCase.java b/test/java/org/apache/fop/util/LanguageTagsTestCase.java index f7383c720..91861dcc6 100644 --- a/test/java/org/apache/fop/util/LanguageTagsTestCase.java +++ b/test/java/org/apache/fop/util/LanguageTagsTestCase.java @@ -19,12 +19,12 @@ package org.apache.fop.util; -import static org.junit.Assert.assertEquals; - import java.util.Locale; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** * Tests {@link LanguageTags}. */ diff --git a/test/java/org/apache/fop/util/XMLResourceBundleTestCase.java b/test/java/org/apache/fop/util/XMLResourceBundleTestCase.java index 26cfa4406..60aa16d83 100644 --- a/test/java/org/apache/fop/util/XMLResourceBundleTestCase.java +++ b/test/java/org/apache/fop/util/XMLResourceBundleTestCase.java @@ -19,15 +19,15 @@ package org.apache.fop.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + /** * Tests for XMLResourceBundle. */ diff --git a/test/java/org/apache/fop/visual/BitmapComparator.java b/test/java/org/apache/fop/visual/BitmapComparator.java index e0c1d5bd4..f2157176b 100644 --- a/test/java/org/apache/fop/visual/BitmapComparator.java +++ b/test/java/org/apache/fop/visual/BitmapComparator.java @@ -30,11 +30,12 @@ import java.io.IOException; import java.io.InputStream; import java.net.URL; +import org.apache.commons.io.IOUtils; + import org.apache.batik.ext.awt.image.GraphicsUtil; import org.apache.batik.ext.awt.image.renderable.Filter; import org.apache.batik.ext.awt.image.spi.ImageTagRegistry; import org.apache.batik.util.ParsedURL; -import org.apache.commons.io.IOUtils; /** * Helper class to visually compare two bitmap images. @@ -45,7 +46,11 @@ import org.apache.commons.io.IOUtils; * <p> * TODO Move as utility class to XML Graphics Commons when possible */ -public class BitmapComparator { +public final class BitmapComparator { + + + private BitmapComparator() { + } /** * Builds a new BufferedImage that is the difference between the two input images @@ -79,15 +84,14 @@ public class BitmapComparator { int w = ref.getWidth(); int h = ref.getHeight(); - int y, i, val; int [] refPix = null; int [] genPix = null; - for (y = 0; y < h; y++) { - refPix = refWR.getPixels (0, y, w, 1, refPix); - genPix = genWR.getPixels (0, y, w, 1, genPix); - for (i = 0; i < refPix.length; i++) { + for (int y = 0; y < h; y++) { + refPix = refWR.getPixels(0, y, w, 1, refPix); + genPix = genWR.getPixels(0, y, w, 1, genPix); + for (int i = 0; i < refPix.length; i++) { // val = ((genPix[i] - refPix[i]) * 5) + 128; - val = ((refPix[i] - genPix[i]) * 10) + 128; + int val = ((refPix[i] - genPix[i]) * 10) + 128; if ((val & 0xFFFFFF00) != 0) { if ((val & 0x80000000) != 0) { val = 0; diff --git a/test/java/org/apache/fop/visual/ConvertUtils.java b/test/java/org/apache/fop/visual/ConvertUtils.java index e83322f90..aa4dadf47 100644 --- a/test/java/org/apache/fop/visual/ConvertUtils.java +++ b/test/java/org/apache/fop/visual/ConvertUtils.java @@ -27,7 +27,10 @@ import org.apache.commons.logging.Log; /** * Utilities for converting files with external converters. */ -public class ConvertUtils { +public final class ConvertUtils { + + private ConvertUtils() { + } /** * Calls an external converter application (GhostScript, for example). diff --git a/test/layoutengine/standard-testcases/footnote_jira1749.xml b/test/layoutengine/standard-testcases/footnote_jira1749.xml new file mode 100644 index 000000000..6e73d39fd --- /dev/null +++ b/test/layoutengine/standard-testcases/footnote_jira1749.xml @@ -0,0 +1,56 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!-- $Id$ --> +<testcase> + <info> + <p> + FOP-1749: footnotes with margin-top="..." that do not fit on the current + page, but would've fit without top margin cause FOP to hang (instead of + being pushed to the next page). Also, verify the top-offset for the + footnote is calculated properly with margin-top. + </p> + </info> + <fo> + <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> + <fo:layout-master-set> + <fo:simple-page-master page-height="50pt" page-width="240pt" master-name="Body"> + <fo:region-body/> + </fo:simple-page-master> + </fo:layout-master-set> + <fo:page-sequence master-reference="Body"> + <fo:flow flow-name="xsl-region-body" font-size="10pt"> + <fo:block>No footnote</fo:block> + <fo:block>Footnote call<fo:footnote> + <fo:inline>*</fo:inline> + <fo:footnote-body> + <fo:block margin-top="20pt">The footnote</fo:block> + </fo:footnote-body> + </fo:footnote> + </fo:block> + </fo:flow> + </fo:page-sequence> + </fo:root> + </fo> + <checks> + <!-- The block with footnote reference is on page 2 --> + <eval expected="Footnote call" xpath="//pageViewport[2]//mainReference//text"/> + <eval expected="The footnote" xpath="//pageViewport[2]//footnote//text"/> + <!-- And footnote's top-offset positions it on the page, not below --> + <eval expected="18000" xpath="//pageViewport[2]//footnote/@top-offset"/> + </checks> +</testcase> diff --git a/test/layoutengine/standard-testcases/footnote_reset.xml b/test/layoutengine/standard-testcases/footnote_reset.xml new file mode 100644 index 000000000..e9015fef7 --- /dev/null +++ b/test/layoutengine/standard-testcases/footnote_reset.xml @@ -0,0 +1,58 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!-- $Id$ --> +<testcase> + <info> + <p> + This test checks that footnote content is properly reset when the algorithm has to restart + page breaking after a too short/long node. + </p> + </info> + <fo> + <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> + <fo:layout-master-set> + <fo:simple-page-master master-name="page" + page-height="55pt" page-width="200pt"> + <fo:region-body/> + </fo:simple-page-master> + </fo:layout-master-set> + <fo:page-sequence master-reference="page"> + <fo:flow flow-name="xsl-region-body" font-size="8pt" line-height="10pt"> + <fo:block>Line 1</fo:block> + <fo:block>Line 2</fo:block> + <fo:block>Line 3<fo:footnote> + <fo:inline>*</fo:inline> + <fo:footnote-body> + <fo:block>Footnote line 1 of 3</fo:block> + <fo:block>Footnote line 2 of 3</fo:block> + <fo:block>Footnote line 3 of 3</fo:block> + </fo:footnote-body> + </fo:footnote></fo:block> + <fo:block>Line 4</fo:block> + </fo:flow> + </fo:page-sequence> + </fo:root> + </fo> + <checks> + <eval expected="2" xpath="count(//pageViewport[1]//footnote/block)"/> + <eval expected="Footnote line 1 of 3" xpath="//pageViewport[1]//footnote[1]/block[1]//text"/> + <eval expected="Footnote line 2 of 3" xpath="//pageViewport[1]//footnote[1]/block[2]//text"/> + <eval expected="1" xpath="count(//pageViewport[2]//footnote/block)"/> + <eval expected="Footnote line 3 of 3" xpath="//pageViewport[2]//footnote[1]/block[1]//text"/> + </checks> +</testcase> diff --git a/test/layoutengine/standard-testcases/pdf-dictionary-extension_2.xml b/test/layoutengine/standard-testcases/pdf-dictionary-extension_2.xml new file mode 100644 index 000000000..486b8601c --- /dev/null +++ b/test/layoutengine/standard-testcases/pdf-dictionary-extension_2.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!-- $Id$ --> +<testcase> + <info> + <p> + This test checks the PDF dictionary extensions related to optional content groups (layers). + </p> + </info> + <fo> + <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:pdf="http://xmlgraphics.apache.org/fop/extensions/pdf" + xmlns:fox="http://xmlgraphics.apache.org/fop/extensions"> + <fo:layout-master-set> + <fo:simple-page-master master-name="simple"> + <fo:region-body/> + <fo:region-before/> + <fo:region-after/> + </fo:simple-page-master> + </fo:layout-master-set> + <fo:declarations> + <!-- Optional Content Group Layers --> + <pdf:layer id="layer1"> + <pdf:string key="Name">Bullet 1</pdf:string> + </pdf:layer> + <pdf:layer id="layer2"> + <pdf:string key="Name">Bullet 2</pdf:string> + </pdf:layer> + <!-- Document Catalog's Optional Content (Layers) Directory and Default State --> + <pdf:catalog> + <pdf:dictionary key="OCProperties"> + <!-- Directory of OCGs (layers) in Document --> + <pdf:array key="OCGs"> + <pdf:reference refid="layer1"/> + <pdf:reference refid="layer2"/> + </pdf:array> + <!-- Default State for OCGs --> + <pdf:dictionary key="D"> + <pdf:string key="Name">Default</pdf:string> + <pdf:name key="BaseState">OFF</pdf:name> + </pdf:dictionary> + </pdf:dictionary> + </pdf:catalog> + </fo:declarations> + <fo:page-sequence master-reference="simple"> + <fo:flow flow-name="xsl-region-body"> + <fo:block fox:layer="layer1"> + <fo:block>BULLET 1A</fo:block> + <fo:block>BULLET 1B</fo:block> + </fo:block> + <fo:block fox:layer="layer2">BULLET 2</fo:block> + </fo:flow> + </fo:page-sequence> + </fo:root> + </fo> + <checks xmlns:pdf="apache:fop:extensions:pdf"> + <eval expected="layer1" xpath="//flow/block[1]/@layer"/> + <eval expected="layer2" xpath="//flow/block[2]/@layer"/> + </checks> +</testcase> diff --git a/test/layoutengine/standard-testcases/pdf-dictionary-extension_3.xml b/test/layoutengine/standard-testcases/pdf-dictionary-extension_3.xml new file mode 100644 index 000000000..ee5061497 --- /dev/null +++ b/test/layoutengine/standard-testcases/pdf-dictionary-extension_3.xml @@ -0,0 +1,122 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!-- $Id$ --> +<testcase> + <info> + <p> + This test checks the PDF dictionary extensions related to optional content groups (layers), + including navigator and action dictionaries. + </p> + </info> + <fo> + <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:pdf="http://xmlgraphics.apache.org/fop/extensions/pdf" + xmlns:fox="http://xmlgraphics.apache.org/fop/extensions"> + <fo:layout-master-set> + <fo:simple-page-master master-name="simple"> + <fo:region-body/> + <fo:region-before/> + <fo:region-after/> + <!-- Initial Layers Navigation Node for Page 1 --> + <pdf:page page-numbers="1"> + <pdf:reference key="PresSteps" refid="navInitial"/> + </pdf:page> + </fo:simple-page-master> + </fo:layout-master-set> + <fo:declarations> + <!-- Optional Content Group Layers --> + <pdf:layer id="layer1"> + <pdf:string key="Name">Bullet 1</pdf:string> + </pdf:layer> + <pdf:layer id="layer2"> + <pdf:string key="Name">Bullet 2</pdf:string> + </pdf:layer> + <!-- Navigator Actions --> + <pdf:action type="SetOCGState" id="setStateInitial"> + <pdf:array key="State"> + <pdf:name>OFF</pdf:name> + <pdf:reference refid="layer1"/> + <pdf:reference refid="layer2"/> + </pdf:array> + </pdf:action> + <pdf:action type="SetOCGState" id="setStateBullet1"> + <pdf:array key="State"> + <pdf:name>OFF</pdf:name> + <pdf:reference refid="layer2"/> + <pdf:name>ON</pdf:name> + <pdf:reference refid="layer1"/> + </pdf:array> + </pdf:action> + <pdf:action type="SetOCGState" id="setStateBullet2"> + <pdf:array key="State"> + <pdf:name>OFF</pdf:name> + <pdf:reference refid="layer1"/> + <pdf:name>ON</pdf:name> + <pdf:reference refid="layer2"/> + </pdf:array> + </pdf:action> + <!-- Navigators --> + <pdf:navigator id="navInitial"> + <pdf:reference key="NA" refid="setStateBullet1"/> + <pdf:reference key="Next" refid="navBullet1"/> + <pdf:reference key="PA" refid="setStateInitial"/> + <pdf:reference key="Prev" refid="navInitial"/> + </pdf:navigator> + <pdf:navigator id="navBullet1"> + <pdf:reference key="NA" refid="setStateBullet2"/> + <pdf:reference key="Next" refid="navBullet2"/> + <pdf:reference key="PA" refid="setStateInitial"/> + <pdf:reference key="Prev" refid="navInitial"/> + </pdf:navigator> + <pdf:navigator id="navBullet2"> + <pdf:reference key="NA" refid="setStateBullet2"/> + <pdf:reference key="Next" refid="navBullet2"/> + <pdf:reference key="PA" refid="setStateBullet1"/> + <pdf:reference key="Prev" refid="navBullet1"/> + </pdf:navigator> + <!-- Document Catalog's Optional Content (Layers) Directory and Default State --> + <pdf:catalog> + <pdf:dictionary key="OCProperties"> + <!-- Directory of OCGs (layers) in Document --> + <pdf:array key="OCGs"> + <pdf:reference refid="layer1"/> + <pdf:reference refid="layer2"/> + </pdf:array> + <!-- Default State for OCGs --> + <pdf:dictionary key="D"> + <pdf:string key="Name">Default</pdf:string> + <pdf:name key="BaseState">OFF</pdf:name> + </pdf:dictionary> + </pdf:dictionary> + </pdf:catalog> + </fo:declarations> + <fo:page-sequence master-reference="simple"> + <fo:flow flow-name="xsl-region-body"> + <fo:block fox:layer="layer1"> + <fo:block>BULLET 1A</fo:block> + <fo:block>BULLET 1B</fo:block> + </fo:block> + <fo:block fox:layer="layer2">BULLET 2</fo:block> + </fo:flow> + </fo:page-sequence> + </fo:root> + </fo> + <checks xmlns:pdf="apache:fop:extensions:pdf"> + <eval expected="layer1" xpath="//flow/block[1]/@layer"/> + <eval expected="layer2" xpath="//flow/block[2]/@layer"/> + </checks> +</testcase> |