From 29e8badcec8bd40eca2ef4940133f08eeefdda11 Mon Sep 17 00:00:00 2001 From: Jeremias Maerki Date: Sat, 14 Aug 2010 17:17:00 +0000 Subject: Bugzilla #49733: Resolved compilation (safe one), Checkstyle and many Javadoc warnings. Submitted by: Glenn Adams Changes to patch: - Restored the deprecated Graphics2DAdapter method (to be removed after Barcode4J 2.1 is released). - Restored Renderer.startPageSequence(LineArea) pending discussion about removal. - build.xml: set max VM to 1024MB instead of 2048MB to allow for 32-bit JVMs. - build.xml: restored longer taskdef names. - Restored Checkstyle 4 file for people running older IDEs. git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@985537 13f79535-47bb-0310-9956-ffa450edef68 --- test/java/org/apache/fop/URIResolutionTestCase.java | 4 ++-- test/java/org/apache/fop/fotreetest/FOTreeUnitTester.java | 2 +- test/java/org/apache/fop/layoutengine/LayoutEngineTester.java | 2 +- test/java/org/apache/fop/memory/MemoryEater.java | 2 +- test/java/org/apache/fop/visual/AbstractPSPDFBitmapProducer.java | 2 +- test/java/org/apache/fop/visual/BitmapProducerJava2D.java | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) (limited to 'test') diff --git a/test/java/org/apache/fop/URIResolutionTestCase.java b/test/java/org/apache/fop/URIResolutionTestCase.java index fd4f879da..0a197722b 100644 --- a/test/java/org/apache/fop/URIResolutionTestCase.java +++ b/test/java/org/apache/fop/URIResolutionTestCase.java @@ -92,7 +92,7 @@ public class URIResolutionTestCase extends AbstractFOPTestCase { MyURIResolver resolver = new MyURIResolver(withStream); ua.setURIResolver(resolver); - ua.setBaseURL(foFile.getParentFile().toURL().toString()); + ua.setBaseURL(foFile.getParentFile().toURI().toURL().toString()); Document doc = createAreaTree(foFile, ua); @@ -119,7 +119,7 @@ public class URIResolutionTestCase extends AbstractFOPTestCase { FOUserAgent ua = fopFactory.newFOUserAgent(); MyURIResolver resolver = new MyURIResolver(false); ua.setURIResolver(resolver); - ua.setBaseURL(foFile.getParentFile().toURL().toString()); + ua.setBaseURL(foFile.getParentFile().toURI().toURL().toString()); ByteArrayOutputStream baout = new ByteArrayOutputStream(); diff --git a/test/java/org/apache/fop/fotreetest/FOTreeUnitTester.java b/test/java/org/apache/fop/fotreetest/FOTreeUnitTester.java index bfe9018b1..5513a89ab 100644 --- a/test/java/org/apache/fop/fotreetest/FOTreeUnitTester.java +++ b/test/java/org/apache/fop/fotreetest/FOTreeUnitTester.java @@ -94,6 +94,6 @@ public abstract class FOTreeUnitTester extends TestCase { foReader.setErrorHandler(fop.getDefaultHandler()); foReader.setEntityResolver(fop.getDefaultHandler()); - foReader.parse(new File("test/fotree/unittests/" + filename).toURL().toExternalForm()); + foReader.parse(new File("test/fotree/unittests/" + filename).toURI().toURL().toExternalForm()); } } diff --git a/test/java/org/apache/fop/layoutengine/LayoutEngineTester.java b/test/java/org/apache/fop/layoutengine/LayoutEngineTester.java index d938a852b..2c0cf8504 100644 --- a/test/java/org/apache/fop/layoutengine/LayoutEngineTester.java +++ b/test/java/org/apache/fop/layoutengine/LayoutEngineTester.java @@ -116,7 +116,7 @@ public class LayoutEngineTester { //Setup FOP for area tree rendering FOUserAgent ua = effFactory.newFOUserAgent(); - ua.setBaseURL(testFile.getParentFile().toURL().toString()); + ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString()); ua.getEventBroadcaster().addEventListener( new ConsoleEventListenerForTests(testFile.getName(), EventSeverity.WARN)); diff --git a/test/java/org/apache/fop/memory/MemoryEater.java b/test/java/org/apache/fop/memory/MemoryEater.java index a665580ae..337027dc4 100644 --- a/test/java/org/apache/fop/memory/MemoryEater.java +++ b/test/java/org/apache/fop/memory/MemoryEater.java @@ -79,7 +79,7 @@ public class MemoryEater { OutputStream out = new NullOutputStream(); //write to /dev/nul try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); - userAgent.setBaseURL(foFile.getParentFile().toURL().toExternalForm()); + userAgent.setBaseURL(foFile.getParentFile().toURI().toURL().toExternalForm()); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out); Result res = new SAXResult(fop.getDefaultHandler()); diff --git a/test/java/org/apache/fop/visual/AbstractPSPDFBitmapProducer.java b/test/java/org/apache/fop/visual/AbstractPSPDFBitmapProducer.java index 0d976219d..678e80e7d 100644 --- a/test/java/org/apache/fop/visual/AbstractPSPDFBitmapProducer.java +++ b/test/java/org/apache/fop/visual/AbstractPSPDFBitmapProducer.java @@ -122,7 +122,7 @@ public abstract class AbstractPSPDFBitmapProducer extends AbstractBitmapProducer try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setTargetResolution(context.getTargetResolution()); - userAgent.setBaseURL(src.getParentFile().toURL().toString()); + userAgent.setBaseURL(src.getParentFile().toURI().toURL().toString()); File tempOut = new File(context.getTargetDir(), src.getName() + "." + index + "." + getTargetExtension()); diff --git a/test/java/org/apache/fop/visual/BitmapProducerJava2D.java b/test/java/org/apache/fop/visual/BitmapProducerJava2D.java index bd78fd93f..997a75931 100644 --- a/test/java/org/apache/fop/visual/BitmapProducerJava2D.java +++ b/test/java/org/apache/fop/visual/BitmapProducerJava2D.java @@ -70,7 +70,7 @@ public class BitmapProducerJava2D extends AbstractBitmapProducer implements Conf try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setTargetResolution(context.getTargetResolution()); - userAgent.setBaseURL(src.getParentFile().toURL().toString()); + userAgent.setBaseURL(src.getParentFile().toURI().toURL().toString()); File outputFile = new File(context.getTargetDir(), src.getName() + "." + index + ".java2d.png"); -- cgit v1.2.3 From aba436311c935f145aa984c855f88bfd3a9cb1c1 Mon Sep 17 00:00:00 2001 From: Jeremias Maerki Date: Sat, 14 Aug 2010 19:28:26 +0000 Subject: Removed many "// CSOK: ConstantName" instances for constants, by converting them to uppercase as they should really be. Fixed some other non-Checkstyle issues on the way, imports mainly. Removed some "log" instances that were not used. git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@985571 13f79535-47bb-0310-9956-ffa450edef68 --- .../plan/src/org/apache/fop/plan/PlanHints.java | 18 ++--- .../plan/src/org/apache/fop/plan/PlanRenderer.java | 5 +- .../src/org/apache/fop/plan/SimplePlanDrawer.java | 8 +- src/java/org/apache/fop/afp/AFPDataObjectInfo.java | 5 -- src/java/org/apache/fop/afp/AFPGraphics2D.java | 24 +++--- src/java/org/apache/fop/afp/AFPStreamer.java | 7 +- src/java/org/apache/fop/afp/DataStream.java | 13 ++-- src/java/org/apache/fop/afp/Factory.java | 5 -- .../org/apache/fop/afp/fonts/CharacterSet.java | 1 - src/java/org/apache/fop/afp/fonts/RasterFont.java | 11 ++- .../fop/afp/goca/GraphicsSetProcessColor.java | 2 +- .../apache/fop/afp/modca/AbstractAFPObject.java | 6 +- .../fop/afp/modca/AbstractEnvironmentGroup.java | 2 +- .../fop/afp/modca/AbstractNamedAFPObject.java | 4 +- .../afp/modca/AbstractTripletStructuredObject.java | 4 +- .../fop/afp/modca/ActiveEnvironmentGroup.java | 2 +- .../org/apache/fop/afp/modca/MapCodedFont.java | 4 +- .../org/apache/fop/afp/modca/MapPageOverlay.java | 6 +- .../org/apache/fop/afp/modca/MapPageSegment.java | 6 +- .../apache/fop/afp/ptoca/LineDataInfoProducer.java | 5 +- .../fop/afp/svg/AFPGraphicsConfiguration.java | 8 +- src/java/org/apache/fop/area/IDTracker.java | 15 ++-- .../apache/fop/events/model/EventModelParser.java | 5 +- src/java/org/apache/fop/fo/FOEventHandler.java | 5 +- src/java/org/apache/fop/fo/FObj.java | 4 +- .../fop/fo/extensions/ExtensionElementMapping.java | 16 ++-- src/java/org/apache/fop/fo/flow/Marker.java | 1 - src/java/org/apache/fop/fo/pagination/Region.java | 1 - .../fop/fo/properties/CharacterProperty.java | 4 +- .../apache/fop/fo/properties/ColorProperty.java | 4 +- .../properties/CommonBorderPaddingBackground.java | 12 +-- .../org/apache/fop/fo/properties/CommonFont.java | 4 +- .../fop/fo/properties/CommonHyphenation.java | 10 +-- .../fop/fo/properties/CondLengthProperty.java | 4 +- .../fo/properties/CorrespondingPropertyMaker.java | 2 +- .../org/apache/fop/fo/properties/EnumNumber.java | 4 +- .../org/apache/fop/fo/properties/EnumProperty.java | 4 +- .../org/apache/fop/fo/properties/FixedLength.java | 4 +- .../fop/fo/properties/FontFamilyProperty.java | 4 +- .../org/apache/fop/fo/properties/KeepProperty.java | 4 +- .../apache/fop/fo/properties/NumberProperty.java | 10 +-- .../apache/fop/fo/properties/StringProperty.java | 9 +-- src/java/org/apache/fop/fonts/FontSetup.java | 8 -- .../BalancingColumnBreakingAlgorithm.java | 20 ++--- .../apache/fop/layoutmgr/LayoutManagerMapping.java | 11 +-- .../org/apache/fop/layoutmgr/SpaceResolver.java | 87 +++++++++++----------- src/java/org/apache/fop/layoutmgr/TraitSetter.java | 11 ++- .../AbstractPageNumberCitationLayoutManager.java | 1 - .../layoutmgr/inline/BasicScaledBaselineTable.java | 4 +- .../layoutmgr/inline/LineLayoutPossibilities.java | 10 +-- .../inline/PageNumberCitationLayoutManager.java | 1 - .../fop/layoutmgr/inline/ScaledBaselineTable.java | 2 - .../layoutmgr/table/TableContentLayoutManager.java | 23 +++--- .../fop/layoutmgr/table/TableRowIterator.java | 2 - src/java/org/apache/fop/pdf/PDFEmbeddedFile.java | 6 -- src/java/org/apache/fop/pdf/PDFEncryptionJCE.java | 1 - .../org/apache/fop/pdf/PDFEncryptionManager.java | 19 +++-- .../fop/render/afp/AFPForeignAttributeReader.java | 11 ++- .../fop/render/afp/extensions/AFPPageOverlay.java | 2 - .../intermediate/AbstractIFDocumentHandler.java | 6 -- .../apache/fop/render/java2d/Java2DPainter.java | 6 -- .../org/apache/fop/render/pcl/HardcodedFonts.java | 5 +- src/java/org/apache/fop/render/pcl/PCLPainter.java | 6 -- .../apache/fop/render/pcl/PCLRendererContext.java | 3 - .../apache/fop/render/pdf/PDFBorderPainter.java | 5 +- .../org/apache/fop/render/ps/PSSVGHandler.java | 5 -- .../fop/render/rtf/rtflib/rtfdoc/RtfList.java | 3 +- .../org/apache/fop/render/svg/SVGPainter.java | 8 +- test/java/org/apache/fop/GenericFOPTestCase.java | 13 ++-- .../apache/fop/config/BaseUserConfigTestCase.java | 2 +- test/java/org/apache/fop/events/EventChecker.java | 2 +- test/java/org/apache/fop/memory/Stats.java | 2 +- .../org/apache/fop/render/pdf/PDFCMapTestCase.java | 60 +++++++-------- test/java/org/apache/fop/util/DigestFilter.java | 4 +- 74 files changed, 264 insertions(+), 357 deletions(-) (limited to 'test') diff --git a/examples/plan/src/org/apache/fop/plan/PlanHints.java b/examples/plan/src/org/apache/fop/plan/PlanHints.java index 2a2c1333a..a50d91139 100644 --- a/examples/plan/src/org/apache/fop/plan/PlanHints.java +++ b/examples/plan/src/org/apache/fop/plan/PlanHints.java @@ -25,22 +25,22 @@ package org.apache.fop.plan; public interface PlanHints { /** Border attribute */ - public static final String PLAN_BORDER = "border"; + String PLAN_BORDER = "border"; /** Legend attribute */ - public static final String PLAN_LEGEND = "legend"; + String PLAN_LEGEND = "legend"; /** Font family attribute */ - public static final String FONT_FAMILY = "font-family"; + String FONT_FAMILY = "font-family"; /** Font size attribute */ - public static final String FONT_SIZE = "font-size"; + String FONT_SIZE = "font-size"; /** Legent type attribute */ - public static final String LEGEND_TYPE = "legendType"; + String LEGEND_TYPE = "legendType"; /** Locale attribute */ - public static final String LOCALE = "locale"; + String LOCALE = "locale"; /** Label type attribute */ - public static final String LABEL_TYPE = "labelType"; + String LABEL_TYPE = "labelType"; /** Label font size attribute */ - public static final String LABEL_FONT_SIZE = "labelFontSize"; + String LABEL_FONT_SIZE = "labelFontSize"; /** Label font attribute */ - public static final String LABEL_FONT = "labelFont"; + String LABEL_FONT = "labelFont"; } diff --git a/examples/plan/src/org/apache/fop/plan/PlanRenderer.java b/examples/plan/src/org/apache/fop/plan/PlanRenderer.java index 8b7978259..7d41962fb 100644 --- a/examples/plan/src/org/apache/fop/plan/PlanRenderer.java +++ b/examples/plan/src/org/apache/fop/plan/PlanRenderer.java @@ -109,8 +109,8 @@ public class PlanRenderer { hints.put(PlanHints.FONT_FAMILY, fontFamily); hints.put(PlanHints.FONT_SIZE, new Float(fontSize)); hints.put(PlanHints.LOCALE, locale); - Document doc = - planDrawer.createDocument(data, width, height, hints); + Document doc + = planDrawer.createDocument(data, width, height, hints); return doc; } @@ -152,6 +152,7 @@ public class PlanRenderer { } else if (t.equals("grouping")) { data.setType(ActionInfo.GROUPING); } else { + throw new IllegalArgumentException("Unknown action type: " + t); } for (int i = 0; i < childs.getLength(); i++) { diff --git a/examples/plan/src/org/apache/fop/plan/SimplePlanDrawer.java b/examples/plan/src/org/apache/fop/plan/SimplePlanDrawer.java index 46b07601a..a8ba062ed 100644 --- a/examples/plan/src/org/apache/fop/plan/SimplePlanDrawer.java +++ b/examples/plan/src/org/apache/fop/plan/SimplePlanDrawer.java @@ -243,8 +243,8 @@ public class SimplePlanDrawer implements PlanDrawer { - lastWeek.getTime() + 43200000) / 86400000); int days = (int)((end.getTime() - start.getTime() + 43200000) / 86400000); - int daysFromEnd = - (int)((future.getTime() - end.getTime() + int daysFromEnd + = (int)((future.getTime() - end.getTime() + 43200000) / 86400000); Element taskGraphic; switch (type) { @@ -299,8 +299,8 @@ public class SimplePlanDrawer implements PlanDrawer { topEdge = lastTop; } } - int currentDays = - (int)((currentDate.getTime() - lastWeek.getTime() + int currentDays + = (int)((currentDate.getTime() - lastWeek.getTime() + 43200000) / 86400000); text = SVGUtilities.createText(doc, diff --git a/src/java/org/apache/fop/afp/AFPDataObjectInfo.java b/src/java/org/apache/fop/afp/AFPDataObjectInfo.java index 66ef8e595..7589ef4fe 100644 --- a/src/java/org/apache/fop/afp/AFPDataObjectInfo.java +++ b/src/java/org/apache/fop/afp/AFPDataObjectInfo.java @@ -19,9 +19,6 @@ package org.apache.fop.afp; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.apache.fop.afp.modca.Registry; import org.apache.fop.afp.modca.triplets.MappingOptionTriplet; @@ -29,8 +26,6 @@ import org.apache.fop.afp.modca.triplets.MappingOptionTriplet; * A list of parameters associated with an AFP data objects */ public class AFPDataObjectInfo { - private static final Log log // CSOK: ConstantName - = LogFactory.getLog("org.apache.xmlgraphics.afp"); /** the object area info */ private AFPObjectAreaInfo objectAreaInfo; diff --git a/src/java/org/apache/fop/afp/AFPGraphics2D.java b/src/java/org/apache/fop/afp/AFPGraphics2D.java index 5fa6bae2d..af58b5471 100644 --- a/src/java/org/apache/fop/afp/AFPGraphics2D.java +++ b/src/java/org/apache/fop/afp/AFPGraphics2D.java @@ -75,7 +75,7 @@ import org.apache.fop.svg.NativeImageHandler; */ public class AFPGraphics2D extends AbstractGraphics2D implements NativeImageHandler { - private static final Log log = LogFactory.getLog(AFPGraphics2D.class); // CSOK: ConstantName + private static final Log LOG = LogFactory.getLog(AFPGraphics2D.class); private static final int X = 0; @@ -321,7 +321,7 @@ public class AFPGraphics2D extends AbstractGraphics2D implements NativeImageHand graphicsObj.setLineType(type); } } else { - log.warn("Unsupported Stroke: " + stroke.getClass().getName()); + LOG.warn("Unsupported Stroke: " + stroke.getClass().getName()); } } @@ -339,7 +339,7 @@ public class AFPGraphics2D extends AbstractGraphics2D implements NativeImageHand if (paint instanceof Color) { return true; } - log.debug("NYI: applyPaint() " + paint + " fill=" + fill); + LOG.debug("NYI: applyPaint() " + paint + " fill=" + fill); if (paint instanceof TexturePaint) { // TexturePaint texturePaint = (TexturePaint)paint; // BufferedImage bufferedImage = texturePaint.getImage(); @@ -490,7 +490,7 @@ public class AFPGraphics2D extends AbstractGraphics2D implements NativeImageHand currentPosition = new double[]{openingCoords[0], openingCoords[1]}; break; default: - log.debug("Unrecognised path iterator type"); + LOG.debug("Unrecognised path iterator type"); break; } } @@ -498,13 +498,13 @@ public class AFPGraphics2D extends AbstractGraphics2D implements NativeImageHand /** {@inheritDoc} */ public void draw(Shape shape) { - log.debug("draw() shape=" + shape); + LOG.debug("draw() shape=" + shape); doDrawing(shape, false); } /** {@inheritDoc} */ public void fill(Shape shape) { - log.debug("fill() shape=" + shape); + LOG.debug("fill() shape=" + shape); doDrawing(shape, true); } @@ -516,7 +516,7 @@ public class AFPGraphics2D extends AbstractGraphics2D implements NativeImageHand */ public void handleIOException(IOException ioe) { // TODO Surely, there's a better way to do this. - log.error(ioe.getMessage()); + LOG.error(ioe.getMessage()); ioe.printStackTrace(); } @@ -659,29 +659,29 @@ public class AFPGraphics2D extends AbstractGraphics2D implements NativeImageHand /** {@inheritDoc} */ public void drawRenderableImage(RenderableImage img, AffineTransform xform) { - log.debug("drawRenderableImage() NYI: img=" + img + ", xform=" + xform); + LOG.debug("drawRenderableImage() NYI: img=" + img + ", xform=" + xform); } /** {@inheritDoc} */ public FontMetrics getFontMetrics(Font f) { - log.debug("getFontMetrics() NYI: f=" + f); + LOG.debug("getFontMetrics() NYI: f=" + f); return null; } /** {@inheritDoc} */ public void setXORMode(Color col) { - log.debug("setXORMode() NYI: col=" + col); + LOG.debug("setXORMode() NYI: col=" + col); } /** {@inheritDoc} */ public void addNativeImage(org.apache.xmlgraphics.image.loader.Image image, float x, float y, float width, float height) { - log.debug("NYI: addNativeImage() " + "image=" + image + LOG.debug("NYI: addNativeImage() " + "image=" + image + ",x=" + x + ",y=" + y + ",width=" + width + ",height=" + height); } /** {@inheritDoc} */ public void copyArea(int x, int y, int width, int height, int dx, int dy) { - log.debug("copyArea() NYI: "); + LOG.debug("copyArea() NYI: "); } } diff --git a/src/java/org/apache/fop/afp/AFPStreamer.java b/src/java/org/apache/fop/afp/AFPStreamer.java index a24e90cbf..33d1dbf90 100644 --- a/src/java/org/apache/fop/afp/AFPStreamer.java +++ b/src/java/org/apache/fop/afp/AFPStreamer.java @@ -31,6 +31,7 @@ import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.apache.fop.afp.modca.ResourceGroup; import org.apache.fop.afp.modca.StreamedResourceGroup; @@ -39,7 +40,7 @@ import org.apache.fop.afp.modca.StreamedResourceGroup; */ public class AFPStreamer implements Streamable { /** Static logging instance */ - private static final Log log = LogFactory.getLog(AFPStreamer.class); // CSOK: ConstantName + private static final Log LOG = LogFactory.getLog(AFPStreamer.class); private static final String AFPDATASTREAM_TEMP_FILE_PREFIX = "AFPDataStream_"; @@ -119,7 +120,7 @@ public class AFPStreamer implements Streamable { if (level.isExternal()) { String filePath = level.getExternalFilePath(); if (filePath == null) { - log.warn("No file path provided for external resource, using default."); + LOG.warn("No file path provided for external resource, using default."); filePath = defaultResourceGroupFilePath; } resourceGroup = (ResourceGroup)pathResourceGroupMap.get(filePath); @@ -128,7 +129,7 @@ public class AFPStreamer implements Streamable { try { os = new BufferedOutputStream(new FileOutputStream(filePath)); } catch (FileNotFoundException fnfe) { - log.error("Failed to create/open external resource group file '" + LOG.error("Failed to create/open external resource group file '" + filePath + "'"); } finally { if (os != null) { diff --git a/src/java/org/apache/fop/afp/DataStream.java b/src/java/org/apache/fop/afp/DataStream.java index 096c2e60e..843e3fa65 100644 --- a/src/java/org/apache/fop/afp/DataStream.java +++ b/src/java/org/apache/fop/afp/DataStream.java @@ -30,8 +30,8 @@ import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.fop.afp.fonts.AFPFontAttributes; import org.apache.fop.afp.fonts.AFPFont; +import org.apache.fop.afp.fonts.AFPFontAttributes; import org.apache.fop.afp.fonts.CharacterSet; import org.apache.fop.afp.modca.AbstractPageObject; import org.apache.fop.afp.modca.Document; @@ -42,10 +42,10 @@ import org.apache.fop.afp.modca.PageObject; import org.apache.fop.afp.modca.ResourceGroup; import org.apache.fop.afp.modca.TagLogicalElementBean; import org.apache.fop.afp.modca.triplets.FullyQualifiedNameTriplet; -import org.apache.fop.afp.ptoca.PtocaProducer; import org.apache.fop.afp.ptoca.PtocaBuilder; -import org.apache.fop.util.CharUtilities; +import org.apache.fop.afp.ptoca.PtocaProducer; import org.apache.fop.fonts.Font; +import org.apache.fop.util.CharUtilities; /** * A data stream is a continuous ordered stream of data elements and objects @@ -65,8 +65,7 @@ import org.apache.fop.fonts.Font; public class DataStream { /** Static logging instance */ - protected static final Log log // CSOK: ConstantName - = LogFactory.getLog("org.apache.xmlgraphics.afp"); + protected static final Log LOG = LogFactory.getLog("org.apache.xmlgraphics.afp"); /** Boolean completion indicator */ private boolean complete = false; @@ -163,7 +162,7 @@ public class DataStream { public void endDocument() throws IOException { if (complete) { String msg = "Invalid state - document already ended."; - log.warn("endDocument():: " + msg); + LOG.warn("endDocument():: " + msg); throw new IllegalStateException(msg); } @@ -357,7 +356,7 @@ public class DataStream { * @param letterSpacing letter spacing to draw text with * @param wordSpacing word Spacing to draw text with * @param font is the font to draw text with - * @param charSet is the AFP Character Set to use with the text + * @param charSet is the AFP Character Set to use with the text * @throws UnsupportedEncodingException thrown if character encoding is not supported */ public void createText diff --git a/src/java/org/apache/fop/afp/Factory.java b/src/java/org/apache/fop/afp/Factory.java index f29453cf5..ef68a22fb 100644 --- a/src/java/org/apache/fop/afp/Factory.java +++ b/src/java/org/apache/fop/afp/Factory.java @@ -21,8 +21,6 @@ package org.apache.fop.afp; import java.io.OutputStream; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.apache.fop.afp.goca.GraphicsData; import org.apache.fop.afp.ioca.ImageContent; import org.apache.fop.afp.ioca.ImageRasterData; @@ -65,9 +63,6 @@ import org.apache.fop.afp.util.StringUtils; */ public class Factory { - /** Static logging instance */ - private static final Log log = LogFactory.getLog(Factory.class); // CSOK: ConstantName - private static final String OBJECT_ENVIRONMENT_GROUP_NAME_PREFIX = "OEG"; private static final String ACTIVE_ENVIRONMENT_GROUP_NAME_PREFIX = "AEG"; diff --git a/src/java/org/apache/fop/afp/fonts/CharacterSet.java b/src/java/org/apache/fop/afp/fonts/CharacterSet.java index 22cb52d4d..7123d4138 100644 --- a/src/java/org/apache/fop/afp/fonts/CharacterSet.java +++ b/src/java/org/apache/fop/afp/fonts/CharacterSet.java @@ -21,7 +21,6 @@ package org.apache.fop.afp.fonts; import java.io.File; import java.io.UnsupportedEncodingException; -import java.net.URI; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; diff --git a/src/java/org/apache/fop/afp/fonts/RasterFont.java b/src/java/org/apache/fop/afp/fonts/RasterFont.java index 6ad5375bf..2a4d5d270 100644 --- a/src/java/org/apache/fop/afp/fonts/RasterFont.java +++ b/src/java/org/apache/fop/afp/fonts/RasterFont.java @@ -37,8 +37,7 @@ import org.apache.commons.logging.LogFactory; public class RasterFont extends AFPFont { /** Static logging instance */ - protected static final Log log // CSOK: ConstantName - = LogFactory.getLog("org.apache.fop.afp.fonts"); + protected static final Log LOG = LogFactory.getLog("org.apache.fop.afp.fonts"); private final SortedMap/**/ charSets = new java.util.TreeMap/**/(); @@ -118,7 +117,7 @@ public class RasterFont extends AFPFont { substitutionCharSets.put(requestedSize, csm); String msg = "No " + (size / 1000f) + "pt font " + getFontName() + " found, substituted with " + fontSize.intValue() / 1000f + "pt font"; - log.warn(msg); + LOG.warn(msg); } } @@ -126,7 +125,7 @@ public class RasterFont extends AFPFont { // Still no match -> error String msg = "No font found for font " + getFontName() + " with point size " + size / 1000f; - log.error(msg); + LOG.error(msg); throw new FontRuntimeException(msg); } @@ -145,7 +144,7 @@ public class RasterFont extends AFPFont { return csm.getFirstChar(); } else { String msg = "getFirstChar() - No character set found for font:" + getFontName(); - log.error(msg); + LOG.error(msg); throw new FontRuntimeException(msg); } } @@ -162,7 +161,7 @@ public class RasterFont extends AFPFont { return csm.getLastChar(); } else { String msg = "getLastChar() - No character set found for font:" + getFontName(); - log.error(msg); + LOG.error(msg); throw new FontRuntimeException(msg); } diff --git a/src/java/org/apache/fop/afp/goca/GraphicsSetProcessColor.java b/src/java/org/apache/fop/afp/goca/GraphicsSetProcessColor.java index 4d45b22cb..aba02f76c 100644 --- a/src/java/org/apache/fop/afp/goca/GraphicsSetProcessColor.java +++ b/src/java/org/apache/fop/afp/goca/GraphicsSetProcessColor.java @@ -75,7 +75,7 @@ public class GraphicsSetProcessColor extends AbstractGraphicsDrawingOrder { } else if (colSpaceType == ColorSpace.TYPE_RGB) { colspace = RGB; } else { - log.error("unsupported colorspace " + colSpaceType); + LOG.error("unsupported colorspace " + colSpaceType); colspace = RGB; } diff --git a/src/java/org/apache/fop/afp/modca/AbstractAFPObject.java b/src/java/org/apache/fop/afp/modca/AbstractAFPObject.java index be92ce0b6..4b1439da0 100644 --- a/src/java/org/apache/fop/afp/modca/AbstractAFPObject.java +++ b/src/java/org/apache/fop/afp/modca/AbstractAFPObject.java @@ -27,6 +27,7 @@ import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.apache.fop.afp.Streamable; import org.apache.fop.afp.util.BinaryUtils; @@ -38,8 +39,7 @@ import org.apache.fop.afp.util.BinaryUtils; public abstract class AbstractAFPObject implements Streamable { /** Static logging instance */ - protected static final Log log // CSOK: ConstantName - = LogFactory.getLog("org.apache.xmlgraphics.afp.modca"); + protected static final Log LOG = LogFactory.getLog("org.apache.xmlgraphics.afp.modca"); /** the structured field class id */ protected static final byte SF_CLASS = (byte)0xD3; @@ -189,7 +189,7 @@ public abstract class AbstractAFPObject implements Streamable { protected String truncate(String str, int maxLength) { if (str.length() > maxLength) { str = str.substring(0, maxLength); - log.warn("truncated character string '" + LOG.warn("truncated character string '" + str + "', longer than " + maxLength + " chars"); } return str; diff --git a/src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java b/src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java index 19f2c94a3..d06311a47 100644 --- a/src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java +++ b/src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java @@ -73,7 +73,7 @@ public abstract class AbstractEnvironmentGroup extends AbstractNamedAFPObject { mpo.addOverlay(name); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) - log.error("createOverlay():: resulted in a MaximumSizeExceededException"); + LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); } } } diff --git a/src/java/org/apache/fop/afp/modca/AbstractNamedAFPObject.java b/src/java/org/apache/fop/afp/modca/AbstractNamedAFPObject.java index 4e0dbc349..b349e1f7d 100644 --- a/src/java/org/apache/fop/afp/modca/AbstractNamedAFPObject.java +++ b/src/java/org/apache/fop/afp/modca/AbstractNamedAFPObject.java @@ -73,7 +73,7 @@ public abstract class AbstractNamedAFPObject extends AbstractTripletStructuredOb name = (name + " ").substring(0, afpNameLen); } else if (name.length() > afpNameLen) { String truncatedName = name.substring(nameLen - afpNameLen, nameLen); - log.warn("Constructor:: name '" + name + "'" + LOG.warn("Constructor:: name '" + name + "'" + " truncated to " + afpNameLen + " chars" + " ('" + truncatedName + "')"); name = truncatedName; @@ -83,7 +83,7 @@ public abstract class AbstractNamedAFPObject extends AbstractTripletStructuredOb nameBytes = name.getBytes(AFPConstants.EBCIDIC_ENCODING); } catch (UnsupportedEncodingException usee) { nameBytes = name.getBytes(); - log.warn( + LOG.warn( "Constructor:: UnsupportedEncodingException translating the name " + name); } diff --git a/src/java/org/apache/fop/afp/modca/AbstractTripletStructuredObject.java b/src/java/org/apache/fop/afp/modca/AbstractTripletStructuredObject.java index efc38f3b8..4b269086e 100644 --- a/src/java/org/apache/fop/afp/modca/AbstractTripletStructuredObject.java +++ b/src/java/org/apache/fop/afp/modca/AbstractTripletStructuredObject.java @@ -27,8 +27,6 @@ import java.util.List; import org.apache.fop.afp.modca.Registry.ObjectType; import org.apache.fop.afp.modca.triplets.AbstractTriplet; -import org.apache.fop.afp.modca.triplets.AttributeQualifierTriplet; -import org.apache.fop.afp.modca.triplets.AttributeValueTriplet; import org.apache.fop.afp.modca.triplets.CommentTriplet; import org.apache.fop.afp.modca.triplets.FullyQualifiedNameTriplet; import org.apache.fop.afp.modca.triplets.ObjectClassificationTriplet; @@ -150,7 +148,7 @@ public class AbstractTripletStructuredObject extends AbstractStructuredObject { if (fqNameTriplet != null) { return fqNameTriplet.getFullyQualifiedName(); } - log.warn(this + " has no fully qualified name"); + LOG.warn(this + " has no fully qualified name"); return null; } diff --git a/src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java b/src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java index 4af687a92..696787bc4 100644 --- a/src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java +++ b/src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java @@ -185,7 +185,7 @@ public final class ActiveEnvironmentGroup extends AbstractEnvironmentGroup { mapCodedFont.addFont(fontRef, font, size, orientation); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) - log.error("createFont():: resulted in a MaximumSizeExceededException"); + LOG.error("createFont():: resulted in a MaximumSizeExceededException"); } } } diff --git a/src/java/org/apache/fop/afp/modca/MapCodedFont.java b/src/java/org/apache/fop/afp/modca/MapCodedFont.java index 8d99d8eaa..69d8ccf31 100644 --- a/src/java/org/apache/fop/afp/modca/MapCodedFont.java +++ b/src/java/org/apache/fop/afp/modca/MapCodedFont.java @@ -180,7 +180,7 @@ public class MapCodedFont extends AbstractStructuredObject { if (cs == null) { String msg = "Character set not found for font " + font.getFontName() + " with point size " + size; - log.error(msg); + LOG.error(msg); throw new FontRuntimeException(msg); } @@ -243,7 +243,7 @@ public class MapCodedFont extends AbstractStructuredObject { } else { String msg = "Font of type " + font.getClass().getName() + " not recognized."; - log.error(msg); + LOG.error(msg); throw new FontRuntimeException(msg); } diff --git a/src/java/org/apache/fop/afp/modca/MapPageOverlay.java b/src/java/org/apache/fop/afp/modca/MapPageOverlay.java index 9fd3c7059..6f5855c93 100644 --- a/src/java/org/apache/fop/afp/modca/MapPageOverlay.java +++ b/src/java/org/apache/fop/afp/modca/MapPageOverlay.java @@ -69,14 +69,14 @@ public class MapPageOverlay extends AbstractAFPObject { throw new IllegalArgumentException("The name of overlay " + name + " must be 8 characters"); } - if (log.isDebugEnabled()) { - log.debug("addOverlay():: adding overlay " + name); + if (LOG.isDebugEnabled()) { + LOG.debug("addOverlay():: adding overlay " + name); } try { byte[] data = name.getBytes(AFPConstants.EBCIDIC_ENCODING); getOverlays().add(data); } catch (UnsupportedEncodingException usee) { - log.error("addOverlay():: UnsupportedEncodingException translating the name " + LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); } } diff --git a/src/java/org/apache/fop/afp/modca/MapPageSegment.java b/src/java/org/apache/fop/afp/modca/MapPageSegment.java index e2afd0257..8bb7afe46 100644 --- a/src/java/org/apache/fop/afp/modca/MapPageSegment.java +++ b/src/java/org/apache/fop/afp/modca/MapPageSegment.java @@ -67,8 +67,8 @@ public class MapPageSegment extends AbstractAFPObject { throw new IllegalArgumentException("The name of page segment " + name + " must not be longer than 8 characters"); } - if (log.isDebugEnabled()) { - log.debug("addPageSegment():: adding page segment " + name); + if (LOG.isDebugEnabled()) { + LOG.debug("addPageSegment():: adding page segment " + name); } getPageSegments().add(name); } @@ -124,7 +124,7 @@ public class MapPageSegment extends AbstractAFPObject { byte[] nameBytes = name.getBytes(AFPConstants.EBCIDIC_ENCODING); System.arraycopy(nameBytes, 0, data, pos, nameBytes.length); } catch (UnsupportedEncodingException usee) { - log.error("UnsupportedEncodingException translating the name " + LOG.error("UnsupportedEncodingException translating the name " + name); } pos += 8; diff --git a/src/java/org/apache/fop/afp/ptoca/LineDataInfoProducer.java b/src/java/org/apache/fop/afp/ptoca/LineDataInfoProducer.java index ad2a5d716..cf00674fb 100644 --- a/src/java/org/apache/fop/afp/ptoca/LineDataInfoProducer.java +++ b/src/java/org/apache/fop/afp/ptoca/LineDataInfoProducer.java @@ -32,8 +32,7 @@ import org.apache.fop.afp.AFPLineDataInfo; public class LineDataInfoProducer implements PtocaProducer, PtocaConstants { /** Static logging instance */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(LineDataInfoProducer.class); + private static final Log LOG = LogFactory.getLog(LineDataInfoProducer.class); private AFPLineDataInfo lineDataInfo; @@ -62,7 +61,7 @@ public class LineDataInfoProducer implements PtocaProducer, PtocaConstants { } else if (x1 == x2) { builder.drawBaxisRule(y2 - y1, thickness); } else { - log.error("Invalid axis rule: unable to draw line"); + LOG.error("Invalid axis rule: unable to draw line"); return; } } diff --git a/src/java/org/apache/fop/afp/svg/AFPGraphicsConfiguration.java b/src/java/org/apache/fop/afp/svg/AFPGraphicsConfiguration.java index b8ed5159a..0a051e675 100644 --- a/src/java/org/apache/fop/afp/svg/AFPGraphicsConfiguration.java +++ b/src/java/org/apache/fop/afp/svg/AFPGraphicsConfiguration.java @@ -109,7 +109,7 @@ public class AFPGraphicsConfiguration extends GraphicsConfiguration { } } - private static final Log log // CSOK: ConstantName + private static final Log LOG = LogFactory.getLog(AFPGraphicsConfiguration.class); private AffineTransform defaultTransform = null; @@ -122,7 +122,7 @@ public class AFPGraphicsConfiguration extends GraphicsConfiguration { * @return the default transform for the configuration */ public AffineTransform getDefaultTransform() { - log.debug("getDefaultTransform()"); + LOG.debug("getDefaultTransform()"); if (defaultTransform == null) { defaultTransform = new AffineTransform(); } @@ -137,7 +137,7 @@ public class AFPGraphicsConfiguration extends GraphicsConfiguration { * @return the normalizing transform for the configuration */ public AffineTransform getNormalizingTransform() { - log.debug("getNormalizingTransform()"); + LOG.debug("getNormalizingTransform()"); if (normalizingTransform == null) { normalizingTransform = new AffineTransform(2, 0, 0, 2, 0, 0); } @@ -146,7 +146,7 @@ public class AFPGraphicsConfiguration extends GraphicsConfiguration { /** {@inheritDoc} */ public GraphicsDevice getDevice() { - log.debug("getDevice()"); + LOG.debug("getDevice()"); return graphicsDevice; } } diff --git a/src/java/org/apache/fop/area/IDTracker.java b/src/java/org/apache/fop/area/IDTracker.java index c0607d1bd..829c8c58d 100644 --- a/src/java/org/apache/fop/area/IDTracker.java +++ b/src/java/org/apache/fop/area/IDTracker.java @@ -34,8 +34,7 @@ import org.apache.commons.logging.LogFactory; */ public class IDTracker { - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(IDTracker.class); + private static final Log LOG = LogFactory.getLog(IDTracker.class); // HashMap of ID's whose area is located on one or more consecutive // PageViewports. Each ID has an arraylist of PageViewports that @@ -59,8 +58,8 @@ public class IDTracker { * @param pv a page viewport that contains the area with this ID */ public void associateIDWithPageViewport(String id, PageViewport pv) { - if (log.isDebugEnabled()) { - log.debug("associateIDWithPageViewport(" + id + ", " + pv + ")"); + if (LOG.isDebugEnabled()) { + LOG.debug("associateIDWithPageViewport(" + id + ", " + pv + ")"); } List pvList = (List) idLocations.get(id); if (pvList == null) { // first time ID located @@ -93,8 +92,8 @@ public class IDTracker { * @param id the id of the object being processed */ public void signalPendingID(String id) { - if (log.isDebugEnabled()) { - log.debug("signalPendingID(" + id + ")"); + if (LOG.isDebugEnabled()) { + LOG.debug("signalPendingID(" + id + ")"); } unfinishedIDs.add(id); } @@ -107,8 +106,8 @@ public class IDTracker { * @param id the id of the formatting object which was just finished */ public void signalIDProcessed(String id) { - if (log.isDebugEnabled()) { - log.debug("signalIDProcessed(" + id + ")"); + if (LOG.isDebugEnabled()) { + LOG.debug("signalIDProcessed(" + id + ")"); } alreadyResolvedIDs.add(id); diff --git a/src/java/org/apache/fop/events/model/EventModelParser.java b/src/java/org/apache/fop/events/model/EventModelParser.java index be7c61790..5441d1c4f 100644 --- a/src/java/org/apache/fop/events/model/EventModelParser.java +++ b/src/java/org/apache/fop/events/model/EventModelParser.java @@ -46,8 +46,7 @@ public final class EventModelParser { } /** Logger instance */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(EventModelParser.class); + private static final Log LOG = LogFactory.getLog(EventModelParser.class); private static SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); @@ -61,7 +60,7 @@ public final class EventModelParser { public static EventModel parse(Source src) throws TransformerException { Transformer transformer = tFactory.newTransformer(); - transformer.setErrorListener(new DefaultErrorListener(log)); + transformer.setErrorListener(new DefaultErrorListener(LOG)); EventModel model = new EventModel(); SAXResult res = new SAXResult(getContentHandler(model)); diff --git a/src/java/org/apache/fop/fo/FOEventHandler.java b/src/java/org/apache/fop/fo/FOEventHandler.java index 238a4ced6..e280af2d7 100644 --- a/src/java/org/apache/fop/fo/FOEventHandler.java +++ b/src/java/org/apache/fop/fo/FOEventHandler.java @@ -40,11 +40,10 @@ import org.apache.fop.fo.flow.PageNumberCitation; import org.apache.fop.fo.flow.PageNumberCitationLast; import org.apache.fop.fo.flow.table.Table; import org.apache.fop.fo.flow.table.TableBody; -import org.apache.fop.fo.flow.table.TableFooter; -import org.apache.fop.fo.flow.table.TableHeader; -import org.apache.fop.fo.flow.table.TablePart; import org.apache.fop.fo.flow.table.TableCell; import org.apache.fop.fo.flow.table.TableColumn; +import org.apache.fop.fo.flow.table.TableFooter; +import org.apache.fop.fo.flow.table.TableHeader; import org.apache.fop.fo.flow.table.TableRow; import org.apache.fop.fo.pagination.Flow; import org.apache.fop.fo.pagination.PageSequence; diff --git a/src/java/org/apache/fop/fo/FObj.java b/src/java/org/apache/fop/fo/FObj.java index 244013c4d..cb265b008 100644 --- a/src/java/org/apache/fop/fo/FObj.java +++ b/src/java/org/apache/fop/fo/FObj.java @@ -44,7 +44,7 @@ import org.apache.fop.fo.properties.PropertyMaker; public abstract class FObj extends FONode implements Constants { /** the list of property makers */ - private static final PropertyMaker[] propertyListTable // CSOK: ConstantName + private static final PropertyMaker[] PROPERTY_LIST_TABLE = FOPropertyMapping.getGenericMappings(); /** @@ -108,7 +108,7 @@ public abstract class FObj extends FONode implements Constants { * @return the requested Property Maker */ public static PropertyMaker getPropertyMakerFor(int propId) { - return propertyListTable[propId]; + return PROPERTY_LIST_TABLE[propId]; } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java b/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java index 32d0d745c..a12bed0fa 100644 --- a/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java +++ b/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java @@ -37,18 +37,18 @@ public class ExtensionElementMapping extends ElementMapping { /** The FOP extension namespace URI */ public static final String URI = "http://xmlgraphics.apache.org/fop/extensions"; - private static final Set propertyAttributes // CSOK: ConstantName + private static final Set PROPERTY_ATTRIBUTES = new java.util.HashSet(); static { //These are FOP's standard extension properties (fox:*) - propertyAttributes.add("block-progression-unit"); - propertyAttributes.add("widow-content-limit"); - propertyAttributes.add("orphan-content-limit"); - propertyAttributes.add("internal-destination"); - propertyAttributes.add("disable-column-balancing"); + PROPERTY_ATTRIBUTES.add("block-progression-unit"); + PROPERTY_ATTRIBUTES.add("widow-content-limit"); + PROPERTY_ATTRIBUTES.add("orphan-content-limit"); + PROPERTY_ATTRIBUTES.add("internal-destination"); + PROPERTY_ATTRIBUTES.add("disable-column-balancing"); //These are FOP's extension properties for accessibility - propertyAttributes.add("alt-text"); + PROPERTY_ATTRIBUTES.add("alt-text"); } /** @@ -93,7 +93,7 @@ public class ExtensionElementMapping extends ElementMapping { if (!URI.equals(attributeName.getNamespaceURI())) { throw new IllegalArgumentException("The namespace URIs don't match"); } - return propertyAttributes.contains(attributeName.getLocalName()); + return PROPERTY_ATTRIBUTES.contains(attributeName.getLocalName()); } } diff --git a/src/java/org/apache/fop/fo/flow/Marker.java b/src/java/org/apache/fop/fo/flow/Marker.java index e23a13f33..d8f69af28 100644 --- a/src/java/org/apache/fop/fo/flow/Marker.java +++ b/src/java/org/apache/fop/fo/flow/Marker.java @@ -19,7 +19,6 @@ package org.apache.fop.fo.flow; -import java.util.Collections; import java.util.Map; import org.xml.sax.Attributes; diff --git a/src/java/org/apache/fop/fo/pagination/Region.java b/src/java/org/apache/fop/fo/pagination/Region.java index 6f94418be..ea449cdff 100644 --- a/src/java/org/apache/fop/fo/pagination/Region.java +++ b/src/java/org/apache/fop/fo/pagination/Region.java @@ -31,7 +31,6 @@ import org.apache.fop.fo.FONode; import org.apache.fop.fo.FObj; import org.apache.fop.fo.PropertyList; import org.apache.fop.fo.ValidationException; -import org.apache.fop.fo.expr.PropertyException; import org.apache.fop.fo.properties.CommonBorderPaddingBackground; /** diff --git a/src/java/org/apache/fop/fo/properties/CharacterProperty.java b/src/java/org/apache/fop/fo/properties/CharacterProperty.java index 71b70ebee..5fef57a8b 100644 --- a/src/java/org/apache/fop/fo/properties/CharacterProperty.java +++ b/src/java/org/apache/fop/fo/properties/CharacterProperty.java @@ -51,7 +51,7 @@ public final class CharacterProperty extends Property { } /** cache containing all canonical CharacterProperty instances */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(CharacterProperty.class); private final char character; @@ -69,7 +69,7 @@ public final class CharacterProperty extends Property { * @return the character property instance */ public static CharacterProperty getInstance(char character) { - return (CharacterProperty) cache.fetch( + return (CharacterProperty) CACHE.fetch( new CharacterProperty(character)); } diff --git a/src/java/org/apache/fop/fo/properties/ColorProperty.java b/src/java/org/apache/fop/fo/properties/ColorProperty.java index 95725f3e8..e7b8d5931 100644 --- a/src/java/org/apache/fop/fo/properties/ColorProperty.java +++ b/src/java/org/apache/fop/fo/properties/ColorProperty.java @@ -33,7 +33,7 @@ import org.apache.fop.util.ColorUtil; public final class ColorProperty extends Property { /** cache holding canonical ColorProperty instances */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(ColorProperty.class); /** @@ -103,7 +103,7 @@ public final class ColorProperty extends Property { ColorProperty instance = new ColorProperty( ColorUtil.parseColorString( foUserAgent, value)); - return (ColorProperty)cache.fetch(instance); + return (ColorProperty)CACHE.fetch(instance); } /** diff --git a/src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java b/src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java index b3ae7d8cd..d39dc24f0 100644 --- a/src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java +++ b/src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java @@ -48,7 +48,7 @@ public class CommonBorderPaddingBackground { // CSOK: FinalCl * cache holding all canonical instances * (w/ absolute background-position-* and padding-*) */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(CommonBorderPaddingBackground.class); private int hash = -1; @@ -102,7 +102,7 @@ public class CommonBorderPaddingBackground { // CSOK: FinalCl public static final class BorderInfo { /** cache holding all canonical instances */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(BorderInfo.class); private int mStyle; // Enum for border style @@ -129,7 +129,7 @@ public class CommonBorderPaddingBackground { // CSOK: FinalCl * @return a cached BorderInfo instance */ public static BorderInfo getInstance(int style, CondLengthProperty width, Color color) { - return cache.fetch(new BorderInfo(style, width, color)); + return CACHE.fetch(new BorderInfo(style, width, color)); } /** @@ -214,7 +214,7 @@ public class CommonBorderPaddingBackground { // CSOK: FinalCl * A border info with style "none". Used as a singleton, in the collapsing-border model, * for elements which don't specify any border on some of their sides. */ - private static final BorderInfo defaultBorderInfo // CSOK: ConstantName + private static final BorderInfo DEFAULT_BORDER_INFO = BorderInfo.getInstance(Constants.EN_NONE, new ConditionalNullLength(), null); /** @@ -276,7 +276,7 @@ public class CommonBorderPaddingBackground { // CSOK: FinalCl * @return a BorderInfo instance with style set to {@link Constants#EN_NONE} */ public static BorderInfo getDefaultBorderInfo() { - return defaultBorderInfo; + return DEFAULT_BORDER_INFO; } private BorderInfo[] borderInfo = new BorderInfo[4]; @@ -366,7 +366,7 @@ public class CommonBorderPaddingBackground { // CSOK: FinalCl || newInstance.backgroundPositionHorizontal.isAbsolute()) && (newInstance.backgroundPositionVertical == null || newInstance.backgroundPositionVertical.isAbsolute())) { - cachedInstance = cache.fetch(newInstance); + cachedInstance = CACHE.fetch(newInstance); } /* for non-cached, or not-yet-cached instances, preload the image */ diff --git a/src/java/org/apache/fop/fo/properties/CommonFont.java b/src/java/org/apache/fop/fo/properties/CommonFont.java index f3f7d3f69..b12f84ad2 100644 --- a/src/java/org/apache/fop/fo/properties/CommonFont.java +++ b/src/java/org/apache/fop/fo/properties/CommonFont.java @@ -37,7 +37,7 @@ public final class CommonFont { /** cache holding canonical CommonFont instances (only those with * absolute font-size and font-size-adjust) */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(CommonFont.class); /** hashcode of this instance */ @@ -129,7 +129,7 @@ public final class CommonFont { fontSize, fontSizeAdjust); - return cache.fetch(commonFont); + return CACHE.fetch(commonFont); } /** @return an array with the font-family names */ diff --git a/src/java/org/apache/fop/fo/properties/CommonHyphenation.java b/src/java/org/apache/fop/fo/properties/CommonHyphenation.java index c65b5b616..65b2cebbd 100644 --- a/src/java/org/apache/fop/fo/properties/CommonHyphenation.java +++ b/src/java/org/apache/fop/fo/properties/CommonHyphenation.java @@ -36,11 +36,9 @@ import org.apache.fop.fonts.Typeface; public final class CommonHyphenation { /** Logger */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(CommonHyphenation.class); + private static final Log LOG = LogFactory.getLog(CommonHyphenation.class); - private static final PropertyCache cache // CSOK: ConstantName - = new PropertyCache(CommonHyphenation.class); + private static final PropertyCache CACHE = new PropertyCache(CommonHyphenation.class); private int hash = 0; @@ -119,7 +117,7 @@ public final class CommonHyphenation { hyphenationPushCharacterCount, hyphenationRemainCharacterCount); - return cache.fetch(instance); + return CACHE.fetch(instance); } @@ -168,7 +166,7 @@ public final class CommonHyphenation { } } if (warn) { - log.warn("Substituted specified hyphenation character (0x" + LOG.warn("Substituted specified hyphenation character (0x" + Integer.toHexString(hyphChar) + ") with 0x" + Integer.toHexString(effHyphChar) + " because the font doesn't have the specified hyphenation character: " diff --git a/src/java/org/apache/fop/fo/properties/CondLengthProperty.java b/src/java/org/apache/fop/fo/properties/CondLengthProperty.java index dc7d80c39..1ab7ec3ad 100644 --- a/src/java/org/apache/fop/fo/properties/CondLengthProperty.java +++ b/src/java/org/apache/fop/fo/properties/CondLengthProperty.java @@ -33,7 +33,7 @@ import org.apache.fop.fo.expr.PropertyException; public class CondLengthProperty extends Property implements CompoundDatatype { /** cache holding canonical instances (for absolute conditional lengths) */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(CondLengthProperty.class); /** components */ @@ -159,7 +159,7 @@ public class CondLengthProperty extends Property implements CompoundDatatype { */ public CondLengthProperty getCondLength() { if (this.length.getLength().isAbsolute()) { - CondLengthProperty clp = (CondLengthProperty) cache.fetch(this); + CondLengthProperty clp = (CondLengthProperty) CACHE.fetch(this); if (clp == this) { isCached = true; } diff --git a/src/java/org/apache/fop/fo/properties/CorrespondingPropertyMaker.java b/src/java/org/apache/fop/fo/properties/CorrespondingPropertyMaker.java index 18c6f09a6..6183b9e56 100644 --- a/src/java/org/apache/fop/fo/properties/CorrespondingPropertyMaker.java +++ b/src/java/org/apache/fop/fo/properties/CorrespondingPropertyMaker.java @@ -19,12 +19,12 @@ package org.apache.fop.fo.properties; -import org.apache.fop.apps.FOPException; import org.apache.fop.fo.FObj; import org.apache.fop.fo.PropertyList; import org.apache.fop.fo.expr.PropertyException; /** + * Maker class for handling corresponding properties. */ public class CorrespondingPropertyMaker { /** base property maker */ diff --git a/src/java/org/apache/fop/fo/properties/EnumNumber.java b/src/java/org/apache/fop/fo/properties/EnumNumber.java index 6a2879479..153a716df 100644 --- a/src/java/org/apache/fop/fo/properties/EnumNumber.java +++ b/src/java/org/apache/fop/fo/properties/EnumNumber.java @@ -29,7 +29,7 @@ import org.apache.fop.fo.expr.PropertyException; public final class EnumNumber extends Property implements Numeric { /** cache holding all canonical EnumNumber instances */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(EnumNumber.class); private final EnumProperty enumProperty; @@ -50,7 +50,7 @@ public final class EnumNumber extends Property implements Numeric { * @return the canonical instance */ public static EnumNumber getInstance(Property enumProperty) { - return (EnumNumber)cache.fetch( + return (EnumNumber)CACHE.fetch( new EnumNumber((EnumProperty) enumProperty)); } diff --git a/src/java/org/apache/fop/fo/properties/EnumProperty.java b/src/java/org/apache/fop/fo/properties/EnumProperty.java index db26cfdc6..ae704f1c9 100644 --- a/src/java/org/apache/fop/fo/properties/EnumProperty.java +++ b/src/java/org/apache/fop/fo/properties/EnumProperty.java @@ -29,7 +29,7 @@ import org.apache.fop.fo.expr.PropertyException; public final class EnumProperty extends Property { /** cache holding all canonical EnumProperty instances */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(EnumProperty.class); /** @@ -93,7 +93,7 @@ public final class EnumProperty extends Property { * @return an enumeration property */ public static EnumProperty getInstance(int explicitValue, String text) { - return (EnumProperty) cache.fetch( + return (EnumProperty) CACHE.fetch( new EnumProperty(explicitValue, text)); } diff --git a/src/java/org/apache/fop/fo/properties/FixedLength.java b/src/java/org/apache/fop/fo/properties/FixedLength.java index cc4d04c69..c35c6f6c9 100644 --- a/src/java/org/apache/fop/fo/properties/FixedLength.java +++ b/src/java/org/apache/fop/fo/properties/FixedLength.java @@ -45,7 +45,7 @@ public final class FixedLength extends LengthProperty { public static final String MPT = "mpt"; /** cache holding all canonical FixedLength instances */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(FixedLength.class); /** canonical zero-length instance */ @@ -82,7 +82,7 @@ public final class FixedLength extends LengthProperty { if (numUnits == 0.0) { return ZERO_FIXED_LENGTH; } else { - return (FixedLength)cache.fetch( + return (FixedLength)CACHE.fetch( new FixedLength(numUnits, units, sourceResolution)); } diff --git a/src/java/org/apache/fop/fo/properties/FontFamilyProperty.java b/src/java/org/apache/fop/fo/properties/FontFamilyProperty.java index 5b05aa959..330101ee7 100644 --- a/src/java/org/apache/fop/fo/properties/FontFamilyProperty.java +++ b/src/java/org/apache/fop/fo/properties/FontFamilyProperty.java @@ -31,7 +31,7 @@ import org.apache.fop.fo.expr.PropertyException; public final class FontFamilyProperty extends ListProperty { /** cache holding all canonical FontFamilyProperty instances */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(FontFamilyProperty.class); private int hash = 0; @@ -95,7 +95,7 @@ public final class FontFamilyProperty extends ListProperty { prop.addProperty(StringProperty.getInstance(tmpVal)); } } - return cache.fetch(prop); + return CACHE.fetch(prop); } } diff --git a/src/java/org/apache/fop/fo/properties/KeepProperty.java b/src/java/org/apache/fop/fo/properties/KeepProperty.java index 7c5b6124f..0bc44e459 100644 --- a/src/java/org/apache/fop/fo/properties/KeepProperty.java +++ b/src/java/org/apache/fop/fo/properties/KeepProperty.java @@ -30,7 +30,7 @@ import org.apache.fop.fo.expr.PropertyException; public final class KeepProperty extends Property implements CompoundDatatype { /** class holding all canonical KeepProperty instances*/ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(KeepProperty.class); private boolean isCachedValue = false; @@ -165,7 +165,7 @@ public final class KeepProperty extends Property implements CompoundDatatype { * this property */ public KeepProperty getKeep() { - KeepProperty keep = (KeepProperty) cache.fetch(this); + KeepProperty keep = (KeepProperty) CACHE.fetch(this); /* make sure setComponent() can never alter cached values */ keep.isCachedValue = true; return keep; diff --git a/src/java/org/apache/fop/fo/properties/NumberProperty.java b/src/java/org/apache/fop/fo/properties/NumberProperty.java index d54161b8d..97844d723 100644 --- a/src/java/org/apache/fop/fo/properties/NumberProperty.java +++ b/src/java/org/apache/fop/fo/properties/NumberProperty.java @@ -106,7 +106,7 @@ public final class NumberProperty extends Property implements Numeric { } /** cache holding all canonical NumberProperty instances */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(NumberProperty.class); private final Number number; @@ -144,7 +144,7 @@ public final class NumberProperty extends Property implements Numeric { * @return the canonical NumberProperty */ public static NumberProperty getInstance(Double num) { - return (NumberProperty)cache.fetch( + return (NumberProperty)CACHE.fetch( new NumberProperty(num.doubleValue())); } @@ -155,7 +155,7 @@ public final class NumberProperty extends Property implements Numeric { * @return the canonical NumberProperty */ public static NumberProperty getInstance(Integer num) { - return (NumberProperty)cache.fetch( + return (NumberProperty)CACHE.fetch( new NumberProperty(num.intValue())); } @@ -166,7 +166,7 @@ public final class NumberProperty extends Property implements Numeric { * @return the canonical NumberProperty */ public static NumberProperty getInstance(double num) { - return (NumberProperty)cache.fetch( + return (NumberProperty)CACHE.fetch( new NumberProperty(num)); } @@ -177,7 +177,7 @@ public final class NumberProperty extends Property implements Numeric { * @return the canonical NumberProperty */ public static NumberProperty getInstance(int num) { - return (NumberProperty)cache.fetch( + return (NumberProperty)CACHE.fetch( new NumberProperty(num)); } diff --git a/src/java/org/apache/fop/fo/properties/StringProperty.java b/src/java/org/apache/fop/fo/properties/StringProperty.java index ab4544c0a..9bbe33070 100644 --- a/src/java/org/apache/fop/fo/properties/StringProperty.java +++ b/src/java/org/apache/fop/fo/properties/StringProperty.java @@ -21,11 +21,6 @@ package org.apache.fop.fo.properties; import org.apache.fop.fo.FObj; import org.apache.fop.fo.PropertyList; -import org.apache.fop.fo.FOValidationEventProducer; -import org.apache.fop.fo.ValidationException; -import org.apache.fop.fo.expr.PropertyException; - -import java.util.Set; /** * Exists primarily as a container for its Maker inner class, which is @@ -83,7 +78,7 @@ public final class StringProperty extends Property { } /** cache containing all canonical StringProperty instances */ - private static final PropertyCache cache // CSOK: ConstantName + private static final PropertyCache CACHE = new PropertyCache(StringProperty.class); /** canonical instance for empty strings */ @@ -109,7 +104,7 @@ public final class StringProperty extends Property { if ("".equals(str) || str == null) { return EMPTY_STRING_PROPERTY; } else { - return (StringProperty)cache.fetch( + return (StringProperty)CACHE.fetch( new StringProperty(str)); } } diff --git a/src/java/org/apache/fop/fonts/FontSetup.java b/src/java/org/apache/fop/fonts/FontSetup.java index 7ceef5a9c..1f49f7bb5 100644 --- a/src/java/org/apache/fop/fonts/FontSetup.java +++ b/src/java/org/apache/fop/fonts/FontSetup.java @@ -25,8 +25,6 @@ import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.apache.fop.fonts.base14.Courier; import org.apache.fop.fonts.base14.CourierBold; import org.apache.fop.fonts.base14.CourierBoldOblique; @@ -56,12 +54,6 @@ public final class FontSetup { private FontSetup() { } - /** - * logging instance - */ - private static Log log // CSOK: ConstantName - = LogFactory.getLog(FontSetup.class); - /** * Sets up a font info * @param fontInfo font info diff --git a/src/java/org/apache/fop/layoutmgr/BalancingColumnBreakingAlgorithm.java b/src/java/org/apache/fop/layoutmgr/BalancingColumnBreakingAlgorithm.java index a6fbdd49c..b8bbc0c6c 100644 --- a/src/java/org/apache/fop/layoutmgr/BalancingColumnBreakingAlgorithm.java +++ b/src/java/org/apache/fop/layoutmgr/BalancingColumnBreakingAlgorithm.java @@ -21,6 +21,7 @@ package org.apache.fop.layoutmgr; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.apache.fop.fo.Constants; import org.apache.fop.traits.MinOptMax; @@ -30,8 +31,7 @@ import org.apache.fop.traits.MinOptMax; */ public class BalancingColumnBreakingAlgorithm extends PageBreakingAlgorithm { - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(BalancingColumnBreakingAlgorithm.class); + private static final Log LOG = LogFactory.getLog(BalancingColumnBreakingAlgorithm.class); private int columnCount; private int fullLen; @@ -74,8 +74,8 @@ public class BalancingColumnBreakingAlgorithm extends PageBreakingAlgorithm { protected double computeDemerits(KnuthNode activeNode, KnuthElement element, int fitnessClass, double r) { double dem = super.computeDemerits(activeNode, element, fitnessClass, r); - if (log.isTraceEnabled()) { - log.trace("original demerit=" + dem + " " + totalWidth + if (LOG.isTraceEnabled()) { + LOG.trace("original demerit=" + dem + " " + totalWidth + " line=" + activeNode.line + "/" + columnCount + " pos=" + activeNode.position + "/" + (par.size() - 1)); } @@ -91,13 +91,13 @@ public class BalancingColumnBreakingAlgorithm extends PageBreakingAlgorithm { if (remParts > 0) { avgRestLen = restLen / remParts; } - if (log.isTraceEnabled()) { - log.trace("remaining parts: " + remParts + " rest len: " + restLen + if (LOG.isTraceEnabled()) { + LOG.trace("remaining parts: " + remParts + " rest len: " + restLen + " avg=" + avgRestLen); } double balance = (idealPartLen - partLen) / 1000f; - if (log.isTraceEnabled()) { - log.trace("balance=" + balance); + if (LOG.isTraceEnabled()) { + LOG.trace("balance=" + balance); } double absBalance = Math.abs(balance); dem = absBalance; @@ -120,8 +120,8 @@ public class BalancingColumnBreakingAlgorithm extends PageBreakingAlgorithm { //We don't want more columns than available dem = Double.MAX_VALUE; } - if (log.isTraceEnabled()) { - log.trace("effective dem=" + dem + " " + totalWidth); + if (LOG.isTraceEnabled()) { + LOG.trace("effective dem=" + dem + " " + totalWidth); } return dem; } diff --git a/src/java/org/apache/fop/layoutmgr/LayoutManagerMapping.java b/src/java/org/apache/fop/layoutmgr/LayoutManagerMapping.java index 1a31f8d49..2acf67c1f 100644 --- a/src/java/org/apache/fop/layoutmgr/LayoutManagerMapping.java +++ b/src/java/org/apache/fop/layoutmgr/LayoutManagerMapping.java @@ -67,14 +67,12 @@ import org.apache.fop.fo.pagination.SideRegion; import org.apache.fop.fo.pagination.StaticContent; import org.apache.fop.fo.pagination.Title; import org.apache.fop.layoutmgr.inline.BasicLinkLayoutManager; -import org.apache.fop.layoutmgr.inline.BidiLayoutManager; import org.apache.fop.layoutmgr.inline.CharacterLayoutManager; import org.apache.fop.layoutmgr.inline.ContentLayoutManager; import org.apache.fop.layoutmgr.inline.ExternalGraphicLayoutManager; import org.apache.fop.layoutmgr.inline.FootnoteLayoutManager; import org.apache.fop.layoutmgr.inline.ICLayoutManager; import org.apache.fop.layoutmgr.inline.InlineLayoutManager; -import org.apache.fop.layoutmgr.inline.InlineLevelLayoutManager; import org.apache.fop.layoutmgr.inline.InstreamForeignObjectLM; import org.apache.fop.layoutmgr.inline.LeaderLayoutManager; import org.apache.fop.layoutmgr.inline.PageNumberCitationLastLayoutManager; @@ -93,8 +91,7 @@ import org.apache.fop.util.CharUtilities; public class LayoutManagerMapping implements LayoutManagerMaker { /** logging instance */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(LayoutManagerMapping.class); + private static final Log LOG = LogFactory.getLog(LayoutManagerMapping.class); /** The map of LayoutManagerMakers */ private Map makers = new HashMap(); @@ -159,10 +156,10 @@ public class LayoutManagerMapping implements LayoutManagerMaker { Maker maker = (Maker) makers.get(node.getClass()); if (maker == null) { if (FOElementMapping.URI.equals(node.getNamespaceURI())) { - log.error("No LayoutManager maker for class " + node.getClass()); + LOG.error("No LayoutManager maker for class " + node.getClass()); } else { - if (log.isDebugEnabled()) { - log.debug("Skipping the creation of a layout manager for " + node.getClass()); + if (LOG.isDebugEnabled()) { + LOG.debug("Skipping the creation of a layout manager for " + node.getClass()); } } } else { diff --git a/src/java/org/apache/fop/layoutmgr/SpaceResolver.java b/src/java/org/apache/fop/layoutmgr/SpaceResolver.java index c49bb2d9a..6890d4ebc 100644 --- a/src/java/org/apache/fop/layoutmgr/SpaceResolver.java +++ b/src/java/org/apache/fop/layoutmgr/SpaceResolver.java @@ -35,8 +35,7 @@ import org.apache.fop.traits.MinOptMax; public final class SpaceResolver { /** Logger instance */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(SpaceResolver.class); + private static final Log LOG = LogFactory.getLog(SpaceResolver.class); private UnresolvedListElementWithLength[] firstPart; private BreakElement breakPoss; @@ -94,25 +93,25 @@ public final class SpaceResolver { //Add pending elements from higher level FOs if (breakPoss != null) { if (breakPoss.getPendingAfterMarks() != null) { - if (log.isTraceEnabled()) { - log.trace(" adding pending before break: " + if (LOG.isTraceEnabled()) { + LOG.trace(" adding pending before break: " + breakPoss.getPendingAfterMarks()); } first.addAll(0, breakPoss.getPendingAfterMarks()); } if (breakPoss.getPendingBeforeMarks() != null) { - if (log.isTraceEnabled()) { - log.trace(" adding pending after break: " + if (LOG.isTraceEnabled()) { + LOG.trace(" adding pending after break: " + breakPoss.getPendingBeforeMarks()); } second.addAll(0, breakPoss.getPendingBeforeMarks()); } } - if (log.isTraceEnabled()) { - log.trace("before: " + first); - log.trace(" break: " + breakPoss); - log.trace("after: " + second); - log.trace("NO-BREAK: " + toString(noBreak, noBreakLengths)); + if (LOG.isTraceEnabled()) { + LOG.trace("before: " + first); + LOG.trace(" break: " + breakPoss); + LOG.trace("after: " + second); + LOG.trace("NO-BREAK: " + toString(noBreak, noBreakLengths)); } if (first != null) { @@ -164,15 +163,15 @@ public final class SpaceResolver { if (elems[effIndex] instanceof BorderOrPaddingElement) { BorderOrPaddingElement bop = (BorderOrPaddingElement)elems[effIndex]; if (bop.isConditional() && !(bop.isFirst() || bop.isLast())) { - if (log.isDebugEnabled()) { - log.debug("Nulling conditional element: " + bop); + if (LOG.isDebugEnabled()) { + LOG.debug("Nulling conditional element: " + bop); } lengths[effIndex] = null; } } } - if (log.isTraceEnabled() && elems.length > 0) { - log.trace("-->Resulting list: " + toString(elems, lengths)); + if (LOG.isTraceEnabled() && elems.length > 0) { + LOG.trace("-->Resulting list: " + toString(elems, lengths)); } } @@ -194,20 +193,20 @@ public final class SpaceResolver { } else if (!elems[effIndex].isConditional()) { break; } - if (log.isDebugEnabled()) { - log.debug("Nulling conditional element using 4.3.1, rule 1: " + elems[effIndex]); + if (LOG.isDebugEnabled()) { + LOG.debug("Nulling conditional element using 4.3.1, rule 1: " + elems[effIndex]); } lengths[effIndex] = null; } - if (log.isTraceEnabled() && elems.length > 0) { - log.trace("-->Resulting list: " + toString(elems, lengths)); + if (LOG.isTraceEnabled() && elems.length > 0) { + LOG.trace("-->Resulting list: " + toString(elems, lengths)); } } private void performSpaceResolutionRules2to3(UnresolvedListElement[] elems, MinOptMax[] lengths, int start, int end) { - if (log.isTraceEnabled()) { - log.trace("rule 2-3: " + start + "-" + end); + if (LOG.isTraceEnabled()) { + LOG.trace("rule 2-3: " + start + "-" + end); } SpaceElement space; int remaining; @@ -236,8 +235,8 @@ public final class SpaceResolver { } space = (SpaceElement)elems[i]; if (!space.isForcing()) { - if (log.isDebugEnabled()) { - log.debug("Nulling non-forcing space-specifier using 4.3.1, rule 2: " + if (LOG.isDebugEnabled()) { + LOG.debug("Nulling non-forcing space-specifier using 4.3.1, rule 2: " + elems[i]); } lengths[i] = null; @@ -256,8 +255,8 @@ public final class SpaceResolver { space = (SpaceElement)elems[i]; highestPrecedence = Math.max(highestPrecedence, space.getPrecedence()); } - if (highestPrecedence != 0 && log.isDebugEnabled()) { - log.debug("Highest precedence is " + highestPrecedence); + if (highestPrecedence != 0 && LOG.isDebugEnabled()) { + LOG.debug("Highest precedence is " + highestPrecedence); } //Suppress space-specifiers with lower precedence remaining = 0; @@ -268,8 +267,8 @@ public final class SpaceResolver { } space = (SpaceElement)elems[i]; if (space.getPrecedence() != highestPrecedence) { - if (log.isDebugEnabled()) { - log.debug("Nulling space-specifier with precedence " + if (LOG.isDebugEnabled()) { + LOG.debug("Nulling space-specifier with precedence " + space.getPrecedence() + " using 4.3.1, rule 3: " + elems[i]); } @@ -279,8 +278,8 @@ public final class SpaceResolver { remaining++; } } - if (log.isDebugEnabled()) { - log.debug("Greatest optimum: " + greatestOptimum); + if (LOG.isDebugEnabled()) { + LOG.debug("Greatest optimum: " + greatestOptimum); } if (remaining <= 1) { return; @@ -293,8 +292,8 @@ public final class SpaceResolver { } space = (SpaceElement)elems[i]; if (space.getLength().getOpt() < greatestOptimum) { - if (log.isDebugEnabled()) { - log.debug("Nulling space-specifier with smaller optimum length " + if (LOG.isDebugEnabled()) { + LOG.debug("Nulling space-specifier with smaller optimum length " + "using 4.3.1, rule 3: " + elems[i]); } @@ -317,8 +316,8 @@ public final class SpaceResolver { min = Math.max(min, space.getLength().getMin()); max = Math.min(max, space.getLength().getMax()); if (remaining > 1) { - if (log.isDebugEnabled()) { - log.debug("Nulling non-last space-specifier using 4.3.1, rule 3, second part: " + if (LOG.isDebugEnabled()) { + LOG.debug("Nulling non-last space-specifier using 4.3.1, rule 3, second part: " + elems[i]); } lengths[i] = null; @@ -328,9 +327,9 @@ public final class SpaceResolver { } } - if (log.isTraceEnabled() && elems.length > 0) { - log.trace("Remaining spaces: " + remaining); - log.trace("-->Resulting list: " + toString(elems, lengths)); + if (LOG.isTraceEnabled() && elems.length > 0) { + LOG.trace("Remaining spaces: " + remaining); + LOG.trace("-->Resulting list: " + toString(elems, lengths)); } } @@ -390,7 +389,7 @@ public final class SpaceResolver { if (hasFirstPart()) { //Now that we've handled isFirst/isLast conditions, we need to look at the //active part in its normal order so swap it back. - log.trace("Swapping first and second parts."); + LOG.trace("Swapping first and second parts."); UnresolvedListElementWithLength[] tempList; MinOptMax[] tempLengths; tempList = secondPart; @@ -598,8 +597,8 @@ public final class SpaceResolver { * @param elems the element list */ public static void resolveElementList(List elems) { - if (log.isTraceEnabled()) { - log.trace(elems); + if (LOG.isTraceEnabled()) { + LOG.trace(elems); } boolean first = true; boolean last = false; @@ -611,8 +610,8 @@ public final class SpaceResolver { while (iter.hasNext()) { ListElement el = (ListElement)iter.next(); if (el.isUnresolvedElement()) { - if (log.isTraceEnabled()) { - log.trace("unresolved found: " + el + " " + first + "/" + last); + if (LOG.isTraceEnabled()) { + LOG.trace("unresolved found: " + el + " " + first + "/" + last); } BreakElement breakPoss = null; //Clear temp lists @@ -649,7 +648,7 @@ public final class SpaceResolver { } //last = !iter.hasNext(); if (breakPoss == null && unresolvedSecond.size() == 0 && !last) { - log.trace("Swap first and second parts in no-break condition," + LOG.trace("Swap first and second parts in no-break condition," + " second part is empty."); //The first list is reversed, so swap if this shouldn't happen List swapList = unresolvedSecond; @@ -657,7 +656,7 @@ public final class SpaceResolver { unresolvedFirst = swapList; } - log.debug("----start space resolution (first=" + first + ", last=" + last + ")..."); + LOG.debug("----start space resolution (first=" + first + ", last=" + last + ")..."); SpaceResolver resolver = new SpaceResolver( unresolvedFirst, breakPoss, unresolvedSecond, first, last); if (!last) { @@ -667,7 +666,7 @@ public final class SpaceResolver { if (!last && skipNextElement) { iter.next(); } - log.debug("----end space resolution."); + LOG.debug("----end space resolution."); } first = false; } diff --git a/src/java/org/apache/fop/layoutmgr/TraitSetter.java b/src/java/org/apache/fop/layoutmgr/TraitSetter.java index 800850177..6039ad941 100644 --- a/src/java/org/apache/fop/layoutmgr/TraitSetter.java +++ b/src/java/org/apache/fop/layoutmgr/TraitSetter.java @@ -45,8 +45,7 @@ public final class TraitSetter { } /** logger */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(TraitSetter.class); + private static final Log LOG = LogFactory.getLog(TraitSetter.class); /** * Sets border and padding traits on areas. @@ -343,7 +342,7 @@ public final class TraitSetter { + backProps.backgroundPositionHorizontal.getValue(refContext)); } else { // TODO Area IPD has to be set for this to work - log.warn("Horizontal background image positioning ignored" + LOG.warn("Horizontal background image positioning ignored" + " because the IPD was not set on the area." + " (Yes, it's a bug in FOP)"); } @@ -360,7 +359,7 @@ public final class TraitSetter { + backProps.backgroundPositionVertical.getValue(refContext)); } else { // TODO Area BPD has to be set for this to work - log.warn("Vertical background image positioning ignored" + LOG.warn("Vertical background image positioning ignored" + " because the BPD was not set on the area." + " (Yes, it's a bug in FOP)"); } @@ -411,7 +410,7 @@ public final class TraitSetter { back.setHoriz(horizontal); } else { //TODO Area IPD has to be set for this to work - log.warn("Horizontal background image positioning ignored" + LOG.warn("Horizontal background image positioning ignored" + " because the IPD was not set on the area." + " (Yes, it's a bug in FOP)"); } @@ -435,7 +434,7 @@ public final class TraitSetter { back.setVertical(vertical); } else { //TODO Area BPD has to be set for this to work - log.warn("Vertical background image positioning ignored" + LOG.warn("Vertical background image positioning ignored" + " because the BPD was not set on the area." + " (Yes, it's a bug in FOP)"); } diff --git a/src/java/org/apache/fop/layoutmgr/inline/AbstractPageNumberCitationLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/AbstractPageNumberCitationLayoutManager.java index c2dde9f9e..e090fbae6 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/AbstractPageNumberCitationLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/AbstractPageNumberCitationLayoutManager.java @@ -30,7 +30,6 @@ import org.apache.fop.fonts.Font; import org.apache.fop.fonts.FontInfo; import org.apache.fop.fonts.FontTriplet; import org.apache.fop.layoutmgr.LayoutContext; -import org.apache.fop.layoutmgr.LayoutManager; import org.apache.fop.layoutmgr.PositionIterator; import org.apache.fop.layoutmgr.TraitSetter; diff --git a/src/java/org/apache/fop/layoutmgr/inline/BasicScaledBaselineTable.java b/src/java/org/apache/fop/layoutmgr/inline/BasicScaledBaselineTable.java index f2664ed1c..467f2e154 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/BasicScaledBaselineTable.java +++ b/src/java/org/apache/fop/layoutmgr/inline/BasicScaledBaselineTable.java @@ -21,9 +21,7 @@ package org.apache.fop.layoutmgr.inline; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.fop.datatypes.Length; -import org.apache.fop.datatypes.LengthBase; -import org.apache.fop.datatypes.SimplePercentBaseContext; + import org.apache.fop.fo.Constants; diff --git a/src/java/org/apache/fop/layoutmgr/inline/LineLayoutPossibilities.java b/src/java/org/apache/fop/layoutmgr/inline/LineLayoutPossibilities.java index 3eed124b2..49c97b7b6 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/LineLayoutPossibilities.java +++ b/src/java/org/apache/fop/layoutmgr/inline/LineLayoutPossibilities.java @@ -23,6 +23,7 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.apache.fop.layoutmgr.Position; /** @@ -31,8 +32,7 @@ import org.apache.fop.layoutmgr.Position; public class LineLayoutPossibilities { /** logger instance */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(LineLayoutPossibilities.class); + private static final Log LOG = LogFactory.getLog(LineLayoutPossibilities.class); private final class Possibility { private int lineCount; @@ -157,7 +157,7 @@ public class LineLayoutPossibilities { possibilitiesList.set(index, restoredPossibility); } else { // this should not happen - log.error("LineLayoutPossibilities restorePossibilities()," + LOG.error("LineLayoutPossibilities restorePossibilities()," + " min= " + getMinLineCount() + " max= " + getMaxLineCount() + " restored= " + restoredPossibility.getLineCount()); @@ -258,12 +258,12 @@ public class LineLayoutPossibilities { && adj <= (getMaxLineCount() - getChosenLineCount()) && getLineCount(chosenIndex + adj) == getChosenLineCount() + adj) { chosenIndex += adj; - log.debug("chosenLineCount= " + (getChosenLineCount() - adj) + " adjustment= " + adj + LOG.debug("chosenLineCount= " + (getChosenLineCount() - adj) + " adjustment= " + adj + " => chosenLineCount= " + getLineCount(chosenIndex)); return adj; } else { // this should not happen! - log.warn("Cannot apply the desired line count adjustment."); + LOG.warn("Cannot apply the desired line count adjustment."); return 0; } } diff --git a/src/java/org/apache/fop/layoutmgr/inline/PageNumberCitationLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/PageNumberCitationLayoutManager.java index 62041e888..b9f786c97 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/PageNumberCitationLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/PageNumberCitationLayoutManager.java @@ -25,7 +25,6 @@ import org.apache.fop.area.inline.TextArea; import org.apache.fop.area.inline.UnresolvedPageNumber; import org.apache.fop.fo.flow.PageNumberCitation; import org.apache.fop.layoutmgr.LayoutContext; -import org.apache.fop.layoutmgr.LayoutManager; /** * LayoutManager for the fo:page-number-citation formatting object diff --git a/src/java/org/apache/fop/layoutmgr/inline/ScaledBaselineTable.java b/src/java/org/apache/fop/layoutmgr/inline/ScaledBaselineTable.java index a2a1dce27..19a1a1f8a 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/ScaledBaselineTable.java +++ b/src/java/org/apache/fop/layoutmgr/inline/ScaledBaselineTable.java @@ -19,8 +19,6 @@ package org.apache.fop.layoutmgr.inline; -import org.apache.fop.datatypes.Length; - /** * The FOP specific incarnation of the XSL-FO scaled baseline table. * All baseline tables are scaled to the font size of the font they diff --git a/src/java/org/apache/fop/layoutmgr/table/TableContentLayoutManager.java b/src/java/org/apache/fop/layoutmgr/table/TableContentLayoutManager.java index 1a3297ad5..db5b4736c 100644 --- a/src/java/org/apache/fop/layoutmgr/table/TableContentLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/table/TableContentLayoutManager.java @@ -55,8 +55,7 @@ import org.apache.fop.util.BreakUtil; public class TableContentLayoutManager implements PercentBaseContext { /** Logger **/ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(TableContentLayoutManager.class); + private static final Log LOG = LogFactory.getLog(TableContentLayoutManager.class); private TableLayoutManager tableLM; private TableRowIterator bodyIter; @@ -138,8 +137,8 @@ public class TableContentLayoutManager implements PercentBaseContext { * @see org.apache.fop.layoutmgr.LayoutManager#getNextKnuthElements(LayoutContext, int) */ public List getNextKnuthElements(LayoutContext context, int alignment) { - if (log.isDebugEnabled()) { - log.debug("==> Columns: " + getTableLM().getColumns()); + if (LOG.isDebugEnabled()) { + LOG.debug("==> Columns: " + getTableLM().getColumns()); } KnuthBox headerAsFirst = null; KnuthBox headerAsSecondToLast = null; @@ -149,8 +148,8 @@ public class TableContentLayoutManager implements PercentBaseContext { headerIter, context, alignment, TableRowIterator.HEADER); this.headerNetHeight = ElementListUtils.calcContentLength(this.headerList); - if (log.isDebugEnabled()) { - log.debug("==> Header: " + if (LOG.isDebugEnabled()) { + LOG.debug("==> Header: " + headerNetHeight + " - " + this.headerList); } TableHeaderFooterPosition pos = new TableHeaderFooterPosition( @@ -169,8 +168,8 @@ public class TableContentLayoutManager implements PercentBaseContext { footerIter, context, alignment, TableRowIterator.FOOTER); this.footerNetHeight = ElementListUtils.calcContentLength(this.footerList); - if (log.isDebugEnabled()) { - log.debug("==> Footer: " + if (LOG.isDebugEnabled()) { + LOG.debug("==> Footer: " + footerNetHeight + " - " + this.footerList); } //We can simply add the table footer at the end of the whole list @@ -378,14 +377,14 @@ public class TableContentLayoutManager implements PercentBaseContext { } else if (pos instanceof TableContentPosition) { tablePositions.add(pos); } else { - if (log.isDebugEnabled()) { - log.debug("Ignoring position: " + pos); + if (LOG.isDebugEnabled()) { + LOG.debug("Ignoring position: " + pos); } } } if (lastPos instanceof TableHFPenaltyPosition) { TableHFPenaltyPosition penaltyPos = (TableHFPenaltyPosition)lastPos; - log.debug("Break at penalty!"); + LOG.debug("Break at penalty!"); if (penaltyPos.headerElements != null) { //Header positions for the penalty position are in the last element and need to //be handled first before all other TableContentPositions @@ -411,7 +410,7 @@ public class TableContentLayoutManager implements PercentBaseContext { if (tablePositions.isEmpty()) { // TODO make sure this actually never happens - log.error("tablePositions empty." + LOG.error("tablePositions empty." + " Please send your FO file to fop-users@xmlgraphics.apache.org"); } else { // Here we are sure that posIter iterates only over TableContentPosition instances diff --git a/src/java/org/apache/fop/layoutmgr/table/TableRowIterator.java b/src/java/org/apache/fop/layoutmgr/table/TableRowIterator.java index 282cd0fd5..35cba6da6 100644 --- a/src/java/org/apache/fop/layoutmgr/table/TableRowIterator.java +++ b/src/java/org/apache/fop/layoutmgr/table/TableRowIterator.java @@ -28,8 +28,6 @@ import org.apache.fop.fo.FONode.FONodeIterator; import org.apache.fop.fo.flow.table.EffRow; import org.apache.fop.fo.flow.table.Table; import org.apache.fop.fo.flow.table.TableBody; -import org.apache.fop.fo.flow.table.TablePart; - /** * Iterator that lets the table layout manager step over all the rows of a part of the diff --git a/src/java/org/apache/fop/pdf/PDFEmbeddedFile.java b/src/java/org/apache/fop/pdf/PDFEmbeddedFile.java index db9a49271..24a471e1e 100644 --- a/src/java/org/apache/fop/pdf/PDFEmbeddedFile.java +++ b/src/java/org/apache/fop/pdf/PDFEmbeddedFile.java @@ -21,17 +21,11 @@ package org.apache.fop.pdf; import java.util.Date; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - /** * This class represents an embedded file stream. */ public class PDFEmbeddedFile extends PDFStream { - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(PDFEmbeddedFile.class.getName()); - /** * Creates a new embedded file stream. */ diff --git a/src/java/org/apache/fop/pdf/PDFEncryptionJCE.java b/src/java/org/apache/fop/pdf/PDFEncryptionJCE.java index 90b530774..269f0639d 100644 --- a/src/java/org/apache/fop/pdf/PDFEncryptionJCE.java +++ b/src/java/org/apache/fop/pdf/PDFEncryptionJCE.java @@ -21,7 +21,6 @@ package org.apache.fop.pdf; // Java import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.security.InvalidKeyException; import java.security.MessageDigest; diff --git a/src/java/org/apache/fop/pdf/PDFEncryptionManager.java b/src/java/org/apache/fop/pdf/PDFEncryptionManager.java index 60844c588..3f5ae2a3d 100644 --- a/src/java/org/apache/fop/pdf/PDFEncryptionManager.java +++ b/src/java/org/apache/fop/pdf/PDFEncryptionManager.java @@ -37,8 +37,7 @@ public final class PDFEncryptionManager { } /** logging instance */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(PDFEncryptionManager.class); + private static final Log LOG = LogFactory.getLog(PDFEncryptionManager.class); /** * Indicates whether JCE is available. @@ -64,12 +63,12 @@ public final class PDFEncryptionManager { Provider[] providers; providers = Security.getProviders("Cipher.RC4"); if (providers == null) { - log.warn("Cipher provider for RC4 not available."); + LOG.warn("Cipher provider for RC4 not available."); return false; } providers = Security.getProviders("MessageDigest.MD5"); if (providers == null) { - log.warn("MessageDigest provider for MD5 not available."); + LOG.warn("MessageDigest provider for MD5 not available."); return false; } return true; @@ -92,13 +91,13 @@ public final class PDFEncryptionManager { if (params != null) { if (!checkAvailableAlgorithms()) { if (isJCEAvailable()) { - log.warn("PDF encryption has been requested, JCE is " + LOG.warn("PDF encryption has been requested, JCE is " + "available but there's no " + "JCE provider available that provides the " + "necessary algorithms. The PDF won't be " + "encrypted."); } else { - log.warn("PDF encryption has been requested but JCE is " + LOG.warn("PDF encryption has been requested but JCE is " + "unavailable! The PDF won't be encrypted."); } } @@ -123,19 +122,19 @@ public final class PDFEncryptionManager { return (PDFEncryption)obj; } catch (ClassNotFoundException e) { if (checkAvailableAlgorithms()) { - log.warn("JCE and algorithms available, but the " + LOG.warn("JCE and algorithms available, but the " + "implementation class unavailable. Please do a full " + "rebuild."); } return null; } catch (NoSuchMethodException e) { - log.error(e); + LOG.error(e); return null; } catch (IllegalAccessException e) { - log.error(e); + LOG.error(e); return null; } catch (InvocationTargetException e) { - log.error(e); + LOG.error(e); return null; } } diff --git a/src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java b/src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java index aad31f18e..a03aaf816 100644 --- a/src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java +++ b/src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java @@ -35,8 +35,7 @@ import org.apache.fop.render.afp.extensions.AFPElementMapping; * Parses any AFP foreign attributes */ public class AFPForeignAttributeReader { - private static final Log log // CSOK: ConstantName - = LogFactory.getLog("org.apache.xmlgraphics.afp"); + private static final Log LOG = LogFactory.getLog("org.apache.xmlgraphics.afp"); /** the resource-name attribute */ public static final QName RESOURCE_NAME = new QName( @@ -95,7 +94,7 @@ public class AFPForeignAttributeReader { = (String)foreignAttributes.get(RESOURCE_GROUP_FILE); if (resourceGroupFile == null) { String msg = RESOURCE_GROUP_FILE + " not specified"; - log.error(msg); + LOG.error(msg); throw new UnsupportedOperationException(msg); } File resourceExternalGroupFile = new File(resourceGroupFile); @@ -107,20 +106,20 @@ public class AFPForeignAttributeReader { } catch (SecurityException ex) { String msg = "unable to gain write access to external resource file: " + resourceGroupFile; - log.error(msg); + LOG.error(msg); } try { boolean exists = resourceExternalGroupFile.exists(); if (exists) { - log.warn("overwriting external resource file: " + LOG.warn("overwriting external resource file: " + resourceGroupFile); } resourceLevel.setExternalFilePath(resourceGroupFile); } catch (SecurityException ex) { String msg = "unable to gain read access to external resource file: " + resourceGroupFile; - log.error(msg); + LOG.error(msg); } } } diff --git a/src/java/org/apache/fop/render/afp/extensions/AFPPageOverlay.java b/src/java/org/apache/fop/render/afp/extensions/AFPPageOverlay.java index b14a4eb9d..a82fe3457 100644 --- a/src/java/org/apache/fop/render/afp/extensions/AFPPageOverlay.java +++ b/src/java/org/apache/fop/render/afp/extensions/AFPPageOverlay.java @@ -19,8 +19,6 @@ package org.apache.fop.render.afp.extensions; -import java.net.URI; - import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; diff --git a/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java b/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java index cd15a9d72..b156b6c3a 100644 --- a/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java +++ b/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java @@ -19,9 +19,6 @@ package org.apache.fop.render.intermediate; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.apache.fop.apps.FOUserAgent; /** @@ -29,9 +26,6 @@ import org.apache.fop.apps.FOUserAgent; */ public abstract class AbstractIFDocumentHandler implements IFDocumentHandler { - /** logging instance */ - private static Log log = LogFactory.getLog(AbstractIFDocumentHandler.class); - private IFContext ifContext; /** diff --git a/src/java/org/apache/fop/render/java2d/Java2DPainter.java b/src/java/org/apache/fop/render/java2d/Java2DPainter.java index a2b9c9613..396645768 100644 --- a/src/java/org/apache/fop/render/java2d/Java2DPainter.java +++ b/src/java/org/apache/fop/render/java2d/Java2DPainter.java @@ -33,9 +33,6 @@ import java.util.Stack; import org.w3c.dom.Document; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.apache.fop.fonts.Font; import org.apache.fop.fonts.FontInfo; import org.apache.fop.fonts.FontTriplet; @@ -54,9 +51,6 @@ import org.apache.fop.util.CharUtilities; */ public class Java2DPainter extends AbstractIFPainter { - /** logging instance */ - private static Log log = LogFactory.getLog(Java2DPainter.class); - /** the IF context */ protected IFContext ifContext; diff --git a/src/java/org/apache/fop/render/pcl/HardcodedFonts.java b/src/java/org/apache/fop/render/pcl/HardcodedFonts.java index 429d36167..185e1ece5 100644 --- a/src/java/org/apache/fop/render/pcl/HardcodedFonts.java +++ b/src/java/org/apache/fop/render/pcl/HardcodedFonts.java @@ -34,8 +34,7 @@ final class HardcodedFonts { } /** logging instance */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(HardcodedFonts.class); + private static final Log LOG = LogFactory.getLog(HardcodedFonts.class); /** * Sets the current font (NOTE: Hard-coded font mappings ATM!) @@ -62,7 +61,7 @@ final class HardcodedFonts { try { fontcode = Integer.parseInt(name.substring(1)); } catch (Exception e) { - log.error(e); + LOG.error(e); } } //Note "(ON" selects ISO 8859-1 symbol set as used by PCLGenerator diff --git a/src/java/org/apache/fop/render/pcl/PCLPainter.java b/src/java/org/apache/fop/render/pcl/PCLPainter.java index d0e82ed7d..00b25a5e3 100644 --- a/src/java/org/apache/fop/render/pcl/PCLPainter.java +++ b/src/java/org/apache/fop/render/pcl/PCLPainter.java @@ -34,9 +34,6 @@ import java.util.Stack; import org.w3c.dom.Document; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.apache.xmlgraphics.image.loader.ImageException; import org.apache.xmlgraphics.image.loader.ImageInfo; import org.apache.xmlgraphics.image.loader.ImageProcessingHints; @@ -65,9 +62,6 @@ import org.apache.fop.util.CharUtilities; */ public class PCLPainter extends AbstractIFPainter implements PCLConstants { - /** logging instance */ - private static Log log = LogFactory.getLog(PCLPainter.class); - private static final boolean DEBUG = false; private PCLDocumentHandler parent; diff --git a/src/java/org/apache/fop/render/pcl/PCLRendererContext.java b/src/java/org/apache/fop/render/pcl/PCLRendererContext.java index 6c2c592b1..d54973ac8 100644 --- a/src/java/org/apache/fop/render/pcl/PCLRendererContext.java +++ b/src/java/org/apache/fop/render/pcl/PCLRendererContext.java @@ -19,9 +19,6 @@ package org.apache.fop.render.pcl; -import org.apache.xmlgraphics.util.QName; - -import org.apache.fop.fo.extensions.ExtensionElementMapping; import org.apache.fop.render.ImageHandlerUtil; import org.apache.fop.render.RendererContext; diff --git a/src/java/org/apache/fop/render/pdf/PDFBorderPainter.java b/src/java/org/apache/fop/render/pdf/PDFBorderPainter.java index 10db33b0f..287f89607 100644 --- a/src/java/org/apache/fop/render/pdf/PDFBorderPainter.java +++ b/src/java/org/apache/fop/render/pdf/PDFBorderPainter.java @@ -37,8 +37,7 @@ import org.apache.fop.util.ColorUtil; public class PDFBorderPainter extends BorderPainter { /** logging instance */ - private static final Log log // CSOK: ConstantName - = LogFactory.getLog(PDFBorderPainter.class); + private static final Log LOG = LogFactory.getLog(PDFBorderPainter.class); private PDFContentGenerator generator; @@ -70,7 +69,7 @@ public class PDFBorderPainter extends BorderPainter { float w = x2 - x1; float h = y2 - y1; if ((w < 0) || (h < 0)) { - log.error("Negative extent received (w=" + w + ", h=" + h + LOG.error("Negative extent received (w=" + w + ", h=" + h + "). Border won't be painted."); return; } diff --git a/src/java/org/apache/fop/render/ps/PSSVGHandler.java b/src/java/org/apache/fop/render/ps/PSSVGHandler.java index 5cc1a1b01..66b26fb33 100644 --- a/src/java/org/apache/fop/render/ps/PSSVGHandler.java +++ b/src/java/org/apache/fop/render/ps/PSSVGHandler.java @@ -30,8 +30,6 @@ import org.apache.avalon.framework.configuration.Configuration; import org.apache.batik.bridge.BridgeContext; import org.apache.batik.bridge.GVTBuilder; import org.apache.batik.gvt.GraphicsNode; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.apache.xmlgraphics.java2d.ps.PSGraphics2D; import org.apache.xmlgraphics.ps.PSGenerator; @@ -57,9 +55,6 @@ import org.apache.fop.svg.SVGUserAgent; public class PSSVGHandler extends AbstractGenericSVGHandler implements PSRendererContextConstants { - /** logging instance */ - private static Log log = LogFactory.getLog(PSSVGHandler.class); - /** * Create a new PostScript XML handler for use by the PostScript renderer. */ diff --git a/src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfList.java b/src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfList.java index f44199bee..13748a3bf 100644 --- a/src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfList.java +++ b/src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfList.java @@ -26,9 +26,8 @@ package org.apache.fop.render.rtf.rtflib.rtfdoc; * the FOP project. */ -import java.io.Writer; import java.io.IOException; -import java.util.Date; +import java.io.Writer; import java.util.Random; /** diff --git a/src/sandbox/org/apache/fop/render/svg/SVGPainter.java b/src/sandbox/org/apache/fop/render/svg/SVGPainter.java index 2477099a4..bcc3a6913 100644 --- a/src/sandbox/org/apache/fop/render/svg/SVGPainter.java +++ b/src/sandbox/org/apache/fop/render/svg/SVGPainter.java @@ -34,17 +34,14 @@ import org.w3c.dom.Document; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.apache.xmlgraphics.image.loader.ImageException; import org.apache.xmlgraphics.image.loader.ImageInfo; import org.apache.xmlgraphics.image.loader.ImageManager; import org.apache.xmlgraphics.image.loader.ImageSessionContext; import org.apache.xmlgraphics.xmp.Metadata; -import org.apache.fop.apps.MimeConstants; import org.apache.fop.ResourceEventProducer; +import org.apache.fop.apps.MimeConstants; import org.apache.fop.render.ImageHandlerUtil; import org.apache.fop.render.RenderingContext; import org.apache.fop.render.intermediate.AbstractIFPainter; @@ -64,9 +61,6 @@ import org.apache.fop.util.XMLUtil; */ public class SVGPainter extends AbstractIFPainter implements SVGConstants { - /** logging instance */ - private static Log log = LogFactory.getLog(SVGPainter.class); - private AbstractSVGDocumentHandler parent; /** The SAX content handler that receives the generated XML events. */ diff --git a/test/java/org/apache/fop/GenericFOPTestCase.java b/test/java/org/apache/fop/GenericFOPTestCase.java index 26053cdad..5b51a34e1 100644 --- a/test/java/org/apache/fop/GenericFOPTestCase.java +++ b/test/java/org/apache/fop/GenericFOPTestCase.java @@ -31,12 +31,13 @@ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; -import org.apache.fop.apps.Fop; +import org.xml.sax.InputSource; + import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; import org.apache.fop.apps.MimeConstants; import org.apache.fop.util.DigestFilter; -import org.xml.sax.InputSource; /** * Framework for simple regression testing. @@ -76,8 +77,8 @@ public final class GenericFOPTestCase extends TestCase { public void testSimple() throws Exception { final String digestIn = "17bf13298796065f7775db8707133aeb"; final String digestOut = "e2761f51152f6663911e567901596707"; - final String fo = - "" + final String fo + = "" + " " + " " @@ -118,8 +119,8 @@ public final class GenericFOPTestCase extends TestCase { FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); foUserAgent.setCreationDate(new Date(10000)); MessageDigest outDigest = MessageDigest.getInstance("MD5"); - DigestOutputStream out = - new DigestOutputStream(new ByteArrayOutputStream(), outDigest); + DigestOutputStream out + = new DigestOutputStream(new ByteArrayOutputStream(), outDigest); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); InputSource source = new InputSource(new StringReader(fo)); DigestFilter filter = new DigestFilter("MD5"); diff --git a/test/java/org/apache/fop/config/BaseUserConfigTestCase.java b/test/java/org/apache/fop/config/BaseUserConfigTestCase.java index 5c803317e..6ce833312 100644 --- a/test/java/org/apache/fop/config/BaseUserConfigTestCase.java +++ b/test/java/org/apache/fop/config/BaseUserConfigTestCase.java @@ -100,7 +100,7 @@ public abstract class BaseUserConfigTestCase extends BasePDFTestCase { /** * @return user config File */ - abstract protected String getUserConfigFilename(); + protected abstract String getUserConfigFilename(); /* * @see junit.framework.TestCase#getName() diff --git a/test/java/org/apache/fop/events/EventChecker.java b/test/java/org/apache/fop/events/EventChecker.java index 767c590ed..afef11d87 100644 --- a/test/java/org/apache/fop/events/EventChecker.java +++ b/test/java/org/apache/fop/events/EventChecker.java @@ -40,7 +40,7 @@ class EventChecker extends Assert implements EventListener { if (event.getEventID().equals(expectedEventID)) { eventReceived = true; } else { - fail("Unexpected event: id = " + event.getEventID() + ": "+ msg); + fail("Unexpected event: id = " + event.getEventID() + ": " + msg); } } diff --git a/test/java/org/apache/fop/memory/Stats.java b/test/java/org/apache/fop/memory/Stats.java index 9e371251d..354952347 100644 --- a/test/java/org/apache/fop/memory/Stats.java +++ b/test/java/org/apache/fop/memory/Stats.java @@ -71,7 +71,7 @@ class Stats { public void dumpFinalStats() { long duration = System.currentTimeMillis() - startTime; System.out.println("Final statistics"); - System.out.println("Pages produced: " +totalPagesProduced); + System.out.println("Pages produced: " + totalPagesProduced); long ppm = 60000 * totalPagesProduced / duration; System.out.println("Average speed: " + ppm + "ppm"); } diff --git a/test/java/org/apache/fop/render/pdf/PDFCMapTestCase.java b/test/java/org/apache/fop/render/pdf/PDFCMapTestCase.java index f5d2f84cf..bd5c8ade1 100644 --- a/test/java/org/apache/fop/render/pdf/PDFCMapTestCase.java +++ b/test/java/org/apache/fop/render/pdf/PDFCMapTestCase.java @@ -27,38 +27,38 @@ import org.apache.fop.pdf.CMapBuilder; /** Simple sanity test of the PDFCmap class */ public class PDFCMapTestCase extends TestCase { + private static final String EOL = "\n"; public void testPDFCMapFillInPDF() throws Exception { - final String EOL = "\n"; - final String expected = - "%!PS-Adobe-3.0 Resource-CMap" + EOL - +"%%DocumentNeededResources: ProcSet (CIDInit)" + EOL - +"%%IncludeResource: ProcSet (CIDInit)" + EOL - +"%%BeginResource: CMap (test)" + EOL - +"%%EndComments" + EOL - +"/CIDInit /ProcSet findresource begin" + EOL - +"12 dict begin" + EOL - +"begincmap" + EOL - +"/CIDSystemInfo 3 dict dup begin" + EOL - +" /Registry (Adobe) def" + EOL - +" /Ordering (Identity) def" + EOL - +" /Supplement 0 def" + EOL - +"end def" + EOL - +"/CMapVersion 1 def" + EOL - +"/CMapType 1 def" + EOL - +"/CMapName /test def" + EOL - +"1 begincodespacerange" + EOL - +"<0000> " + EOL - +"endcodespacerange" + EOL - +"1 begincidrange" + EOL - +"<0000> 0" + EOL - +"endcidrange" + EOL - +"endcmap" + EOL - +"CMapName currentdict /CMap defineresource pop" + EOL - +"end" + EOL - +"end" + EOL - +"%%EndResource" + EOL - +"%%EOF" + EOL + final String expected + = "%!PS-Adobe-3.0 Resource-CMap" + EOL + + "%%DocumentNeededResources: ProcSet (CIDInit)" + EOL + + "%%IncludeResource: ProcSet (CIDInit)" + EOL + + "%%BeginResource: CMap (test)" + EOL + + "%%EndComments" + EOL + + "/CIDInit /ProcSet findresource begin" + EOL + + "12 dict begin" + EOL + + "begincmap" + EOL + + "/CIDSystemInfo 3 dict dup begin" + EOL + + " /Registry (Adobe) def" + EOL + + " /Ordering (Identity) def" + EOL + + " /Supplement 0 def" + EOL + + "end def" + EOL + + "/CMapVersion 1 def" + EOL + + "/CMapType 1 def" + EOL + + "/CMapName /test def" + EOL + + "1 begincodespacerange" + EOL + + "<0000> " + EOL + + "endcodespacerange" + EOL + + "1 begincidrange" + EOL + + "<0000> 0" + EOL + + "endcidrange" + EOL + + "endcmap" + EOL + + "CMapName currentdict /CMap defineresource pop" + EOL + + "end" + EOL + + "end" + EOL + + "%%EndResource" + EOL + + "%%EOF" + EOL ; final StringWriter w = new StringWriter(); diff --git a/test/java/org/apache/fop/util/DigestFilter.java b/test/java/org/apache/fop/util/DigestFilter.java index 0384b42df..94e8d67d2 100644 --- a/test/java/org/apache/fop/util/DigestFilter.java +++ b/test/java/org/apache/fop/util/DigestFilter.java @@ -43,7 +43,7 @@ import org.xml.sax.helpers.XMLFilterImpl; public class DigestFilter extends XMLFilterImpl { private MessageDigest digest; - private byte value[]; + private byte[] value; private boolean isNamespaceAware; public DigestFilter(String algorithm) throws NoSuchAlgorithmException { @@ -133,7 +133,7 @@ public class DigestFilter extends XMLFilterImpl { */ public void setFeature(String feature, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { - if(feature.equals("http://xml.org/sax/features/namespaces")) { + if (feature.equals("http://xml.org/sax/features/namespaces")) { isNamespaceAware = value; } super.setFeature(feature, value); -- cgit v1.2.3 From 26393f0e181ca1c71c83e594fa67cc7c26b49df3 Mon Sep 17 00:00:00 2001 From: Vincent Hennebert Date: Wed, 25 Aug 2010 15:43:55 +0000 Subject: Removed old Renderer implementations for AFP, PCL, PDF, PS. git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@989178 13f79535-47bb-0310-9956-ffa450edef68 --- .../content/xdocs/trunk/configuration.xml | 2 + .../services/org.apache.fop.render.Renderer | 4 - .../org.apache.fop.render.afp.AFPImageHandler | 5 - .../org.apache.fop.render.pdf.PDFImageHandler | 5 - .../org/apache/fop/cli/CommandLineOptions.java | 6 +- src/java/org/apache/fop/pdf/PDFFactory.java | 3 + .../fop/render/AbstractImageHandlerRegistry.java | 209 --- .../org/apache/fop/render/afp/AFPImageHandler.java | 41 - .../fop/render/afp/AFPImageHandlerGraphics2D.java | 41 - .../fop/render/afp/AFPImageHandlerRegistry.java | 42 - .../render/afp/AFPImageHandlerRenderedImage.java | 20 - .../apache/fop/render/afp/AFPImageHandlerXML.java | 77 - .../org/apache/fop/render/afp/AFPRenderer.java | 924 ------------ .../fop/render/afp/AFPRendererConfigurator.java | 23 +- .../apache/fop/render/afp/AFPRendererMaker.java | 58 - .../org/apache/fop/render/afp/AFPSVGHandler.java | 2 +- .../afp/AbstractAFPImageHandlerRawStream.java | 15 - .../fop/render/pcl/PCLGraphics2DAdapter.java | 123 -- .../org/apache/fop/render/pcl/PCLRenderer.java | 1516 -------------------- .../fop/render/pcl/PCLRendererConfigurator.java | 16 +- .../apache/fop/render/pcl/PCLRendererMaker.java | 57 - .../org/apache/fop/render/pcl/PCLSVGHandler.java | 3 +- .../fop/render/pdf/PDFGraphics2DAdapter.java | 132 -- .../org/apache/fop/render/pdf/PDFImageHandler.java | 52 - .../fop/render/pdf/PDFImageHandlerGraphics2D.java | 29 +- .../fop/render/pdf/PDFImageHandlerRawCCITTFax.java | 29 +- .../fop/render/pdf/PDFImageHandlerRawJPEG.java | 29 +- .../fop/render/pdf/PDFImageHandlerRegistry.java | 36 - .../render/pdf/PDFImageHandlerRenderedImage.java | 29 +- .../apache/fop/render/pdf/PDFImageHandlerXML.java | 72 - .../org/apache/fop/render/pdf/PDFRenderer.java | 1361 ------------------ .../fop/render/pdf/PDFRendererConfigurator.java | 40 +- .../apache/fop/render/pdf/PDFRendererMaker.java | 55 - .../org/apache/fop/render/pdf/PDFSVGHandler.java | 159 +- .../apache/fop/render/ps/PSGraphics2DAdapter.java | 14 +- src/java/org/apache/fop/render/ps/PSRenderer.java | 1290 ----------------- .../fop/render/ps/PSRendererConfigurator.java | 16 +- .../org/apache/fop/render/ps/PSRendererMaker.java | 54 - .../org/apache/fop/render/ps/PSSVGHandler.java | 2 +- status.xml | 4 + test/java/org/apache/fop/StandardTestSuite.java | 2 - .../org/apache/fop/fonts/TrueTypeAnsiTestCase.java | 107 -- test/java/org/apache/fop/fonts/fonttest.xsl | 24 - .../org/apache/fop/render/RendererFactoryTest.java | 15 - .../fop/render/ps/ImageHandlingTestCase.java | 48 +- .../render/ps/ResourceOptimizationTestCase.java | 22 +- 46 files changed, 60 insertions(+), 6753 deletions(-) delete mode 100644 src/java/META-INF/services/org.apache.fop.render.afp.AFPImageHandler delete mode 100644 src/java/META-INF/services/org.apache.fop.render.pdf.PDFImageHandler delete mode 100644 src/java/org/apache/fop/render/AbstractImageHandlerRegistry.java delete mode 100644 src/java/org/apache/fop/render/afp/AFPImageHandlerRegistry.java delete mode 100644 src/java/org/apache/fop/render/afp/AFPImageHandlerXML.java delete mode 100644 src/java/org/apache/fop/render/afp/AFPRenderer.java delete mode 100644 src/java/org/apache/fop/render/afp/AFPRendererMaker.java delete mode 100644 src/java/org/apache/fop/render/pcl/PCLGraphics2DAdapter.java delete mode 100644 src/java/org/apache/fop/render/pcl/PCLRenderer.java delete mode 100644 src/java/org/apache/fop/render/pcl/PCLRendererMaker.java delete mode 100644 src/java/org/apache/fop/render/pdf/PDFGraphics2DAdapter.java delete mode 100644 src/java/org/apache/fop/render/pdf/PDFImageHandler.java delete mode 100644 src/java/org/apache/fop/render/pdf/PDFImageHandlerRegistry.java delete mode 100644 src/java/org/apache/fop/render/pdf/PDFImageHandlerXML.java delete mode 100644 src/java/org/apache/fop/render/pdf/PDFRenderer.java delete mode 100644 src/java/org/apache/fop/render/pdf/PDFRendererMaker.java delete mode 100644 src/java/org/apache/fop/render/ps/PSRenderer.java delete mode 100644 src/java/org/apache/fop/render/ps/PSRendererMaker.java delete mode 100644 test/java/org/apache/fop/fonts/TrueTypeAnsiTestCase.java delete mode 100644 test/java/org/apache/fop/fonts/fonttest.xsl (limited to 'test') diff --git a/src/documentation/content/xdocs/trunk/configuration.xml b/src/documentation/content/xdocs/trunk/configuration.xml index 0f4100bf7..aae7de7f0 100644 --- a/src/documentation/content/xdocs/trunk/configuration.xml +++ b/src/documentation/content/xdocs/trunk/configuration.xml @@ -151,6 +151,7 @@ default-page-settings element to specify the two values. "height" 11 inches, "width" 8.26 inches + use-cache boolean (true, false) diff --git a/src/java/META-INF/services/org.apache.fop.render.Renderer b/src/java/META-INF/services/org.apache.fop.render.Renderer index 0e6f12cb5..2bf59a805 100644 --- a/src/java/META-INF/services/org.apache.fop.render.Renderer +++ b/src/java/META-INF/services/org.apache.fop.render.Renderer @@ -1,10 +1,6 @@ -org.apache.fop.render.pdf.PDFRendererMaker -org.apache.fop.render.ps.PSRendererMaker org.apache.fop.render.txt.TXTRendererMaker org.apache.fop.render.bitmap.PNGRendererMaker org.apache.fop.render.bitmap.TIFFRendererMaker org.apache.fop.render.xml.XMLRendererMaker org.apache.fop.render.awt.AWTRendererMaker org.apache.fop.render.print.PrintRendererMaker -org.apache.fop.render.afp.AFPRendererMaker -org.apache.fop.render.pcl.PCLRendererMaker \ No newline at end of file diff --git a/src/java/META-INF/services/org.apache.fop.render.afp.AFPImageHandler b/src/java/META-INF/services/org.apache.fop.render.afp.AFPImageHandler deleted file mode 100644 index 3f8c8dea6..000000000 --- a/src/java/META-INF/services/org.apache.fop.render.afp.AFPImageHandler +++ /dev/null @@ -1,5 +0,0 @@ -org.apache.fop.render.afp.AFPImageHandlerRenderedImage -org.apache.fop.render.afp.AFPImageHandlerRawCCITTFax -org.apache.fop.render.afp.AFPImageHandlerRawStream -org.apache.fop.render.afp.AFPImageHandlerGraphics2D -org.apache.fop.render.afp.AFPImageHandlerXML diff --git a/src/java/META-INF/services/org.apache.fop.render.pdf.PDFImageHandler b/src/java/META-INF/services/org.apache.fop.render.pdf.PDFImageHandler deleted file mode 100644 index 18fc3e96a..000000000 --- a/src/java/META-INF/services/org.apache.fop.render.pdf.PDFImageHandler +++ /dev/null @@ -1,5 +0,0 @@ -org.apache.fop.render.pdf.PDFImageHandlerRawJPEG -org.apache.fop.render.pdf.PDFImageHandlerRawCCITTFax -org.apache.fop.render.pdf.PDFImageHandlerGraphics2D -org.apache.fop.render.pdf.PDFImageHandlerRenderedImage -org.apache.fop.render.pdf.PDFImageHandlerXML diff --git a/src/java/org/apache/fop/cli/CommandLineOptions.java b/src/java/org/apache/fop/cli/CommandLineOptions.java index fbd263633..6b4ec1a1d 100644 --- a/src/java/org/apache/fop/cli/CommandLineOptions.java +++ b/src/java/org/apache/fop/cli/CommandLineOptions.java @@ -51,7 +51,7 @@ import org.apache.fop.render.awt.AWTRenderer; import org.apache.fop.render.intermediate.IFContext; import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFSerializer; -import org.apache.fop.render.pdf.PDFRenderer; +import org.apache.fop.render.pdf.PDFConfigurationConstants; import org.apache.fop.render.print.PagesMode; import org.apache.fop.render.print.PrintRenderer; import org.apache.fop.render.xml.XMLRenderer; @@ -805,14 +805,14 @@ public class CommandLineOptions { private PDFEncryptionParams getPDFEncryptionParams() throws FOPException { PDFEncryptionParams params = (PDFEncryptionParams)renderingOptions.get( - PDFRenderer.ENCRYPTION_PARAMS); + PDFConfigurationConstants.ENCRYPTION_PARAMS); if (params == null) { if (!PDFEncryptionManager.checkAvailableAlgorithms()) { throw new FOPException("PDF encryption requested but it is not available." + " Please make sure MD5 and RC4 algorithms are available."); } params = new PDFEncryptionParams(); - renderingOptions.put(PDFRenderer.ENCRYPTION_PARAMS, params); + renderingOptions.put(PDFConfigurationConstants.ENCRYPTION_PARAMS, params); } return params; } diff --git a/src/java/org/apache/fop/pdf/PDFFactory.java b/src/java/org/apache/fop/pdf/PDFFactory.java index 4c00f3187..8ebd15127 100644 --- a/src/java/org/apache/fop/pdf/PDFFactory.java +++ b/src/java/org/apache/fop/pdf/PDFFactory.java @@ -65,6 +65,9 @@ import org.apache.fop.fonts.type1.PFBParser; */ public class PDFFactory { + /** Resolution of the User Space coordinate system (72dpi). */ + public static final int DEFAULT_PDF_RESOLUTION = 72; + private PDFDocument document; private Log log = LogFactory.getLog(PDFFactory.class); diff --git a/src/java/org/apache/fop/render/AbstractImageHandlerRegistry.java b/src/java/org/apache/fop/render/AbstractImageHandlerRegistry.java deleted file mode 100644 index 4196a1b19..000000000 --- a/src/java/org/apache/fop/render/AbstractImageHandlerRegistry.java +++ /dev/null @@ -1,209 +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; - -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.apache.xmlgraphics.image.loader.Image; -import org.apache.xmlgraphics.image.loader.ImageFlavor; -import org.apache.xmlgraphics.util.Service; - -/** - * This class holds references to various image handlers used by the renderers. It also - * supports automatic discovery of additional handlers available through - * the class path. - */ -public abstract class AbstractImageHandlerRegistry { - - /** the logger */ - private static Log log = LogFactory.getLog(AbstractImageHandlerRegistry.class); - - private static final Comparator HANDLER_COMPARATOR = new Comparator() { - public int compare(Object o1, Object o2) { - ImageHandlerBase h1 = (ImageHandlerBase)o1; - ImageHandlerBase h2 = (ImageHandlerBase)o2; - return h1.getPriority() - h2.getPriority(); - } - }; - - /** Map containing image handlers for various MIME types */ - private final Map/**/ handlers - = new java.util.HashMap/**/(); - - /** List containing the same handlers as above but ordered by priority */ - private final List/**/ handlerList - = new java.util.LinkedList/**/(); - - /** Sorted Set of registered handlers */ - private ImageFlavor[] supportedFlavors = new ImageFlavor[0]; - - private int handlerRegistrations; - private int lastSync; - - /** - * Default constructor. - */ - public AbstractImageHandlerRegistry() { - discoverHandlers(); - } - - /** - * Add an ImageHandler. The handler itself is inspected to find out what it supports. - * @param classname the fully qualified class name - */ - public void addHandler(String classname) { - try { - ImageHandlerBase handlerInstance - = (ImageHandlerBase)Class.forName(classname).newInstance(); - addHandler(handlerInstance); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("Could not find " - + classname); - } catch (InstantiationException e) { - throw new IllegalArgumentException("Could not instantiate " - + classname); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException("Could not access " - + classname); - } catch (ClassCastException e) { - throw new IllegalArgumentException(classname - + " is not an " - + getHandlerClass().getName()); - } - } - - /** - * Add an image handler. The handler itself is inspected to find out what it supports. - * @param handler the ImageHandler instance - */ - public synchronized void addHandler(ImageHandlerBase handler) { - this.handlers.put(handler.getSupportedImageClass(), handler); - - //Sorted insert - ListIterator iter = this.handlerList.listIterator(); - while (iter.hasNext()) { - ImageHandlerBase h = (ImageHandlerBase)iter.next(); - if (getHandlerComparator().compare(handler, h) < 0) { - iter.previous(); - break; - } - } - iter.add(handler); - this.handlerRegistrations++; - } - - /** - * Returns an ImageHandler which handles an specific image type given the MIME type - * of the image. - * @param img the Image to be handled - * @return the ImageHandler responsible for handling the image or null if none is available - */ - public ImageHandlerBase getHandler(Image img) { - return getHandler(img.getClass()); - } - - /** - * Returns an ImageHandler which handles an specific image type given the MIME type - * of the image. - * @param imageClass the Image subclass for which to get a handler - * @return the ImageHandler responsible for handling the image or null if none is available - */ - public synchronized ImageHandlerBase getHandler(Class imageClass) { - ImageHandlerBase handler = null; - Class cl = imageClass; - while (cl != null) { - handler = (ImageHandlerBase)handlers.get(cl); - if (handler != null) { - break; - } - cl = cl.getSuperclass(); - } - return handler; - } - - /** - * Returns the ordered array of supported image flavors. - * @return the array of image flavors - */ - public synchronized ImageFlavor[] getSupportedFlavors() { - if (this.lastSync != this.handlerRegistrations) { - //Extract all ImageFlavors into a single array - List flavors = new java.util.ArrayList(); - Iterator iter = this.handlerList.iterator(); - while (iter.hasNext()) { - ImageFlavor[] f = ((ImageHandlerBase)iter.next()).getSupportedImageFlavors(); - for (int i = 0; i < f.length; i++) { - flavors.add(f[i]); - } - } - this.supportedFlavors = (ImageFlavor[])flavors.toArray(new ImageFlavor[flavors.size()]); - this.lastSync = this.handlerRegistrations; - } - return this.supportedFlavors; - } - - /** - * Discovers ImageHandler implementations through the classpath and dynamically - * registers them. - */ - private void discoverHandlers() { - // add mappings from available services - Class imageHandlerClass = getHandlerClass(); - Iterator providers = Service.providers(imageHandlerClass); - if (providers != null) { - while (providers.hasNext()) { - ImageHandlerBase handler = (ImageHandlerBase)providers.next(); - try { - if (log.isDebugEnabled()) { - log.debug("Dynamically adding ImageHandler: " - + handler.getClass().getName()); - } - addHandler(handler); - } catch (IllegalArgumentException e) { - log.error("Error while adding ImageHandler", e); - } - - } - } - } - - /** - * Returns the ImageHandler comparator - * - * @return the ImageHandler comparator - */ - public Comparator getHandlerComparator() { - return HANDLER_COMPARATOR; - } - - /** - * Returns the ImageHandler implementing class - * - * @return the ImageHandler implementing class - */ - public abstract Class getHandlerClass(); -} diff --git a/src/java/org/apache/fop/render/afp/AFPImageHandler.java b/src/java/org/apache/fop/render/afp/AFPImageHandler.java index 4a985db00..244263213 100644 --- a/src/java/org/apache/fop/render/afp/AFPImageHandler.java +++ b/src/java/org/apache/fop/render/afp/AFPImageHandler.java @@ -19,10 +19,7 @@ package org.apache.fop.render.afp; -import java.awt.Point; import java.awt.Rectangle; -import java.awt.geom.Rectangle2D; -import java.io.IOException; import java.util.Map; import org.apache.fop.afp.AFPDataObjectInfo; @@ -43,44 +40,6 @@ public abstract class AFPImageHandler implements ImageHandlerBase { private final AFPForeignAttributeReader foreignAttributeReader = new AFPForeignAttributeReader(); - /** - * Generates an intermediate AFPDataObjectInfo that is later used to construct - * the appropriate data object in the AFP DataStream. - * - * @param rendererImageInfo the renderer image info - * @return a data object info object - * @throws IOException thrown if an I/O exception of some sort has occurred. - */ - public AFPDataObjectInfo generateDataObjectInfo( - AFPRendererImageInfo rendererImageInfo) throws IOException { - AFPDataObjectInfo dataObjectInfo = createDataObjectInfo(); - - // set resource information - setResourceInformation(dataObjectInfo, - rendererImageInfo.getURI(), - rendererImageInfo.getForeignAttributes()); - - - Point origin = rendererImageInfo.getOrigin(); - Rectangle2D position = rendererImageInfo.getPosition(); - int srcX = Math.round(origin.x + (float)position.getX()); - int srcY = Math.round(origin.y + (float)position.getY()); - Rectangle targetRect = new Rectangle( - srcX, - srcY, - (int)Math.round(position.getWidth()), - (int)Math.round(position.getHeight())); - - AFPRendererContext rendererContext - = (AFPRendererContext)rendererImageInfo.getRendererContext(); - AFPInfo afpInfo = rendererContext.getInfo(); - AFPPaintingState paintingState = afpInfo.getPaintingState(); - - dataObjectInfo.setObjectAreaInfo(createObjectAreaInfo(paintingState, targetRect)); - - return dataObjectInfo; - } - /** * Sets resource information on the data object info. * @param dataObjectInfo the data object info instance diff --git a/src/java/org/apache/fop/render/afp/AFPImageHandlerGraphics2D.java b/src/java/org/apache/fop/render/afp/AFPImageHandlerGraphics2D.java index aaaecf2ea..07b712ceb 100644 --- a/src/java/org/apache/fop/render/afp/AFPImageHandlerGraphics2D.java +++ b/src/java/org/apache/fop/render/afp/AFPImageHandlerGraphics2D.java @@ -49,47 +49,6 @@ public class AFPImageHandlerGraphics2D extends AFPImageHandler implements ImageH ImageFlavor.GRAPHICS2D }; - /** {@inheritDoc} */ - public AFPDataObjectInfo generateDataObjectInfo( - AFPRendererImageInfo rendererImageInfo) throws IOException { - - AFPRendererContext rendererContext - = (AFPRendererContext)rendererImageInfo.getRendererContext(); - AFPInfo afpInfo = rendererContext.getInfo(); - ImageGraphics2D imageG2D = (ImageGraphics2D)rendererImageInfo.getImage(); - Graphics2DImagePainter painter = imageG2D.getGraphics2DImagePainter(); - - if (afpInfo.paintAsBitmap()) { - int x = afpInfo.getX(); - int y = afpInfo.getY(); - int width = afpInfo.getWidth(); - int height = afpInfo.getHeight(); - AFPPaintingState paintingState = afpInfo.getPaintingState(); - AFPGraphics2DAdapter g2dAdapter = new AFPGraphics2DAdapter(paintingState); - g2dAdapter.paintImage(painter, rendererContext, x, y, width, height); - return null; - } else { - AFPGraphicsObjectInfo graphicsObjectInfo - = (AFPGraphicsObjectInfo)super.generateDataObjectInfo(rendererImageInfo); - - setDefaultResourceLevel(graphicsObjectInfo, afpInfo.getResourceManager()); - - // set mime type (unsupported by MOD:CA registry) - graphicsObjectInfo.setMimeType(MimeConstants.MIME_AFP_GOCA); - - // set g2d - boolean textAsShapes = false; - AFPGraphics2D g2d = afpInfo.createGraphics2D(textAsShapes); - - graphicsObjectInfo.setGraphics2D(g2d); - - // set painter - graphicsObjectInfo.setPainter(painter); - - return graphicsObjectInfo; - } - } - private void setDefaultResourceLevel(AFPGraphicsObjectInfo graphicsObjectInfo, AFPResourceManager resourceManager) { AFPResourceInfo resourceInfo = graphicsObjectInfo.getResourceInfo(); diff --git a/src/java/org/apache/fop/render/afp/AFPImageHandlerRegistry.java b/src/java/org/apache/fop/render/afp/AFPImageHandlerRegistry.java deleted file mode 100644 index 59ca6cf38..000000000 --- a/src/java/org/apache/fop/render/afp/AFPImageHandlerRegistry.java +++ /dev/null @@ -1,42 +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.afp; - -import org.apache.fop.render.AbstractImageHandlerRegistry; - -/** - * This class holds references to various image handlers used by the AFP renderer. It also - * supports automatic discovery of additional handlers available through - * the class path. - */ -public class AFPImageHandlerRegistry extends AbstractImageHandlerRegistry { - - /** - * Main constructor - */ - public AFPImageHandlerRegistry() { - } - - /** {@inheritDoc} */ - public Class getHandlerClass() { - return AFPImageHandler.class; - } - -} diff --git a/src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java b/src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java index 09b93d41a..ca0544542 100644 --- a/src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java +++ b/src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java @@ -66,26 +66,6 @@ public class AFPImageHandlerRenderedImage extends AFPImageHandler implements Ima ImageFlavor.RENDERED_IMAGE }; - /** {@inheritDoc} */ - public AFPDataObjectInfo generateDataObjectInfo( - AFPRendererImageInfo rendererImageInfo) throws IOException { - AFPImageObjectInfo imageObjectInfo - = (AFPImageObjectInfo)super.generateDataObjectInfo(rendererImageInfo); - - AFPRendererContext rendererContext - = (AFPRendererContext)rendererImageInfo.getRendererContext(); - AFPInfo afpInfo = rendererContext.getInfo(); - - setDefaultResourceLevel(imageObjectInfo, afpInfo.getResourceManager()); - - AFPPaintingState paintingState = afpInfo.getPaintingState(); - ImageRendered imageRendered = (ImageRendered) rendererImageInfo.img; - Dimension targetSize = new Dimension(afpInfo.getWidth(), afpInfo.getHeight()); - - updateDataObjectInfo(imageObjectInfo, paintingState, imageRendered, targetSize); - return imageObjectInfo; - } - private AFPDataObjectInfo updateDataObjectInfo // CSOK: MethodLength (AFPImageObjectInfo imageObjectInfo, AFPPaintingState paintingState, ImageRendered imageRendered, Dimension targetSize) diff --git a/src/java/org/apache/fop/render/afp/AFPImageHandlerXML.java b/src/java/org/apache/fop/render/afp/AFPImageHandlerXML.java deleted file mode 100644 index 7ea1a7a10..000000000 --- a/src/java/org/apache/fop/render/afp/AFPImageHandlerXML.java +++ /dev/null @@ -1,77 +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.afp; - -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.util.Map; - -import org.apache.fop.afp.AFPDataObjectInfo; -import org.apache.fop.render.RendererContext; -import org.apache.fop.render.RendererContextConstants; -import org.apache.xmlgraphics.image.loader.ImageFlavor; -import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM; -import org.w3c.dom.Document; - -/** - * PDFImageHandler implementation which handles XML-based images. - */ -public class AFPImageHandlerXML extends AFPImageHandler { - - private static final ImageFlavor[] FLAVORS = new ImageFlavor[] { - ImageFlavor.XML_DOM, - }; - - /** {@inheritDoc} */ - public AFPDataObjectInfo generateDataObjectInfo(AFPRendererImageInfo rendererImageInfo) - throws IOException { - RendererContext rendererContext = rendererImageInfo.getRendererContext(); - AFPRenderer renderer = (AFPRenderer)rendererContext.getRenderer(); - ImageXMLDOM imgXML = (ImageXMLDOM)rendererImageInfo.getImage(); - Document doc = imgXML.getDocument(); - String ns = imgXML.getRootNamespace(); - Map foreignAttributes = (Map)rendererContext.getProperty( - RendererContextConstants.FOREIGN_ATTRIBUTES); - Rectangle2D pos = rendererImageInfo.getPosition(); - renderer.renderDocument(doc, ns, pos, foreignAttributes); - return null; - } - - /** {@inheritDoc} */ - public int getPriority() { - return 400; - } - - /** {@inheritDoc} */ - public Class getSupportedImageClass() { - return ImageXMLDOM.class; - } - - /** {@inheritDoc} */ - public ImageFlavor[] getSupportedImageFlavors() { - return FLAVORS; - } - - /** {@inheritDoc} */ - protected AFPDataObjectInfo createDataObjectInfo() { - return null; - } - -} diff --git a/src/java/org/apache/fop/render/afp/AFPRenderer.java b/src/java/org/apache/fop/render/afp/AFPRenderer.java deleted file mode 100644 index df6cf2c5f..000000000 --- a/src/java/org/apache/fop/render/afp/AFPRenderer.java +++ /dev/null @@ -1,924 +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.afp; - -import java.awt.Color; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.RenderedImage; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.xmlgraphics.image.loader.ImageException; -import org.apache.xmlgraphics.image.loader.ImageFlavor; -import org.apache.xmlgraphics.image.loader.ImageInfo; -import org.apache.xmlgraphics.image.loader.ImageManager; -import org.apache.xmlgraphics.image.loader.ImageSessionContext; -import org.apache.xmlgraphics.image.loader.util.ImageUtil; -import org.apache.xmlgraphics.ps.ImageEncodingHelper; - -import org.apache.fop.ResourceEventProducer; -import org.apache.fop.afp.AFPBorderPainter; -import org.apache.fop.afp.AFPDataObjectInfo; -import org.apache.fop.afp.AFPDitheredRectanglePainter; -import org.apache.fop.afp.AFPEventProducer; -import org.apache.fop.afp.AFPPaintingState; -import org.apache.fop.afp.AFPRectanglePainter; -import org.apache.fop.afp.AFPResourceLevelDefaults; -import org.apache.fop.afp.AFPResourceManager; -import org.apache.fop.afp.AFPTextDataInfo; -import org.apache.fop.afp.AFPUnitConverter; -import org.apache.fop.afp.AbstractAFPPainter; -import org.apache.fop.afp.BorderPaintingInfo; -import org.apache.fop.afp.DataStream; -import org.apache.fop.afp.RectanglePaintingInfo; -import org.apache.fop.afp.fonts.AFPFont; -import org.apache.fop.afp.fonts.AFPFontAttributes; -import org.apache.fop.afp.fonts.AFPFontCollection; -import org.apache.fop.afp.fonts.AFPPageFonts; -import org.apache.fop.afp.fonts.CharacterSet; -import org.apache.fop.afp.modca.PageObject; -import org.apache.fop.afp.modca.ResourceObject; -import org.apache.fop.afp.util.DefaultFOPResourceAccessor; -import org.apache.fop.afp.util.ResourceAccessor; -import org.apache.fop.apps.FOPException; -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.area.CTM; -import org.apache.fop.area.OffDocumentExtensionAttachment; -import org.apache.fop.area.OffDocumentItem; -import org.apache.fop.area.PageSequence; -import org.apache.fop.area.PageViewport; -import org.apache.fop.area.Trait; -import org.apache.fop.area.inline.Image; -import org.apache.fop.area.inline.Leader; -import org.apache.fop.area.inline.TextArea; -import org.apache.fop.datatypes.URISpecification; -import org.apache.fop.fo.extensions.ExtensionAttachment; -import org.apache.fop.fonts.Font; -import org.apache.fop.fonts.FontCollection; -import org.apache.fop.fonts.FontInfo; -import org.apache.fop.fonts.FontManager; -import org.apache.fop.render.AbstractPathOrientedRenderer; -import org.apache.fop.render.Graphics2DAdapter; -import org.apache.fop.render.RendererContext; -import org.apache.fop.render.afp.extensions.AFPElementMapping; -import org.apache.fop.render.afp.extensions.AFPExtensionAttachment; -import org.apache.fop.render.afp.extensions.AFPIncludeFormMap; -import org.apache.fop.render.afp.extensions.AFPInvokeMediumMap; -import org.apache.fop.render.afp.extensions.AFPPageOverlay; -import org.apache.fop.render.afp.extensions.AFPPageSetup; - -/** - * This is an implementation of a FOP Renderer that renders areas to AFP. - *

- * A renderer is primarily designed to convert a given area tree into the output - * document format. It should be able to produce pages and fill the pages with - * the text and graphical content. Usually the output is sent to an output - * stream. Some output formats may support extra information that is not - * available from the area tree or depends on the destination of the document. - * Each renderer is given an area tree to render to its output format. The area - * tree is simply a representation of the pages and the placement of text and - * graphical objects on those pages. - *

- *

- * The renderer will be given each page as it is ready and an output stream to - * write the data out. All pages are supplied in the order they appear in the - * document. In order to save memory it is possible to render the pages out of - * order. Any page that is not ready to be rendered is setup by the renderer - * first so that it can reserve a space or reference for when the page is ready - * to be rendered.The renderer is responsible for managing the output format and - * associated data and flow. - *

- *

- * Each renderer is totally responsible for its output format. Because font - * metrics (and therefore layout) are obtained in two different ways depending - * on the renderer, the renderer actually sets up the fonts being used. The font - * metrics are used during the layout process to determine the size of - * characters. - *

- *

- * The render context is used by handlers. It contains information about the - * current state of the renderer, such as the page, the position, and any other - * miscellaneous objects that are required to draw into the page. - *

- *

- * A renderer is created by implementing the Renderer interface. However, the - * AbstractRenderer does most of what is needed, including iterating through the - * tree parts, so it is this that is extended. This means that this object only - * need to implement the basic functionality such as text, images, and lines. - * AbstractRenderer's methods can easily be overridden to handle things in a - * different way or do some extra processing. - *

- *

- * The relevant AreaTree structures that will need to be rendered are Page, - * Viewport, Region, Span, Block, Line, Inline. A renderer implementation - * renders each individual page, clips and aligns child areas to a viewport, - * handle all types of inline area, text, image etc and draws various lines and - * rectangles. - *

- * - * Note: There are specific extensions that have been added to the FO. They are - * specific to their location within the FO and have to be processed accordingly - * (ie. at the start or end of the page). - * - */ -public class AFPRenderer extends AbstractPathOrientedRenderer implements AFPCustomizable { - - private static final int X = 0; - private static final int Y = 1; - - /** the resource manager */ - private AFPResourceManager resourceManager; - - /** the painting state */ - private final AFPPaintingState paintingState; - - /** unit converter */ - private final AFPUnitConverter unitConv; - - /** the line painter */ - private AFPBorderPainter borderPainter; - - /** the map of page segments */ - private final Map/**/pageSegmentMap - = new java.util.HashMap/**/(); - - /** the map of saved incomplete pages */ - private final Map pages = new java.util.HashMap/**/(); - - /** the AFP datastream */ - private DataStream dataStream; - - /** the image handler registry */ - private final AFPImageHandlerRegistry imageHandlerRegistry; - - private AbstractAFPPainter rectanglePainter; - - /** the shading mode for filled rectangles */ - private AFPShadingMode shadingMode = AFPShadingMode.COLOR; - - /** medium map referenced used on previous page **/ - private String lastMediumMap; - - /** - * Constructor for AFPRenderer. - */ - public AFPRenderer() { - super(); - this.imageHandlerRegistry = new AFPImageHandlerRegistry(); - this.resourceManager = new AFPResourceManager(); - this.paintingState = new AFPPaintingState(); - this.unitConv = paintingState.getUnitConverter(); - } - - /** {@inheritDoc} */ - public void setupFontInfo(FontInfo inFontInfo) { - this.fontInfo = inFontInfo; - FontManager fontManager = userAgent.getFactory().getFontManager(); - FontCollection[] fontCollections = new FontCollection[] { - new AFPFontCollection(userAgent.getEventBroadcaster(), getFontList()) - }; - fontManager.setup(getFontInfo(), fontCollections); - } - - /** {@inheritDoc} */ - public void setUserAgent(FOUserAgent agent) { - super.setUserAgent(agent); - } - - /** {@inheritDoc} */ - public void startRenderer(OutputStream outputStream) throws IOException { - paintingState.setColor(Color.WHITE); - - this.dataStream = resourceManager.createDataStream(paintingState, outputStream); - this.borderPainter = new AFPBorderPainter(paintingState, dataStream); - this.rectanglePainter = createRectanglePainter(); - - dataStream.startDocument(); - } - - AbstractAFPPainter createRectanglePainter() { - if (AFPShadingMode.DITHERED.equals(this.shadingMode)) { - return new AFPDitheredRectanglePainter( - this.paintingState, this.dataStream, this.resourceManager); - } else { - return new AFPRectanglePainter( - this.paintingState, this.dataStream); - } - } - - /** {@inheritDoc} */ - public void stopRenderer() throws IOException { - dataStream.endDocument(); - resourceManager.writeToStream(); - resourceManager = null; - } - - /** {@inheritDoc} */ - public void startPageSequence(PageSequence pageSequence) { - super.startPageSequence(pageSequence); - try { - dataStream.startPageGroup(); - } catch (IOException e) { - log.error(e.getMessage()); - } - if (pageSequence.hasExtensionAttachments()) { - for (Iterator iter = pageSequence.getExtensionAttachments().iterator(); - iter.hasNext();) { - ExtensionAttachment attachment = (ExtensionAttachment)iter.next(); - if (attachment instanceof AFPInvokeMediumMap) { - AFPInvokeMediumMap imm = (AFPInvokeMediumMap)attachment; - String mediumMap = imm.getName(); - if (mediumMap != null) { - dataStream.createInvokeMediumMap(mediumMap); - } - } else if (attachment instanceof AFPPageSetup) { - AFPPageSetup aps = (AFPPageSetup)attachment; - String name = aps.getName(); - String value = aps.getValue(); - dataStream.createTagLogicalElement(name, value); - } - } - } - } - - /** {@inheritDoc} */ - public boolean supportsOutOfOrder() { - return false; - } - - /** {@inheritDoc} */ - public void preparePage(PageViewport page) { - int pageRotation = paintingState.getPageRotation(); - int pageWidth = paintingState.getPageWidth(); - int pageHeight = paintingState.getPageHeight(); - int resolution = paintingState.getResolution(); - dataStream.startPage(pageWidth, pageHeight, pageRotation, - resolution, resolution); - - renderPageObjectExtensions(page); - - PageObject currentPage = dataStream.savePage(); - pages.put(page, currentPage); - } - - /** {@inheritDoc} */ - public void processOffDocumentItem(OffDocumentItem odi) { - if (odi instanceof OffDocumentExtensionAttachment) { - ExtensionAttachment attachment = ((OffDocumentExtensionAttachment)odi).getAttachment(); - if (attachment != null) { - if (AFPExtensionAttachment.CATEGORY.equals(attachment.getCategory())) { - if (attachment instanceof AFPIncludeFormMap) { - handleIncludeFormMap((AFPIncludeFormMap)attachment); - } - } - } - } - } - - private void handleIncludeFormMap(AFPIncludeFormMap formMap) { - ResourceAccessor accessor = new DefaultFOPResourceAccessor( - getUserAgent(), null, null); - try { - this.resourceManager.createIncludedResource(formMap.getName(), - formMap.getSrc(), accessor, - ResourceObject.TYPE_FORMDEF); - } catch (IOException ioe) { - AFPEventProducer eventProducer - = AFPEventProducer.Provider.get(userAgent.getEventBroadcaster()); - eventProducer.resourceEmbeddingError(this, formMap.getName(), ioe); - } - } - - /** {@inheritDoc} */ - public Graphics2DAdapter getGraphics2DAdapter() { - return new AFPGraphics2DAdapter(paintingState); - } - - /** {@inheritDoc} */ - public void startVParea(CTM ctm, Rectangle2D clippingRect) { - saveGraphicsState(); - if (ctm != null) { - AffineTransform at = ctm.toAffineTransform(); - concatenateTransformationMatrix(at); - } - if (clippingRect != null) { - clipRect((float)clippingRect.getX() / 1000f, - (float)clippingRect.getY() / 1000f, - (float)clippingRect.getWidth() / 1000f, - (float)clippingRect.getHeight() / 1000f); - } - } - - /** {@inheritDoc} */ - public void endVParea() { - restoreGraphicsState(); - } - - /** {@inheritDoc} */ - protected void concatenateTransformationMatrix(AffineTransform at) { - if (!at.isIdentity()) { - paintingState.concatenate(at); - } - } - - /** - * Returns the base AFP transform - * - * @return the base AFP transform - */ - private AffineTransform getBaseTransform() { - AffineTransform baseTransform = new AffineTransform(); - double scale = unitConv.mpt2units(1); - baseTransform.scale(scale, scale); - return baseTransform; - } - - /** {@inheritDoc} */ - public void renderPage(PageViewport pageViewport) throws IOException, FOPException { - paintingState.clear(); - - Rectangle2D bounds = pageViewport.getViewArea(); - - AffineTransform baseTransform = getBaseTransform(); - paintingState.concatenate(baseTransform); - - if (pages.containsKey(pageViewport)) { - dataStream.restorePage( - (PageObject)pages.remove(pageViewport)); - } else { - int pageWidth - = Math.round(unitConv.mpt2units((float)bounds.getWidth())); - paintingState.setPageWidth(pageWidth); - - int pageHeight - = Math.round(unitConv.mpt2units((float)bounds.getHeight())); - paintingState.setPageHeight(pageHeight); - - int pageRotation = paintingState.getPageRotation(); - - int resolution = paintingState.getResolution(); - - // IMM should occur before BPG - renderInvokeMediumMap(pageViewport); - - dataStream.startPage(pageWidth, pageHeight, pageRotation, - resolution, resolution); - - renderPageObjectExtensions(pageViewport); - } - - super.renderPage(pageViewport); - - AFPPageFonts pageFonts = paintingState.getPageFonts(); - if (pageFonts != null && !pageFonts.isEmpty()) { - dataStream.addFontsToCurrentPage(pageFonts); - } - - dataStream.endPage(); - } - - /** {@inheritDoc} */ - public void drawBorderLine // CSOK: ParameterNumber - (float x1, float y1, float x2, float y2, - boolean horz, boolean startOrBefore, int style, Color col) { - BorderPaintingInfo borderPaintInfo - = new BorderPaintingInfo(x1, y1, x2, y2, horz, style, col); - borderPainter.paint(borderPaintInfo); - } - - /** {@inheritDoc} */ - public void fillRect(float x, float y, float width, float height) { - RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo(x, y, width, height); - try { - rectanglePainter.paint(rectanglePaintInfo); - } catch (IOException ioe) { - //TODO not ideal, but the AFPRenderer is legacy - throw new RuntimeException("I/O error while painting a filled rectangle", ioe); - } - } - - /** {@inheritDoc} */ - protected RendererContext instantiateRendererContext() { - return new AFPRendererContext(this, getMimeType()); - } - - /** {@inheritDoc} */ - protected RendererContext createRendererContext(int x, int y, int width, - int height, Map foreignAttributes) { - RendererContext context; - context = super.createRendererContext(x, y, width, height, - foreignAttributes); - context.setProperty(AFPRendererContextConstants.AFP_FONT_INFO, - this.fontInfo); - context.setProperty(AFPRendererContextConstants.AFP_RESOURCE_MANAGER, - this.resourceManager); - context.setProperty(AFPRendererContextConstants.AFP_PAINTING_STATE, paintingState); - return context; - } - - private static final ImageFlavor[] NATIVE_FLAVORS = new ImageFlavor[] { - ImageFlavor.XML_DOM, - /*ImageFlavor.RAW_PNG, */ // PNG not natively supported in AFP - ImageFlavor.RAW_JPEG, ImageFlavor.RAW_CCITTFAX, ImageFlavor.RAW_EPS, - ImageFlavor.RAW_TIFF, - ImageFlavor.GRAPHICS2D, ImageFlavor.BUFFERED_IMAGE, ImageFlavor.RENDERED_IMAGE }; - - private static final ImageFlavor[] FLAVORS = new ImageFlavor[] { - ImageFlavor.XML_DOM, - ImageFlavor.GRAPHICS2D, ImageFlavor.BUFFERED_IMAGE, ImageFlavor.RENDERED_IMAGE }; - - /** {@inheritDoc} */ - public void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) { - uri = URISpecification.getURL(uri); - paintingState.setImageUri(uri); - - Point origin = new Point(currentIPPosition, currentBPPosition); - Rectangle posInt = new Rectangle( - (int)Math.round(pos.getX()), - (int)Math.round(pos.getY()), - (int)Math.round(pos.getWidth()), - (int)Math.round(pos.getHeight()) - ); - int x = origin.x + posInt.x; - int y = origin.y + posInt.y; - - String name = (String)pageSegmentMap.get(uri); - if (name != null) { - float[] srcPts = {x, y, posInt.width, posInt.height}; - int[] coords = unitConv.mpts2units(srcPts); - int width = Math.round(unitConv.mpt2units(posInt.width)); - int height = Math.round(unitConv.mpt2units(posInt.height)); - dataStream.createIncludePageSegment(name, coords[X], coords[Y], width, height); - } else { - ImageManager manager = userAgent.getFactory().getImageManager(); - ImageInfo info = null; - try { - ImageSessionContext sessionContext = userAgent - .getImageSessionContext(); - info = manager.getImageInfo(uri, sessionContext); - - // Only now fully load/prepare the image - Map hints = ImageUtil.getDefaultHints(sessionContext); - - boolean nativeImagesSupported = paintingState.isNativeImagesSupported(); - ImageFlavor[] flavors = nativeImagesSupported ? NATIVE_FLAVORS : FLAVORS; - - // Load image - org.apache.xmlgraphics.image.loader.Image img = manager.getImage( - info, flavors, hints, sessionContext); - - // Handle image - AFPImageHandler imageHandler - = (AFPImageHandler)imageHandlerRegistry.getHandler(img); - if (imageHandler != null) { - RendererContext rendererContext = createRendererContext( - x, y, posInt.width, posInt.height, foreignAttributes); - AFPRendererImageInfo rendererImageInfo = new AFPRendererImageInfo( - uri, pos, origin, info, img, rendererContext, foreignAttributes); - AFPDataObjectInfo dataObjectInfo = null; - try { - dataObjectInfo = imageHandler.generateDataObjectInfo(rendererImageInfo); - // Create image - if (dataObjectInfo != null) { - resourceManager.createObject(dataObjectInfo); - } - } catch (IOException ioe) { - ResourceEventProducer eventProducer - = ResourceEventProducer.Provider.get(userAgent.getEventBroadcaster()); - eventProducer.imageWritingError(this, ioe); - throw ioe; - } - } else { - throw new UnsupportedOperationException( - "No AFPImageHandler available for image: " - + info + " (" + img.getClass().getName() + ")"); - } - - } catch (ImageException ie) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider - .get(userAgent.getEventBroadcaster()); - eventProducer.imageError(this, (info != null ? info.toString() - : uri), ie, null); - } catch (FileNotFoundException fe) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider - .get(userAgent.getEventBroadcaster()); - eventProducer.imageNotFound(this, (info != null ? info.toString() - : uri), fe, null); - } catch (IOException ioe) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider - .get(userAgent.getEventBroadcaster()); - eventProducer.imageIOError(this, (info != null ? info.toString() - : uri), ioe, null); - } - } - } - - /** - * Writes a RenderedImage to an OutputStream as raw sRGB bitmaps. - * - * @param image - * the RenderedImage - * @param out - * the OutputStream - * @throws IOException - * In case of an I/O error. - * @deprecated use ImageEncodingHelper.encodeRenderedImageAsRGB(image, out) - * directly instead - */ - public static void writeImage(RenderedImage image, OutputStream out) - throws IOException { - ImageEncodingHelper.encodeRenderedImageAsRGB(image, out); - } - - /** {@inheritDoc} */ - public void updateColor(Color col, boolean fill) { - if (fill) { - paintingState.setColor(col); - } - } - - /** {@inheritDoc} */ - public void restoreStateStackAfterBreakOut(List breakOutList) { - log.debug("Block.FIXED --> restoring context after break-out"); - paintingState.saveAll(breakOutList); - } - - /** {@inheritDoc} */ - protected List breakOutOfStateStack() { - log.debug("Block.FIXED --> break out"); - return paintingState.restoreAll(); - } - - /** {@inheritDoc} */ - public void saveGraphicsState() { - paintingState.save(); - } - - /** {@inheritDoc} */ - public void restoreGraphicsState() { - paintingState.restore(); - } - - /** {@inheritDoc} */ - public void renderImage(Image image, Rectangle2D pos) { - drawImage(image.getURL(), pos, image.getForeignAttributes()); - } - - /** {@inheritDoc} */ - public void renderText(TextArea text) { - renderInlineAreaBackAndBorders(text); - - // set font size - int fontSize = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue(); - paintingState.setFontSize(fontSize); - - // register font as necessary - String internalFontName = getInternalFontNameForArea(text); - Map/**/ fontMetricMap = fontInfo.getFonts(); - AFPFont font = (AFPFont)fontMetricMap.get(internalFontName); - AFPPageFonts pageFonts = paintingState.getPageFonts(); - AFPFontAttributes fontAttributes = pageFonts.registerFont(internalFontName, font, fontSize); - Font fnt = getFontFromArea(text); - - if (font.isEmbeddable()) { - CharacterSet charSet = font.getCharacterSet(fontSize); - try { - this.resourceManager.embedFont(font, charSet); - } catch (IOException ioe) { - AFPEventProducer eventProducer - = AFPEventProducer.Provider.get(userAgent.getEventBroadcaster()); - eventProducer.resourceEmbeddingError(this, charSet.getName(), ioe); - } - } - - // create text data info - AFPTextDataInfo textDataInfo = new AFPTextDataInfo(); - - int fontReference = fontAttributes.getFontReference(); - textDataInfo.setFontReference(fontReference); - - int x = (currentIPPosition + text.getBorderAndPaddingWidthStart()); - int y = (currentBPPosition + text.getOffset() + text.getBaselineOffset()); - - int[] coords = unitConv.mpts2units(new float[] {x, y} ); - textDataInfo.setX(coords[X]); - textDataInfo.setY(coords[Y]); - - Color color = (Color) text.getTrait(Trait.COLOR); - textDataInfo.setColor(color); - - int textWordSpaceAdjust = text.getTextWordSpaceAdjust(); - int textLetterSpaceAdjust = text.getTextLetterSpaceAdjust(); - int textWidth = font.getWidth(' ', fontSize) / 1000; - textWidth = 0; //JM, the above is strange - int variableSpaceCharacterIncrement - = textWidth + textWordSpaceAdjust + textLetterSpaceAdjust; - - variableSpaceCharacterIncrement - = Math.round(unitConv.mpt2units(variableSpaceCharacterIncrement)); - textDataInfo.setVariableSpaceCharacterIncrement(variableSpaceCharacterIncrement); - - int interCharacterAdjustment - = Math.round(unitConv.mpt2units(textLetterSpaceAdjust)); - textDataInfo.setInterCharacterAdjustment(interCharacterAdjustment); - - CharacterSet charSet = font.getCharacterSet(fontSize); - String encoding = charSet.getEncoding(); - textDataInfo.setEncoding(encoding); - - String textString = text.getText(); - textDataInfo.setString(textString); - - try { - dataStream.createText - (textDataInfo, textLetterSpaceAdjust, textWordSpaceAdjust, fnt, charSet); - } catch (UnsupportedEncodingException e) { - AFPEventProducer eventProducer - = AFPEventProducer.Provider.get(userAgent.getEventBroadcaster()); - eventProducer.characterSetEncodingError(this, charSet.getName(), encoding); - } - // word.getOffset() = only height of text itself - // currentBlockIPPosition: 0 for beginning of line; nonzero - // where previous line area failed to take up entire allocated space - - super.renderText(text); - - renderTextDecoration(font, fontSize, text, y, x); - } - - /** - * Render leader area. This renders a leader area which is an area with a - * rule. - * - * @param area - * the leader area to render - */ - public void renderLeader(Leader area) { - renderInlineAreaBackAndBorders(area); - - int style = area.getRuleStyle(); - float startx = (currentIPPosition + area - .getBorderAndPaddingWidthStart()) / 1000f; - float starty = (currentBPPosition + area.getOffset()) / 1000f; - float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart() + area - .getIPD()) / 1000f; - float ruleThickness = area.getRuleThickness() / 1000f; - Color col = (Color) area.getTrait(Trait.COLOR); - - switch (style) { - case EN_SOLID: - case EN_DASHED: - case EN_DOUBLE: - case EN_DOTTED: - case EN_GROOVE: - case EN_RIDGE: - drawBorderLine(startx, starty, endx, starty + ruleThickness, true, - true, style, col); - break; - default: - throw new UnsupportedOperationException("rule style not supported"); - } - super.renderLeader(area); - } - - /** - * Get the MIME type of the renderer. - * - * @return The MIME type of the renderer - */ - public String getMimeType() { - return MimeConstants.MIME_AFP; - } - - /** - * checks for IMM Extension and renders if found and different - * from previous page - * - * @param pageViewport the page object - */ - private void renderInvokeMediumMap(PageViewport pageViewport) { - if (pageViewport.getExtensionAttachments() != null - && pageViewport.getExtensionAttachments().size() > 0) { - Iterator it = pageViewport.getExtensionAttachments().iterator(); - while (it.hasNext()) { - ExtensionAttachment attachment = (ExtensionAttachment) it.next(); - if (AFPExtensionAttachment.CATEGORY.equals(attachment.getCategory())) { - AFPExtensionAttachment aea = (AFPExtensionAttachment)attachment; - if (AFPElementMapping.INVOKE_MEDIUM_MAP.equals(aea.getElementName())) { - AFPInvokeMediumMap imm = (AFPInvokeMediumMap)attachment; - String mediumMap = imm.getName(); - if (mediumMap != null) { - if (!mediumMap.equals(lastMediumMap)) { - dataStream.createInvokeMediumMap(mediumMap); - lastMediumMap = mediumMap; - } - } - } - } - } - } - } - - /** - * Method to render the page extension. - *

- * - * @param pageViewport - * the page object - */ - private void renderPageObjectExtensions(PageViewport pageViewport) { - pageSegmentMap.clear(); - if (pageViewport.getExtensionAttachments() != null - && pageViewport.getExtensionAttachments().size() > 0) { - // Extract all AFPPageSetup instances from the attachment list on - // the s-p-m - Iterator it = pageViewport.getExtensionAttachments().iterator(); - while (it.hasNext()) { - ExtensionAttachment attachment = (ExtensionAttachment) it.next(); - if (AFPPageSetup.CATEGORY.equals(attachment.getCategory())) { - if (attachment instanceof AFPPageSetup) { - AFPPageSetup aps = (AFPPageSetup) attachment; - String element = aps.getElementName(); - if (AFPElementMapping.INCLUDE_PAGE_SEGMENT - .equals(element)) { - String name = aps.getName(); - String source = aps.getValue(); - pageSegmentMap.put(source, name); - } else if (AFPElementMapping.TAG_LOGICAL_ELEMENT - .equals(element)) { - String name = aps.getName(); - String value = aps.getValue(); - dataStream.createTagLogicalElement(name, value); - } else if (AFPElementMapping.NO_OPERATION.equals(element)) { - String content = aps.getContent(); - if (content != null) { - dataStream.createNoOperation(content); - } - } - } else if (attachment instanceof AFPPageOverlay) { - AFPPageOverlay ipo = (AFPPageOverlay) attachment; - String element = ipo.getElementName(); - if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(element)) { - String overlay = ipo.getName(); - if (overlay != null) { - dataStream.createIncludePageOverlay - (overlay, ipo.getX(), ipo.getY()); - } - } - } - } - } - } - - } - - /** - * Sets the rotation to be used for portrait pages, valid values are 0 - * (default), 90, 180, 270. - * - * @param rotation - * The rotation in degrees. - */ - public void setPortraitRotation(int rotation) { - paintingState.setPortraitRotation(rotation); - } - - /** - * Sets the rotation to be used for landscape pages, valid values are 0, 90, - * 180, 270 (default). - * - * @param rotation - * The rotation in degrees. - */ - public void setLandscapeRotation(int rotation) { - paintingState.setLandscapeRotation(rotation); - } - - // ---=== AFPCustomizable ===--- - - /** {@inheritDoc} */ - public void setBitsPerPixel(int bitsPerPixel) { - paintingState.setBitsPerPixel(bitsPerPixel); - } - - /** {@inheritDoc} */ - public void setColorImages(boolean colorImages) { - paintingState.setColorImages(colorImages); - } - - /** {@inheritDoc} */ - public void setNativeImagesSupported(boolean nativeImages) { - paintingState.setNativeImagesSupported(nativeImages); - } - - /** {@inheritDoc} */ - public void setCMYKImagesSupported(boolean value) { - paintingState.setCMYKImagesSupported(value); - } - - /** {@inheritDoc} */ - public void setDitheringQuality(float quality) { - this.paintingState.setDitheringQuality(quality); - } - - /** {@inheritDoc} */ - public void setShadingMode(AFPShadingMode shadingMode) { - this.shadingMode = shadingMode; - } - - /** {@inheritDoc} */ - public void setResolution(int resolution) { - paintingState.setResolution(resolution); - } - - /** {@inheritDoc} */ - public int getResolution() { - return paintingState.getResolution(); - } - - /** {@inheritDoc} */ - public void setDefaultResourceGroupFilePath(String filePath) { - resourceManager.setDefaultResourceGroupFilePath(filePath); - } - - /** {@inheritDoc} */ - public void setResourceLevelDefaults(AFPResourceLevelDefaults defaults) { - resourceManager.setResourceLevelDefaults(defaults); - } - - /** {@inheritDoc} */ - protected void establishTransformationMatrix(AffineTransform at) { - saveGraphicsState(); - concatenateTransformationMatrix(at); - } - - /** {@inheritDoc} */ - public void clip() { - // TODO -// log.debug("NYI clip()"); - } - - /** {@inheritDoc} */ - public void clipRect(float x, float y, float width, float height) { - // TODO -// log.debug("NYI clipRect(x=" + x + ",y=" + y -// + ",width=" + width + ", height=" + height + ")"); - } - - /** {@inheritDoc} */ - public void moveTo(float x, float y) { - // TODO -// log.debug("NYI moveTo(x=" + x + ",y=" + y + ")"); - } - - /** {@inheritDoc} */ - public void lineTo(float x, float y) { - // TODO -// log.debug("NYI lineTo(x=" + x + ",y=" + y + ")"); - } - - /** {@inheritDoc} */ - public void closePath() { - // TODO -// log.debug("NYI closePath()"); - } - - /** Indicates the beginning of a text object. */ - public void beginTextObject() { - //TODO PDF specific maybe? -// log.debug("NYI beginTextObject()"); - } - - /** Indicates the end of a text object. */ - public void endTextObject() { - //TODO PDF specific maybe? -// log.debug("NYI endTextObject()"); - } - -} diff --git a/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java b/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java index 77d02b8c5..8d4b3370c 100644 --- a/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java +++ b/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java @@ -348,27 +348,12 @@ public class AFPRendererConfigurator extends PrintRendererConfigurator private static final String IMAGES_MODE_COLOR = "color"; /** - * Configure the AFP renderer. + * Throws an UnsupportedOperationException. * - * @param renderer AFP renderer - * @throws FOPException fop exception - * @see org.apache.fop.render.PrintRendererConfigurator#configure(Renderer) + * @param renderer not used */ - public void configure(Renderer renderer) throws FOPException { - Configuration cfg = super.getRendererConfig(renderer); - if (cfg != null) { - AFPRenderer afpRenderer = (AFPRenderer)renderer; - - try { - List/**/ fontList = buildFontListFromConfiguration(cfg); - afpRenderer.setFontList(fontList); - } catch (ConfigurationException e) { - LogUtil.handleException(log, e, - userAgent.getFactory().validateUserConfigStrictly()); - } - - configure(afpRenderer, cfg); - } + public void configure(Renderer renderer) { + throw new UnsupportedOperationException(); } private void configure(AFPCustomizable customizable, Configuration cfg) throws FOPException { diff --git a/src/java/org/apache/fop/render/afp/AFPRendererMaker.java b/src/java/org/apache/fop/render/afp/AFPRendererMaker.java deleted file mode 100644 index d283d992a..000000000 --- a/src/java/org/apache/fop/render/afp/AFPRendererMaker.java +++ /dev/null @@ -1,58 +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.afp; - -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.render.AbstractRendererMaker; -import org.apache.fop.render.Renderer; -import org.apache.fop.render.RendererConfigurator; - -/** - * RendererMaker for the AFP Renderer. - */ -public class AFPRendererMaker extends AbstractRendererMaker { - - private static final String[] MIMES = new String[] { - MimeConstants.MIME_AFP, - MimeConstants.MIME_AFP_ALT}; - - - /**{@inheritDoc} */ - public Renderer makeRenderer(FOUserAgent userAgent) { - return new AFPRenderer(); - } - - /** {@inheritDoc} */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return new AFPRendererConfigurator(userAgent); - } - - /** {@inheritDoc} */ - public boolean needsOutputStream() { - return true; - } - - /** {@inheritDoc} */ - public String[] getSupportedMimeTypes() { - return MIMES; - } - -} diff --git a/src/java/org/apache/fop/render/afp/AFPSVGHandler.java b/src/java/org/apache/fop/render/afp/AFPSVGHandler.java index 587c57e5b..7ade64006 100644 --- a/src/java/org/apache/fop/render/afp/AFPSVGHandler.java +++ b/src/java/org/apache/fop/render/afp/AFPSVGHandler.java @@ -214,7 +214,7 @@ public class AFPSVGHandler extends AbstractGenericSVGHandler { /** {@inheritDoc} */ public boolean supportsRenderer(Renderer renderer) { - return (renderer instanceof AFPRenderer); + return false; } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java b/src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java index 1228365f2..5374c7051 100644 --- a/src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java +++ b/src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java @@ -44,21 +44,6 @@ import org.apache.fop.render.RenderingContext; public abstract class AbstractAFPImageHandlerRawStream extends AFPImageHandler implements ImageHandler { - /** {@inheritDoc} */ - public AFPDataObjectInfo generateDataObjectInfo( - AFPRendererImageInfo rendererImageInfo) throws IOException { - AFPDataObjectInfo dataObjectInfo = super.generateDataObjectInfo(rendererImageInfo); - ImageRawStream rawStream = (ImageRawStream) rendererImageInfo.getImage(); - AFPRendererContext rendererContext - = (AFPRendererContext)rendererImageInfo.getRendererContext(); - AFPInfo afpInfo = rendererContext.getInfo(); - - updateDataObjectInfo(dataObjectInfo, rawStream, afpInfo.getResourceManager()); - - setAdditionalParameters(dataObjectInfo, rawStream); - return dataObjectInfo; - } - /** * Sets additional parameters on the image object info being built. By default, this * method does nothing but it can be overridden to provide additional functionality. diff --git a/src/java/org/apache/fop/render/pcl/PCLGraphics2DAdapter.java b/src/java/org/apache/fop/render/pcl/PCLGraphics2DAdapter.java deleted file mode 100644 index f8c9682e9..000000000 --- a/src/java/org/apache/fop/render/pcl/PCLGraphics2DAdapter.java +++ /dev/null @@ -1,123 +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.pcl; - -import java.awt.Dimension; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; - -import org.apache.commons.io.output.ByteArrayOutputStream; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.apache.xmlgraphics.java2d.GraphicContext; -import org.apache.xmlgraphics.java2d.Graphics2DImagePainter; - -import org.apache.fop.render.AbstractGraphics2DAdapter; -import org.apache.fop.render.RendererContext; -import org.apache.xmlgraphics.util.UnitConv; - -/** - * Graphics2DAdapter implementation for PCL and HP GL/2. - */ -public class PCLGraphics2DAdapter extends AbstractGraphics2DAdapter { - - /** logging instance */ - private static Log log = LogFactory.getLog(PCLGraphics2DAdapter.class); - - /** - * Main constructor - */ - public PCLGraphics2DAdapter() { - } - - /** {@inheritDoc} */ - public void paintImage(Graphics2DImagePainter painter, - RendererContext context, - int x, int y, int width, int height) throws IOException { - PCLRendererContext pclContext = PCLRendererContext.wrapRendererContext(context); - PCLRenderer pcl = (PCLRenderer)context.getRenderer(); - PCLGenerator gen = pcl.gen; - - // get the 'width' and 'height' attributes of the image/document - Dimension dim = painter.getImageSize(); - float imw = (float)dim.getWidth(); - float imh = (float)dim.getHeight(); - - boolean painted = false; - boolean paintAsBitmap = pclContext.paintAsBitmap(); - if (!paintAsBitmap) { - ByteArrayOutputStream baout = new ByteArrayOutputStream(); - PCLGenerator tempGen = new PCLGenerator(baout, gen.getMaximumBitmapResolution()); - try { - GraphicContext ctx = (GraphicContext)pcl.getGraphicContext().clone(); - - AffineTransform prepareHPGL2 = new AffineTransform(); - prepareHPGL2.scale(0.001, 0.001); - ctx.setTransform(prepareHPGL2); - - PCLGraphics2D graphics = new PCLGraphics2D(tempGen); - graphics.setGraphicContext(ctx); - graphics.setClippingDisabled(pclContext.isClippingDisabled()); - Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); - painter.paint(graphics, area); - - //If we arrive here, the graphic is natively paintable, so write the graphic - pcl.saveGraphicsState(); - pcl.setCursorPos(x, y); - gen.writeCommand("*c" + gen.formatDouble4(width / 100f) + "x" - + gen.formatDouble4(height / 100f) + "Y"); - gen.writeCommand("*c0T"); - gen.enterHPGL2Mode(false); - gen.writeText("\nIN;"); - gen.writeText("SP1;"); - //One Plotter unit is 0.025mm! - double scale = imw / UnitConv.mm2pt(imw * 0.025); - gen.writeText("SC0," + gen.formatDouble4(scale) - + ",0,-" + gen.formatDouble4(scale) + ",2;"); - gen.writeText("IR0,100,0,100;"); - gen.writeText("PU;PA0,0;\n"); - baout.writeTo(gen.getOutputStream()); //Buffer is written to output stream - gen.writeText("\n"); - - gen.enterPCLMode(false); - pcl.restoreGraphicsState(); - painted = true; - } catch (UnsupportedOperationException uoe) { - log.debug( - "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " - + uoe.getMessage()); - } - } - - if (!painted) { - //Fallback solution: Paint to a BufferedImage - int resolution = Math.round(context.getUserAgent().getTargetResolution()); - BufferedImage bi = paintToBufferedImage(painter, pclContext, - resolution, !pclContext.isColorCanvas(), false); - - pcl.setCursorPos(x, y); - gen.paintBitmap(bi, new Dimension(width, height), pclContext.isSourceTransparency()); - } - } - -} diff --git a/src/java/org/apache/fop/render/pcl/PCLRenderer.java b/src/java/org/apache/fop/render/pcl/PCLRenderer.java deleted file mode 100644 index 659997e8f..000000000 --- a/src/java/org/apache/fop/render/pcl/PCLRenderer.java +++ /dev/null @@ -1,1516 +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.pcl; - -//Java -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.RenderedImage; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import java.util.Stack; - -import org.w3c.dom.Document; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.apache.xmlgraphics.image.loader.ImageException; -import org.apache.xmlgraphics.image.loader.ImageFlavor; -import org.apache.xmlgraphics.image.loader.ImageInfo; -import org.apache.xmlgraphics.image.loader.ImageManager; -import org.apache.xmlgraphics.image.loader.ImageSessionContext; -import org.apache.xmlgraphics.image.loader.ImageSize; -import org.apache.xmlgraphics.image.loader.impl.ImageGraphics2D; -import org.apache.xmlgraphics.image.loader.impl.ImageRendered; -import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM; -import org.apache.xmlgraphics.image.loader.util.ImageUtil; -import org.apache.xmlgraphics.java2d.GraphicContext; -import org.apache.xmlgraphics.java2d.Graphics2DImagePainter; -import org.apache.xmlgraphics.util.UnitConv; - -import org.apache.fop.ResourceEventProducer; -import org.apache.fop.apps.FOPException; -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.area.Area; -import org.apache.fop.area.Block; -import org.apache.fop.area.BlockViewport; -import org.apache.fop.area.CTM; -import org.apache.fop.area.NormalFlow; -import org.apache.fop.area.PageViewport; -import org.apache.fop.area.RegionViewport; -import org.apache.fop.area.Trait; -import org.apache.fop.area.inline.AbstractTextArea; -import org.apache.fop.area.inline.ForeignObject; -import org.apache.fop.area.inline.Image; -import org.apache.fop.area.inline.InlineArea; -import org.apache.fop.area.inline.Leader; -import org.apache.fop.area.inline.SpaceArea; -import org.apache.fop.area.inline.TextArea; -import org.apache.fop.area.inline.Viewport; -import org.apache.fop.area.inline.WordArea; -import org.apache.fop.datatypes.URISpecification; -import org.apache.fop.fonts.Font; -import org.apache.fop.fonts.FontCollection; -import org.apache.fop.fonts.FontInfo; -import org.apache.fop.fonts.FontMetrics; -import org.apache.fop.render.Graphics2DAdapter; -import org.apache.fop.render.ImageHandlerUtil; -import org.apache.fop.render.PrintRenderer; -import org.apache.fop.render.RendererContext; -import org.apache.fop.render.RendererContextConstants; -import org.apache.fop.render.RendererEventProducer; -import org.apache.fop.render.java2d.Base14FontCollection; -import org.apache.fop.render.java2d.ConfiguredFontCollection; -import org.apache.fop.render.java2d.FontMetricsMapper; -import org.apache.fop.render.java2d.InstalledFontCollection; -import org.apache.fop.render.java2d.Java2DFontMetrics; -import org.apache.fop.render.java2d.Java2DRenderer; -import org.apache.fop.render.pcl.extensions.PCLElementMapping; -import org.apache.fop.traits.BorderProps; - -/* Note: - * There are some commonalities with AbstractPathOrientedRenderer but it's not possible - * to derive from it due to PCL's restrictions. We may need an additional common subclass to - * avoid methods copied from AbstractPathOrientedRenderer. Or we wait until after the IF redesign. - */ - -/** - * Renderer for the PCL 5 printer language. It also uses HP GL/2 for certain graphic elements. - */ -public class PCLRenderer extends PrintRenderer implements PCLConstants { - - /** logging instance */ - private static Log log = LogFactory.getLog(PCLRenderer.class); - - /** The MIME type for PCL */ - public static final String MIME_TYPE = MimeConstants.MIME_PCL_ALT; - - /** The OutputStream to write the PCL stream to */ - protected OutputStream out; - - /** The PCL generator */ - protected PCLGenerator gen; - private boolean ioTrouble = false; - - private final Stack graphicContextStack = new Stack(); - private GraphicContext graphicContext = new GraphicContext(); - - private PCLPageDefinition currentPageDefinition; - private int currentPrintDirection = 0; - private GeneralPath currentPath = null; - private java.awt.Color currentFillColor = null; - - /** - * Utility class which enables all sorts of features that are not directly connected to the - * normal rendering process. - */ - private PCLRenderingUtil pclUtil; - - /** contains the pageWith of the last printed page */ - private long pageWidth = 0; - /** contains the pageHeight of the last printed page */ - private long pageHeight = 0; - - /** - * Create the PCL renderer - */ - public PCLRenderer() { - } - - /** {@inheritDoc} */ - public void setUserAgent(FOUserAgent agent) { - super.setUserAgent(agent); - this.pclUtil = new PCLRenderingUtil(getUserAgent()); - } - - PCLRenderingUtil getPCLUtil() { - return this.pclUtil; - } - - /** - * Configures the renderer to trade speed for quality if desired. One example here is the way - * that borders are rendered. - * @param qualityBeforeSpeed true if quality is more important than speed - */ - public void setQualityBeforeSpeed(boolean qualityBeforeSpeed) { - pclUtil.setRenderingMode(qualityBeforeSpeed - ? PCLRenderingMode.QUALITY : PCLRenderingMode.SPEED); - } - - /** - * Controls whether PJL commands shall be generated by the PCL renderer. - * @param disable true to disable PJL commands - */ - public void setPJLDisabled(boolean disable) { - pclUtil.setPJLDisabled(disable); - } - - /** - * Indicates whether PJL generation is disabled. - * @return true if PJL generation is disabled. - */ - public boolean isPJLDisabled() { - return pclUtil.isPJLDisabled(); - } - - /** - * Controls whether all text should be generated as bitmaps or only text for which there's - * no native font. - * @param allTextAsBitmaps true if all text should be painted as bitmaps - */ - public void setAllTextAsBitmaps(boolean allTextAsBitmaps) { - pclUtil.setAllTextAsBitmaps(allTextAsBitmaps); - } - - /** - * {@inheritDoc} - */ - public void setupFontInfo(FontInfo inFontInfo) { - //Don't call super.setupFontInfo() here! - //The PCLRenderer uses the Java2D FontSetup which needs a special font setup - //create a temp Image to test font metrics on - fontInfo = inFontInfo; - Graphics2D graphics2D = Java2DFontMetrics.createFontMetricsGraphics2D(); - - FontCollection[] fontCollections = new FontCollection[] { - new Base14FontCollection(graphics2D), - new InstalledFontCollection(graphics2D), - new ConfiguredFontCollection(getFontResolver(), getFontList()) - }; - userAgent.getFactory().getFontManager().setup( - getFontInfo(), fontCollections); - } - - /** - * Central exception handler for I/O exceptions. - * @param ioe IOException to handle - */ - protected void handleIOTrouble(IOException ioe) { - if (!ioTrouble) { - RendererEventProducer eventProducer = RendererEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.ioError(this, ioe); - ioTrouble = true; - } - } - - /** {@inheritDoc} */ - public Graphics2DAdapter getGraphics2DAdapter() { - return new PCLGraphics2DAdapter(); - } - - /** @return the GraphicContext used to track coordinate system transformations */ - public GraphicContext getGraphicContext() { - return this.graphicContext; - } - - /** @return the target resolution */ - protected int getResolution() { - int resolution = Math.round(userAgent.getTargetResolution()); - if (resolution <= 300) { - return 300; - } else { - return 600; - } - } - - /** {@inheritDoc} */ - public void startRenderer(OutputStream outputStream) throws IOException { - log.debug("Rendering areas to PCL..."); - this.out = outputStream; - this.gen = new PCLGenerator(out, getResolution()); - - if (!isPJLDisabled()) { - gen.universalEndOfLanguage(); - gen.writeText("@PJL COMMENT Produced by " + userAgent.getProducer() + "\n"); - if (userAgent.getTitle() != null) { - gen.writeText("@PJL JOB NAME = \"" + userAgent.getTitle() + "\"\n"); - } - gen.writeText("@PJL SET RESOLUTION = " + getResolution() + "\n"); - gen.writeText("@PJL ENTER LANGUAGE = PCL\n"); - } - gen.resetPrinter(); - gen.setUnitOfMeasure(getResolution()); - gen.setRasterGraphicsResolution(getResolution()); - } - - /** {@inheritDoc} */ - public void stopRenderer() throws IOException { - gen.separateJobs(); - gen.resetPrinter(); - if (!isPJLDisabled()) { - gen.universalEndOfLanguage(); - } - } - - /** {@inheritDoc} */ - public String getMimeType() { - return MIME_TYPE; - } - - /** {@inheritDoc} */ - public void renderPage(PageViewport page) throws IOException, FOPException { - saveGraphicsState(); - - //Paper source - String paperSource = page.getForeignAttributeValue(PCLElementMapping.PCL_PAPER_SOURCE); - if (paperSource != null) { - gen.selectPaperSource(Integer.parseInt(paperSource)); - } - - //Output bin - String outputBin = page.getForeignAttributeValue(PCLElementMapping.PCL_OUTPUT_BIN); - if (outputBin != null) { - gen.selectOutputBin(Integer.parseInt(outputBin)); - } - - // Is Page duplex? - String pageDuplex = page.getForeignAttributeValue(PCLElementMapping.PCL_DUPLEX_MODE); - if (pageDuplex != null) { - gen.selectDuplexMode(Integer.parseInt(pageDuplex)); - } - - //Page size - final long pagewidth = Math.round(page.getViewArea().getWidth()); - final long pageheight = Math.round(page.getViewArea().getHeight()); - selectPageFormat(pagewidth, pageheight); - - super.renderPage(page); - - //Eject page - gen.formFeed(); - restoreGraphicsState(); - } - - private void selectPageFormat(long pagewidth, long pageheight) throws IOException { - //Only set the page format if it changes (otherwise duplex printing won't work) - if ((pagewidth != this.pageWidth) || (pageheight != this.pageHeight)) { - this.pageWidth = pagewidth; - this.pageHeight = pageheight; - - this.currentPageDefinition = PCLPageDefinition.getPageDefinition( - pagewidth, pageheight, 1000); - - if (this.currentPageDefinition == null) { - this.currentPageDefinition = PCLPageDefinition.getDefaultPageDefinition(); - log.warn("Paper type could not be determined. Falling back to: " - + this.currentPageDefinition.getName()); - } - if (log.isDebugEnabled()) { - log.debug("page size: " + currentPageDefinition.getPhysicalPageSize()); - log.debug("logical page: " + currentPageDefinition.getLogicalPageRect()); - } - - if (this.currentPageDefinition.isLandscapeFormat()) { - gen.writeCommand("&l1O"); //Landscape Orientation - } else { - gen.writeCommand("&l0O"); //Portrait Orientation - } - gen.selectPageSize(this.currentPageDefinition.getSelector()); - - gen.clearHorizontalMargins(); - gen.setTopMargin(0); - } - } - - /** Saves the current graphics state on the stack. */ - protected void saveGraphicsState() { - graphicContextStack.push(graphicContext); - graphicContext = (GraphicContext)graphicContext.clone(); - } - - /** Restores the last graphics state from the stack. */ - protected void restoreGraphicsState() { - graphicContext = (GraphicContext)graphicContextStack.pop(); - } - - /** - * Clip an area. write a clipping operation given coordinates in the current - * transform. Coordinates are in points. - * - * @param x the x coordinate - * @param y the y coordinate - * @param width the width of the area - * @param height the height of the area - */ - protected void clipRect(float x, float y, float width, float height) { - //PCL cannot clip (only HP GL/2 can) - } - - private Point2D transformedPoint(float x, float y) { - return transformedPoint(Math.round(x), Math.round(y)); - } - - private Point2D transformedPoint(int x, int y) { - return PCLRenderingUtil.transformedPoint(x, y, graphicContext.getTransform(), - currentPageDefinition, currentPrintDirection); - } - - private void changePrintDirection() { - AffineTransform at = graphicContext.getTransform(); - int newDir; - try { - newDir = PCLRenderingUtil.determinePrintDirection(at); - if (newDir != this.currentPrintDirection) { - this.currentPrintDirection = newDir; - gen.changePrintDirection(this.currentPrintDirection); - } - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** - * {@inheritDoc} - */ - protected void startVParea(CTM ctm, Rectangle2D clippingRect) { - saveGraphicsState(); - AffineTransform at = new AffineTransform(ctm.toArray()); - graphicContext.transform(at); - changePrintDirection(); - if (log.isDebugEnabled()) { - log.debug("startVPArea: " + at + " --> " + graphicContext.getTransform()); - } - } - - /** - * {@inheritDoc} - */ - protected void endVParea() { - restoreGraphicsState(); - changePrintDirection(); - if (log.isDebugEnabled()) { - log.debug("endVPArea() --> " + graphicContext.getTransform()); - } - } - - /** - * Handle block traits. - * The block could be any sort of block with any positioning - * so this should render the traits such as border and background - * in its position. - * - * @param block the block to render the traits - */ - protected void handleBlockTraits(Block block) { - int borderPaddingStart = block.getBorderAndPaddingWidthStart(); - int borderPaddingBefore = block.getBorderAndPaddingWidthBefore(); - - float startx = currentIPPosition / 1000f; - float starty = currentBPPosition / 1000f; - float width = block.getIPD() / 1000f; - float height = block.getBPD() / 1000f; - - startx += block.getStartIndent() / 1000f; - startx -= block.getBorderAndPaddingWidthStart() / 1000f; - - width += borderPaddingStart / 1000f; - width += block.getBorderAndPaddingWidthEnd() / 1000f; - height += borderPaddingBefore / 1000f; - height += block.getBorderAndPaddingWidthAfter() / 1000f; - - drawBackAndBorders(block, startx, starty, width, height); - } - - /** - * {@inheritDoc} - * @asf.todo Copied from AbstractPathOrientedRenderer - */ - protected void handleRegionTraits(RegionViewport region) { - Rectangle2D viewArea = region.getViewArea(); - float startx = (float)(viewArea.getX() / 1000f); - float starty = (float)(viewArea.getY() / 1000f); - float width = (float)(viewArea.getWidth() / 1000f); - float height = (float)(viewArea.getHeight() / 1000f); - - if (region.getRegionReference().getRegionClass() == FO_REGION_BODY) { - currentBPPosition = region.getBorderAndPaddingWidthBefore(); - currentIPPosition = region.getBorderAndPaddingWidthStart(); - } - drawBackAndBorders(region, startx, starty, width, height); - } - - /** - * {@inheritDoc} - */ - protected void renderText(final TextArea text) { - renderInlineAreaBackAndBorders(text); - - String fontname = getInternalFontNameForArea(text); - final int fontsize = text.getTraitAsInteger(Trait.FONT_SIZE); - - //Determine position - int saveIP = currentIPPosition; - final int rx = currentIPPosition + text.getBorderAndPaddingWidthStart(); - int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset(); - - try { - - final Color col = (Color)text.getTrait(Trait.COLOR); - boolean pclFont = pclUtil.isAllTextAsBitmaps() - ? false - : HardcodedFonts.setFont(gen, fontname, fontsize, text.getText()); - if (pclFont) { - //this.currentFill = col; - if (col != null) { - //useColor(ct); - gen.setTransparencyMode(true, false); - gen.selectGrayscale(col); - } - - saveGraphicsState(); - graphicContext.translate(rx, bl); - setCursorPos(0, 0); - gen.setTransparencyMode(true, true); - if (text.hasUnderline()) { - gen.writeCommand("&d0D"); - } - super.renderText(text); //Updates IPD and renders words and spaces - if (text.hasUnderline()) { - gen.writeCommand("&d@"); - } - restoreGraphicsState(); - } else { - //Use Java2D to paint different fonts via bitmap - final Font font = getFontFromArea(text); - final int baseline = text.getBaselineOffset(); - - //for cursive fonts, so the text isn't clipped - int extraWidth = font.getFontSize() / 3; - final FontMetricsMapper mapper = (FontMetricsMapper)fontInfo.getMetricsFor( - font.getFontName()); - int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000; - final int additionalBPD = maxAscent - baseline; - - Graphics2DAdapter g2a = getGraphics2DAdapter(); - final Rectangle paintRect = new Rectangle( - rx, currentBPPosition + text.getOffset() - additionalBPD, - text.getIPD() + extraWidth, text.getBPD() + additionalBPD); - RendererContext rc = createRendererContext(paintRect.x, paintRect.y, - paintRect.width, paintRect.height, null); - Map atts = new java.util.HashMap(); - atts.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP); - atts.put(SRC_TRANSPARENCY, "true"); - rc.setProperty(RendererContextConstants.FOREIGN_ATTRIBUTES, atts); - - Graphics2DImagePainter painter = new Graphics2DImagePainter() { - - public void paint(Graphics2D g2d, Rectangle2D area) { - g2d.setFont(mapper.getFont(font.getFontSize())); - g2d.translate(0, baseline + additionalBPD); - g2d.scale(1000, 1000); - g2d.setColor(col); - Java2DRenderer.renderText(text, g2d, font); - renderTextDecoration(g2d, mapper, fontsize, text, 0, 0); - } - - public Dimension getImageSize() { - return paintRect.getSize(); - } - - }; - g2a.paintImage(painter, rc, - paintRect.x, paintRect.y, paintRect.width, paintRect.height); - currentIPPosition = saveIP + text.getAllocIPD(); - } - - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** - * Paints the text decoration marks. - * @param g2d Graphics2D instance to paint to - * @param fm Current typeface - * @param fontsize Current font size - * @param inline inline area to paint the marks for - * @param baseline position of the baseline - * @param startx start IPD - */ - private static void renderTextDecoration(Graphics2D g2d, - FontMetrics fm, int fontsize, InlineArea inline, - int baseline, int startx) { - boolean hasTextDeco = inline.hasUnderline() - || inline.hasOverline() - || inline.hasLineThrough(); - if (hasTextDeco) { - float descender = fm.getDescender(fontsize) / 1000f; - float capHeight = fm.getCapHeight(fontsize) / 1000f; - float lineWidth = (descender / -4f) / 1000f; - float endx = (startx + inline.getIPD()) / 1000f; - if (inline.hasUnderline()) { - Color ct = (Color) inline.getTrait(Trait.UNDERLINE_COLOR); - g2d.setColor(ct); - float y = baseline - descender / 2f; - g2d.setStroke(new BasicStroke(lineWidth)); - g2d.draw(new Line2D.Float(startx / 1000f, y / 1000f, - endx, y / 1000f)); - } - if (inline.hasOverline()) { - Color ct = (Color) inline.getTrait(Trait.OVERLINE_COLOR); - g2d.setColor(ct); - float y = (float)(baseline - (1.1 * capHeight)); - g2d.setStroke(new BasicStroke(lineWidth)); - g2d.draw(new Line2D.Float(startx / 1000f, y / 1000f, - endx, y / 1000f)); - } - if (inline.hasLineThrough()) { - Color ct = (Color) inline.getTrait(Trait.LINETHROUGH_COLOR); - g2d.setColor(ct); - float y = (float)(baseline - (0.45 * capHeight)); - g2d.setStroke(new BasicStroke(lineWidth)); - g2d.draw(new Line2D.Float(startx / 1000f, y / 1000f, - endx, y / 1000f)); - } - } - } - - /** - * Sets the current cursor position. The coordinates are transformed to the absolute position - * on the logical PCL page and then passed on to the PCLGenerator. - * @param x the x coordinate (in millipoints) - * @param y the y coordinate (in millipoints) - */ - void setCursorPos(float x, float y) { - try { - Point2D transPoint = transformedPoint(x, y); - gen.setCursorPos(transPoint.getX(), transPoint.getY()); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** Clip using the current path. */ - protected void clip() { - if (currentPath == null) { - throw new IllegalStateException("No current path available!"); - } - //TODO Find a good way to do clipping. PCL itself cannot clip. - currentPath = null; - } - - /** - * Closes the current subpath by appending a straight line segment from - * the current point to the starting point of the subpath. - */ - protected void closePath() { - currentPath.closePath(); - } - - /** - * Appends a straight line segment from the current point to (x, y). The - * new current point is (x, y). - * @param x x coordinate - * @param y y coordinate - */ - protected void lineTo(float x, float y) { - if (currentPath == null) { - currentPath = new GeneralPath(); - } - currentPath.lineTo(x, y); - } - - /** - * Moves the current point to (x, y), omitting any connecting line segment. - * @param x x coordinate - * @param y y coordinate - */ - protected void moveTo(float x, float y) { - if (currentPath == null) { - currentPath = new GeneralPath(); - } - currentPath.moveTo(x, y); - } - - /** - * Fill a rectangular area. - * @param x the x coordinate (in pt) - * @param y the y coordinate (in pt) - * @param width the width of the rectangle - * @param height the height of the rectangle - */ - protected void fillRect(float x, float y, float width, float height) { - try { - setCursorPos(x * 1000, y * 1000); - gen.fillRect((int)(width * 1000), (int)(height * 1000), - this.currentFillColor); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** - * Sets the new current fill color. - * @param color the color - */ - protected void updateFillColor(java.awt.Color color) { - this.currentFillColor = color; - } - - /** - * {@inheritDoc} - */ - protected void renderWord(WordArea word) { - //Font font = getFontFromArea(word.getParentArea()); - - String s = word.getWord(); - - try { - gen.writeText(s); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - - super.renderWord(word); - } - - /** - * {@inheritDoc} - */ - protected void renderSpace(SpaceArea space) { - AbstractTextArea textArea = (AbstractTextArea)space.getParentArea(); - String s = space.getSpace(); - char sp = s.charAt(0); - Font font = getFontFromArea(textArea); - - int tws = (space.isAdjustable() - ? textArea.getTextWordSpaceAdjust() - + 2 * textArea.getTextLetterSpaceAdjust() - : 0); - - double dx = (font.getCharWidth(sp) + tws) / 100f; - try { - gen.writeCommand("&a+" + gen.formatDouble2(dx) + "H"); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - super.renderSpace(space); - } - - /** - * Render an inline viewport. - * This renders an inline viewport by clipping if necessary. - * @param viewport the viewport to handle - * @asf.todo Copied from AbstractPathOrientedRenderer - */ - public void renderViewport(Viewport viewport) { - - float x = currentIPPosition / 1000f; - float y = (currentBPPosition + viewport.getOffset()) / 1000f; - float width = viewport.getIPD() / 1000f; - float height = viewport.getBPD() / 1000f; - // TODO: Calculate the border rect correctly. - float borderPaddingStart = viewport.getBorderAndPaddingWidthStart() / 1000f; - float borderPaddingBefore = viewport.getBorderAndPaddingWidthBefore() / 1000f; - float bpwidth = borderPaddingStart - + (viewport.getBorderAndPaddingWidthEnd() / 1000f); - float bpheight = borderPaddingBefore - + (viewport.getBorderAndPaddingWidthAfter() / 1000f); - - drawBackAndBorders(viewport, x, y, width + bpwidth, height + bpheight); - - if (viewport.getClip()) { - saveGraphicsState(); - - clipRect(x + borderPaddingStart, y + borderPaddingBefore, width, height); - } - super.renderViewport(viewport); - - if (viewport.getClip()) { - restoreGraphicsState(); - } - } - - /** - * {@inheritDoc} - */ - protected void renderBlockViewport(BlockViewport bv, List children) { - // clip and position viewport if necessary - - // save positions - int saveIP = currentIPPosition; - int saveBP = currentBPPosition; - - CTM ctm = bv.getCTM(); - int borderPaddingStart = bv.getBorderAndPaddingWidthStart(); - int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore(); - //This is the content-rect - float width = bv.getIPD() / 1000f; - float height = bv.getBPD() / 1000f; - - - if (bv.getPositioning() == Block.ABSOLUTE - || bv.getPositioning() == Block.FIXED) { - - //For FIXED, we need to break out of the current viewports to the - //one established by the page. We save the state stack for restoration - //after the block-container has been painted. See below. - List breakOutList = null; - if (bv.getPositioning() == Block.FIXED) { - breakOutList = breakOutOfStateStack(); - } - - AffineTransform positionTransform = new AffineTransform(); - positionTransform.translate(bv.getXOffset(), bv.getYOffset()); - - //"left/"top" (bv.getX/YOffset()) specify the position of the content rectangle - positionTransform.translate(-borderPaddingStart, -borderPaddingBefore); - - saveGraphicsState(); - //Viewport position - concatenateTransformationMatrix(UnitConv.mptToPt(positionTransform)); - - //Background and borders - float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd()) / 1000f; - float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter()) / 1000f; - drawBackAndBorders(bv, 0, 0, width + bpwidth, height + bpheight); - - //Shift to content rectangle after border painting - AffineTransform contentRectTransform = new AffineTransform(); - contentRectTransform.translate(borderPaddingStart, borderPaddingBefore); - concatenateTransformationMatrix(UnitConv.mptToPt(contentRectTransform)); - - //Clipping - if (bv.getClip()) { - clipRect(0f, 0f, width, height); - } - - saveGraphicsState(); - //Set up coordinate system for content rectangle - AffineTransform contentTransform = ctm.toAffineTransform(); - concatenateTransformationMatrix(UnitConv.mptToPt(contentTransform)); - - currentIPPosition = 0; - currentBPPosition = 0; - renderBlocks(bv, children); - - restoreGraphicsState(); - restoreGraphicsState(); - - if (breakOutList != null) { - restoreStateStackAfterBreakOut(breakOutList); - } - - currentIPPosition = saveIP; - currentBPPosition = saveBP; - } else { - - currentBPPosition += bv.getSpaceBefore(); - - //borders and background in the old coordinate system - handleBlockTraits(bv); - - //Advance to start of content area - currentIPPosition += bv.getStartIndent(); - - CTM tempctm = new CTM(containingIPPosition, currentBPPosition); - ctm = tempctm.multiply(ctm); - - //Now adjust for border/padding - currentBPPosition += borderPaddingBefore; - - Rectangle2D clippingRect = null; - if (bv.getClip()) { - clippingRect = new Rectangle(currentIPPosition, currentBPPosition, - bv.getIPD(), bv.getBPD()); - } - - startVParea(ctm, clippingRect); - currentIPPosition = 0; - currentBPPosition = 0; - renderBlocks(bv, children); - endVParea(); - - currentIPPosition = saveIP; - currentBPPosition = saveBP; - - currentBPPosition += (bv.getAllocBPD()); - } - //currentFontName = saveFontName; - } - - /** {@inheritDoc} */ - protected void renderReferenceArea(Block block) { - //TODO This is the same code as in AbstractPathOrientedRenderer - //So there's some optimization potential but not otherwise PCLRenderer is a little - //difficult to derive from AbstractPathOrientedRenderer. Maybe an additional layer - //between PrintRenderer and AbstractPathOrientedRenderer is necessary. - - // save position and offset - int saveIP = currentIPPosition; - int saveBP = currentBPPosition; - - //Establish a new coordinate system - AffineTransform at = new AffineTransform(); - at.translate(currentIPPosition, currentBPPosition); - at.translate(block.getXOffset(), block.getYOffset()); - at.translate(0, block.getSpaceBefore()); - - if (!at.isIdentity()) { - saveGraphicsState(); - concatenateTransformationMatrix(UnitConv.mptToPt(at)); - } - - currentIPPosition = 0; - currentBPPosition = 0; - handleBlockTraits(block); - - List children = block.getChildAreas(); - if (children != null) { - renderBlocks(block, children); - } - - if (!at.isIdentity()) { - restoreGraphicsState(); - } - - // stacked and relative blocks effect stacking - currentIPPosition = saveIP; - currentBPPosition = saveBP; - } - - /** {@inheritDoc} */ - protected void renderFlow(NormalFlow flow) { - //TODO This is the same code as in AbstractPathOrientedRenderer - //So there's some optimization potential but not otherwise PCLRenderer is a little - //difficult to derive from AbstractPathOrientedRenderer. Maybe an additional layer - //between PrintRenderer and AbstractPathOrientedRenderer is necessary. - - // save position and offset - int saveIP = currentIPPosition; - int saveBP = currentBPPosition; - - //Establish a new coordinate system - AffineTransform at = new AffineTransform(); - at.translate(currentIPPosition, currentBPPosition); - - if (!at.isIdentity()) { - saveGraphicsState(); - concatenateTransformationMatrix(UnitConv.mptToPt(at)); - } - - currentIPPosition = 0; - currentBPPosition = 0; - super.renderFlow(flow); - - if (!at.isIdentity()) { - restoreGraphicsState(); - } - - // stacked and relative blocks effect stacking - currentIPPosition = saveIP; - currentBPPosition = saveBP; - } - - /** - * Concatenates the current transformation matrix with the given one, therefore establishing - * a new coordinate system. - * @param at the transformation matrix to process (coordinates in points) - */ - protected void concatenateTransformationMatrix(AffineTransform at) { - if (!at.isIdentity()) { - graphicContext.transform(UnitConv.ptToMpt(at)); - changePrintDirection(); - } - } - - private List breakOutOfStateStack() { - log.debug("Block.FIXED --> break out"); - List breakOutList = new java.util.ArrayList(); - while (!this.graphicContextStack.empty()) { - breakOutList.add(0, this.graphicContext); - restoreGraphicsState(); - } - return breakOutList; - } - - private void restoreStateStackAfterBreakOut(List breakOutList) { - log.debug("Block.FIXED --> restoring context after break-out"); - for (int i = 0, c = breakOutList.size(); i < c; i++) { - saveGraphicsState(); - this.graphicContext = (GraphicContext)breakOutList.get(i); - } - } - - /** {@inheritDoc} */ - protected RendererContext createRendererContext(int x, int y, int width, int height, - Map foreignAttributes) { - RendererContext context = super.createRendererContext( - x, y, width, height, foreignAttributes); - context.setProperty(PCLRendererContextConstants.PCL_COLOR_CANVAS, - Boolean.valueOf(pclUtil.isColorCanvasEnabled())); - return context; - } - - /** {@inheritDoc} */ - public void renderImage(Image image, Rectangle2D pos) { - drawImage(image.getURL(), pos, image.getForeignAttributes()); - } - - private static final ImageFlavor[] FLAVORS = new ImageFlavor[] - {ImageFlavor.GRAPHICS2D, - ImageFlavor.BUFFERED_IMAGE, - ImageFlavor.RENDERED_IMAGE, - ImageFlavor.XML_DOM}; - /** - * Draw an image at the indicated location. - * @param uri the URI/URL of the image - * @param pos the position of the image - * @param foreignAttributes an optional Map with foreign attributes, may be null - */ - protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) { - uri = URISpecification.getURL(uri); - Rectangle posInt = new Rectangle( - (int)pos.getX(), - (int)pos.getY(), - (int)pos.getWidth(), - (int)pos.getHeight()); - Point origin = new Point(currentIPPosition, currentBPPosition); - int x = origin.x + posInt.x; - int y = origin.y + posInt.y; - - ImageManager manager = getUserAgent().getFactory().getImageManager(); - ImageInfo info = null; - try { - ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); - info = manager.getImageInfo(uri, sessionContext); - - //Only now fully load/prepare the image - Map hints = ImageUtil.getDefaultHints(sessionContext); - org.apache.xmlgraphics.image.loader.Image img = manager.getImage( - info, FLAVORS, hints, sessionContext); - - //...and process the image - if (img instanceof ImageGraphics2D) { - ImageGraphics2D imageG2D = (ImageGraphics2D)img; - RendererContext context = createRendererContext( - posInt.x, posInt.y, - posInt.width, posInt.height, foreignAttributes); - getGraphics2DAdapter().paintImage(imageG2D.getGraphics2DImagePainter(), - context, x, y, posInt.width, posInt.height); - } else if (img instanceof ImageRendered) { - ImageRendered imgRend = (ImageRendered)img; - RenderedImage ri = imgRend.getRenderedImage(); - setCursorPos(x, y); - gen.paintBitmap(ri, - new Dimension(posInt.width, posInt.height), - false); - } else if (img instanceof ImageXMLDOM) { - ImageXMLDOM imgXML = (ImageXMLDOM)img; - renderDocument(imgXML.getDocument(), imgXML.getRootNamespace(), - pos, foreignAttributes); - } else { - throw new UnsupportedOperationException("Unsupported image type: " + img); - } - - } catch (ImageException ie) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); - } catch (FileNotFoundException fe) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); - } catch (IOException ioe) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); - } - } - - /** {@inheritDoc} */ - public void renderForeignObject(ForeignObject fo, Rectangle2D pos) { - Document doc = fo.getDocument(); - String ns = fo.getNameSpace(); - renderDocument(doc, ns, pos, fo.getForeignAttributes()); - } - - /** - * Common method to render the background and borders for any inline area. - * The all borders and padding are drawn outside the specified area. - * @param area the inline area for which the background, border and padding is to be - * rendered - * @asf.todo Copied from AbstractPathOrientedRenderer - */ - protected void renderInlineAreaBackAndBorders(InlineArea area) { - float x = currentIPPosition / 1000f; - float y = (currentBPPosition + area.getOffset()) / 1000f; - float width = area.getIPD() / 1000f; - float height = area.getBPD() / 1000f; - float borderPaddingStart = area.getBorderAndPaddingWidthStart() / 1000f; - float borderPaddingBefore = area.getBorderAndPaddingWidthBefore() / 1000f; - float bpwidth = borderPaddingStart - + (area.getBorderAndPaddingWidthEnd() / 1000f); - float bpheight = borderPaddingBefore - + (area.getBorderAndPaddingWidthAfter() / 1000f); - - if (height != 0.0f || bpheight != 0.0f && bpwidth != 0.0f) { - drawBackAndBorders(area, x, y - borderPaddingBefore - , width + bpwidth - , height + bpheight); - } - } - - /** - * Draw the background and borders. This draws the background and border - * traits for an area given the position. - * - * @param area the area whose traits are used - * @param startx the start x position - * @param starty the start y position - * @param width the width of the area - * @param height the height of the area - */ - protected void drawBackAndBorders(Area area, float startx, float starty, - float width, float height) { - BorderProps bpsBefore = (BorderProps) area.getTrait(Trait.BORDER_BEFORE); - BorderProps bpsAfter = (BorderProps) area.getTrait(Trait.BORDER_AFTER); - BorderProps bpsStart = (BorderProps) area.getTrait(Trait.BORDER_START); - BorderProps bpsEnd = (BorderProps) area.getTrait(Trait.BORDER_END); - - // draw background - Trait.Background back; - back = (Trait.Background) area.getTrait(Trait.BACKGROUND); - if (back != null) { - - // Calculate padding rectangle - float sx = startx; - float sy = starty; - float paddRectWidth = width; - float paddRectHeight = height; - - if (bpsStart != null) { - sx += bpsStart.width / 1000f; - paddRectWidth -= bpsStart.width / 1000f; - } - if (bpsBefore != null) { - sy += bpsBefore.width / 1000f; - paddRectHeight -= bpsBefore.width / 1000f; - } - if (bpsEnd != null) { - paddRectWidth -= bpsEnd.width / 1000f; - } - if (bpsAfter != null) { - paddRectHeight -= bpsAfter.width / 1000f; - } - - if (back.getColor() != null) { - updateFillColor(back.getColor()); - fillRect(sx, sy, paddRectWidth, paddRectHeight); - } - - // background image - if (back.getImageInfo() != null) { - ImageSize imageSize = back.getImageInfo().getSize(); - saveGraphicsState(); - clipRect(sx, sy, paddRectWidth, paddRectHeight); - int horzCount = (int) ((paddRectWidth * 1000 / imageSize.getWidthMpt()) + 1.0f); - int vertCount = (int) ((paddRectHeight * 1000 / imageSize.getHeightMpt()) + 1.0f); - if (back.getRepeat() == EN_NOREPEAT) { - horzCount = 1; - vertCount = 1; - } else if (back.getRepeat() == EN_REPEATX) { - vertCount = 1; - } else if (back.getRepeat() == EN_REPEATY) { - horzCount = 1; - } - // change from points to millipoints - sx *= 1000; - sy *= 1000; - if (horzCount == 1) { - sx += back.getHoriz(); - } - if (vertCount == 1) { - sy += back.getVertical(); - } - for (int x = 0; x < horzCount; x++) { - for (int y = 0; y < vertCount; y++) { - // place once - Rectangle2D pos; - // Image positions are relative to the currentIP/BP - pos = new Rectangle2D.Float( - sx - currentIPPosition - + (x * imageSize.getWidthMpt()), - sy - currentBPPosition - + (y * imageSize.getHeightMpt()), - imageSize.getWidthMpt(), - imageSize.getHeightMpt()); - drawImage(back.getURL(), pos, null); - } - } - restoreGraphicsState(); - } - } - - Rectangle2D.Float borderRect = new Rectangle2D.Float(startx, starty, width, height); - drawBorders(borderRect, bpsBefore, bpsAfter, bpsStart, bpsEnd); - } - - /** - * Draws borders. - * @param borderRect the border rectangle - * @param bpsBefore the border specification on the before side - * @param bpsAfter the border specification on the after side - * @param bpsStart the border specification on the start side - * @param bpsEnd the border specification on the end side - */ - protected void drawBorders(Rectangle2D.Float borderRect, - final BorderProps bpsBefore, final BorderProps bpsAfter, - final BorderProps bpsStart, final BorderProps bpsEnd) { - if (bpsBefore == null && bpsAfter == null && bpsStart == null && bpsEnd == null) { - return; //no borders to paint - } - if (PCLRenderingMode.SPEED == pclUtil.getRenderingMode()) { - drawFastBorders(borderRect, bpsBefore, bpsAfter, bpsStart, bpsEnd); - } else { - drawQualityBorders(borderRect, bpsBefore, bpsAfter, bpsStart, bpsEnd); - } - } - - /** - * Draws borders. Borders are drawn as shaded rectangles with no clipping. - * @param borderRect the border rectangle - * @param bpsBefore the border specification on the before side - * @param bpsAfter the border specification on the after side - * @param bpsStart the border specification on the start side - * @param bpsEnd the border specification on the end side - */ - protected void drawFastBorders(Rectangle2D.Float borderRect, - final BorderProps bpsBefore, final BorderProps bpsAfter, - final BorderProps bpsStart, final BorderProps bpsEnd) { - float startx = borderRect.x; - float starty = borderRect.y; - float width = borderRect.width; - float height = borderRect.height; - if (bpsBefore != null) { - float borderWidth = bpsBefore.width / 1000f; - updateFillColor(bpsBefore.color); - fillRect(startx, starty, width, borderWidth); - } - if (bpsAfter != null) { - float borderWidth = bpsAfter.width / 1000f; - updateFillColor(bpsAfter.color); - fillRect(startx, (starty + height - borderWidth), - width, borderWidth); - } - if (bpsStart != null) { - float borderWidth = bpsStart.width / 1000f; - updateFillColor(bpsStart.color); - fillRect(startx, starty, borderWidth, height); - } - if (bpsEnd != null) { - float borderWidth = bpsEnd.width / 1000f; - updateFillColor(bpsEnd.color); - fillRect((startx + width - borderWidth), starty, borderWidth, height); - } - } - - /** - * Draws borders. Borders are drawn in-memory and painted as a bitmap. - * @param borderRect the border rectangle - * @param bpsBefore the border specification on the before side - * @param bpsAfter the border specification on the after side - * @param bpsStart the border specification on the start side - * @param bpsEnd the border specification on the end side - */ - protected void drawQualityBorders // CSOK: MethodLength - (Rectangle2D.Float borderRect, - final BorderProps bpsBefore, final BorderProps bpsAfter, - final BorderProps bpsStart, final BorderProps bpsEnd) { - Graphics2DAdapter g2a = getGraphics2DAdapter(); - final Rectangle.Float effBorderRect = new Rectangle2D.Float( - 0, - 0, - borderRect.width, - borderRect.height); - final Rectangle paintRect = new Rectangle( - Math.round(borderRect.x * 1000f), - Math.round(borderRect.y * 1000f), - (int)Math.floor(borderRect.width * 1000f) + 1, - (int)Math.floor(borderRect.height * 1000f) + 1); - //Add one pixel wide safety margin around the paint area - int pixelWidth = (int)Math.round(UnitConv.in2mpt(1) / userAgent.getTargetResolution()); - final int xoffset = Math.round(-effBorderRect.x * 1000f) + pixelWidth; - final int yoffset = pixelWidth; - paintRect.x += xoffset; - paintRect.y += yoffset; - paintRect.width += 2 * pixelWidth; - paintRect.height += 2 * pixelWidth; - - RendererContext rc = createRendererContext(paintRect.x, paintRect.y, - paintRect.width, paintRect.height, null); - Map atts = new java.util.HashMap(); - atts.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP); - atts.put(SRC_TRANSPARENCY, "true"); - rc.setProperty(RendererContextConstants.FOREIGN_ATTRIBUTES, atts); - - Graphics2DImagePainter painter = new Graphics2DImagePainter() { - - public void paint // CSOK: MethodLength - (Graphics2D g2d, Rectangle2D area) { - g2d.translate(xoffset, yoffset); - g2d.scale(1000, 1000); - float startx = effBorderRect.x; - float starty = effBorderRect.y; - float width = effBorderRect.width; - float height = effBorderRect.height; - boolean[] b = new boolean[] { - (bpsBefore != null), (bpsEnd != null), - (bpsAfter != null), (bpsStart != null)}; - if (!b[0] && !b[1] && !b[2] && !b[3]) { - return; - } - float[] bw = new float[] { - (b[0] ? bpsBefore.width / 1000f : 0.0f), - (b[1] ? bpsEnd.width / 1000f : 0.0f), - (b[2] ? bpsAfter.width / 1000f : 0.0f), - (b[3] ? bpsStart.width / 1000f : 0.0f)}; - float[] clipw = new float[] { - BorderProps.getClippedWidth(bpsBefore) / 1000f, - BorderProps.getClippedWidth(bpsEnd) / 1000f, - BorderProps.getClippedWidth(bpsAfter) / 1000f, - BorderProps.getClippedWidth(bpsStart) / 1000f}; - starty += clipw[0]; - height -= clipw[0]; - height -= clipw[2]; - startx += clipw[3]; - width -= clipw[3]; - width -= clipw[1]; - - boolean[] slant = new boolean[] { - (b[3] && b[0]), (b[0] && b[1]), (b[1] && b[2]), (b[2] && b[3])}; - if (bpsBefore != null) { - //endTextObject(); - - float sx1 = startx; - float sx2 = (slant[0] ? sx1 + bw[3] - clipw[3] : sx1); - float ex1 = startx + width; - float ex2 = (slant[1] ? ex1 - bw[1] + clipw[1] : ex1); - float outery = starty - clipw[0]; - float clipy = outery + clipw[0]; - float innery = outery + bw[0]; - - //saveGraphicsState(); - Graphics2D g = (Graphics2D)g2d.create(); - moveTo(sx1, clipy); - float sx1a = sx1; - float ex1a = ex1; - if (bpsBefore.mode == BorderProps.COLLAPSE_OUTER) { - if (bpsStart != null && bpsStart.mode == BorderProps.COLLAPSE_OUTER) { - sx1a -= clipw[3]; - } - if (bpsEnd != null && bpsEnd.mode == BorderProps.COLLAPSE_OUTER) { - ex1a += clipw[1]; - } - lineTo(sx1a, outery); - lineTo(ex1a, outery); - } - lineTo(ex1, clipy); - lineTo(ex2, innery); - lineTo(sx2, innery); - closePath(); - //clip(); - g.clip(currentPath); - currentPath = null; - Rectangle2D.Float lineRect = new Rectangle2D.Float( - sx1a, outery, ex1a - sx1a, innery - outery); - Java2DRenderer.drawBorderLine(lineRect, true, true, - bpsBefore.style, bpsBefore.color, g); - //restoreGraphicsState(); - } - if (bpsEnd != null) { - //endTextObject(); - - float sy1 = starty; - float sy2 = (slant[1] ? sy1 + bw[0] - clipw[0] : sy1); - float ey1 = starty + height; - float ey2 = (slant[2] ? ey1 - bw[2] + clipw[2] : ey1); - float outerx = startx + width + clipw[1]; - float clipx = outerx - clipw[1]; - float innerx = outerx - bw[1]; - - //saveGraphicsState(); - Graphics2D g = (Graphics2D)g2d.create(); - moveTo(clipx, sy1); - float sy1a = sy1; - float ey1a = ey1; - if (bpsEnd.mode == BorderProps.COLLAPSE_OUTER) { - if (bpsBefore != null && bpsBefore.mode == BorderProps.COLLAPSE_OUTER) { - sy1a -= clipw[0]; - } - if (bpsAfter != null && bpsAfter.mode == BorderProps.COLLAPSE_OUTER) { - ey1a += clipw[2]; - } - lineTo(outerx, sy1a); - lineTo(outerx, ey1a); - } - lineTo(clipx, ey1); - lineTo(innerx, ey2); - lineTo(innerx, sy2); - closePath(); - //clip(); - g.setClip(currentPath); - currentPath = null; - Rectangle2D.Float lineRect = new Rectangle2D.Float( - innerx, sy1a, outerx - innerx, ey1a - sy1a); - Java2DRenderer.drawBorderLine(lineRect, false, false, - bpsEnd.style, bpsEnd.color, g); - //restoreGraphicsState(); - } - if (bpsAfter != null) { - //endTextObject(); - - float sx1 = startx; - float sx2 = (slant[3] ? sx1 + bw[3] - clipw[3] : sx1); - float ex1 = startx + width; - float ex2 = (slant[2] ? ex1 - bw[1] + clipw[1] : ex1); - float outery = starty + height + clipw[2]; - float clipy = outery - clipw[2]; - float innery = outery - bw[2]; - - //saveGraphicsState(); - Graphics2D g = (Graphics2D)g2d.create(); - moveTo(ex1, clipy); - float sx1a = sx1; - float ex1a = ex1; - if (bpsAfter.mode == BorderProps.COLLAPSE_OUTER) { - if (bpsStart != null && bpsStart.mode == BorderProps.COLLAPSE_OUTER) { - sx1a -= clipw[3]; - } - if (bpsEnd != null && bpsEnd.mode == BorderProps.COLLAPSE_OUTER) { - ex1a += clipw[1]; - } - lineTo(ex1a, outery); - lineTo(sx1a, outery); - } - lineTo(sx1, clipy); - lineTo(sx2, innery); - lineTo(ex2, innery); - closePath(); - //clip(); - g.setClip(currentPath); - currentPath = null; - Rectangle2D.Float lineRect = new Rectangle2D.Float( - sx1a, innery, ex1a - sx1a, outery - innery); - Java2DRenderer.drawBorderLine(lineRect, true, false, - bpsAfter.style, bpsAfter.color, g); - //restoreGraphicsState(); - } - if (bpsStart != null) { - //endTextObject(); - - float sy1 = starty; - float sy2 = (slant[0] ? sy1 + bw[0] - clipw[0] : sy1); - float ey1 = sy1 + height; - float ey2 = (slant[3] ? ey1 - bw[2] + clipw[2] : ey1); - float outerx = startx - clipw[3]; - float clipx = outerx + clipw[3]; - float innerx = outerx + bw[3]; - - //saveGraphicsState(); - Graphics2D g = (Graphics2D)g2d.create(); - moveTo(clipx, ey1); - float sy1a = sy1; - float ey1a = ey1; - if (bpsStart.mode == BorderProps.COLLAPSE_OUTER) { - if (bpsBefore != null && bpsBefore.mode == BorderProps.COLLAPSE_OUTER) { - sy1a -= clipw[0]; - } - if (bpsAfter != null && bpsAfter.mode == BorderProps.COLLAPSE_OUTER) { - ey1a += clipw[2]; - } - lineTo(outerx, ey1a); - lineTo(outerx, sy1a); - } - lineTo(clipx, sy1); - lineTo(innerx, sy2); - lineTo(innerx, ey2); - closePath(); - //clip(); - g.setClip(currentPath); - currentPath = null; - Rectangle2D.Float lineRect = new Rectangle2D.Float( - outerx, sy1a, innerx - outerx, ey1a - sy1a); - Java2DRenderer.drawBorderLine(lineRect, false, false, - bpsStart.style, bpsStart.color, g); - //restoreGraphicsState(); - } - } - - public Dimension getImageSize() { - return paintRect.getSize(); - } - - }; - try { - g2a.paintImage(painter, rc, - paintRect.x - xoffset, paintRect.y, paintRect.width, paintRect.height); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** {@inheritDoc} */ - public void renderLeader(Leader area) { - renderInlineAreaBackAndBorders(area); - - saveGraphicsState(); - int style = area.getRuleStyle(); - float startx = (currentIPPosition + area.getBorderAndPaddingWidthStart()) / 1000f; - float starty = (currentBPPosition + area.getOffset()) / 1000f; - float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart() - + area.getIPD()) / 1000f; - float ruleThickness = area.getRuleThickness() / 1000f; - Color col = (Color)area.getTrait(Trait.COLOR); - - switch (style) { - case EN_SOLID: - case EN_DASHED: //TODO Improve me and following (this is just a quick-fix ATM) - case EN_DOUBLE: - case EN_DOTTED: - case EN_GROOVE: - case EN_RIDGE: - updateFillColor(col); - fillRect(startx, starty, endx - startx, ruleThickness); - break; - default: - throw new UnsupportedOperationException("rule style not supported"); - } - - restoreGraphicsState(); - super.renderLeader(area); - } - -} diff --git a/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java b/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java index 802ba4176..339880b64 100644 --- a/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java +++ b/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java @@ -57,20 +57,12 @@ public class PCLRendererConfigurator extends PrintRendererConfigurator } /** - * Configure the PCL renderer. + * Throws an UnsupportedOperationException. * - * @param renderer PCL renderer - * @throws FOPException fop exception + * @param renderer not used */ - public void configure(Renderer renderer) throws FOPException { - Configuration cfg = super.getRendererConfig(renderer); - if (cfg != null) { - PCLRenderer pclRenderer = (PCLRenderer)renderer; - - PCLRenderingUtil pclUtil = pclRenderer.getPCLUtil(); - configure(cfg, pclUtil); - } - super.configure(renderer); + public void configure(Renderer renderer) { + throw new UnsupportedOperationException(); } private void configure(Configuration cfg, PCLRenderingUtil pclUtil) throws FOPException { diff --git a/src/java/org/apache/fop/render/pcl/PCLRendererMaker.java b/src/java/org/apache/fop/render/pcl/PCLRendererMaker.java deleted file mode 100644 index a7651a6ac..000000000 --- a/src/java/org/apache/fop/render/pcl/PCLRendererMaker.java +++ /dev/null @@ -1,57 +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.pcl; - -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.render.AbstractRendererMaker; -import org.apache.fop.render.Renderer; -import org.apache.fop.render.RendererConfigurator; - -/** - * RendererMaker for the PCL Renderer. - */ -public class PCLRendererMaker extends AbstractRendererMaker { - - private static final String[] MIMES = new String[] { - MimeConstants.MIME_PCL, - MimeConstants.MIME_PCL_ALT - }; - - /**{@inheritDoc} */ - public Renderer makeRenderer(FOUserAgent userAgent) { - return new PCLRenderer(); - } - - /** {@inheritDoc} */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return new PCLRendererConfigurator(userAgent); - } - - /** {@inheritDoc} */ - public boolean needsOutputStream() { - return true; - } - - /** {@inheritDoc} */ - public String[] getSupportedMimeTypes() { - return MIMES; - } -} diff --git a/src/java/org/apache/fop/render/pcl/PCLSVGHandler.java b/src/java/org/apache/fop/render/pcl/PCLSVGHandler.java index fb2389758..f07a7a7e2 100644 --- a/src/java/org/apache/fop/render/pcl/PCLSVGHandler.java +++ b/src/java/org/apache/fop/render/pcl/PCLSVGHandler.java @@ -28,13 +28,12 @@ import org.apache.fop.render.RendererContext; * PCL XML handler for SVG. Uses Apache Batik for SVG processing. * This handler handles XML for foreign objects when rendering to HP GL/2. * It renders SVG to HP GL/2 using the PCLGraphics2D. - * @see PCLGraphics2DAdapter */ public class PCLSVGHandler extends AbstractGenericSVGHandler { /** {@inheritDoc} */ public boolean supportsRenderer(Renderer renderer) { - return (renderer instanceof PCLRenderer); + return false; } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/pdf/PDFGraphics2DAdapter.java b/src/java/org/apache/fop/render/pdf/PDFGraphics2DAdapter.java deleted file mode 100644 index 102c1ab45..000000000 --- a/src/java/org/apache/fop/render/pdf/PDFGraphics2DAdapter.java +++ /dev/null @@ -1,132 +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; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; - -import org.apache.xmlgraphics.java2d.Graphics2DImagePainter; - -import org.apache.fop.render.AbstractGraphics2DAdapter; -import org.apache.fop.render.RendererContext; -import org.apache.fop.render.RendererContext.RendererContextWrapper; -import org.apache.fop.svg.PDFGraphics2D; - -/** - * Graphics2DAdapter implementation for PDF. - */ -public class PDFGraphics2DAdapter extends AbstractGraphics2DAdapter { - - private PDFRenderer renderer; - - /** - * Main constructor - * @param renderer the Renderer instance to which this instance belongs - */ - public PDFGraphics2DAdapter(PDFRenderer renderer) { - this.renderer = renderer; - } - - /** {@inheritDoc} */ - public void paintImage(Graphics2DImagePainter painter, - RendererContext context, - int x, int y, int width, int height) throws IOException { - - PDFContentGenerator generator = renderer.getGenerator(); - PDFSVGHandler.PDFInfo pdfInfo = PDFSVGHandler.getPDFInfo(context); - float fwidth = width / 1000f; - float fheight = height / 1000f; - float fx = x / 1000f; - float fy = y / 1000f; - - // get the 'width' and 'height' attributes of the SVG document - Dimension dim = painter.getImageSize(); - float imw = (float)dim.getWidth() / 1000f; - float imh = (float)dim.getHeight() / 1000f; - - float sx = pdfInfo.paintAsBitmap ? 1.0f : (fwidth / (float)imw); - float sy = pdfInfo.paintAsBitmap ? 1.0f : (fheight / (float)imh); - - generator.comment("G2D start"); - generator.saveGraphicsState(); - generator.updateColor(Color.black, false, null); - generator.updateColor(Color.black, true, null); - - //TODO Clip to the image area. - - // 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. - generator.add(sx + " 0 0 " + sy + " " + fx + " " - + fy + " cm\n"); - - - final boolean textAsShapes = false; - if (pdfInfo.pdfContext == null) { - pdfInfo.pdfContext = pdfInfo.pdfPage; - } - PDFGraphics2D graphics = new PDFGraphics2D(textAsShapes, - pdfInfo.fi, pdfInfo.pdfDoc, - pdfInfo.pdfContext, pdfInfo.pdfPage.referencePDF(), - pdfInfo.currentFontName, - pdfInfo.currentFontSize); - graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); - - AffineTransform transform = new AffineTransform(); - transform.translate(fx, fy); - generator.getState().concatenate(transform); - graphics.setPaintingState(generator.getState()); - graphics.setOutputStream(pdfInfo.outputStream); - - if (pdfInfo.paintAsBitmap) { - //Fallback solution: Paint to a BufferedImage - int resolution = (int)Math.round(context.getUserAgent().getTargetResolution()); - RendererContextWrapper ctx = RendererContext.wrapRendererContext(context); - BufferedImage bi = paintToBufferedImage(painter, ctx, resolution, false, false); - - float scale = PDFRenderer.NORMAL_PDF_RESOLUTION - / context.getUserAgent().getTargetResolution(); - graphics.drawImage(bi, new AffineTransform(scale, 0, 0, scale, 0, 0), null); - } else { - Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); - painter.paint(graphics, area); - } - - generator.add(graphics.getString()); - generator.restoreGraphicsState(); - generator.comment("G2D end"); - } - - /** {@inheritDoc} */ - protected void setRenderingHintsForBufferedImage(Graphics2D g2d) { - super.setRenderingHintsForBufferedImage(g2d); - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, - RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - } - -} diff --git a/src/java/org/apache/fop/render/pdf/PDFImageHandler.java b/src/java/org/apache/fop/render/pdf/PDFImageHandler.java deleted file mode 100644 index 934d306b9..000000000 --- a/src/java/org/apache/fop/render/pdf/PDFImageHandler.java +++ /dev/null @@ -1,52 +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; - -import java.awt.Point; -import java.awt.Rectangle; -import java.io.IOException; - -import org.apache.xmlgraphics.image.loader.Image; - -import org.apache.fop.pdf.PDFXObject; -import org.apache.fop.render.ImageHandlerBase; -import org.apache.fop.render.RendererContext; - -/** - * This interface is used for handling all sorts of image type for PDF output. - */ -public interface PDFImageHandler extends ImageHandlerBase { - - /** - * Generates the PDF objects for the given {@link Image} instance. If the handler generates - * an XObject, it shall return it or otherwise return null. A generated XObject shall be - * placed in the current viewport according to the two parameters "origin" and "pos". - * @param context the PDF renderer context - * @param image the image to be handled - * @param origin the current position in the current viewport (in millipoints) - * @param pos the position and scaling of the image relative to the origin point - * (in millipoints) - * @return the generated XObject or null if no XObject was generated - * @throws IOException if an I/O error occurs - */ - PDFXObject generateImage(RendererContext context, Image image, - Point origin, Rectangle pos) throws IOException; - -} diff --git a/src/java/org/apache/fop/render/pdf/PDFImageHandlerGraphics2D.java b/src/java/org/apache/fop/render/pdf/PDFImageHandlerGraphics2D.java index c3242827a..d309a00aa 100644 --- a/src/java/org/apache/fop/render/pdf/PDFImageHandlerGraphics2D.java +++ b/src/java/org/apache/fop/render/pdf/PDFImageHandlerGraphics2D.java @@ -21,7 +21,6 @@ package org.apache.fop.render.pdf; import java.awt.Color; import java.awt.Dimension; -import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; @@ -31,9 +30,7 @@ import org.apache.xmlgraphics.image.loader.Image; import org.apache.xmlgraphics.image.loader.ImageFlavor; import org.apache.xmlgraphics.image.loader.impl.ImageGraphics2D; -import org.apache.fop.pdf.PDFXObject; import org.apache.fop.render.AbstractImageHandlerGraphics2D; -import org.apache.fop.render.RendererContext; import org.apache.fop.render.RenderingContext; import org.apache.fop.render.pdf.PDFLogicalStructureHandler.MarkedContentInfo; import org.apache.fop.svg.PDFGraphics2D; @@ -41,36 +38,12 @@ import org.apache.fop.svg.PDFGraphics2D; /** * PDFImageHandler implementation which handles Graphics2D images. */ -public class PDFImageHandlerGraphics2D extends AbstractImageHandlerGraphics2D - implements PDFImageHandler { +public class PDFImageHandlerGraphics2D extends AbstractImageHandlerGraphics2D { private static final ImageFlavor[] FLAVORS = new ImageFlavor[] { ImageFlavor.GRAPHICS2D, }; - /** {@inheritDoc} */ - public PDFXObject generateImage(RendererContext context, Image image, - Point origin, Rectangle pos) - throws IOException { - PDFRenderer renderer = (PDFRenderer)context.getRenderer(); - /* - ImageGraphics2D imageG2D = (ImageGraphics2D)image; - renderer.getGraphics2DAdapter().paintImage(imageG2D.getGraphics2DImagePainter(), - context, origin.x + pos.x, origin.y + pos.y, pos.width, pos.height); - */ - PDFRenderingContext pdfContext = new PDFRenderingContext( - context.getUserAgent(), - renderer.getGenerator(), - renderer.currentPage, - renderer.getFontInfo()); - Rectangle effPos = new Rectangle(origin.x + pos.x, origin.y + pos.y, pos.width, pos.height); - if (context.getUserAgent().isAccessibilityEnabled()) { - pdfContext.setMarkedContentInfo(renderer.addCurrentImageToStructureTree()); - } - handleImage(pdfContext, image, effPos); - return null; - } - /** {@inheritDoc} */ public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { diff --git a/src/java/org/apache/fop/render/pdf/PDFImageHandlerRawCCITTFax.java b/src/java/org/apache/fop/render/pdf/PDFImageHandlerRawCCITTFax.java index 75b1d356e..b7d47ad58 100644 --- a/src/java/org/apache/fop/render/pdf/PDFImageHandlerRawCCITTFax.java +++ b/src/java/org/apache/fop/render/pdf/PDFImageHandlerRawCCITTFax.java @@ -19,7 +19,6 @@ package org.apache.fop.render.pdf; -import java.awt.Point; import java.awt.Rectangle; import java.io.IOException; @@ -27,47 +26,21 @@ import org.apache.xmlgraphics.image.loader.Image; import org.apache.xmlgraphics.image.loader.ImageFlavor; import org.apache.xmlgraphics.image.loader.impl.ImageRawCCITTFax; -import org.apache.fop.pdf.PDFDocument; import org.apache.fop.pdf.PDFImage; -import org.apache.fop.pdf.PDFResourceContext; import org.apache.fop.pdf.PDFXObject; import org.apache.fop.render.ImageHandler; -import org.apache.fop.render.RendererContext; import org.apache.fop.render.RenderingContext; /** * Image handler implementation which handles CCITT encoded images (CCITT fax group 3/4) * for PDF output. */ -public class PDFImageHandlerRawCCITTFax implements PDFImageHandler, ImageHandler { +public class PDFImageHandlerRawCCITTFax implements ImageHandler { private static final ImageFlavor[] FLAVORS = new ImageFlavor[] { ImageFlavor.RAW_CCITTFAX, }; - /** {@inheritDoc} */ - public PDFXObject generateImage(RendererContext context, Image image, - Point origin, Rectangle pos) - throws IOException { - PDFRenderer renderer = (PDFRenderer)context.getRenderer(); - ImageRawCCITTFax ccitt = (ImageRawCCITTFax)image; - PDFDocument pdfDoc = (PDFDocument)context.getProperty( - PDFRendererContextConstants.PDF_DOCUMENT); - PDFResourceContext resContext = (PDFResourceContext)context.getProperty( - PDFRendererContextConstants.PDF_CONTEXT); - - PDFImage pdfimage = new ImageRawCCITTFaxAdapter(ccitt, image.getInfo().getOriginalURI()); - PDFXObject xobj = pdfDoc.addImage(resContext, pdfimage); - - float x = (float)pos.getX() / 1000f; - float y = (float)pos.getY() / 1000f; - float w = (float)pos.getWidth() / 1000f; - float h = (float)pos.getHeight() / 1000f; - renderer.placeImage(x, y, w, h, xobj); - - return xobj; - } - /** {@inheritDoc} */ public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { diff --git a/src/java/org/apache/fop/render/pdf/PDFImageHandlerRawJPEG.java b/src/java/org/apache/fop/render/pdf/PDFImageHandlerRawJPEG.java index 02dd98ecf..7ac181014 100644 --- a/src/java/org/apache/fop/render/pdf/PDFImageHandlerRawJPEG.java +++ b/src/java/org/apache/fop/render/pdf/PDFImageHandlerRawJPEG.java @@ -19,7 +19,6 @@ package org.apache.fop.render.pdf; -import java.awt.Point; import java.awt.Rectangle; import java.io.IOException; @@ -27,47 +26,21 @@ import org.apache.xmlgraphics.image.loader.Image; import org.apache.xmlgraphics.image.loader.ImageFlavor; import org.apache.xmlgraphics.image.loader.impl.ImageRawJPEG; -import org.apache.fop.pdf.PDFDocument; import org.apache.fop.pdf.PDFImage; -import org.apache.fop.pdf.PDFResourceContext; import org.apache.fop.pdf.PDFXObject; import org.apache.fop.render.ImageHandler; -import org.apache.fop.render.RendererContext; import org.apache.fop.render.RenderingContext; import org.apache.fop.render.pdf.PDFLogicalStructureHandler.MarkedContentInfo; /** * Image handler implementation which handles raw JPEG images for PDF output. */ -public class PDFImageHandlerRawJPEG implements PDFImageHandler, ImageHandler { +public class PDFImageHandlerRawJPEG implements ImageHandler { private static final ImageFlavor[] FLAVORS = new ImageFlavor[] { ImageFlavor.RAW_JPEG, }; - /** {@inheritDoc} */ - public PDFXObject generateImage(RendererContext context, Image image, - Point origin, Rectangle pos) - throws IOException { - PDFRenderer renderer = (PDFRenderer)context.getRenderer(); - ImageRawJPEG jpeg = (ImageRawJPEG)image; - PDFDocument pdfDoc = (PDFDocument)context.getProperty( - PDFRendererContextConstants.PDF_DOCUMENT); - PDFResourceContext resContext = (PDFResourceContext)context.getProperty( - PDFRendererContextConstants.PDF_CONTEXT); - - PDFImage pdfimage = new ImageRawJPEGAdapter(jpeg, image.getInfo().getOriginalURI()); - PDFXObject xobj = pdfDoc.addImage(resContext, pdfimage); - - float x = (float)pos.getX() / 1000f; - float y = (float)pos.getY() / 1000f; - float w = (float)pos.getWidth() / 1000f; - float h = (float)pos.getHeight() / 1000f; - renderer.placeImage(x, y, w, h, xobj); - - return xobj; - } - /** {@inheritDoc} */ public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { diff --git a/src/java/org/apache/fop/render/pdf/PDFImageHandlerRegistry.java b/src/java/org/apache/fop/render/pdf/PDFImageHandlerRegistry.java deleted file mode 100644 index 1d4c733a3..000000000 --- a/src/java/org/apache/fop/render/pdf/PDFImageHandlerRegistry.java +++ /dev/null @@ -1,36 +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; - -import org.apache.fop.render.AbstractImageHandlerRegistry; - -/** - * This class holds references to various image handlers used by the PDF renderer. It also - * supports automatic discovery of additional handlers available through - * the class path. - */ -public class PDFImageHandlerRegistry extends AbstractImageHandlerRegistry { - - /** {@inheritDoc} */ - public Class getHandlerClass() { - return PDFImageHandler.class; - } - -} diff --git a/src/java/org/apache/fop/render/pdf/PDFImageHandlerRenderedImage.java b/src/java/org/apache/fop/render/pdf/PDFImageHandlerRenderedImage.java index 3c02cb6f3..e0ff3cdd4 100644 --- a/src/java/org/apache/fop/render/pdf/PDFImageHandlerRenderedImage.java +++ b/src/java/org/apache/fop/render/pdf/PDFImageHandlerRenderedImage.java @@ -19,7 +19,6 @@ package org.apache.fop.render.pdf; -import java.awt.Point; import java.awt.Rectangle; import java.io.IOException; @@ -27,48 +26,22 @@ import org.apache.xmlgraphics.image.loader.Image; import org.apache.xmlgraphics.image.loader.ImageFlavor; import org.apache.xmlgraphics.image.loader.impl.ImageRendered; -import org.apache.fop.pdf.PDFDocument; import org.apache.fop.pdf.PDFImage; -import org.apache.fop.pdf.PDFResourceContext; import org.apache.fop.pdf.PDFXObject; import org.apache.fop.render.ImageHandler; -import org.apache.fop.render.RendererContext; import org.apache.fop.render.RenderingContext; import org.apache.fop.render.pdf.PDFLogicalStructureHandler.MarkedContentInfo; /** * Image handler implementation which handles RenderedImage instances for PDF output. */ -public class PDFImageHandlerRenderedImage implements PDFImageHandler, ImageHandler { +public class PDFImageHandlerRenderedImage implements ImageHandler { private static final ImageFlavor[] FLAVORS = new ImageFlavor[] { ImageFlavor.BUFFERED_IMAGE, ImageFlavor.RENDERED_IMAGE }; - /** {@inheritDoc} */ - public PDFXObject generateImage(RendererContext context, Image image, - Point origin, Rectangle pos) - throws IOException { - PDFRenderer renderer = (PDFRenderer)context.getRenderer(); - ImageRendered imageRend = (ImageRendered)image; - PDFDocument pdfDoc = (PDFDocument)context.getProperty( - PDFRendererContextConstants.PDF_DOCUMENT); - PDFResourceContext resContext = (PDFResourceContext)context.getProperty( - PDFRendererContextConstants.PDF_CONTEXT); - - PDFImage pdfimage = new ImageRenderedAdapter(imageRend, image.getInfo().getOriginalURI()); - PDFXObject xobj = pdfDoc.addImage(resContext, pdfimage); - - float x = (float)pos.getX() / 1000f; - float y = (float)pos.getY() / 1000f; - float w = (float)pos.getWidth() / 1000f; - float h = (float)pos.getHeight() / 1000f; - renderer.placeImage(x, y, w, h, xobj); - - return xobj; - } - /** {@inheritDoc} */ public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { diff --git a/src/java/org/apache/fop/render/pdf/PDFImageHandlerXML.java b/src/java/org/apache/fop/render/pdf/PDFImageHandlerXML.java deleted file mode 100644 index 26ba83371..000000000 --- a/src/java/org/apache/fop/render/pdf/PDFImageHandlerXML.java +++ /dev/null @@ -1,72 +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; - -import java.awt.Point; -import java.awt.Rectangle; -import java.io.IOException; -import java.util.Map; - -import org.apache.fop.pdf.PDFXObject; -import org.apache.fop.render.RendererContext; -import org.apache.xmlgraphics.image.loader.Image; -import org.apache.xmlgraphics.image.loader.ImageFlavor; -import org.apache.xmlgraphics.image.loader.impl.ImageXMLDOM; -import org.w3c.dom.Document; - -/** - * PDFImageHandler implementation which handles XML-based images. - */ -public class PDFImageHandlerXML implements PDFImageHandler { - - private static final ImageFlavor[] FLAVORS = new ImageFlavor[] { - ImageFlavor.XML_DOM, - }; - - /** {@inheritDoc} */ - public PDFXObject generateImage(RendererContext context, Image image, - Point origin, Rectangle pos) - throws IOException { - PDFRenderer renderer = (PDFRenderer)context.getRenderer(); - ImageXMLDOM imgXML = (ImageXMLDOM)image; - Document doc = imgXML.getDocument(); - String ns = imgXML.getRootNamespace(); - Map foreignAttributes = (Map)context.getProperty( - PDFRendererContextConstants.FOREIGN_ATTRIBUTES); - renderer.renderDocument(doc, ns, pos, foreignAttributes); - return null; - } - - /** {@inheritDoc} */ - public int getPriority() { - return 400; - } - - /** {@inheritDoc} */ - public Class getSupportedImageClass() { - return ImageXMLDOM.class; - } - - /** {@inheritDoc} */ - public ImageFlavor[] getSupportedImageFlavors() { - return FLAVORS; - } - -} diff --git a/src/java/org/apache/fop/render/pdf/PDFRenderer.java b/src/java/org/apache/fop/render/pdf/PDFRenderer.java deleted file mode 100644 index 1aa5ac74e..000000000 --- a/src/java/org/apache/fop/render/pdf/PDFRenderer.java +++ /dev/null @@ -1,1361 +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; - -// Java -import java.awt.Color; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; - -import org.apache.xmlgraphics.image.loader.ImageException; -import org.apache.xmlgraphics.image.loader.ImageFlavor; -import org.apache.xmlgraphics.image.loader.ImageInfo; -import org.apache.xmlgraphics.image.loader.ImageManager; -import org.apache.xmlgraphics.image.loader.ImageSessionContext; -import org.apache.xmlgraphics.image.loader.util.ImageUtil; - -import org.apache.fop.ResourceEventProducer; -import org.apache.fop.apps.FOPException; -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.area.Area; -import org.apache.fop.area.Block; -import org.apache.fop.area.BookmarkData; -import org.apache.fop.area.CTM; -import org.apache.fop.area.DestinationData; -import org.apache.fop.area.LineArea; -import org.apache.fop.area.OffDocumentExtensionAttachment; -import org.apache.fop.area.OffDocumentItem; -import org.apache.fop.area.PageSequence; -import org.apache.fop.area.PageViewport; -import org.apache.fop.area.Trait; -import org.apache.fop.area.inline.AbstractTextArea; -import org.apache.fop.area.inline.Image; -import org.apache.fop.area.inline.InlineArea; -import org.apache.fop.area.inline.InlineParent; -import org.apache.fop.area.inline.Leader; -import org.apache.fop.area.inline.SpaceArea; -import org.apache.fop.area.inline.TextArea; -import org.apache.fop.area.inline.Viewport; -import org.apache.fop.area.inline.WordArea; -import org.apache.fop.datatypes.URISpecification; -import org.apache.fop.fo.extensions.ExtensionAttachment; -import org.apache.fop.fo.extensions.xmp.XMPMetadata; -import org.apache.fop.fonts.Font; -import org.apache.fop.fonts.LazyFont; -import org.apache.fop.fonts.SingleByteFont; -import org.apache.fop.fonts.Typeface; -import org.apache.fop.pdf.PDFAMode; -import org.apache.fop.pdf.PDFAction; -import org.apache.fop.pdf.PDFAnnotList; -import org.apache.fop.pdf.PDFDocument; -import org.apache.fop.pdf.PDFEncryptionParams; -import org.apache.fop.pdf.PDFFactory; -import org.apache.fop.pdf.PDFGoTo; -import org.apache.fop.pdf.PDFInfo; -import org.apache.fop.pdf.PDFLink; -import org.apache.fop.pdf.PDFNumber; -import org.apache.fop.pdf.PDFOutline; -import org.apache.fop.pdf.PDFPage; -import org.apache.fop.pdf.PDFPaintingState; -import org.apache.fop.pdf.PDFResourceContext; -import org.apache.fop.pdf.PDFResources; -import org.apache.fop.pdf.PDFTextUtil; -import org.apache.fop.pdf.PDFXMode; -import org.apache.fop.pdf.PDFXObject; -import org.apache.fop.render.AbstractPathOrientedRenderer; -import org.apache.fop.render.Graphics2DAdapter; -import org.apache.fop.render.RendererContext; -import org.apache.fop.render.pdf.PDFLogicalStructureHandler.MarkedContentInfo; -import org.apache.fop.render.pdf.extensions.PDFEmbeddedFileExtensionAttachment; -import org.apache.fop.traits.RuleStyle; -import org.apache.fop.util.AbstractPaintingState; -import org.apache.fop.util.CharUtilities; -import org.apache.fop.util.XMLUtil; -import org.apache.fop.util.AbstractPaintingState.AbstractData; - -/** - * Renderer that renders areas to PDF. - */ -public class PDFRenderer extends AbstractPathOrientedRenderer implements PDFConfigurationConstants { - - /** The MIME type for PDF */ - public static final String MIME_TYPE = MimeConstants.MIME_PDF; - - /** Normal PDF resolution (72dpi) */ - public static final int NORMAL_PDF_RESOLUTION = 72; - - - /** Controls whether comments are written to the PDF stream. */ - protected static final boolean WRITE_COMMENTS = true; - - /** - * the PDF Document being created - */ - protected PDFDocument pdfDoc; - - /** - * Utility class which enables all sorts of features that are not directly connected to the - * normal rendering process. - */ - protected PDFRenderingUtil pdfUtil; - - /** - * Map of pages using the PageViewport as the key - * this is used for prepared pages that cannot be immediately - * rendered - */ - private Map pages; - - /** - * Maps unique PageViewport key to PDF page reference - */ - protected Map pageReferences = new java.util.HashMap(); - - /** - * Maps unique PageViewport key back to PageViewport itself - */ - //protected Map pvReferences = new java.util.HashMap(); - - /** - * Maps XSL-FO element IDs to their on-page XY-positions - * Must be used in conjunction with the page reference to fully specify the PDFGoTo details - */ - protected Map idPositions = new java.util.HashMap(); - - /** - * Maps XSL-FO element IDs to PDFGoTo objects targeting the corresponding areas - * These objects may not all be fully filled in yet - */ - protected Map idGoTos = new java.util.HashMap(); - - /** - * The PDFGoTos in idGoTos that are not complete yet - */ - protected List unfinishedGoTos = new java.util.ArrayList(); - // can't use a Set because PDFGoTo.equals returns true if the target is the same, - // even if the object number differs - - /** - * The output stream to write the document to - */ - protected OutputStream ostream; - - /** - * the /Resources object of the PDF document being created - */ - protected PDFResources pdfResources; - - /** The current content generator to produce PDF commands with */ - protected PDFContentGenerator generator; - private PDFBorderPainter borderPainter; - - /** - * the current annotation list to add annotations to - */ - protected PDFResourceContext currentContext = null; - - /** - * the current page to add annotations to - */ - protected PDFPage currentPage; - - /** - * the current page's PDF reference string (to avoid numerous function calls) - */ - protected String currentPageRef; - - /** page height */ - protected int pageHeight; - - /** Image handler registry */ - private final PDFImageHandlerRegistry imageHandlerRegistry = new PDFImageHandlerRegistry(); - - private boolean accessEnabled; - - private PDFLogicalStructureHandler logicalStructureHandler; - - private int pageSequenceIndex; - - /** Reference in the structure tree to the image being rendered. */ - private String imageReference; - - /** - * create the PDF renderer - */ - public PDFRenderer() { - } - - /** {@inheritDoc} */ - public void setUserAgent(FOUserAgent agent) { - super.setUserAgent(agent); - this.pdfUtil = new PDFRenderingUtil(getUserAgent()); - accessEnabled = agent.isAccessibilityEnabled(); - } - - PDFRenderingUtil getPDFUtil() { - return this.pdfUtil; - } - - PDFContentGenerator getGenerator() { - return this.generator; - } - - PDFPaintingState getState() { - return getGenerator().getState(); - } - - /** {@inheritDoc} */ - public void startRenderer(OutputStream stream) throws IOException { - if (userAgent == null) { - throw new IllegalStateException("UserAgent must be set before starting the renderer"); - } - ostream = stream; - this.pdfDoc = pdfUtil.setupPDFDocument(stream); - if (accessEnabled) { - pdfDoc.getRoot().makeTagged(); - logicalStructureHandler = new PDFLogicalStructureHandler(pdfDoc, - userAgent.getEventBroadcaster()); - } - } - - /** - * Checks if there are any unfinished PDFGoTos left in the list and resolves them - * to a default position on the page. Logs a warning, as this should not happen. - */ - protected void finishOpenGoTos() { - int count = unfinishedGoTos.size(); - if (count > 0) { - // TODO : page height may not be the same for all targeted pages - Point2D.Float defaultPos = new Point2D.Float(0f, pageHeight / 1000f); // top-o-page - while (!unfinishedGoTos.isEmpty()) { - PDFGoTo gt = (PDFGoTo) unfinishedGoTos.get(0); - finishIDGoTo(gt, defaultPos); - } - PDFEventProducer eventProducer = PDFEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.nonFullyResolvedLinkTargets(this, count); - // dysfunctional if pageref is null - } - } - - /** {@inheritDoc} */ - public void stopRenderer() throws IOException { - finishOpenGoTos(); - - pdfDoc.getResources().addFonts(pdfDoc, fontInfo); - pdfDoc.outputTrailer(ostream); - - this.pdfDoc = null; - ostream = null; - - pages = null; - - pageReferences.clear(); - //pvReferences.clear(); - pdfResources = null; - this.generator = null; - currentContext = null; - currentPage = null; - - idPositions.clear(); - idGoTos.clear(); - } - - /** - * {@inheritDoc} - */ - public boolean supportsOutOfOrder() { - return !accessEnabled; - } - - /** - * {@inheritDoc} - */ - public void processOffDocumentItem(OffDocumentItem odi) { - if (odi instanceof DestinationData) { - // render Destinations - renderDestination((DestinationData) odi); - } else if (odi instanceof BookmarkData) { - // render Bookmark-Tree - renderBookmarkTree((BookmarkData) odi); - } else if (odi instanceof OffDocumentExtensionAttachment) { - ExtensionAttachment attachment = ((OffDocumentExtensionAttachment)odi).getAttachment(); - if (XMPMetadata.CATEGORY.equals(attachment.getCategory())) { - pdfUtil.renderXMPMetadata((XMPMetadata)attachment); - } else if (PDFEmbeddedFileExtensionAttachment.CATEGORY.equals( - attachment.getCategory())) { - try { - pdfUtil.addEmbeddedFile((PDFEmbeddedFileExtensionAttachment)attachment); - } catch (IOException ioe) { - throw new RuntimeException("Error embedding file", ioe); - } - } - } - } - - private void renderDestination(DestinationData dd) { - String targetID = dd.getIDRef(); - if (targetID == null || targetID.length() == 0) { - throw new IllegalArgumentException("DestinationData must contain a ID reference"); - } - PageViewport pv = dd.getPageViewport(); - if (pv != null) { - PDFGoTo gt = getPDFGoToForID(targetID, pv.getKey()); - pdfDoc.getFactory().makeDestination( - dd.getIDRef(), gt.makeReference()); - } else { - //Warning already issued by AreaTreeHandler (debug level is sufficient) - log.debug("Unresolved destination item received: " + dd.getIDRef()); - } - } - - /** - * Renders a Bookmark-Tree object - * @param bookmarks the BookmarkData object containing all the Bookmark-Items - */ - protected void renderBookmarkTree(BookmarkData bookmarks) { - for (int i = 0; i < bookmarks.getCount(); i++) { - BookmarkData ext = bookmarks.getSubData(i); - renderBookmarkItem(ext, null); - } - } - - private void renderBookmarkItem(BookmarkData bookmarkItem, - PDFOutline parentBookmarkItem) { - PDFOutline pdfOutline = null; - - String targetID = bookmarkItem.getIDRef(); - if (targetID == null || targetID.length() == 0) { - throw new IllegalArgumentException("DestinationData must contain a ID reference"); - } - PageViewport pv = bookmarkItem.getPageViewport(); - if (pv != null) { - String pvKey = pv.getKey(); - PDFGoTo gt = getPDFGoToForID(targetID, pvKey); - // create outline object: - PDFOutline parent = parentBookmarkItem != null - ? parentBookmarkItem - : pdfDoc.getOutlineRoot(); - pdfOutline = pdfDoc.getFactory().makeOutline(parent, - bookmarkItem.getBookmarkTitle(), gt, bookmarkItem.showChildItems()); - } else { - //Warning already issued by AreaTreeHandler (debug level is sufficient) - log.debug("Bookmark with IDRef \"" + targetID + "\" has a null PageViewport."); - } - - for (int i = 0; i < bookmarkItem.getCount(); i++) { - renderBookmarkItem(bookmarkItem.getSubData(i), pdfOutline); - } - } - - /** {@inheritDoc} */ - public Graphics2DAdapter getGraphics2DAdapter() { - return new PDFGraphics2DAdapter(this); - } - - /** {@inheritDoc} */ - protected void saveGraphicsState() { - generator.saveGraphicsState(); - } - - /** {@inheritDoc} */ - protected void restoreGraphicsState() { - generator.restoreGraphicsState(); - } - - /** Indicates the beginning of a text object. */ - protected void beginTextObject() { - generator.beginTextObject(); - } - - /** Indicates the end of a text object. */ - protected void endTextObject() { - generator.endTextObject(); - } - - /** - * Start the next page sequence. - * For the PDF renderer there is no concept of page sequences - * but it uses the first available page sequence title to set - * as the title of the PDF document, and the language of the - * document. - * @param pageSequence the page sequence - */ - public void startPageSequence(PageSequence pageSequence) { - super.startPageSequence(pageSequence); - LineArea seqTitle = pageSequence.getTitle(); - if (seqTitle != null) { - String str = convertTitleToString(seqTitle); - PDFInfo info = this.pdfDoc.getInfo(); - if (info.getTitle() == null) { - info.setTitle(str); - } - } - Locale language = null; - if (pageSequence.getLanguage() != null) { - String lang = pageSequence.getLanguage(); - String country = pageSequence.getCountry(); - if (lang != null) { - language = (country == null) ? new Locale(lang) : new Locale(lang, country); - } - if (pdfDoc.getRoot().getLanguage() == null) { - //Only set if not set already (first non-null is used) - //Note: No checking is performed whether the values are valid! - pdfDoc.getRoot().setLanguage(XMLUtil.toRFC3066(language)); - } - } - pdfUtil.generateDefaultXMPMetadata(); - if (accessEnabled) { - NodeList nodes = getUserAgent().getStructureTree().getPageSequence(pageSequenceIndex++); - logicalStructureHandler.processStructureTree(nodes, language); - } - } - - /** - * The pdf page is prepared by making the page. - * The page is made in the pdf document without any contents - * and then stored to add the contents later. - * The page objects is stored using the area tree PageViewport - * as a key. - * - * @param page the page to prepare - */ - public void preparePage(PageViewport page) { - setupPage(page); - if (pages == null) { - pages = new java.util.HashMap(); - } - pages.put(page, currentPage); - } - - private void setupPage(PageViewport page) { - this.pdfResources = this.pdfDoc.getResources(); - - Rectangle2D bounds = page.getViewArea(); - double w = bounds.getWidth(); - double h = bounds.getHeight(); - this.currentPage = this.pdfDoc.getFactory().makePage( - this.pdfResources, - (int) Math.round(w / 1000), (int) Math.round(h / 1000), - page.getPageIndex()); - pageReferences.put(page.getKey(), currentPage.referencePDF()); - //pvReferences.put(page.getKey(), page); - - pdfUtil.generatePageLabel(page.getPageIndex(), page.getPageNumberString()); - } - - /** - * This method creates a PDF stream for the current page - * uses it as the contents of a new page. The page is written - * immediately to the output stream. - * {@inheritDoc} - */ - public void renderPage(PageViewport page) - throws IOException, FOPException { - if (pages != null - && (currentPage = (PDFPage) pages.get(page)) != null) { // CSOK: InnerAssignment - //Retrieve previously prepared page (out-of-line rendering) - pages.remove(page); - } else { - setupPage(page); - } - currentPageRef = currentPage.referencePDF(); - - if (accessEnabled) { - logicalStructureHandler.startPage(currentPage); - } - - Rectangle bounds = page.getViewArea(); - pageHeight = bounds.height; - - this.generator = new PDFContentGenerator(this.pdfDoc, this.ostream, this.currentPage); - this.borderPainter = new PDFBorderPainter(this.generator); - - // Transform the PDF's default coordinate system (0,0 at lower left) to the PDFRenderer's - saveGraphicsState(); - AffineTransform basicPageTransform = new AffineTransform(1, 0, 0, -1, 0, - pageHeight / 1000f); - generator.concatenate(basicPageTransform); - - super.renderPage(page); - - restoreGraphicsState(); - if (accessEnabled) { - logicalStructureHandler.endPage(); - } - - this.pdfDoc.registerObject(generator.getStream()); - currentPage.setContents(generator.getStream()); - PDFAnnotList annots = currentPage.getAnnotations(); - if (annots != null) { - this.pdfDoc.addObject(annots); - } - this.pdfDoc.addObject(currentPage); - this.borderPainter = null; - this.generator.flushPDFDoc(); - this.generator = null; - } - - /** {@inheritDoc} */ - protected void startVParea(CTM ctm, Rectangle2D clippingRect) { - saveGraphicsState(); - // Set the given CTM in the graphics state - /* - currentState.concatenate( - new AffineTransform(CTMHelper.toPDFArray(ctm))); - */ - - if (clippingRect != null) { - clipRect((float)clippingRect.getX() / 1000f, - (float)clippingRect.getY() / 1000f, - (float)clippingRect.getWidth() / 1000f, - (float)clippingRect.getHeight() / 1000f); - } - // multiply with current CTM - generator.concatenate(new AffineTransform(CTMHelper.toPDFArray(ctm))); - } - - /** {@inheritDoc} */ - protected void endVParea() { - restoreGraphicsState(); - } - - /** {@inheritDoc} */ - protected void concatenateTransformationMatrix(AffineTransform at) { - generator.concatenate(at); - } - - /** - * Formats a float value (normally coordinates) as Strings. - * @param value the value - * @return the formatted value - */ - protected static String format(float value) { - return PDFNumber.doubleOut(value); - } - - /** {@inheritDoc} */ - protected void drawBorderLine // CSOK: ParameterNumber - (float x1, float y1, float x2, float y2, - boolean horz, boolean startOrBefore, int style, Color col) { - PDFBorderPainter.drawBorderLine(generator, x1, y1, x2, y2, horz, startOrBefore, style, col); - } - - /** {@inheritDoc} */ - protected void clipRect(float x, float y, float width, float height) { - generator.add(format(x) + " " + format(y) + " " - + format(width) + " " + format(height) + " re "); - clip(); - } - - /** - * Clip an area. - */ - protected void clip() { - generator.add("W\n" + "n\n"); - } - - /** - * Moves the current point to (x, y), omitting any connecting line segment. - * @param x x coordinate - * @param y y coordinate - */ - protected void moveTo(float x, float y) { - generator.add(format(x) + " " + format(y) + " m "); - } - - /** - * Appends a straight line segment from the current point to (x, y). The - * new current point is (x, y). - * @param x x coordinate - * @param y y coordinate - */ - protected void lineTo(float x, float y) { - generator.add(format(x) + " " + format(y) + " l "); - } - - /** - * Closes the current subpath by appending a straight line segment from - * the current point to the starting point of the subpath. - */ - protected void closePath() { - generator.add("h "); - } - - /** - * {@inheritDoc} - */ - protected void fillRect(float x, float y, float width, float height) { - if (width > 0 && height > 0) { - generator.add(format(x) + " " + format(y) + " " - + format(width) + " " + format(height) + " re f\n"); - } - } - - /** - * Draw a line. - * - * @param startx the start x position - * @param starty the start y position - * @param endx the x end position - * @param endy the y end position - */ - private void drawLine(float startx, float starty, float endx, float endy) { - generator.add(format(startx) + " " + format(starty) + " m "); - generator.add(format(endx) + " " + format(endy) + " l S\n"); - } - - /** - * Breaks out of the state stack to handle fixed block-containers. - * @return the saved state stack to recreate later - */ - protected List breakOutOfStateStack() { - PDFPaintingState paintingState = getState(); - List breakOutList = new java.util.ArrayList(); - AbstractPaintingState.AbstractData data; - while (true) { - data = paintingState.getData(); - if (paintingState.restore() == null) { - break; - } - if (breakOutList.size() == 0) { - generator.comment("------ break out!"); - } - breakOutList.add(0, data); //Insert because of stack-popping - generator.restoreGraphicsState(false); - } - return breakOutList; - } - - /** - * Restores the state stack after a break out. - * @param breakOutList the state stack to restore. - */ - protected void restoreStateStackAfterBreakOut(List breakOutList) { - generator.comment("------ restoring context after break-out..."); -// currentState.pushAll(breakOutList); - AbstractData data; - Iterator i = breakOutList.iterator(); - while (i.hasNext()) { - data = (AbstractData)i.next(); - saveGraphicsState(); - AffineTransform at = data.getTransform(); - concatenateTransformationMatrix(at); - //TODO Break-out: Also restore items such as line width and color - //Left out for now because all this painting stuff is very - //inconsistent. Some values go over PDFState, some don't. - } - generator.comment("------ done."); - } - - /** - * Returns area's id if it is the first area in the document with that id - * (i.e. if the area qualifies as a link target). - * Otherwise, or if the area has no id, null is returned. - * - * NOTE: area must be on currentPageViewport, otherwise result may be wrong! - * - * @param area the area for which to return the id - * @return the area's id (null if the area has no id or - * other preceding areas have the same id) - */ - protected String getTargetableID(Area area) { - String id = (String) area.getTrait(Trait.PROD_ID); - if (id == null || id.length() == 0 - || !currentPageViewport.isFirstWithID(id) - || idPositions.containsKey(id)) { - return null; - } else { - return id; - } - } - - /** - * Set XY position in the PDFGoTo and add it to the PDF trailer. - * - * @param gt the PDFGoTo object - * @param position the X,Y position to set - */ - protected void finishIDGoTo(PDFGoTo gt, Point2D.Float position) { - gt.setPosition(position); - pdfDoc.addTrailerObject(gt); - unfinishedGoTos.remove(gt); - } - - /** - * Set page reference and XY position in the PDFGoTo and add it to the PDF trailer. - * - * @param gt the PDFGoTo object - * @param pdfPageRef the PDF reference string of the target page object - * @param position the X,Y position to set - */ - protected void finishIDGoTo(PDFGoTo gt, String pdfPageRef, Point2D.Float position) { - gt.setPageReference(pdfPageRef); - finishIDGoTo(gt, position); - } - - /** - * Get a PDFGoTo pointing to the given id. Create one if necessary. - * It is possible that the PDFGoTo is not fully resolved yet. In that case - * it must be completed (and added to the PDF trailer) later. - * - * @param targetID the target id of the PDFGoTo - * @param pvKey the unique key of the target PageViewport - * - * @return the PDFGoTo that was found or created - */ - protected PDFGoTo getPDFGoToForID(String targetID, String pvKey) { - // Already a PDFGoTo present for this target? If not, create. - PDFGoTo gt = (PDFGoTo) idGoTos.get(targetID); - if (gt == null) { - String pdfPageRef = (String) pageReferences.get(pvKey); - Point2D.Float position = (Point2D.Float) idPositions.get(targetID); - // can the GoTo already be fully filled in? - if (pdfPageRef != null && position != null) { - // getPDFGoTo shares PDFGoTo objects as much as possible. - // It also takes care of assignObjectNumber and addTrailerObject. - gt = pdfDoc.getFactory().getPDFGoTo(pdfPageRef, position); - } else { - // Not complete yet, can't use getPDFGoTo: - gt = new PDFGoTo(pdfPageRef); - pdfDoc.assignObjectNumber(gt); - // pdfDoc.addTrailerObject() will be called later, from finishIDGoTo() - unfinishedGoTos.add(gt); - } - idGoTos.put(targetID, gt); - } - return gt; - } - - /** - * Saves id's absolute position on page for later retrieval by PDFGoTos - * - * @param id the id of the area whose position must be saved - * @param pdfPageRef the PDF page reference string - * @param relativeIPP the *relative* IP position in millipoints - * @param relativeBPP the *relative* BP position in millipoints - * @param tf the transformation to apply once the relative positions have been - * converted to points - */ - protected void saveAbsolutePosition(String id, String pdfPageRef, - int relativeIPP, int relativeBPP, AffineTransform tf) { - Point2D.Float position = new Point2D.Float(relativeIPP / 1000f, relativeBPP / 1000f); - tf.transform(position, position); - idPositions.put(id, position); - // is there already a PDFGoTo waiting to be completed? - PDFGoTo gt = (PDFGoTo) idGoTos.get(id); - if (gt != null) { - finishIDGoTo(gt, pdfPageRef, position); - } -/* - // The code below auto-creates a named destination for every id in the document. - // This should probably be controlled by a user-configurable setting, as it may - // make the PDF file grow noticeably. - // *** NOT YET WELL-TESTED ! *** - if (true) { - PDFFactory factory = pdfDoc.getFactory(); - if (gt == null) { - gt = factory.getPDFGoTo(pdfPageRef, position); - idGoTos.put(id, gt); // so others can pick it up too - } - factory.makeDestination(id, gt.referencePDF(), currentPageViewport); - // Note: using currentPageViewport is only correct if the id is indeed on - // the current PageViewport. But even if incorrect, it won't interfere with - // what gets created in the PDF. - // For speedup, we should also create a lookup map id -> PDFDestination - } -*/ - } - - /** - * Saves id's absolute position on page for later retrieval by PDFGoTos, - * using the currently valid transformation and the currently valid PDF page reference - * - * @param id the id of the area whose position must be saved - * @param relativeIPP the *relative* IP position in millipoints - * @param relativeBPP the *relative* BP position in millipoints - */ - protected void saveAbsolutePosition(String id, int relativeIPP, int relativeBPP) { - saveAbsolutePosition(id, currentPageRef, - relativeIPP, relativeBPP, getState().getTransform()); - } - - /** - * If the given block area is a possible link target, its id + absolute position will - * be saved. The saved position is only correct if this function is called at the very - * start of renderBlock! - * - * @param block the block area in question - */ - protected void saveBlockPosIfTargetable(Block block) { - String id = getTargetableID(block); - if (id != null) { - // FIXME: Like elsewhere in the renderer code, absolute and relative - // directions are happily mixed here. This makes sure that the - // links point to the right location, but it is not correct. - int ipp = block.getXOffset(); - int bpp = block.getYOffset() + block.getSpaceBefore(); - int positioning = block.getPositioning(); - if (!(positioning == Block.FIXED || positioning == Block.ABSOLUTE)) { - ipp += currentIPPosition; - bpp += currentBPPosition; - } - AffineTransform tf = positioning == Block.FIXED - ? getState().getBaseTransform() - : getState().getTransform(); - saveAbsolutePosition(id, currentPageRef, ipp, bpp, tf); - } - } - - /** - * If the given inline area is a possible link target, its id + absolute position will - * be saved. The saved position is only correct if this function is called at the very - * start of renderInlineArea! - * - * @param inlineArea the inline area in question - */ - protected void saveInlinePosIfTargetable(InlineArea inlineArea) { - String id = getTargetableID(inlineArea); - if (id != null) { - int extraMarginBefore = 5000; // millipoints - int ipp = currentIPPosition; - int bpp = currentBPPosition + inlineArea.getOffset() - extraMarginBefore; - saveAbsolutePosition(id, ipp, bpp); - } - } - - /** - * {@inheritDoc} - */ - protected void renderBlock(Block block) { - saveBlockPosIfTargetable(block); - super.renderBlock(block); - } - - /** {@inheritDoc} */ - protected void renderLineArea(LineArea line) { - super.renderLineArea(line); - } - - /** - * {@inheritDoc} - */ - protected void renderInlineArea(InlineArea inlineArea) { - saveInlinePosIfTargetable(inlineArea); - super.renderInlineArea(inlineArea); - } - - /** - * Render inline parent area. - * For pdf this handles the inline parent area traits such as - * links, border, background. - * @param ip the inline parent area - */ - public void renderInlineParent(InlineParent ip) { - - boolean annotsAllowed = pdfDoc.getProfile().isAnnotationAllowed(); - - // stuff we only need if a link must be created: - Rectangle2D ipRect = null; - PDFFactory factory = null; - PDFAction action = null; - if (annotsAllowed) { - // make sure the rect is determined *before* calling super! - int ipp = currentIPPosition; - int bpp = currentBPPosition + ip.getOffset(); - ipRect = new Rectangle2D.Float(ipp / 1000f, bpp / 1000f, - ip.getIPD() / 1000f, ip.getBPD() / 1000f); - AffineTransform transform = getState().getTransform(); - ipRect = transform.createTransformedShape(ipRect).getBounds2D(); - - factory = pdfDoc.getFactory(); - } - - // render contents - super.renderInlineParent(ip); - - boolean linkTraitFound = false; - - // try INTERNAL_LINK first - Trait.InternalLink intLink = (Trait.InternalLink) ip.getTrait(Trait.INTERNAL_LINK); - if (intLink != null) { - linkTraitFound = true; - String pvKey = intLink.getPVKey(); - String idRef = intLink.getIDRef(); - boolean pvKeyOK = pvKey != null && pvKey.length() > 0; - boolean idRefOK = idRef != null && idRef.length() > 0; - if (pvKeyOK && idRefOK) { - if (annotsAllowed) { - action = getPDFGoToForID(idRef, pvKey); - } - } else { - //Warnings already issued by AreaTreeHandler - } - } - - // no INTERNAL_LINK, look for EXTERNAL_LINK - if (!linkTraitFound) { - Trait.ExternalLink extLink = (Trait.ExternalLink) ip.getTrait(Trait.EXTERNAL_LINK); - if (extLink != null) { - String extDest = extLink.getDestination(); - if (extDest != null && extDest.length() > 0) { - linkTraitFound = true; - if (annotsAllowed) { - action = factory.getExternalAction(extDest, extLink.newWindow()); - } - } - } - } - - // warn if link trait found but not allowed, else create link - if (linkTraitFound) { - if (!annotsAllowed) { - log.warn("Skipping annotation for a link due to PDF profile: " - + pdfDoc.getProfile()); - } else if (action != null) { - PDFLink pdfLink = factory.makeLink(ipRect, action); - if (accessEnabled) { - String ptr = (String) ip.getTrait(Trait.PTR); - logicalStructureHandler.addLinkContentItem(pdfLink, ptr); - } - currentPage.addAnnotation(pdfLink); - } - } - } - - /** {@inheritDoc} */ - public void renderViewport(Viewport viewport) { - imageReference = (String) viewport.getTrait(Trait.PTR); - super.renderViewport(viewport); - imageReference = null; - } - - private Typeface getTypeface(String fontName) { - Typeface tf = (Typeface) fontInfo.getFonts().get(fontName); - if (tf instanceof LazyFont) { - tf = ((LazyFont)tf).getRealFont(); - } - return tf; - } - - /** {@inheritDoc} */ - public void renderText(TextArea text) { - renderInlineAreaBackAndBorders(text); - Color ct = (Color) text.getTrait(Trait.COLOR); - updateColor(ct, true); - - if (accessEnabled) { - String ptr = (String) text.getTrait(Trait.PTR); - MarkedContentInfo mci = logicalStructureHandler.addTextContentItem(ptr); - if (generator.getTextUtil().isInTextObject()) { - generator.separateTextElements(mci.tag, mci.mcid); - } - generator.beginTextObject(mci.tag, mci.mcid); - } else { - beginTextObject(); - } - - String fontName = getInternalFontNameForArea(text); - int size = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue(); - - // This assumes that *all* CIDFonts use a /ToUnicode mapping - Typeface tf = getTypeface(fontName); - - PDFTextUtil textutil = generator.getTextUtil(); - textutil.updateTf(fontName, size / 1000f, tf.isMultiByte()); - - - // word.getOffset() = only height of text itself - // currentBlockIPPosition: 0 for beginning of line; nonzero - // where previous line area failed to take up entire allocated space - int rx = currentIPPosition + text.getBorderAndPaddingWidthStart(); - int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset(); - - textutil.writeTextMatrix(new AffineTransform(1, 0, 0, -1, rx / 1000f, bl / 1000f)); - - super.renderText(text); - - textutil.writeTJ(); - - renderTextDecoration(tf, size, text, bl, rx); - } - - /** {@inheritDoc} */ - public void renderWord(WordArea word) { - Font font = getFontFromArea(word.getParentArea()); - String s = word.getWord(); - - escapeText(s, word.getLetterAdjustArray(), - font, (AbstractTextArea)word.getParentArea()); - - super.renderWord(word); - } - - /** {@inheritDoc} */ - public void renderSpace(SpaceArea space) { - Font font = getFontFromArea(space.getParentArea()); - String s = space.getSpace(); - - AbstractTextArea textArea = (AbstractTextArea)space.getParentArea(); - escapeText(s, null, font, textArea); - - if (space.isAdjustable()) { - int tws = -((TextArea) space.getParentArea()).getTextWordSpaceAdjust() - - 2 * textArea.getTextLetterSpaceAdjust(); - - if (tws != 0) { - float adjust = tws / (font.getFontSize() / 1000f); - generator.getTextUtil().adjustGlyphTJ(adjust); - } - } - - super.renderSpace(space); - } - - /** - * Escapes text according to PDF rules. - * @param s Text to escape - * @param letterAdjust an array of widths for letter adjustment (may be null) - * @param font to font in use - * @param parentArea the parent text area to retrieve certain traits from - */ - protected void escapeText(String s, - int[] letterAdjust, - Font font, AbstractTextArea parentArea) { - escapeText(s, 0, s.length(), letterAdjust, font, parentArea); - } - - /** - * Escapes text according to PDF rules. - * @param s Text to escape - * @param start the start position in the text - * @param end the end position in the text - * @param letterAdjust an array of widths for letter adjustment (may be null) - * @param font to font in use - * @param parentArea the parent text area to retrieve certain traits from - */ - protected void escapeText(String s, int start, int end, - int[] letterAdjust, - Font font, AbstractTextArea parentArea) { - String fontName = font.getFontName(); - float fontSize = font.getFontSize() / 1000f; - Typeface tf = getTypeface(fontName); - SingleByteFont singleByteFont = null; - if (tf instanceof SingleByteFont) { - singleByteFont = (SingleByteFont)tf; - } - PDFTextUtil textutil = generator.getTextUtil(); - - int l = s.length(); - - for (int i = start; i < end; i++) { - char orgChar = s.charAt(i); - char ch; - float glyphAdjust = 0; - if (font.hasChar(orgChar)) { - ch = font.mapChar(orgChar); - if (singleByteFont != null && singleByteFont.hasAdditionalEncodings()) { - int encoding = ch / 256; - if (encoding == 0) { - textutil.updateTf(fontName, fontSize, tf.isMultiByte()); - } else { - textutil.updateTf(fontName + "_" + Integer.toString(encoding), - fontSize, tf.isMultiByte()); - ch = (char)(ch % 256); - } - } - int tls = (i < l - 1 ? parentArea.getTextLetterSpaceAdjust() : 0); - glyphAdjust -= tls; - } else { - if (CharUtilities.isFixedWidthSpace(orgChar)) { - //Fixed width space are rendered as spaces so copy/paste works in a reader - ch = font.mapChar(CharUtilities.SPACE); - glyphAdjust = font.getCharWidth(ch) - font.getCharWidth(orgChar); - } else { - ch = font.mapChar(orgChar); - } - } - if (letterAdjust != null && i < l - 1) { - glyphAdjust -= letterAdjust[i + 1]; - } - - textutil.writeTJMappedChar(ch); - - float adjust = glyphAdjust / fontSize; - - if (adjust != 0) { - textutil.adjustGlyphTJ(adjust); - } - - } - } - - /** {@inheritDoc} */ - protected void updateColor(Color col, boolean fill) { - generator.updateColor(col, fill, null); - } - - /** {@inheritDoc} */ - public void renderImage(Image image, Rectangle2D pos) { - endTextObject(); - String url = image.getURL(); - putImage(url, pos, image.getForeignAttributes()); - } - - /** {@inheritDoc} */ - protected void drawImage(String url, Rectangle2D pos, Map foreignAttributes) { - endTextObject(); - putImage(url, pos, foreignAttributes); - } - - /** - * Adds a PDF XObject (a bitmap or form) to the PDF that will later be referenced. - * @param uri URL of the bitmap - * @param pos Position of the bitmap - * @deprecated Use {@link #putImage(String, Rectangle2D, Map)} instead. - */ - protected void putImage(String uri, Rectangle2D pos) { - putImage(uri, pos, null); - } - - /** - * Adds a PDF XObject (a bitmap or form) to the PDF that will later be referenced. - * @param uri URL of the bitmap - * @param pos Position of the bitmap - * @param foreignAttributes foreign attributes associated with the image - */ - protected void putImage(String uri, Rectangle2D pos, Map foreignAttributes) { - Rectangle posInt = new Rectangle( - (int)pos.getX(), - (int)pos.getY(), - (int)pos.getWidth(), - (int)pos.getHeight()); - - uri = URISpecification.getURL(uri); - PDFXObject xobject = pdfDoc.getXObject(uri); - if (xobject != null) { - float w = (float) pos.getWidth() / 1000f; - float h = (float) pos.getHeight() / 1000f; - placeImage((float)pos.getX() / 1000f, - (float)pos.getY() / 1000f, w, h, xobject); - return; - } - Point origin = new Point(currentIPPosition, currentBPPosition); - int x = origin.x + posInt.x; - int y = origin.y + posInt.y; - - ImageManager manager = getUserAgent().getFactory().getImageManager(); - ImageInfo info = null; - try { - ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); - info = manager.getImageInfo(uri, sessionContext); - - Map hints = ImageUtil.getDefaultHints(sessionContext); - ImageFlavor[] supportedFlavors = imageHandlerRegistry.getSupportedFlavors(); - org.apache.xmlgraphics.image.loader.Image img = manager.getImage( - info, supportedFlavors, hints, sessionContext); - - //First check for a dynamically registered handler - PDFImageHandler handler - = (PDFImageHandler)imageHandlerRegistry.getHandler(img.getClass()); - if (handler != null) { - if (log.isDebugEnabled()) { - log.debug("Using PDFImageHandler: " + handler.getClass().getName()); - } - try { - RendererContext context = createRendererContext( - x, y, posInt.width, posInt.height, foreignAttributes); - handler.generateImage(context, img, origin, posInt); - } catch (IOException ioe) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageWritingError(this, ioe); - return; - } - } else { - throw new UnsupportedOperationException( - "No PDFImageHandler available for image: " - + info + " (" + img.getClass().getName() + ")"); - } - } catch (ImageException ie) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); - } catch (FileNotFoundException fe) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); - } catch (IOException ioe) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); - } - - // output new data - try { - this.generator.flushPDFDoc(); - } catch (IOException ioe) { - // ioexception will be caught later - log.error(ioe.getMessage()); - } - } - - /** - * Places a previously registered image at a certain place on the page. - * @param x X coordinate - * @param y Y coordinate - * @param w width for image - * @param h height for image - * @param xobj the image XObject - */ - public void placeImage(float x, float y, float w, float h, PDFXObject xobj) { - if (accessEnabled) { - MarkedContentInfo mci = logicalStructureHandler.addImageContentItem(imageReference); - generator.saveGraphicsState(mci.tag, mci.mcid); - } else { - saveGraphicsState(); - } - generator.add(format(w) + " 0 0 " - + format(-h) + " " - + format(currentIPPosition / 1000f + x) + " " - + format(currentBPPosition / 1000f + h + y) - + " cm\n" + xobj.getName() + " Do\n"); - if (accessEnabled) { - generator.restoreGraphicsStateAccess(); - } else { - restoreGraphicsState(); - } - } - - /** {@inheritDoc} */ - protected RendererContext createRendererContext(int x, int y, int width, int height, - Map foreignAttributes) { - RendererContext context = super.createRendererContext( - x, y, width, height, foreignAttributes); - context.setProperty(PDFRendererContextConstants.PDF_DOCUMENT, pdfDoc); - context.setProperty(PDFRendererContextConstants.OUTPUT_STREAM, ostream); - context.setProperty(PDFRendererContextConstants.PDF_PAGE, currentPage); - context.setProperty(PDFRendererContextConstants.PDF_CONTEXT, currentContext); - context.setProperty(PDFRendererContextConstants.PDF_STREAM, generator.getStream()); - context.setProperty(PDFRendererContextConstants.PDF_FONT_INFO, fontInfo); - context.setProperty(PDFRendererContextConstants.PDF_FONT_NAME, ""); - context.setProperty(PDFRendererContextConstants.PDF_FONT_SIZE, new Integer(0)); - return context; - } - - /** {@inheritDoc} */ - public void renderDocument(Document doc, String ns, Rectangle2D pos, Map foreignAttributes) { - if (accessEnabled) { - MarkedContentInfo mci = logicalStructureHandler.addImageContentItem(imageReference); - generator.beginMarkedContentSequence(mci.tag, mci.mcid); - } - super.renderDocument(doc, ns, pos, foreignAttributes); - if (accessEnabled) { - generator.endMarkedContentSequence(); - } - } - - /** - * Render leader area. - * This renders a leader area which is an area with a rule. - * @param area the leader area to render - */ - public void renderLeader(Leader area) { - renderInlineAreaBackAndBorders(area); - - int style = area.getRuleStyle(); - int ruleThickness = area.getRuleThickness(); - int startx = currentIPPosition + area.getBorderAndPaddingWidthStart(); - int starty = currentBPPosition + area.getOffset() + (ruleThickness / 2); - int endx = currentIPPosition - + area.getBorderAndPaddingWidthStart() - + area.getIPD(); - Color col = (Color)area.getTrait(Trait.COLOR); - - endTextObject(); - borderPainter.drawLine(new Point(startx, starty), new Point(endx, starty), - ruleThickness, col, RuleStyle.valueOf(style)); - super.renderLeader(area); - } - - /** {@inheritDoc} */ - public String getMimeType() { - return MIME_TYPE; - } - - /** - * Sets the PDF/A mode for the PDF renderer. - * @param mode the PDF/A mode - */ - public void setAMode(PDFAMode mode) { - this.pdfUtil.setAMode(mode); - } - - /** - * Sets the PDF/X mode for the PDF renderer. - * @param mode the PDF/X mode - */ - public void setXMode(PDFXMode mode) { - this.pdfUtil.setXMode(mode); - } - - /** - * Sets the output color profile for the PDF renderer. - * @param outputProfileURI the URI to the output color profile - */ - public void setOutputProfileURI(String outputProfileURI) { - this.pdfUtil.setOutputProfileURI(outputProfileURI); - } - - /** - * Sets the filter map to be used by the PDF renderer. - * @param filterMap the filter map - */ - public void setFilterMap(Map filterMap) { - this.pdfUtil.setFilterMap(filterMap); - } - - /** - * Sets the encryption parameters used by the PDF renderer. - * @param encryptionParams the encryption parameters - */ - public void setEncryptionParams(PDFEncryptionParams encryptionParams) { - this.pdfUtil.setEncryptionParams(encryptionParams); - } - - MarkedContentInfo addCurrentImageToStructureTree() { - return logicalStructureHandler.addImageContentItem(imageReference); - } -} - diff --git a/src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java b/src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java index f3511298e..9ebb1d5a1 100644 --- a/src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java +++ b/src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java @@ -51,22 +51,12 @@ public class PDFRendererConfigurator extends PrintRendererConfigurator { } /** - * Configure the PDF renderer. - * Get the configuration to be used for pdf stream filters, - * fonts etc. + * Throws an UnsupportedOperationException. * - * @param renderer pdf renderer - * @throws FOPException fop exception + * @param renderer not used */ - public void configure(Renderer renderer) throws FOPException { - Configuration cfg = super.getRendererConfig(renderer); - if (cfg != null) { - PDFRenderer pdfRenderer = (PDFRenderer)renderer; - super.configure(renderer); - - PDFRenderingUtil pdfUtil = pdfRenderer.getPDFUtil(); - configure(cfg, pdfUtil); - } + public void configure(Renderer renderer) { + throw new UnsupportedOperationException(); } private void configure(Configuration cfg, PDFRenderingUtil pdfUtil) throws FOPException { @@ -80,20 +70,20 @@ public class PDFRendererConfigurator extends PrintRendererConfigurator { LogUtil.handleException(log, e, false); } - String s = cfg.getChild(PDFRenderer.PDF_A_MODE, true).getValue(null); + String s = cfg.getChild(PDFConfigurationConstants.PDF_A_MODE, true).getValue(null); if (s != null) { pdfUtil.setAMode(PDFAMode.valueOf(s)); } - s = cfg.getChild(PDFRenderer.PDF_X_MODE, true).getValue(null); + s = cfg.getChild(PDFConfigurationConstants.PDF_X_MODE, true).getValue(null); if (s != null) { pdfUtil.setXMode(PDFXMode.valueOf(s)); } Configuration encryptionParamsConfig - = cfg.getChild(PDFRenderer.ENCRYPTION_PARAMS, false); + = cfg.getChild(PDFConfigurationConstants.ENCRYPTION_PARAMS, false); if (encryptionParamsConfig != null) { PDFEncryptionParams encryptionParams = new PDFEncryptionParams(); Configuration ownerPasswordConfig = encryptionParamsConfig.getChild( - PDFRenderer.OWNER_PASSWORD, false); + PDFConfigurationConstants.OWNER_PASSWORD, false); if (ownerPasswordConfig != null) { String ownerPassword = ownerPasswordConfig.getValue(null); if (ownerPassword != null) { @@ -101,7 +91,7 @@ public class PDFRendererConfigurator extends PrintRendererConfigurator { } } Configuration userPasswordConfig = encryptionParamsConfig.getChild( - PDFRenderer.USER_PASSWORD, false); + PDFConfigurationConstants.USER_PASSWORD, false); if (userPasswordConfig != null) { String userPassword = userPasswordConfig.getValue(null); if (userPassword != null) { @@ -109,33 +99,33 @@ public class PDFRendererConfigurator extends PrintRendererConfigurator { } } Configuration noPrintConfig = encryptionParamsConfig.getChild( - PDFRenderer.NO_PRINT, false); + PDFConfigurationConstants.NO_PRINT, false); if (noPrintConfig != null) { encryptionParams.setAllowPrint(false); } Configuration noCopyContentConfig = encryptionParamsConfig.getChild( - PDFRenderer.NO_COPY_CONTENT, false); + PDFConfigurationConstants.NO_COPY_CONTENT, false); if (noCopyContentConfig != null) { encryptionParams.setAllowCopyContent(false); } Configuration noEditContentConfig = encryptionParamsConfig.getChild( - PDFRenderer.NO_EDIT_CONTENT, false); + PDFConfigurationConstants.NO_EDIT_CONTENT, false); if (noEditContentConfig != null) { encryptionParams.setAllowEditContent(false); } Configuration noAnnotationsConfig = encryptionParamsConfig.getChild( - PDFRenderer.NO_ANNOTATIONS, false); + PDFConfigurationConstants.NO_ANNOTATIONS, false); if (noAnnotationsConfig != null) { encryptionParams.setAllowEditAnnotations(false); } pdfUtil.setEncryptionParams(encryptionParams); } - s = cfg.getChild(PDFRenderer.KEY_OUTPUT_PROFILE, true).getValue(null); + s = cfg.getChild(PDFConfigurationConstants.KEY_OUTPUT_PROFILE, true).getValue(null); if (s != null) { pdfUtil.setOutputProfileURI(s); } Configuration disableColorSpaceConfig = cfg.getChild( - PDFRenderer.KEY_DISABLE_SRGB_COLORSPACE, false); + PDFConfigurationConstants.KEY_DISABLE_SRGB_COLORSPACE, false); if (disableColorSpaceConfig != null) { pdfUtil.setDisableSRGBColorSpace( disableColorSpaceConfig.getValueAsBoolean(false)); diff --git a/src/java/org/apache/fop/render/pdf/PDFRendererMaker.java b/src/java/org/apache/fop/render/pdf/PDFRendererMaker.java deleted file mode 100644 index fb65c9d74..000000000 --- a/src/java/org/apache/fop/render/pdf/PDFRendererMaker.java +++ /dev/null @@ -1,55 +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; - -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.render.AbstractRendererMaker; -import org.apache.fop.render.Renderer; -import org.apache.fop.render.RendererConfigurator; - -/** - * RendererMaker for the PDF Renderer. - */ -public class PDFRendererMaker extends AbstractRendererMaker { - - private static final String[] MIMES = new String[] {MimeConstants.MIME_PDF}; - - /** {@inheritDoc} */ - public Renderer makeRenderer(FOUserAgent userAgent) { - return new PDFRenderer(); - } - - /** {@inheritDoc} */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return new PDFRendererConfigurator(userAgent); - } - - /** {@inheritDoc} */ - public boolean needsOutputStream() { - return true; - } - - /** {@inheritDoc} */ - public String[] getSupportedMimeTypes() { - return MIMES; - } - -} diff --git a/src/java/org/apache/fop/render/pdf/PDFSVGHandler.java b/src/java/org/apache/fop/render/pdf/PDFSVGHandler.java index 6b14566eb..434daa5b0 100644 --- a/src/java/org/apache/fop/render/pdf/PDFSVGHandler.java +++ b/src/java/org/apache/fop/render/pdf/PDFSVGHandler.java @@ -19,26 +19,14 @@ package org.apache.fop.render.pdf; -import java.awt.Color; -import java.awt.geom.AffineTransform; -import java.io.IOException; import java.io.OutputStream; import java.util.Map; -import org.w3c.dom.Document; - import org.apache.avalon.framework.configuration.Configuration; -import org.apache.batik.bridge.BridgeContext; -import org.apache.batik.bridge.GVTBuilder; -import org.apache.batik.dom.svg.SVGDOMImplementation; -import org.apache.batik.gvt.GraphicsNode; -import org.apache.batik.util.SVGConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.fop.apps.FOUserAgent; import org.apache.fop.fonts.FontInfo; -import org.apache.fop.image.loader.batik.BatikUtil; import org.apache.fop.pdf.PDFDocument; import org.apache.fop.pdf.PDFPage; import org.apache.fop.pdf.PDFResourceContext; @@ -47,11 +35,6 @@ import org.apache.fop.render.ImageHandlerUtil; import org.apache.fop.render.Renderer; import org.apache.fop.render.RendererContext; import org.apache.fop.render.RendererContextConstants; -import org.apache.fop.svg.PDFAElementBridge; -import org.apache.fop.svg.PDFBridgeContext; -import org.apache.fop.svg.PDFGraphics2D; -import org.apache.fop.svg.SVGEventProducer; -import org.apache.fop.svg.SVGUserAgent; /** * PDF XML handler for SVG (uses Apache Batik). @@ -126,148 +109,8 @@ public class PDFSVGHandler extends AbstractGenericSVGHandler public boolean paintAsBitmap; // CSOK: VisibilityModifier } - /** - * {@inheritDoc} - */ - protected void renderSVGDocument(RendererContext context, - Document doc) { - PDFRenderer renderer = (PDFRenderer)context.getRenderer(); - PDFInfo pdfInfo = getPDFInfo(context); - if (pdfInfo.paintAsBitmap) { - try { - super.renderSVGDocument(context, doc); - } catch (IOException ioe) { - SVGEventProducer eventProducer = SVGEventProducer.Provider.get( - context.getUserAgent().getEventBroadcaster()); - eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); - } - return; - } - int xOffset = pdfInfo.currentXPosition; - int yOffset = pdfInfo.currentYPosition; - - FOUserAgent userAgent = context.getUserAgent(); - final float deviceResolution = userAgent.getTargetResolution(); - if (log.isDebugEnabled()) { - log.debug("Generating SVG at " + deviceResolution + "dpi."); - } - - final float uaResolution = userAgent.getSourceResolution(); - SVGUserAgent ua = new SVGUserAgent(userAgent, new AffineTransform()); - - //Scale for higher resolution on-the-fly images from Batik - double s = uaResolution / deviceResolution; - AffineTransform resolutionScaling = new AffineTransform(); - resolutionScaling.scale(s, s); - - //Controls whether text painted by Batik is generated using text or path operations - boolean strokeText = false; - Configuration cfg = pdfInfo.cfg; - if (cfg != null) { - strokeText = cfg.getChild("stroke-text", true).getValueAsBoolean(strokeText); - } - - BridgeContext ctx = new PDFBridgeContext(ua, - (strokeText ? null : pdfInfo.fi), - userAgent.getFactory().getImageManager(), - userAgent.getImageSessionContext(), - new AffineTransform()); - - //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) - //to it. - Document clonedDoc = BatikUtil.cloneSVGDocument(doc); - - 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, getDocumentURI(doc)); - 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; - - float sx = pdfInfo.width / w; - float sy = pdfInfo.height / h; - - //Scaling and translation for the bounding box of the image - AffineTransform scaling = new AffineTransform( - sx, 0, 0, sy, xOffset / 1000f, yOffset / 1000f); - - //Transformation matrix that establishes the local coordinate system for the SVG graphic - //in relation to the current coordinate system - AffineTransform imageTransform = new AffineTransform(); - imageTransform.concatenate(scaling); - imageTransform.concatenate(resolutionScaling); - - /* - * Clip to the svg area. - * Note: To have the svg overlay (under) a text area then use - * an fo:block-container - */ - PDFContentGenerator generator = renderer.getGenerator(); - generator.comment("SVG setup"); - generator.saveGraphicsState(); - generator.setColor(Color.black, false); - generator.setColor(Color.black, true); - - if (!scaling.isIdentity()) { - generator.comment("viewbox"); - generator.add(CTMHelper.toPDFString(scaling, false) + " cm\n"); - } - - //SVGSVGElement svg = ((SVGDocument)doc).getRootElement(); - - if (pdfInfo.pdfContext == null) { - pdfInfo.pdfContext = pdfInfo.pdfPage; - } - PDFGraphics2D graphics = new PDFGraphics2D(true, pdfInfo.fi, - pdfInfo.pdfDoc, - pdfInfo.pdfContext, pdfInfo.pdfPage.referencePDF(), - pdfInfo.currentFontName, pdfInfo.currentFontSize); - graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); - - if (!resolutionScaling.isIdentity()) { - generator.comment("resolution scaling for " + uaResolution - + " -> " + deviceResolution + "\n"); - generator.add( - CTMHelper.toPDFString(resolutionScaling, false) + " cm\n"); - graphics.scale(1 / s, 1 / s); - } - - generator.comment("SVG start"); - - //Save state and update coordinate system for the SVG image - generator.getState().save(); - generator.getState().concatenate(imageTransform); - - //Now that we have the complete transformation matrix for the image, we can update the - //transformation matrix for the AElementBridge. - PDFAElementBridge aBridge = (PDFAElementBridge)ctx.getBridge( - SVGDOMImplementation.SVG_NAMESPACE_URI, SVGConstants.SVG_A_TAG); - aBridge.getCurrentTransform().setTransform(generator.getState().getTransform()); - - graphics.setPaintingState(generator.getState()); - graphics.setOutputStream(pdfInfo.outputStream); - try { - root.paint(graphics); - generator.add(graphics.getString()); - } catch (Exception e) { - SVGEventProducer eventProducer = SVGEventProducer.Provider.get( - context.getUserAgent().getEventBroadcaster()); - eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); - } - generator.getState().restore(); - generator.restoreGraphicsState(); - generator.comment("SVG end"); - } - /** {@inheritDoc} */ public boolean supportsRenderer(Renderer renderer) { - return (renderer instanceof PDFRenderer); + return false; } } diff --git a/src/java/org/apache/fop/render/ps/PSGraphics2DAdapter.java b/src/java/org/apache/fop/render/ps/PSGraphics2DAdapter.java index 3858cc716..e13591ae3 100644 --- a/src/java/org/apache/fop/render/ps/PSGraphics2DAdapter.java +++ b/src/java/org/apache/fop/render/ps/PSGraphics2DAdapter.java @@ -30,12 +30,12 @@ import org.apache.xmlgraphics.java2d.Graphics2DImagePainter; import org.apache.xmlgraphics.java2d.ps.PSGraphics2D; import org.apache.xmlgraphics.ps.PSGenerator; +import org.apache.fop.pdf.PDFFactory; import org.apache.fop.render.AbstractGraphics2DAdapter; import org.apache.fop.render.ImageHandlerUtil; import org.apache.fop.render.RendererContext; import org.apache.fop.render.RendererContextConstants; import org.apache.fop.render.RendererContext.RendererContextWrapper; -import org.apache.fop.render.pdf.PDFRenderer; /** * Graphics2DAdapter implementation for PostScript. @@ -46,15 +46,7 @@ public class PSGraphics2DAdapter extends AbstractGraphics2DAdapter { private boolean clip = true; /** - * Main constructor - * @param renderer the Renderer instance to which this instance belongs - */ - public PSGraphics2DAdapter(PSRenderer renderer) { - this(renderer.gen, true); - } - - /** - * Constructor for use without a PSRenderer instance. + * Creates a new instance. * @param gen the PostScript generator * @param clip true if the image should be clipped */ @@ -114,7 +106,7 @@ public class PSGraphics2DAdapter extends AbstractGraphics2DAdapter { RendererContextWrapper ctx = RendererContext.wrapRendererContext(context); BufferedImage bi = paintToBufferedImage(painter, ctx, resolution, false, false); - float scale = PDFRenderer.NORMAL_PDF_RESOLUTION + float scale = PDFFactory.DEFAULT_PDF_RESOLUTION / context.getUserAgent().getTargetResolution(); graphics.drawImage(bi, new AffineTransform(scale, 0, 0, scale, 0, 0), null); } else { diff --git a/src/java/org/apache/fop/render/ps/PSRenderer.java b/src/java/org/apache/fop/render/ps/PSRenderer.java deleted file mode 100644 index 0703912ce..000000000 --- a/src/java/org/apache/fop/render/ps/PSRenderer.java +++ /dev/null @@ -1,1290 +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.ps; - -// Java -import java.awt.Color; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.RenderedImage; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.xml.transform.Source; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.apache.xmlgraphics.image.loader.ImageException; -import org.apache.xmlgraphics.image.loader.ImageFlavor; -import org.apache.xmlgraphics.image.loader.ImageInfo; -import org.apache.xmlgraphics.image.loader.ImageManager; -import org.apache.xmlgraphics.image.loader.ImageSessionContext; -import org.apache.xmlgraphics.image.loader.util.ImageUtil; -import org.apache.xmlgraphics.ps.DSCConstants; -import org.apache.xmlgraphics.ps.PSDictionary; -import org.apache.xmlgraphics.ps.PSDictionaryFormatException; -import org.apache.xmlgraphics.ps.PSGenerator; -import org.apache.xmlgraphics.ps.PSPageDeviceDictionary; -import org.apache.xmlgraphics.ps.PSProcSets; -import org.apache.xmlgraphics.ps.PSResource; -import org.apache.xmlgraphics.ps.PSState; -import org.apache.xmlgraphics.ps.dsc.DSCException; -import org.apache.xmlgraphics.ps.dsc.ResourceTracker; -import org.apache.xmlgraphics.ps.dsc.events.DSCCommentBoundingBox; -import org.apache.xmlgraphics.ps.dsc.events.DSCCommentHiResBoundingBox; - -import org.apache.fop.ResourceEventProducer; -import org.apache.fop.apps.FOPException; -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.area.Area; -import org.apache.fop.area.BlockViewport; -import org.apache.fop.area.CTM; -import org.apache.fop.area.OffDocumentExtensionAttachment; -import org.apache.fop.area.OffDocumentItem; -import org.apache.fop.area.PageViewport; -import org.apache.fop.area.RegionViewport; -import org.apache.fop.area.Trait; -import org.apache.fop.area.inline.AbstractTextArea; -import org.apache.fop.area.inline.Image; -import org.apache.fop.area.inline.InlineParent; -import org.apache.fop.area.inline.Leader; -import org.apache.fop.area.inline.SpaceArea; -import org.apache.fop.area.inline.TextArea; -import org.apache.fop.area.inline.WordArea; -import org.apache.fop.datatypes.URISpecification; -import org.apache.fop.fo.extensions.ExtensionAttachment; -import org.apache.fop.fonts.Font; -import org.apache.fop.fonts.LazyFont; -import org.apache.fop.fonts.SingleByteFont; -import org.apache.fop.fonts.Typeface; -import org.apache.fop.render.AbstractPathOrientedRenderer; -import org.apache.fop.render.Graphics2DAdapter; -import org.apache.fop.render.ImageAdapter; -import org.apache.fop.render.ImageHandler; -import org.apache.fop.render.ImageHandlerRegistry; -import org.apache.fop.render.RendererContext; -import org.apache.fop.render.RendererEventProducer; -import org.apache.fop.render.ps.extensions.PSCommentAfter; -import org.apache.fop.render.ps.extensions.PSCommentBefore; -import org.apache.fop.render.ps.extensions.PSExtensionAttachment; -import org.apache.fop.render.ps.extensions.PSSetPageDevice; -import org.apache.fop.render.ps.extensions.PSSetupCode; -import org.apache.fop.traits.RuleStyle; -import org.apache.fop.util.CharUtilities; - -/** - * Renderer that renders to PostScript. - *
- * This class currently generates PostScript Level 2 code. The only exception - * is the FlateEncode filter which is a Level 3 feature. The filters in use - * are hardcoded at the moment. - *
- * This class follows the Document Structuring Conventions (DSC) version 3.0. - * If anyone modifies this renderer please make - * sure to also follow the DSC to make it simpler to programmatically modify - * the generated Postscript files (ex. extract pages etc.). - *
- * This renderer inserts FOP-specific comments into the PostScript stream which - * may help certain users to do certain types of post-processing of the output. - * These comments all start with "%FOP". - * - * @author Apache FOP Development Team - * @version $Id$ - */ -public class PSRenderer extends AbstractPathOrientedRenderer - implements ImageAdapter, PSSupportedFlavors, PSConfigurationConstants { - - /** logging instance */ - private static Log log = LogFactory.getLog(PSRenderer.class); - - /** The MIME type for PostScript */ - public static final String MIME_TYPE = "application/postscript"; - - /** The application producing the PostScript */ - private int currentPageNumber = 0; - - /** the OutputStream the PS file is written to */ - private OutputStream outputStream; - /** the temporary file in case of two-pass processing */ - private File tempFile; - - /** The PostScript generator used to output the PostScript */ - protected PSGenerator gen; - private boolean ioTrouble = false; - - private boolean inTextMode = false; - - /** Used to temporarily store PSSetupCode instance until they can be written. */ - private List setupCodeList; - - /** This is a map of PSResource instances of all fonts defined (key: font key) */ - private Map fontResources; - /** This is a map of PSResource instances of all forms (key: uri) */ - private Map formResources; - - /** encapsulation of dictionary used in setpagedevice instruction **/ - private PSPageDeviceDictionary pageDeviceDictionary; - - /** - * Utility class which enables all sorts of features that are not directly connected to the - * normal rendering process. - */ - protected PSRenderingUtil psUtil; - private PSBorderPainter borderPainter; - - /** Is used to determine the document's bounding box */ - private Rectangle2D documentBoundingBox; - - /** This is a collection holding all document header comments */ - private Collection headerComments; - - /** This is a collection holding all document footer comments */ - private Collection footerComments; - - /** {@inheritDoc} */ - public void setUserAgent(FOUserAgent agent) { - super.setUserAgent(agent); - this.psUtil = new PSRenderingUtil(getUserAgent()); - } - - PSRenderingUtil getPSUtil() { - return this.psUtil; - } - - /** - * Sets the landscape mode for this renderer. - * @param value false will normally generate a "pseudo-portrait" page, true will rotate - * a "wider-than-long" page by 90 degrees. - */ - public void setAutoRotateLandscape(boolean value) { - getPSUtil().setAutoRotateLandscape(value); - } - - /** @return true if the renderer is configured to rotate landscape pages */ - public boolean isAutoRotateLandscape() { - return getPSUtil().isAutoRotateLandscape(); - } - - /** - * Sets the PostScript language level that the renderer should produce. - * @param level the language level (currently allowed: 2 or 3) - */ - public void setLanguageLevel(int level) { - getPSUtil().setLanguageLevel(level); - } - - /** - * Return the PostScript language level that the renderer produces. - * @return the language level - */ - public int getLanguageLevel() { - return getPSUtil().getLanguageLevel(); - } - - /** - * Sets the resource optimization mode. If set to true, the renderer does two passes to - * only embed the necessary resources in the PostScript file. This is slower, but produces - * smaller files. - * @param value true to enable the resource optimization - */ - public void setOptimizeResources(boolean value) { - getPSUtil().setOptimizeResources(value); - } - - /** @return true if the renderer does two passes to optimize PostScript resources */ - public boolean isOptimizeResources() { - return getPSUtil().isOptimizeResources(); - } - - /** {@inheritDoc} */ - public Graphics2DAdapter getGraphics2DAdapter() { - return new PSGraphics2DAdapter(this); - } - - /** {@inheritDoc} */ - public ImageAdapter getImageAdapter() { - return this; - } - - /** - * Write out a command - * @param cmd PostScript command - */ - protected void writeln(String cmd) { - try { - gen.writeln(cmd); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** - * Central exception handler for I/O exceptions. - * @param ioe IOException to handle - */ - protected void handleIOTrouble(IOException ioe) { - if (!ioTrouble) { - RendererEventProducer eventProducer = RendererEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.ioError(this, ioe); - ioTrouble = true; - } - } - - /** - * Write out a comment - * @param comment Comment to write - */ - protected void comment(String comment) { - try { - if (comment.startsWith("%")) { - gen.commentln(comment); - writeln(comment); - } else { - gen.commentln("%" + comment); - } - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** - * Make sure the cursor is in the right place. - */ - protected void movetoCurrPosition() { - moveTo(this.currentIPPosition, this.currentBPPosition); - } - - /** {@inheritDoc} */ - protected void clip() { - writeln("clip newpath"); - } - - /** {@inheritDoc} */ - protected void clipRect(float x, float y, float width, float height) { - try { - gen.defineRect(x, y, width, height); - clip(); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** {@inheritDoc} */ - protected void moveTo(float x, float y) { - writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " M"); - } - - /** - * Moves the current point by (x, y) relative to the current position, - * omitting any connecting line segment. - * @param x x coordinate - * @param y y coordinate - */ - protected void rmoveTo(float x, float y) { - writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " RM"); - } - - /** {@inheritDoc} */ - protected void lineTo(float x, float y) { - writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " lineto"); - } - - /** {@inheritDoc} */ - protected void closePath() { - writeln("cp"); - } - - /** {@inheritDoc} */ - protected void fillRect(float x, float y, float width, float height) { - if (width != 0 && height != 0) { - try { - gen.defineRect(x, y, width, height); - gen.writeln("fill"); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - } - - /** {@inheritDoc} */ - protected void updateColor(Color col, boolean fill) { - try { - useColor(col); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** {@inheritDoc} */ - protected void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) { - endTextObject(); - int x = currentIPPosition + (int)Math.round(pos.getX()); - int y = currentBPPosition + (int)Math.round(pos.getY()); - uri = URISpecification.getURL(uri); - if (log.isDebugEnabled()) { - log.debug("Handling image: " + uri); - } - int width = (int)pos.getWidth(); - int height = (int)pos.getHeight(); - Rectangle targetRect = new Rectangle(x, y, width, height); - - ImageManager manager = getUserAgent().getFactory().getImageManager(); - ImageInfo info = null; - try { - ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); - info = manager.getImageInfo(uri, sessionContext); - - PSRenderingContext renderingContext = new PSRenderingContext( - getUserAgent(), gen, getFontInfo()); - - if (!isOptimizeResources() - || PSImageUtils.isImageInlined(info, renderingContext)) { - if (log.isDebugEnabled()) { - log.debug("Image " + info + " is inlined"); - } - - //Determine supported flavors - ImageFlavor[] flavors; - ImageHandlerRegistry imageHandlerRegistry - = userAgent.getFactory().getImageHandlerRegistry(); - flavors = imageHandlerRegistry.getSupportedFlavors(renderingContext); - - //Only now fully load/prepare the image - Map hints = ImageUtil.getDefaultHints(sessionContext); - org.apache.xmlgraphics.image.loader.Image img = manager.getImage( - info, flavors, hints, sessionContext); - - //Get handler for image - ImageHandler basicHandler = imageHandlerRegistry.getHandler(renderingContext, img); - - //...and embed as inline image - basicHandler.handleImage(renderingContext, img, targetRect); - } else { - if (log.isDebugEnabled()) { - log.debug("Image " + info + " is embedded as a form later"); - } - //Don't load image at this time, just put a form placeholder in the stream - PSResource form = getFormForImage(info.getOriginalURI()); - PSImageUtils.drawForm(form, info, targetRect, gen); - } - - } catch (ImageException ie) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); - } catch (FileNotFoundException fe) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); - } catch (IOException ioe) { - ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); - } - } - - /** - * Returns a PSResource instance representing a image as a PostScript form. - * @param uri the image URI - * @return a PSResource instance - */ - protected PSResource getFormForImage(String uri) { - if (uri == null || "".equals(uri)) { - throw new IllegalArgumentException("uri must not be empty or null"); - } - if (this.formResources == null) { - this.formResources = new java.util.HashMap(); - } - PSResource form = (PSResource)this.formResources.get(uri); - if (form == null) { - form = new PSImageFormResource(this.formResources.size() + 1, uri); - this.formResources.put(uri, form); - } - return form; - } - - /** {@inheritDoc} */ - public void paintImage(RenderedImage image, RendererContext context, - int x, int y, int width, int height) throws IOException { - float fx = x / 1000f; - x += currentIPPosition / 1000f; - float fy = y / 1000f; - y += currentBPPosition / 1000f; - float fw = width / 1000f; - float fh = height / 1000f; - PSImageUtils.renderBitmapImage(image, fx, fy, fw, fh, gen); - } - - /** - * Draw a line. - * - * @param startx the start x position - * @param starty the start y position - * @param endx the x end position - * @param endy the y end position - */ - private void drawLine(float startx, float starty, float endx, float endy) { - writeln(gen.formatDouble(startx) + " " - + gen.formatDouble(starty) + " M " - + gen.formatDouble(endx) + " " - + gen.formatDouble(endy) + " lineto stroke newpath"); - } - - /** Saves the graphics state of the rendering engine. */ - public void saveGraphicsState() { - endTextObject(); - try { - //delegate - gen.saveGraphicsState(); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** Restores the last graphics state of the rendering engine. */ - public void restoreGraphicsState() { - try { - endTextObject(); - //delegate - gen.restoreGraphicsState(); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** - * Concats the transformation matrix. - * @param a A part - * @param b B part - * @param c C part - * @param d D part - * @param e E part - * @param f F part - */ - protected void concatMatrix(double a, double b, - double c, double d, - double e, double f) { - try { - gen.concatMatrix(a, b, c, d, e, f); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** - * Concats the transformations matrix. - * @param matrix Matrix to use - */ - protected void concatMatrix(double[] matrix) { - try { - gen.concatMatrix(matrix); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** {@inheritDoc} */ - protected void concatenateTransformationMatrix(AffineTransform at) { - try { - gen.concatMatrix(at); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - private String getPostScriptNameForFontKey(String key) { - int pos = key.indexOf('_'); - String postFix = null; - if (pos > 0) { - postFix = key.substring(pos); - key = key.substring(0, pos); - } - Map fonts = fontInfo.getFonts(); - Typeface tf = (Typeface)fonts.get(key); - if (tf instanceof LazyFont) { - tf = ((LazyFont)tf).getRealFont(); - } - if (tf == null) { - throw new IllegalStateException("Font not available: " + key); - } - if (postFix == null) { - return tf.getFontName(); - } else { - return tf.getFontName() + postFix; - } - } - - /** - * Returns the PSResource for the given font key. - * @param key the font key ("F*") - * @return the matching PSResource - */ - protected PSResource getPSResourceForFontKey(String key) { - PSResource res = null; - if (this.fontResources != null) { - res = (PSResource)this.fontResources.get(key); - } else { - this.fontResources = new java.util.HashMap(); - } - if (res == null) { - res = new PSResource(PSResource.TYPE_FONT, getPostScriptNameForFontKey(key)); - this.fontResources.put(key, res); - } - return res; - } - - /** - * Changes the currently used font. - * @param key key of the font ("F*") - * @param size font size - */ - protected void useFont(String key, int size) { - try { - PSResource res = getPSResourceForFontKey(key); - gen.useFont("/" + res.getName(), size / 1000f); - gen.getResourceTracker().notifyResourceUsageOnPage(res); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - private void useColor(Color col) throws IOException { - gen.useColor(col); - } - - /** {@inheritDoc} */ - protected void drawBackAndBorders(Area area, float startx, float starty, - float width, float height) { - if (area.hasTrait(Trait.BACKGROUND) - || area.hasTrait(Trait.BORDER_BEFORE) - || area.hasTrait(Trait.BORDER_AFTER) - || area.hasTrait(Trait.BORDER_START) - || area.hasTrait(Trait.BORDER_END)) { - comment("%FOPBeginBackgroundAndBorder: " - + startx + " " + starty + " " + width + " " + height); - super.drawBackAndBorders(area, startx, starty, width, height); - comment("%FOPEndBackgroundAndBorder"); - } - } - - /** {@inheritDoc} */ - protected void drawBorderLine // CSOK: ParameterNumber - (float x1, float y1, float x2, float y2, - boolean horz, boolean startOrBefore, int style, Color col) { - try { - PSBorderPainter.drawBorderLine(gen, x1, y1, x2, y2, horz, startOrBefore, style, col); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** {@inheritDoc} */ - public void startRenderer(OutputStream outputStream) - throws IOException { - log.debug("Rendering areas to PostScript..."); - - this.outputStream = outputStream; - OutputStream out; - if (isOptimizeResources()) { - this.tempFile = File.createTempFile("fop", null); - out = new java.io.FileOutputStream(this.tempFile); - out = new java.io.BufferedOutputStream(out); - } else { - out = this.outputStream; - } - - //Setup for PostScript generation - this.gen = new PSGenerator(out) { - /** Need to subclass PSGenerator to have better URI resolution */ - public Source resolveURI(String uri) { - return userAgent.resolveURI(uri); - } - }; - this.gen.setPSLevel(getLanguageLevel()); - this.borderPainter = new PSBorderPainter(this.gen); - this.currentPageNumber = 0; - - //Initial default page device dictionary settings - this.pageDeviceDictionary = new PSPageDeviceDictionary(); - pageDeviceDictionary.setFlushOnRetrieval(!getPSUtil().isDSCComplianceEnabled()); - pageDeviceDictionary.put("/ImagingBBox", "null"); - } - - private void writeHeader() throws IOException { - //PostScript Header - writeln(DSCConstants.PS_ADOBE_30); - gen.writeDSCComment(DSCConstants.CREATOR, new String[] {userAgent.getProducer()}); - gen.writeDSCComment(DSCConstants.CREATION_DATE, new Object[] {new java.util.Date()}); - gen.writeDSCComment(DSCConstants.LANGUAGE_LEVEL, new Integer(gen.getPSLevel())); - gen.writeDSCComment(DSCConstants.PAGES, new Object[] {DSCConstants.ATEND}); - gen.writeDSCComment(DSCConstants.BBOX, DSCConstants.ATEND); - gen.writeDSCComment(DSCConstants.HIRES_BBOX, DSCConstants.ATEND); - this.documentBoundingBox = new Rectangle2D.Double(); - gen.writeDSCComment(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES, - new Object[] {DSCConstants.ATEND}); - if (headerComments != null) { - for (Iterator iter = headerComments.iterator(); iter.hasNext();) { - PSExtensionAttachment comment = (PSExtensionAttachment)iter.next(); - gen.writeln("%" + comment.getContent()); - } - } - gen.writeDSCComment(DSCConstants.END_COMMENTS); - - //Defaults - gen.writeDSCComment(DSCConstants.BEGIN_DEFAULTS); - gen.writeDSCComment(DSCConstants.END_DEFAULTS); - - //Prolog and Setup written right before the first page-sequence, see startPageSequence() - //Do this only once, as soon as we have all the content for the Setup section! - //Prolog - gen.writeDSCComment(DSCConstants.BEGIN_PROLOG); - PSProcSets.writeStdProcSet(gen); - PSProcSets.writeEPSProcSet(gen); - gen.writeDSCComment(DSCConstants.END_PROLOG); - - //Setup - gen.writeDSCComment(DSCConstants.BEGIN_SETUP); - PSRenderingUtil.writeSetupCodeList(gen, setupCodeList, "SetupCode"); - if (!isOptimizeResources()) { - this.fontResources = PSFontUtils.writeFontDict(gen, fontInfo); - } else { - gen.commentln("%FOPFontSetup"); //Place-holder, will be replaced in the second pass - } - gen.writeDSCComment(DSCConstants.END_SETUP); - } - - /** {@inheritDoc} */ - public void stopRenderer() throws IOException { - //Write trailer - gen.writeDSCComment(DSCConstants.TRAILER); - if (footerComments != null) { - for (Iterator iter = footerComments.iterator(); iter.hasNext();) { - PSExtensionAttachment comment = (PSExtensionAttachment)iter.next(); - gen.commentln("%" + comment.getContent()); - } - footerComments.clear(); - } - gen.writeDSCComment(DSCConstants.PAGES, new Integer(this.currentPageNumber)); - new DSCCommentBoundingBox(this.documentBoundingBox).generate(gen); - new DSCCommentHiResBoundingBox(this.documentBoundingBox).generate(gen); - gen.getResourceTracker().writeResources(false, gen); - gen.writeDSCComment(DSCConstants.EOF); - gen.flush(); - log.debug("Rendering to PostScript complete."); - if (isOptimizeResources()) { - IOUtils.closeQuietly(gen.getOutputStream()); - rewritePostScriptFile(); - } - if (footerComments != null) { - headerComments.clear(); - } - if (pageDeviceDictionary != null) { - pageDeviceDictionary.clear(); - } - this.borderPainter = null; - this.gen = null; - } - - /** - * Used for two-pass production. This will rewrite the PostScript file from the temporary - * file while adding all needed resources. - * @throws IOException In case of an I/O error. - */ - private void rewritePostScriptFile() throws IOException { - log.debug("Processing PostScript resources..."); - long startTime = System.currentTimeMillis(); - ResourceTracker resTracker = gen.getResourceTracker(); - InputStream in = new java.io.FileInputStream(this.tempFile); - in = new java.io.BufferedInputStream(in); - try { - try { - ResourceHandler handler = new ResourceHandler(this.userAgent, this.fontInfo, - resTracker, this.formResources); - handler.process(in, this.outputStream, - this.currentPageNumber, this.documentBoundingBox); - this.outputStream.flush(); - } catch (DSCException e) { - throw new RuntimeException(e.getMessage()); - } - } finally { - IOUtils.closeQuietly(in); - if (!this.tempFile.delete()) { - this.tempFile.deleteOnExit(); - log.warn("Could not delete temporary file: " + this.tempFile); - } - } - if (log.isDebugEnabled()) { - long duration = System.currentTimeMillis() - startTime; - log.debug("Resource Processing complete in " + duration + " ms."); - } - } - - /** {@inheritDoc} */ - public void processOffDocumentItem(OffDocumentItem oDI) { - if (log.isDebugEnabled()) { - log.debug("Handling OffDocumentItem: " + oDI.getName()); - } - if (oDI instanceof OffDocumentExtensionAttachment) { - ExtensionAttachment attachment = ((OffDocumentExtensionAttachment)oDI).getAttachment(); - if (attachment != null) { - if (PSExtensionAttachment.CATEGORY.equals(attachment.getCategory())) { - if (attachment instanceof PSSetupCode) { - if (setupCodeList == null) { - setupCodeList = new java.util.ArrayList(); - } - if (!setupCodeList.contains(attachment)) { - setupCodeList.add(attachment); - } - } else if (attachment instanceof PSSetPageDevice) { - /** - * Extract all PSSetPageDevice instances from the - * attachment list on the s-p-m and add all dictionary - * entries to our internal representation of the the - * page device dictionary. - */ - PSSetPageDevice setPageDevice = (PSSetPageDevice)attachment; - String content = setPageDevice.getContent(); - if (content != null) { - try { - this.pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); - } catch (PSDictionaryFormatException e) { - PSEventProducer eventProducer = PSEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.postscriptDictionaryParseError(this, content, e); - } - } - } else if (attachment instanceof PSCommentBefore) { - if (headerComments == null) { - headerComments = new java.util.ArrayList(); - } - headerComments.add(attachment); - } else if (attachment instanceof PSCommentAfter) { - if (footerComments == null) { - footerComments = new java.util.ArrayList(); - } - footerComments.add(attachment); - } - } - } - } - super.processOffDocumentItem(oDI); - } - - /** {@inheritDoc} */ - public void renderPage(PageViewport page) - throws IOException, FOPException { - log.debug("renderPage(): " + page); - - if (this.currentPageNumber == 0) { - writeHeader(); - } - - this.currentPageNumber++; - - gen.getResourceTracker().notifyStartNewPage(); - gen.getResourceTracker().notifyResourceUsageOnPage(PSProcSets.STD_PROCSET); - gen.writeDSCComment(DSCConstants.PAGE, new Object[] - {page.getPageNumberString(), - new Integer(this.currentPageNumber)}); - - double pageWidth = page.getViewArea().width / 1000f; - double pageHeight = page.getViewArea().height / 1000f; - boolean rotate = false; - List pageSizes = new java.util.ArrayList(); - if (getPSUtil().isAutoRotateLandscape() && (pageHeight < pageWidth)) { - rotate = true; - pageSizes.add(new Long(Math.round(pageHeight))); - pageSizes.add(new Long(Math.round(pageWidth))); - } else { - pageSizes.add(new Long(Math.round(pageWidth))); - pageSizes.add(new Long(Math.round(pageHeight))); - } - pageDeviceDictionary.put("/PageSize", pageSizes); - - if (page.hasExtensionAttachments()) { - for (Iterator iter = page.getExtensionAttachments().iterator(); - iter.hasNext();) { - ExtensionAttachment attachment = (ExtensionAttachment) iter.next(); - if (attachment instanceof PSSetPageDevice) { - /** - * Extract all PSSetPageDevice instances from the - * attachment list on the s-p-m and add all - * dictionary entries to our internal representation - * of the the page device dictionary. - */ - PSSetPageDevice setPageDevice = (PSSetPageDevice)attachment; - String content = setPageDevice.getContent(); - if (content != null) { - try { - pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); - } catch (PSDictionaryFormatException e) { - PSEventProducer eventProducer = PSEventProducer.Provider.get( - getUserAgent().getEventBroadcaster()); - eventProducer.postscriptDictionaryParseError(this, content, e); - } - } - } - } - } - - try { - if (setupCodeList != null) { - PSRenderingUtil.writeEnclosedExtensionAttachments(gen, setupCodeList); - setupCodeList.clear(); - } - } catch (IOException e) { - log.error(e.getMessage()); - } - final Integer zero = new Integer(0); - Rectangle2D pageBoundingBox = new Rectangle2D.Double(); - if (rotate) { - pageBoundingBox.setRect(0, 0, pageHeight, pageWidth); - gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { - zero, zero, new Long(Math.round(pageHeight)), - new Long(Math.round(pageWidth)) }); - gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { - zero, zero, new Double(pageHeight), - new Double(pageWidth) }); - gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape"); - } else { - pageBoundingBox.setRect(0, 0, pageWidth, pageHeight); - gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { - zero, zero, new Long(Math.round(pageWidth)), - new Long(Math.round(pageHeight)) }); - gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { - zero, zero, new Double(pageWidth), - new Double(pageHeight) }); - if (getPSUtil().isAutoRotateLandscape()) { - gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, - "Portrait"); - } - } - this.documentBoundingBox.add(pageBoundingBox); - gen.writeDSCComment(DSCConstants.PAGE_RESOURCES, - new Object[] {DSCConstants.ATEND}); - - gen.commentln("%FOPSimplePageMaster: " + page.getSimplePageMasterName()); - - gen.writeDSCComment(DSCConstants.BEGIN_PAGE_SETUP); - - if (page.hasExtensionAttachments()) { - List extensionAttachments = page.getExtensionAttachments(); - for (int i = 0; i < extensionAttachments.size(); i++) { - Object attObj = extensionAttachments.get(i); - if (attObj instanceof PSExtensionAttachment) { - PSExtensionAttachment attachment = (PSExtensionAttachment)attObj; - if (attachment instanceof PSCommentBefore) { - gen.commentln("%" + attachment.getContent()); - } else if (attachment instanceof PSSetupCode) { - gen.writeln(attachment.getContent()); - } - } - } - } - - // Write any unwritten changes to page device dictionary - if (!pageDeviceDictionary.isEmpty()) { - String content = pageDeviceDictionary.getContent(); - if (getPSUtil().isSafeSetPageDevice()) { - content += " SSPD"; - } else { - content += " setpagedevice"; - } - PSRenderingUtil.writeEnclosedExtensionAttachment(gen, new PSSetPageDevice(content)); - } - - if (rotate) { - gen.writeln(Math.round(pageHeight) + " 0 translate"); - gen.writeln("90 rotate"); - } - concatMatrix(1, 0, 0, -1, 0, pageHeight); - - gen.writeDSCComment(DSCConstants.END_PAGE_SETUP); - - //Process page - super.renderPage(page); - - //Show page - gen.showPage(); - gen.writeDSCComment(DSCConstants.PAGE_TRAILER); - if (page.hasExtensionAttachments()) { - List extensionAttachments = page.getExtensionAttachments(); - for (int i = 0; i < extensionAttachments.size(); i++) { - Object attObj = extensionAttachments.get(i); - if (attObj instanceof PSExtensionAttachment) { - PSExtensionAttachment attachment = (PSExtensionAttachment)attObj; - if (attachment instanceof PSCommentAfter) { - gen.commentln("%" + attachment.getContent()); - } - } - } - } - gen.getResourceTracker().writeResources(true, gen); - } - - /** {@inheritDoc} */ - protected void renderRegionViewport(RegionViewport port) { - if (port != null) { - comment("%FOPBeginRegionViewport: " + port.getRegionReference().getRegionName()); - super.renderRegionViewport(port); - comment("%FOPEndRegionViewport"); - } - } - - /** Indicates the beginning of a text object. */ - protected void beginTextObject() { - if (!inTextMode) { - saveGraphicsState(); - writeln("BT"); - inTextMode = true; - } - } - - /** Indicates the end of a text object. */ - protected void endTextObject() { - if (inTextMode) { - inTextMode = false; //set before restoreGraphicsState() to avoid recursion - writeln("ET"); - restoreGraphicsState(); - } - } - - /** {@inheritDoc} */ - public void renderText(TextArea area) { - renderInlineAreaBackAndBorders(area); - String fontkey = getInternalFontNameForArea(area); - int fontsize = area.getTraitAsInteger(Trait.FONT_SIZE); - - // This assumes that *all* CIDFonts use a /ToUnicode mapping - Typeface tf = (Typeface) fontInfo.getFonts().get(fontkey); - - //Determine position - int rx = currentIPPosition + area.getBorderAndPaddingWidthStart(); - int bl = currentBPPosition + area.getOffset() + area.getBaselineOffset(); - - Color ct = (Color)area.getTrait(Trait.COLOR); - if (ct != null) { - try { - useColor(ct); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - beginTextObject(); - writeln("1 0 0 -1 " + gen.formatDouble(rx / 1000f) - + " " + gen.formatDouble(bl / 1000f) + " Tm"); - - super.renderText(area); //Updates IPD - - renderTextDecoration(tf, fontsize, area, bl, rx); - } - - /** {@inheritDoc} */ - protected void renderWord(WordArea word) { - renderText((TextArea)word.getParentArea(), word.getWord(), word.getLetterAdjustArray()); - super.renderWord(word); - } - - /** {@inheritDoc} */ - protected void renderSpace(SpaceArea space) { - AbstractTextArea textArea = (AbstractTextArea)space.getParentArea(); - String s = space.getSpace(); - char sp = s.charAt(0); - Font font = getFontFromArea(textArea); - - int tws = (space.isAdjustable() - ? ((TextArea) space.getParentArea()).getTextWordSpaceAdjust() - + 2 * textArea.getTextLetterSpaceAdjust() - : 0); - - rmoveTo((font.getCharWidth(sp) + tws) / 1000f, 0); - super.renderSpace(space); - } - - private Typeface getTypeface(String fontName) { - Typeface tf = (Typeface)fontInfo.getFonts().get(fontName); - if (tf instanceof LazyFont) { - tf = ((LazyFont)tf).getRealFont(); - } - return tf; - } - - private void renderText(AbstractTextArea area, String text, int[] letterAdjust) { - String fontkey = getInternalFontNameForArea(area); - int fontSize = area.getTraitAsInteger(Trait.FONT_SIZE); - Font font = getFontFromArea(area); - Typeface tf = getTypeface(font.getFontName()); - SingleByteFont singleByteFont = null; - if (tf instanceof SingleByteFont) { - singleByteFont = (SingleByteFont)tf; - } - - int textLen = text.length(); - if (singleByteFont != null && singleByteFont.hasAdditionalEncodings()) { - int start = 0; - int currentEncoding = -1; - for (int i = 0; i < textLen; i++) { - char c = text.charAt(i); - char mapped = tf.mapChar(c); - int encoding = mapped / 256; - if (currentEncoding != encoding) { - if (i > 0) { - writeText(area, text, start, i - start, letterAdjust, fontSize, tf); - } - if (encoding == 0) { - useFont(fontkey, fontSize); - } else { - useFont(fontkey + "_" + Integer.toString(encoding), fontSize); - } - currentEncoding = encoding; - start = i; - } - } - writeText(area, text, start, textLen - start, letterAdjust, fontSize, tf); - } else { - useFont(fontkey, fontSize); - writeText(area, text, 0, textLen, letterAdjust, fontSize, tf); - } - } - - private void writeText(AbstractTextArea area, String text, int start, int len, - int[] letterAdjust, int fontsize, Typeface tf) { - int end = start + len; - int initialSize = text.length(); - initialSize += initialSize / 2; - StringBuffer sb = new StringBuffer(initialSize); - if (letterAdjust == null - && area.getTextLetterSpaceAdjust() == 0 - && area.getTextWordSpaceAdjust() == 0) { - sb.append("("); - for (int i = start; i < end; i++) { - final char c = text.charAt(i); - final char mapped = (char)(tf.mapChar(c) % 256); - PSGenerator.escapeChar(mapped, sb); - } - sb.append(") t"); - } else { - sb.append("("); - int[] offsets = new int[len]; - for (int i = start; i < end; i++) { - final char c = text.charAt(i); - final char mapped = tf.mapChar(c); - char codepoint = (char)(mapped % 256); - int wordSpace; - - if (CharUtilities.isAdjustableSpace(mapped)) { - wordSpace = area.getTextWordSpaceAdjust(); - } else { - wordSpace = 0; - } - int cw = tf.getWidth(mapped, fontsize) / 1000; - int ladj = (letterAdjust != null && i < end - 1 ? letterAdjust[i + 1] : 0); - int tls = (i < end - 1 ? area.getTextLetterSpaceAdjust() : 0); - offsets[i - start] = cw + ladj + tls + wordSpace; - PSGenerator.escapeChar(codepoint, sb); - } - sb.append(")" + PSGenerator.LF + "["); - for (int i = 0; i < len; i++) { - if (i > 0) { - if (i % 8 == 0) { - sb.append(PSGenerator.LF); - } else { - sb.append(" "); - } - } - sb.append(gen.formatDouble(offsets[i] / 1000f)); - } - sb.append("]" + PSGenerator.LF + "xshow"); - } - writeln(sb.toString()); - } - - /** {@inheritDoc} */ - protected List breakOutOfStateStack() { - try { - List breakOutList = new java.util.ArrayList(); - PSState state; - while (true) { - if (breakOutList.size() == 0) { - endTextObject(); - comment("------ break out!"); - } - state = gen.getCurrentState(); - if (!gen.restoreGraphicsState()) { - break; - } - breakOutList.add(0, state); //Insert because of stack-popping - } - return breakOutList; - } catch (IOException ioe) { - handleIOTrouble(ioe); - return null; - } - } - - /** {@inheritDoc} */ - protected void restoreStateStackAfterBreakOut(List breakOutList) { - try { - comment("------ restoring context after break-out..."); - PSState state; - Iterator i = breakOutList.iterator(); - while (i.hasNext()) { - state = (PSState)i.next(); - saveGraphicsState(); - state.reestablish(gen); - } - comment("------ done."); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - } - - /** - * {@inheritDoc} - */ - protected void startVParea(CTM ctm, Rectangle2D clippingRect) { - saveGraphicsState(); - if (clippingRect != null) { - clipRect((float)clippingRect.getX() / 1000f, - (float)clippingRect.getY() / 1000f, - (float)clippingRect.getWidth() / 1000f, - (float)clippingRect.getHeight() / 1000f); - } - // multiply with current CTM - final double[] matrix = ctm.toArray(); - matrix[4] /= 1000f; - matrix[5] /= 1000f; - concatMatrix(matrix); - } - - /** - * {@inheritDoc} - */ - protected void endVParea() { - restoreGraphicsState(); - } - - /** {@inheritDoc} */ - protected void renderBlockViewport(BlockViewport bv, List children) { - comment("%FOPBeginBlockViewport: " + bv.toString()); - super.renderBlockViewport(bv, children); - comment("%FOPEndBlockViewport"); - } - - /** {@inheritDoc} */ - protected void renderInlineParent(InlineParent ip) { - super.renderInlineParent(ip); - } - - /** {@inheritDoc} */ - public void renderLeader(Leader area) { - renderInlineAreaBackAndBorders(area); - - int style = area.getRuleStyle(); - int ruleThickness = area.getRuleThickness(); - int startx = currentIPPosition + area.getBorderAndPaddingWidthStart(); - int starty = currentBPPosition + area.getOffset() + (ruleThickness / 2); - int endx = currentIPPosition - + area.getBorderAndPaddingWidthStart() - + area.getIPD(); - Color col = (Color)area.getTrait(Trait.COLOR); - - endTextObject(); - try { - borderPainter.drawLine(new Point(startx, starty), new Point(endx, starty), - ruleThickness, col, RuleStyle.valueOf(style)); - } catch (IOException ioe) { - handleIOTrouble(ioe); - } - - super.renderLeader(area); - } - - /** - * {@inheritDoc} - */ - public void renderImage(Image image, Rectangle2D pos) { - drawImage(image.getURL(), pos, image.getForeignAttributes()); - } - - /** - * {@inheritDoc} - */ - protected RendererContext createRendererContext(int x, int y, int width, int height, - Map foreignAttributes) { - RendererContext context = super.createRendererContext( - x, y, width, height, foreignAttributes); - context.setProperty(PSRendererContextConstants.PS_GENERATOR, this.gen); - context.setProperty(PSRendererContextConstants.PS_FONT_INFO, fontInfo); - return context; - } - - /** {@inheritDoc} */ - public String getMimeType() { - return MIME_TYPE; - } - - /** - * Sets whether or not the safe set page device macro should be used - * (as opposed to directly invoking setpagedevice) when setting the - * postscript page device. - * - * This option is a useful option when you want to guard against the possibility - * of invalid/unsupported postscript key/values being placed in the page device. - * - * @param safeSetPageDevice setting to false and the renderer will make a - * standard "setpagedevice" call, setting to true will make a safe set page - * device macro call (default is false). - */ - public void setSafeSetPageDevice(boolean safeSetPageDevice) { - getPSUtil().setSafeSetPageDevice(safeSetPageDevice); - } - - /** - * Sets whether or not PostScript Document Structuring Conventions (dsc) compliance are - * enforced. - *

- * It can cause problems (unwanted PostScript subsystem initgraphics/erasepage calls) - * on some printers when the pagedevice is set. If this causes problems on a - * particular implementation then use this setting with a 'false' value to try and - * minimize the number of setpagedevice calls in the postscript document output. - *

- * Set this value to false if you experience unwanted blank pages in your - * postscript output. - * @param dscCompliant boolean value (default is true) - */ - public void setDSCCompliant(boolean dscCompliant) { - getPSUtil().setDSCComplianceEnabled(dscCompliant); - } - -} diff --git a/src/java/org/apache/fop/render/ps/PSRendererConfigurator.java b/src/java/org/apache/fop/render/ps/PSRendererConfigurator.java index 0f880a928..2280bf0dc 100644 --- a/src/java/org/apache/fop/render/ps/PSRendererConfigurator.java +++ b/src/java/org/apache/fop/render/ps/PSRendererConfigurator.java @@ -45,18 +45,12 @@ public class PSRendererConfigurator extends PrintRendererConfigurator } /** - * Configure the PS renderer. - * @param renderer postscript renderer - * @throws FOPException fop exception + * Throws an UnsupportedOperationException. + * + * @param renderer not used */ - public void configure(Renderer renderer) throws FOPException { - Configuration cfg = super.getRendererConfig(renderer); - if (cfg != null) { - super.configure(renderer); - - PSRenderer psRenderer = (PSRenderer)renderer; - configure(psRenderer.getPSUtil(), cfg); - } + public void configure(Renderer renderer) { + throw new UnsupportedOperationException(); } private void configure(PSRenderingUtil psUtil, Configuration cfg) { diff --git a/src/java/org/apache/fop/render/ps/PSRendererMaker.java b/src/java/org/apache/fop/render/ps/PSRendererMaker.java deleted file mode 100644 index 8c64f2806..000000000 --- a/src/java/org/apache/fop/render/ps/PSRendererMaker.java +++ /dev/null @@ -1,54 +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.ps; - -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.MimeConstants; -import org.apache.fop.render.AbstractRendererMaker; -import org.apache.fop.render.Renderer; -import org.apache.fop.render.RendererConfigurator; - -/** - * RendererMaker for the PostScript Renderer. - */ -public class PSRendererMaker extends AbstractRendererMaker { - - private static final String[] MIMES = new String[] {MimeConstants.MIME_POSTSCRIPT}; - - /** {@inheritDoc} */ - public Renderer makeRenderer(FOUserAgent userAgent) { - return new PSRenderer(); - } - - /** {@inheritDoc} */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return new PSRendererConfigurator(userAgent); - } - - /** {@inheritDoc} */ - public boolean needsOutputStream() { - return true; - } - - /** {@inheritDoc} */ - public String[] getSupportedMimeTypes() { - return MIMES; - } -} diff --git a/src/java/org/apache/fop/render/ps/PSSVGHandler.java b/src/java/org/apache/fop/render/ps/PSSVGHandler.java index 66b26fb33..14e2beddd 100644 --- a/src/java/org/apache/fop/render/ps/PSSVGHandler.java +++ b/src/java/org/apache/fop/render/ps/PSSVGHandler.java @@ -333,7 +333,7 @@ public class PSSVGHandler extends AbstractGenericSVGHandler /** {@inheritDoc} */ public boolean supportsRenderer(Renderer renderer) { - return (renderer instanceof PSRenderer); + return false; } } diff --git a/status.xml b/status.xml index ae322a0d2..1f0916753 100644 --- a/status.xml +++ b/status.xml @@ -58,6 +58,10 @@ documents. Example: the fix of marks layering will be such a case when it's done. --> + + Removed old Renderer implementations for those output formats that have a version based on + the new DocumentHandler architecture available (AFP, PCL, PDF, PS). + Reinstated support for being able to specify a font cache filepath in the fop user configuration. diff --git a/test/java/org/apache/fop/StandardTestSuite.java b/test/java/org/apache/fop/StandardTestSuite.java index 281301789..caf75b4b4 100644 --- a/test/java/org/apache/fop/StandardTestSuite.java +++ b/test/java/org/apache/fop/StandardTestSuite.java @@ -23,7 +23,6 @@ import junit.framework.Test; import junit.framework.TestSuite; import org.apache.fop.fonts.DejaVuLGCSerifTest; -import org.apache.fop.fonts.TrueTypeAnsiTestCase; import org.apache.fop.image.loader.batik.ImageLoaderTestCase; import org.apache.fop.image.loader.batik.ImagePreloaderTestCase; import org.apache.fop.intermediate.IFMimickingTestCase; @@ -54,7 +53,6 @@ public class StandardTestSuite { suite.addTest(new TestSuite(PDFEncodingTestCase.class)); suite.addTest(new TestSuite(PDFCMapTestCase.class)); suite.addTest(new TestSuite(PDFsRGBSettingsTestCase.class)); - suite.addTest(new TestSuite(TrueTypeAnsiTestCase.class)); suite.addTest(new TestSuite(DejaVuLGCSerifTest.class)); suite.addTest(RichTextFormatTestSuite.suite()); suite.addTest(new TestSuite(ImageLoaderTestCase.class)); diff --git a/test/java/org/apache/fop/fonts/TrueTypeAnsiTestCase.java b/test/java/org/apache/fop/fonts/TrueTypeAnsiTestCase.java deleted file mode 100644 index 3f98c93f4..000000000 --- a/test/java/org/apache/fop/fonts/TrueTypeAnsiTestCase.java +++ /dev/null @@ -1,107 +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.fonts; - -import java.io.File; -import java.io.OutputStream; -import java.io.StringReader; -import java.net.URL; -import java.util.List; - -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.sax.SAXResult; -import javax.xml.transform.stream.StreamSource; - -import junit.framework.TestCase; - -import org.apache.commons.io.output.NullOutputStream; - -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.Fop; -import org.apache.fop.apps.FopFactory; -import org.apache.fop.fonts.apps.TTFReader; -import org.apache.fop.render.pdf.PDFRenderer; - -/** - * Tests XML font metrics file generation and usage for WinAnsi mode. - */ -public class TrueTypeAnsiTestCase extends TestCase { - - /** - * Tests a TrueType font in WinAnsi mode. - * @throws Exception if an error occurs - */ - public void testTrueTypeAnsi() throws Exception { - String fontFamily = "Gladiator Bold"; - File ttfFile = new File("./test/resources/fonts/glb12.ttf"); - File workDir = new File("./build/test-results"); - if (!workDir.isDirectory()) { - assertTrue(workDir.mkdirs()); - } - File metricsFile = new File(workDir, ttfFile.getName() + ".xml"); - if (metricsFile.isFile()) { - assertTrue(metricsFile.delete()); - } - - String[] args = new String[] {"-enc", "ansi", - ttfFile.getCanonicalPath(), metricsFile.getCanonicalPath()}; - TTFReader.main(args); - assertTrue(metricsFile.isFile()); - - FopFactory fopFactory = FopFactory.newInstance(); - FOUserAgent ua = fopFactory.newFOUserAgent(); - PDFRenderer renderer = new PDFRenderer(); - renderer.setUserAgent(ua); - List fontList = new java.util.ArrayList(); - List triplets = new java.util.ArrayList(); - triplets.add(new FontTriplet(fontFamily, "normal", Font.WEIGHT_NORMAL)); - EmbedFontInfo font = new EmbedFontInfo( - metricsFile.toURI().toASCIIString(), - true, triplets, - ttfFile.toURI().toASCIIString(), null); - fontList.add(font); - renderer.addFontList(fontList); - - ua.setRendererOverride(renderer); - OutputStream out = new NullOutputStream(); - - Fop fop = fopFactory.newFop(null, ua, out); - - TransformerFactory tFactory = TransformerFactory.newInstance(); - Source src = new StreamSource(new StringReader( - "Test!")); - Result res = new SAXResult(fop.getDefaultHandler()); - Transformer transformer = tFactory.newTransformer( - getSourceForResource(this, "fonttest.xsl")); - transformer.transform(src, res); - } - - private static Source getSourceForResource(Object reference, String name) { - URL url = reference.getClass().getResource(name); - if (url == null) { - throw new NullPointerException("Resource not found: " + name); - } - return new StreamSource(url.toExternalForm()); - } - -} diff --git a/test/java/org/apache/fop/fonts/fonttest.xsl b/test/java/org/apache/fop/fonts/fonttest.xsl deleted file mode 100644 index 26c7d72a5..000000000 --- a/test/java/org/apache/fop/fonts/fonttest.xsl +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/java/org/apache/fop/render/RendererFactoryTest.java b/test/java/org/apache/fop/render/RendererFactoryTest.java index 4a40ac7c1..6b8e8f5f3 100644 --- a/test/java/org/apache/fop/render/RendererFactoryTest.java +++ b/test/java/org/apache/fop/render/RendererFactoryTest.java @@ -33,7 +33,6 @@ import org.apache.fop.render.intermediate.IFContext; import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFRenderer; import org.apache.fop.render.pdf.PDFDocumentHandler; -import org.apache.fop.render.pdf.PDFRenderer; import org.apache.fop.render.rtf.RTFHandler; /** @@ -73,29 +72,15 @@ public class RendererFactoryTest extends TestCase { RendererFactory factory = fopFactory.getRendererFactory(); FOUserAgent ua; Renderer renderer; - Renderer overrideRenderer; ua = fopFactory.newFOUserAgent(); renderer = factory.createRenderer(ua, MimeConstants.MIME_PDF); assertTrue(renderer instanceof IFRenderer); - factory.setRendererPreferred(true); //Test legacy setting - ua = fopFactory.newFOUserAgent(); - renderer = factory.createRenderer(ua, MimeConstants.MIME_PDF); - assertTrue(renderer instanceof PDFRenderer); - ua = fopFactory.newFOUserAgent(); renderer = factory.createRenderer(ua, MimeConstants.MIME_FOP_IF); assertTrue(renderer instanceof IFRenderer); - factory.setRendererPreferred(false); - ua = fopFactory.newFOUserAgent(); - overrideRenderer = new PDFRenderer(); - overrideRenderer.setUserAgent(ua); - ua.setRendererOverride(overrideRenderer); - renderer = factory.createRenderer(ua, null); - assertTrue(renderer == overrideRenderer); - ua = fopFactory.newFOUserAgent(); IFDocumentHandler overrideHandler; overrideHandler = new PDFDocumentHandler(); diff --git a/test/java/org/apache/fop/render/ps/ImageHandlingTestCase.java b/test/java/org/apache/fop/render/ps/ImageHandlingTestCase.java index 7f0462a75..72c677a0c 100644 --- a/test/java/org/apache/fop/render/ps/ImageHandlingTestCase.java +++ b/test/java/org/apache/fop/render/ps/ImageHandlingTestCase.java @@ -43,52 +43,22 @@ import org.apache.fop.render.intermediate.IFContext; public class ImageHandlingTestCase extends AbstractPostScriptTestCase { /** - * Tests JPEG handling with the {@link PSRenderer}. + * Tests JPEG handling. * @throws Exception if an error occurs */ - public void testJPEGImageWithRendererLevel3() throws Exception { - innerTestJPEGImageWithRenderer(3); + public void testJPEGImageLevel3() throws Exception { + innerTestJPEGImage(3); } /** - * Tests JPEG handling with the {@link PSRenderer}. + * Tests JPEG handling. * @throws Exception if an error occurs */ - public void testJPEGImageWithRendererLevel2() throws Exception { - innerTestJPEGImageWithRenderer(2); + public void testJPEGImageLevel2() throws Exception { + innerTestJPEGImage(2); } - /** - * Tests JPEG handling with the {@link PSDocumentHandler}. - * @throws Exception if an error occurs - */ - public void testJPEGImageWithIFLevel3() throws Exception { - innerTestJPEGImageWithIF(3); - } - - /** - * Tests JPEG handling with the {@link PSDocumentHandler}. - * @throws Exception if an error occurs - */ - public void testJPEGImageWithIFLevel2() throws Exception { - innerTestJPEGImageWithIF(2); - } - - private void innerTestJPEGImageWithRenderer(int level) throws Exception { - FOUserAgent ua = fopFactory.newFOUserAgent(); - PSRenderer renderer = new PSRenderer(); - renderer.setUserAgent(ua); - PSRenderingUtil psUtil = renderer.getPSUtil(); - psUtil.setLanguageLevel(level); - psUtil.setOptimizeResources(true); - ua.setRendererOverride(renderer); - - // Prepare output file - File outputFile = renderFile(ua, "ps-jpeg-image.fo", "-rend-l" + psUtil.getLanguageLevel()); - verifyPostScriptFile(outputFile, psUtil.getLanguageLevel()); - } - - private void innerTestJPEGImageWithIF(int level) throws Exception { + private void innerTestJPEGImage(int level) throws Exception { FOUserAgent ua = fopFactory.newFOUserAgent(); PSDocumentHandler handler = new PSDocumentHandler(); handler.setContext(new IFContext(ua)); @@ -159,10 +129,6 @@ public class ImageHandlingTestCase extends AbstractPostScriptTestCase { } } - private void assertMatches(String text, String regex) { - assertTrue("Text didn't match '" + regex + "'", text.matches(regex)); - } - private void assertContains(String text, String searchString) { assertTrue("Text doesn't contain '" + searchString + "'", text.indexOf(searchString) >= 0); } diff --git a/test/java/org/apache/fop/render/ps/ResourceOptimizationTestCase.java b/test/java/org/apache/fop/render/ps/ResourceOptimizationTestCase.java index e5b9a4d27..862ad5205 100644 --- a/test/java/org/apache/fop/render/ps/ResourceOptimizationTestCase.java +++ b/test/java/org/apache/fop/render/ps/ResourceOptimizationTestCase.java @@ -54,28 +54,10 @@ import org.apache.fop.render.intermediate.IFContext; public class ResourceOptimizationTestCase extends AbstractPostScriptTestCase { /** - * Tests resource optimization with the {@link PSRenderer}. + * Tests resource optimization. * @throws Exception if an error occurs */ - public void testResourceOptimizationWithRenderer() throws Exception { - FOUserAgent ua = fopFactory.newFOUserAgent(); - PSRenderer renderer = new PSRenderer(); - renderer.setUserAgent(ua); - // This is the important part: we're enabling resource optimization - renderer.getPSUtil().setOptimizeResources(true); - ua.setRendererOverride(renderer); - - // Prepare output file - File outputFile = renderFile(ua, "ps-resources.fo", - "-rend-l" + renderer.getPSUtil().getLanguageLevel()); - verifyPostScriptFile(outputFile); - } - - /** - * Tests resource optimization with the {@link PSDocumentHandler}. - * @throws Exception if an error occurs - */ - public void testResourceOptimizationWithIF() throws Exception { + public void testResourceOptimization() throws Exception { FOUserAgent ua = fopFactory.newFOUserAgent(); PSDocumentHandler handler = new PSDocumentHandler(); handler.setContext(new IFContext(ua)); -- cgit v1.2.3 From 6faeb0d39411199ab9db8cd94cd235aa63f8249a Mon Sep 17 00:00:00 2001 From: Vincent Hennebert Date: Thu, 2 Sep 2010 17:34:43 +0000 Subject: Implemented reset method for changing IPD git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@992029 13f79535-47bb-0310-9956-ffa450edef68 --- .../fop/layoutmgr/table/TableLayoutManager.java | 7 +++++++ .../flow_changing-ipd_table-after-break.xml | 23 ++++++++++++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) (limited to 'test') diff --git a/src/java/org/apache/fop/layoutmgr/table/TableLayoutManager.java b/src/java/org/apache/fop/layoutmgr/table/TableLayoutManager.java index 2b432d0d4..7e343697a 100644 --- a/src/java/org/apache/fop/layoutmgr/table/TableLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/table/TableLayoutManager.java @@ -552,4 +552,11 @@ public class TableLayoutManager extends BlockStackingLayoutManager } } + /** {@inheritDoc} */ + public void reset() { + super.reset(); + curBlockArea = null; + tableUnit = 0.0; + } + } diff --git a/test/layoutengine/standard-testcases/flow_changing-ipd_table-after-break.xml b/test/layoutengine/standard-testcases/flow_changing-ipd_table-after-break.xml index 956563e20..1b10d722c 100644 --- a/test/layoutengine/standard-testcases/flow_changing-ipd_table-after-break.xml +++ b/test/layoutengine/standard-testcases/flow_changing-ipd_table-after-break.xml @@ -56,13 +56,19 @@ - - After the table 1 + + Cell 1.1 + + + Cell 1.2 - - After the table 2 + + Cell 2.1 + + + Cell 2.2 @@ -74,7 +80,12 @@ - - + + + + + + + -- cgit v1.2.3 From 144138a6473966a619277390719122ad35b7f097 Mon Sep 17 00:00:00 2001 From: Jeremias Maerki Date: Tue, 7 Sep 2010 13:45:39 +0000 Subject: Bugzilla #49885: Fixed retrieval of available BPD for cases spanning columns and multiple pages with differing page masters. git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@993357 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/fop/area/PageViewport.java | 17 ++++- src/java/org/apache/fop/layoutmgr/Page.java | 6 +- src/java/org/apache/fop/layoutmgr/PageBreaker.java | 14 ++-- .../org/apache/fop/layoutmgr/PageProvider.java | 20 ++++-- status.xml | 3 + .../region-body_column-count_span_4.xml | 84 ++++++++++++++++++++++ 6 files changed, 129 insertions(+), 15 deletions(-) create mode 100644 test/layoutengine/standard-testcases/region-body_column-count_span_4.xml (limited to 'test') diff --git a/src/java/org/apache/fop/area/PageViewport.java b/src/java/org/apache/fop/area/PageViewport.java index 63740386e..bccae8754 100644 --- a/src/java/org/apache/fop/area/PageViewport.java +++ b/src/java/org/apache/fop/area/PageViewport.java @@ -95,8 +95,10 @@ public class PageViewport extends AreaTreeObject implements Resolvable, Cloneabl * @param pageNumber the page number * @param pageStr String representation of the page number * @param blank true if this is a blank page + * @param spanAll true if the first span area spans all columns */ - public PageViewport(SimplePageMaster spm, int pageNumber, String pageStr, boolean blank) { + public PageViewport(SimplePageMaster spm, int pageNumber, String pageStr, + boolean blank, boolean spanAll) { this.simplePageMasterName = spm.getMasterName(); setExtensionAttachments(spm.getExtensionAttachments()); setForeignAttributes(spm.getForeignAttributes()); @@ -107,7 +109,18 @@ public class PageViewport extends AreaTreeObject implements Resolvable, Cloneabl this.pageNumberString = pageStr; this.viewArea = new Rectangle(0, 0, pageWidth, pageHeight); this.page = new Page(spm); - createSpan(false); + createSpan(spanAll); + } + + /** + * Create a page viewport. + * @param spm SimplePageMaster indicating the page and region dimensions + * @param pageNumber the page number + * @param pageStr String representation of the page number + * @param blank true if this is a blank page + */ + public PageViewport(SimplePageMaster spm, int pageNumber, String pageStr, boolean blank) { + this(spm, pageNumber, pageStr, blank, false); } /** diff --git a/src/java/org/apache/fop/layoutmgr/Page.java b/src/java/org/apache/fop/layoutmgr/Page.java index b183efa01..d8ec66e82 100644 --- a/src/java/org/apache/fop/layoutmgr/Page.java +++ b/src/java/org/apache/fop/layoutmgr/Page.java @@ -41,10 +41,12 @@ public class Page { * @param pageNumber the page number (as an int) * @param pageNumberStr the page number (as a String) * @param blank true if this is a blank page + * @param spanAll true if the first span area spans all columns */ - public Page(SimplePageMaster spm, int pageNumber, String pageNumberStr, boolean blank) { + public Page(SimplePageMaster spm, int pageNumber, String pageNumberStr, + boolean blank, boolean spanAll) { this.spm = spm; - this.pageViewport = new PageViewport(spm, pageNumber, pageNumberStr, blank); + this.pageViewport = new PageViewport(spm, pageNumber, pageNumberStr, blank, spanAll); } /** diff --git a/src/java/org/apache/fop/layoutmgr/PageBreaker.java b/src/java/org/apache/fop/layoutmgr/PageBreaker.java index b65433bd7..3a41eb191 100644 --- a/src/java/org/apache/fop/layoutmgr/PageBreaker.java +++ b/src/java/org/apache/fop/layoutmgr/PageBreaker.java @@ -45,6 +45,7 @@ public class PageBreaker extends AbstractBreaker { private boolean needColumnBalancing; private PageProvider pageProvider; private Block separatorArea; + private boolean spanAllActive; /** * The FlowLayoutManager object, which processes @@ -148,8 +149,9 @@ public class PageBreaker extends AbstractBreaker { } firstPart = false; pageBreakHandled = true; + pageProvider.setStartOfNextElementList(pslm.getCurrentPageNum(), - pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex()); + pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex(), this.spanAllActive); return super.getNextBlockList(childLC, nextSequenceStartsOn, positionAtIPDChange, restartLM, firstElements); } @@ -342,8 +344,9 @@ public class PageBreaker extends AbstractBreaker { pageBreakHandled = true; //Update so the available BPD is reported correctly int currentPageNum = pslm.getCurrentPageNum(); + pageProvider.setStartOfNextElementList(currentPageNum, - pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex()); + pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex(), this.spanAllActive); //Make sure we only add the areas we haven't added already effectiveList.ignoreAtStart = newStartPos; @@ -387,7 +390,7 @@ public class PageBreaker extends AbstractBreaker { boolean fitsOnePage = optimalPageCount <= pslm.getCurrentPV() - .getBodyRegion().getMainReference().getCurrentSpan().getColumnCount(); + .getBodyRegion().getMainReference().getCurrentSpan().getColumnCount(); if (needColumnBalancing) { if (!fitsOnePage) { @@ -435,7 +438,8 @@ public class PageBreaker extends AbstractBreaker { handleBreakTrait(breakClass); } pageProvider.setStartOfNextElementList(pslm.getCurrentPageNum(), - pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex()); + pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex(), + this.spanAllActive); } pageBreakHandled = false; // add static areas and resolve any new id areas @@ -503,9 +507,11 @@ public class PageBreaker extends AbstractBreaker { case Constants.EN_ALL: //break due to span change in multi-column layout curPage.getPageViewport().createSpan(true); + this.spanAllActive = true; return; case Constants.EN_NONE: curPage.getPageViewport().createSpan(false); + this.spanAllActive = false; return; case Constants.EN_COLUMN: case Constants.EN_AUTO: diff --git a/src/java/org/apache/fop/layoutmgr/PageProvider.java b/src/java/org/apache/fop/layoutmgr/PageProvider.java index 2e531a8d8..8caafa72b 100644 --- a/src/java/org/apache/fop/layoutmgr/PageProvider.java +++ b/src/java/org/apache/fop/layoutmgr/PageProvider.java @@ -51,6 +51,7 @@ public class PageProvider implements Constants { private int startPageOfPageSequence; private int startPageOfCurrentElementList; private int startColumnOfCurrentElementList; + private boolean spanAllForCurrentElementList; private List cachedPages = new java.util.ArrayList(); private int lastPageIndex = -1; @@ -88,12 +89,17 @@ public class PageProvider implements Constants { * on so it can later retrieve PageViewports relative to this first page. * @param startPage the number of the first page for the element list. * @param startColumn the starting column number for the element list. + * @param spanAll true if the current element list is for a column-spanning section */ - public void setStartOfNextElementList(int startPage, int startColumn) { - log.debug("start of the next element list is:" - + " page=" + startPage + " col=" + startColumn); + public void setStartOfNextElementList(int startPage, int startColumn, boolean spanAll) { + if (log.isDebugEnabled()) { + log.debug("start of the next element list is:" + + " page=" + startPage + " col=" + startColumn + + (spanAll ? ", column-spanning" : "")); + } this.startPageOfCurrentElementList = startPage - startPageOfPageSequence + 1; this.startColumnOfCurrentElementList = startColumn; + this.spanAllForCurrentElementList = spanAll; //Reset Cache this.lastRequestedIndex = -1; this.lastReportedBPD = -1; @@ -290,7 +296,7 @@ public class PageProvider implements Constants { if (log.isTraceEnabled()) { log.trace("Caching " + index); } - cacheNextPage(index, isBlank, isLastPage); + cacheNextPage(index, isBlank, isLastPage, this.spanAllForCurrentElementList); } Page page = (Page)cachedPages.get(intIndex); boolean replace = false; @@ -306,7 +312,7 @@ public class PageProvider implements Constants { } if (replace) { discardCacheStartingWith(intIndex); - page = cacheNextPage(index, isBlank, isLastPage); + page = cacheNextPage(index, isBlank, isLastPage, this.spanAllForCurrentElementList); } return page; } @@ -320,7 +326,7 @@ public class PageProvider implements Constants { } } - private Page cacheNextPage(int index, boolean isBlank, boolean isLastPage) { + private Page cacheNextPage(int index, boolean isBlank, boolean isLastPage, boolean spanAll) { String pageNumberString = pageSeq.makeFormattedPageNumber(index); boolean isFirstPage = (startPageOfPageSequence == index); SimplePageMaster spm = pageSeq.getNextSimplePageMaster( @@ -335,7 +341,7 @@ public class PageProvider implements Constants { eventProducer.flowNotMappingToRegionBody(this, pageSeq.getMainFlow().getFlowName(), spm.getMasterName(), spm.getLocator()); } - Page page = new Page(spm, index, pageNumberString, isBlank); + Page page = new Page(spm, index, pageNumberString, isBlank, spanAll); //Set unique key obtained from the AreaTreeHandler page.getPageViewport().setKey(areaTreeHandler.generatePageViewportKey()); page.getPageViewport().setForeignAttributes(spm.getForeignAttributes()); diff --git a/status.xml b/status.xml index 1f0916753..57b7a94b3 100644 --- a/status.xml +++ b/status.xml @@ -58,6 +58,9 @@ documents. Example: the fix of marks layering will be such a case when it's done. --> + + Fixed retrieval of available BPD for cases spanning columns and multiple pages with differing page masters. + Removed old Renderer implementations for those output formats that have a version based on the new DocumentHandler architecture available (AFP, PCL, PDF, PS). diff --git a/test/layoutengine/standard-testcases/region-body_column-count_span_4.xml b/test/layoutengine/standard-testcases/region-body_column-count_span_4.xml new file mode 100644 index 000000000..8bc4652ce --- /dev/null +++ b/test/layoutengine/standard-testcases/region-body_column-count_span_4.xml @@ -0,0 +1,84 @@ + + + + + +

+ This test checks multi-column documents. Check that spanned section that are broken over + to multiple pages still respect the span setting. This particular test makes sure that pages with different region-body + height are handled properly. +

+ + + + + + + + + + + + + + + + + + + + + Line 1 + Line 2 + Line 3 + Line 4 + Line 5 + Line 6 + Line 7 + Line 8 + Line 9 + Line 10 + Line 11 + Line 12 + Line 13 + Line 14 + Line 15 + Line 16 + Line 17 + Line 18 + Line 19 + Line 20 + Line 21 + Line 22 + + + + + + + + + + + + + + + + + -- cgit v1.2.3 From 04701709af5735bf1ecf236efef93999c2ffe834 Mon Sep 17 00:00:00 2001 From: Simon Pepping Date: Wed, 6 Oct 2010 07:07:38 +0000 Subject: Making fallback from (lang,country) to (lang) consistent git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1004907 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/fop/hyphenation/Hyphenator.java | 91 +++++++++----- .../hyphenation-pattern_fallback.xml | 137 +++++++++++++++++++++ 2 files changed, 198 insertions(+), 30 deletions(-) create mode 100644 test/layoutengine/hyphenation-testcases/hyphenation-pattern_fallback.xml (limited to 'test') diff --git a/src/java/org/apache/fop/hyphenation/Hyphenator.java b/src/java/org/apache/fop/hyphenation/Hyphenator.java index a556fd7fe..7f37b5e28 100644 --- a/src/java/org/apache/fop/hyphenation/Hyphenator.java +++ b/src/java/org/apache/fop/hyphenation/Hyphenator.java @@ -76,8 +76,9 @@ public final class Hyphenator { } /** - * Returns a hyphenation tree for a given language and country. The hyphenation trees are - * cached. + * Returns a hyphenation tree for a given language and country, + * with fallback from (lang,country) to (lang). + * The hyphenation trees are cached. * @param lang the language * @param country the country (may be null or "none") * @param resolver resolver to find the hyphenation files @@ -89,11 +90,62 @@ public final class Hyphenator { String llccKey = HyphenationTreeCache.constructLlccKey(lang, country); HyphenationTreeCache cache = getHyphenationTreeCache(); - // See if there was an error finding this hyphenation tree before + // If this hyphenation tree has been registered as missing, return immediately if (cache.isMissing(llccKey)) { return null; } + HyphenationTree hTree = getHyphenationTree2(lang, country, resolver, hyphPatNames); + + // fallback to lang only + if (hTree == null && country != null && !country.equals("none")) { + String llKey = HyphenationTreeCache.constructLlccKey(lang, null); + if (!cache.isMissing(llKey)) { + hTree = getHyphenationTree2(lang, null, resolver, hyphPatNames); + if (hTree != null && log.isDebugEnabled()) { + log.debug("Couldn't find hyphenation pattern " + + "for lang=\"" + lang + "\",country=\"" + country + "\"." + + " Using general language pattern " + + "for lang=\"" + lang + "\" instead."); + } + if (hTree == null) { + // no fallback; register as missing + cache.noteMissing(llKey); + } else { + // also register for (lang,country) + cache.cache(llccKey, hTree); + } + } + } + + if (hTree == null) { + // (lang,country) and (lang) tried; register as missing + cache.noteMissing(llccKey); + log.error("Couldn't find hyphenation pattern " + + "for lang=\"" + lang + "\"" + + (country != null && !country.equals("none") + ? ",country=\"" + country + "\"" + : "") + + "."); + } + + return hTree; + } + + /** + * Returns a hyphenation tree for a given language and country + * The hyphenation trees are cached. + * @param lang the language + * @param country the country (may be null or "none") + * @param resolver resolver to find the hyphenation files + * @param hyphPatNames the map with user-configured hyphenation pattern file names + * @return the hyphenation tree + */ + private static HyphenationTree getHyphenationTree2(String lang, + String country, HyphenationTreeResolver resolver, Map hyphPatNames) { + String llccKey = HyphenationTreeCache.constructLlccKey(lang, country); + HyphenationTreeCache cache = getHyphenationTreeCache(); + HyphenationTree hTree; // first try to find it in the cache hTree = getHyphenationTreeCache().getHyphenationTree(lang, country); @@ -105,6 +157,7 @@ public final class Hyphenator { if (key == null) { key = llccKey; } + if (resolver != null) { hTree = getUserHyphenationTree(key, resolver); } @@ -115,10 +168,8 @@ public final class Hyphenator { // put it into the pattern cache if (hTree != null) { cache.cache(llccKey, hTree); - } else { - log.error("Couldn't find hyphenation pattern " + llccKey); - cache.noteMissing(llccKey); } + return hTree; } @@ -173,31 +224,11 @@ public final class Hyphenator { try { is = getResourceStream(key); if (is == null) { - if (key.length() == 5) { - String lang = key.substring(0, 2); - is = getResourceStream(lang); - if (is != null) { - if (log.isDebugEnabled()) { - log.debug("Couldn't find hyphenation pattern '" - + key - + "'. Using general language pattern '" - + lang - + "' instead."); - } - } else { - if (log.isDebugEnabled()) { - log.debug("Couldn't find precompiled hyphenation pattern " - + lang + " in resources."); - } - return null; - } - } else { - if (log.isDebugEnabled()) { - log.debug("Couldn't find precompiled hyphenation pattern " - + key + " in resources"); - } - return null; + if (log.isDebugEnabled()) { + log.debug("Couldn't find precompiled hyphenation pattern " + + key + " in resources"); } + return null; } hTree = readHyphenationTree(is); } finally { diff --git a/test/layoutengine/hyphenation-testcases/hyphenation-pattern_fallback.xml b/test/layoutengine/hyphenation-testcases/hyphenation-pattern_fallback.xml new file mode 100644 index 000000000..3af71a3ea --- /dev/null +++ b/test/layoutengine/hyphenation-testcases/hyphenation-pattern_fallback.xml @@ -0,0 +1,137 @@ + + + + + +

+ Checks fallback from hyphenation pattern for (lang,country) to hyphenation pattern for (lang) +

+
+ + + + + + + + + + + + + + + + + language="en",country="IN" + + + This document has been reviewed by W3C Members and other interested parties and has been endorsed by the Director as a + W3C Recommendation. It is a stable document and may be used as reference material or cited as a normative reference from + another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its + widespread deployment. This enhances the functionality and interoperability of the Web. + + + + language="em" + + + This document has been reviewed by W3C Members and other interested parties and has been endorsed by the Director as a + W3C Recommendation. It is a stable document and may be used as reference material or cited as a normative reference from + another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its + widespread deployment. This enhances the functionality and interoperability of the Web. + + + + language="em",country="IN" + + + This document has been reviewed by W3C Members and other interested parties and has been endorsed by the Director as a + W3C Recommendation. It is a stable document and may be used as reference material or cited as a normative reference from + another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its + widespread deployment. This enhances the functionality and interoperability of the Web. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
-- cgit v1.2.3 From 1939c00e198dd9c45bc5847dd58f27485372934e Mon Sep 17 00:00:00 2001 From: Simon Pepping Date: Thu, 11 Nov 2010 09:48:24 +0000 Subject: Applied patch 50240 by Mehdi Houshmand with changes: Java source and target changed to 1.5. EncodingMode changed from class -> enum. git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1033859 13f79535-47bb-0310-9956-ffa450edef68 --- build.xml | 4 +-- src/java/org/apache/fop/fonts/EncodingMode.java | 35 +++++++--------------- .../org/apache/fop/fonts/FontInfoConfigurator.java | 2 +- .../org/apache/fop/fonts/EncodingModeTest.java | 17 +++++++++++ 4 files changed, 31 insertions(+), 27 deletions(-) create mode 100644 test/java/org/apache/fop/fonts/EncodingModeTest.java (limited to 'test') diff --git a/build.xml b/build.xml index 15e6d0ac4..ae4f5c886 100644 --- a/build.xml +++ b/build.xml @@ -149,8 +149,8 @@ list of possible build targets. - - + + diff --git a/src/java/org/apache/fop/fonts/EncodingMode.java b/src/java/org/apache/fop/fonts/EncodingMode.java index 734292c54..8a40d6593 100644 --- a/src/java/org/apache/fop/fonts/EncodingMode.java +++ b/src/java/org/apache/fop/fonts/EncodingMode.java @@ -19,25 +19,19 @@ package org.apache.fop.fonts; -import java.io.ObjectStreamException; -import java.io.Serializable; - - /** * This class enumerates all supported encoding modes for fonts: auto, single-byte and CID. */ -public final class EncodingMode implements Serializable { - - private static final long serialVersionUID = 8311486102457779529L; +public enum EncodingMode { /** Automatic selection of encoding mode. */ - public static final EncodingMode AUTO = new EncodingMode("auto"); + AUTO("auto"), /** Single-byte encoding */ - public static final EncodingMode SINGLE_BYTE = new EncodingMode("single-byte"); + SINGLE_BYTE("single-byte"), /** CID encoding */ - public static final EncodingMode CID = new EncodingMode("cid"); + CID("cid"); private String name; @@ -58,25 +52,18 @@ public final class EncodingMode implements Serializable { * @param name the name of the encoding mode to look up * @return the encoding mode constant */ - public static EncodingMode valueOf(String name) { - if (name.equalsIgnoreCase(EncodingMode.AUTO.getName())) { - return EncodingMode.AUTO; - } else if (name.equalsIgnoreCase(EncodingMode.SINGLE_BYTE.getName())) { - return EncodingMode.SINGLE_BYTE; - } else if (name.equalsIgnoreCase(EncodingMode.CID.getName())) { - return EncodingMode.CID; - } else { - throw new IllegalArgumentException("Invalid encoding mode: " + name); + public static EncodingMode getEncodingMode(String name) { + for (EncodingMode em : EncodingMode.values()) { + if (name.equalsIgnoreCase(em.getName())) { + return em; + } } - } - - private Object readResolve() throws ObjectStreamException { - return valueOf(getName()); + throw new IllegalArgumentException("Invalid encoding mode: " + name); } /** {@inheritDoc} */ public String toString() { - return "EncodingMode:" + getName(); + return "EncodingMode: " + getName(); } } diff --git a/src/java/org/apache/fop/fonts/FontInfoConfigurator.java b/src/java/org/apache/fop/fonts/FontInfoConfigurator.java index f8399b110..9a11f84bc 100644 --- a/src/java/org/apache/fop/fonts/FontInfoConfigurator.java +++ b/src/java/org/apache/fop/fonts/FontInfoConfigurator.java @@ -254,7 +254,7 @@ public class FontInfoConfigurator { } boolean useKerning = fontCfg.getAttributeAsBoolean("kerning", true); - EncodingMode encodingMode = EncodingMode.valueOf( + EncodingMode encodingMode = EncodingMode.getEncodingMode( fontCfg.getAttribute("encoding-mode", EncodingMode.AUTO.getName())); EmbedFontInfo embedFontInfo = new EmbedFontInfo(metricsUrl, useKerning, tripletList, embedUrl, subFont); diff --git a/test/java/org/apache/fop/fonts/EncodingModeTest.java b/test/java/org/apache/fop/fonts/EncodingModeTest.java new file mode 100644 index 000000000..d291f4c0b --- /dev/null +++ b/test/java/org/apache/fop/fonts/EncodingModeTest.java @@ -0,0 +1,17 @@ +package org.apache.fop.fonts; + +import junit.framework.TestCase; + +public class EncodingModeTest extends TestCase { + public void testGetName() { + assertEquals("auto", EncodingMode.AUTO.getName()); + assertEquals("single-byte", EncodingMode.SINGLE_BYTE.getName()); + assertEquals("cid", EncodingMode.CID.getName()); + } + + public void testGetValue() { + assertEquals(EncodingMode.AUTO, EncodingMode.getEncodingMode("auto")); + assertEquals(EncodingMode.SINGLE_BYTE, EncodingMode.getEncodingMode("single-byte")); + assertEquals(EncodingMode.CID, EncodingMode.getEncodingMode("cid")); + } +} -- cgit v1.2.3 From e6245e4939c018c81f41ec548dc61a8669c749d0 Mon Sep 17 00:00:00 2001 From: Jeremias Maerki Date: Mon, 15 Nov 2010 13:51:20 +0000 Subject: Removed tab characters. git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1035275 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/fop/fonts/EncodingModeTest.java | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'test') diff --git a/test/java/org/apache/fop/fonts/EncodingModeTest.java b/test/java/org/apache/fop/fonts/EncodingModeTest.java index d291f4c0b..a76b33e9f 100644 --- a/test/java/org/apache/fop/fonts/EncodingModeTest.java +++ b/test/java/org/apache/fop/fonts/EncodingModeTest.java @@ -3,15 +3,15 @@ package org.apache.fop.fonts; import junit.framework.TestCase; public class EncodingModeTest extends TestCase { - public void testGetName() { - assertEquals("auto", EncodingMode.AUTO.getName()); - assertEquals("single-byte", EncodingMode.SINGLE_BYTE.getName()); - assertEquals("cid", EncodingMode.CID.getName()); - } - - public void testGetValue() { - assertEquals(EncodingMode.AUTO, EncodingMode.getEncodingMode("auto")); - assertEquals(EncodingMode.SINGLE_BYTE, EncodingMode.getEncodingMode("single-byte")); - assertEquals(EncodingMode.CID, EncodingMode.getEncodingMode("cid")); - } + public void testGetName() { + assertEquals("auto", EncodingMode.AUTO.getName()); + assertEquals("single-byte", EncodingMode.SINGLE_BYTE.getName()); + assertEquals("cid", EncodingMode.CID.getName()); + } + + public void testGetValue() { + assertEquals(EncodingMode.AUTO, EncodingMode.getEncodingMode("auto")); + assertEquals(EncodingMode.SINGLE_BYTE, EncodingMode.getEncodingMode("single-byte")); + assertEquals(EncodingMode.CID, EncodingMode.getEncodingMode("cid")); + } } -- cgit v1.2.3 From 3dc848243b02e9a7b1c24b4dfd252dc545bfa0f7 Mon Sep 17 00:00:00 2001 From: Jeremias Maerki Date: Mon, 15 Nov 2010 13:52:58 +0000 Subject: Added missing license header. git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1035276 13f79535-47bb-0310-9956-ffa450edef68 --- test/java/org/apache/fop/fonts/EncodingModeTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'test') diff --git a/test/java/org/apache/fop/fonts/EncodingModeTest.java b/test/java/org/apache/fop/fonts/EncodingModeTest.java index a76b33e9f..4e81c46d6 100644 --- a/test/java/org/apache/fop/fonts/EncodingModeTest.java +++ b/test/java/org/apache/fop/fonts/EncodingModeTest.java @@ -1,3 +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. + */ + +/* $Id$ */ + package org.apache.fop.fonts; import junit.framework.TestCase; -- cgit v1.2.3 From e126edb6ed0c2aaefe0ebd72909d2f2346198f65 Mon Sep 17 00:00:00 2001 From: Vincent Hennebert Date: Tue, 16 Nov 2010 12:18:15 +0000 Subject: Do not re-create an AlignmentContext instance if one already exists. Fixes a bug when the changing IPD hack is triggered and the getNextKnuthElements method is called a second time git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1035609 13f79535-47bb-0310-9956-ffa450edef68 --- .../fop/layoutmgr/inline/LineLayoutManager.java | 12 +++-- .../standard-testcases/flow_changing-ipd_image.xml | 60 ++++++++++++++++++++++ 2 files changed, 67 insertions(+), 5 deletions(-) create mode 100644 test/layoutengine/standard-testcases/flow_changing-ipd_image.xml (limited to 'test') diff --git a/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java index cbae691b1..964a4e2a5 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java @@ -559,11 +559,13 @@ public class LineLayoutManager extends InlineStackingLayoutManager /** {@inheritDoc} */ public List getNextKnuthElements(LayoutContext context, int alignment) { - FontInfo fi = fobj.getFOEventHandler().getFontInfo(); - FontTriplet[] fontkeys = fobj.getCommonFont().getFontState(fi); - Font fs = fi.getFontInstance(fontkeys[0], fobj.getCommonFont().fontSize.getValue(this)); - alignmentContext = new AlignmentContext(fs, lineHeight.getValue(this), - context.getWritingMode()); + if (alignmentContext == null) { + FontInfo fi = fobj.getFOEventHandler().getFontInfo(); + FontTriplet[] fontkeys = fobj.getCommonFont().getFontState(fi); + Font fs = fi.getFontInstance(fontkeys[0], fobj.getCommonFont().fontSize.getValue(this)); + alignmentContext = new AlignmentContext(fs, lineHeight.getValue(this), + context.getWritingMode()); + } context.setAlignmentContext(alignmentContext); ipd = context.getRefIPD(); diff --git a/test/layoutengine/standard-testcases/flow_changing-ipd_image.xml b/test/layoutengine/standard-testcases/flow_changing-ipd_image.xml new file mode 100644 index 000000000..37014f49a --- /dev/null +++ b/test/layoutengine/standard-testcases/flow_changing-ipd_image.xml @@ -0,0 +1,60 @@ + + + + + +

+ This test checks that an image is properly positioned after a page break triggering changing + IPD. +

+
+ + + + + + + + + + + + + + + + + + + First block + Block before the page break. + Block after the page break. + + + + + + + + + + +
-- cgit v1.2.3 From 3231a8001e858244acec7fe09776b8ffb027e11d Mon Sep 17 00:00:00 2001 From: "Andreas L. Delmelle" Date: Thu, 25 Nov 2010 21:27:44 +0000 Subject: Bugzilla 38264: hyphenation in combination with preserved linefeeds and/or white-space no longer causes duplication of content and missing hyphens git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1039188 13f79535-47bb-0310-9956-ffa450edef68 --- .../fop/layoutmgr/inline/LineLayoutManager.java | 32 ++++----- .../fop/layoutmgr/inline/TextLayoutManager.java | 78 +++++++++++++++------- status.xml | 3 + test/layoutengine/disabled-testcases.xml | 6 -- .../block_hyphenation_linefeed_preserve.xml | 40 ++++++++--- 5 files changed, 104 insertions(+), 55 deletions(-) (limited to 'test') diff --git a/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java index fbe487cc5..e41a8f272 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java @@ -771,7 +771,7 @@ public class LineLayoutManager extends InlineStackingLayoutManager // we only need an entry in lineLayoutsList. llPoss = new LineLayoutPossibilities(); } else { - llPoss = findOptimalBreakingPoints(alignment, (Paragraph) seq); + llPoss = findOptimalBreakingPoints(alignment, (Paragraph) seq, !paragraphsIterator.hasNext()); } lineLayoutsList[i] = llPoss; } @@ -783,12 +783,13 @@ public class LineLayoutManager extends InlineStackingLayoutManager } /** - * Fint the optimal linebreaks for a paragraph + * Find the optimal linebreaks for a paragraph * @param alignment alignment of the paragraph * @param currPar the Paragraph for which the linebreaks are found + * @param isLastPar flag indicating whether currPar is the last paragraph * @return the line layout possibilities for the paragraph */ - private LineLayoutPossibilities findOptimalBreakingPoints(int alignment, Paragraph currPar) { + private LineLayoutPossibilities findOptimalBreakingPoints(int alignment, Paragraph currPar, boolean isLastPar) { // use the member lineLayouts, which is read by LineBreakingAlgorithm.updateData1 and 2 lineLayouts = new LineLayoutPossibilities(); double maxAdjustment = 1; @@ -808,7 +809,7 @@ public class LineLayoutManager extends InlineStackingLayoutManager if (canHyphenate && !hyphenationPerformed) { // make sure findHyphenationPoints() is bypassed if // the method is called twice (e.g. due to changing page-ipd) - hyphenationPerformed = true; + hyphenationPerformed = isLastPar; findHyphenationPoints(currPar); } @@ -1423,8 +1424,6 @@ public class LineLayoutManager extends InlineStackingLayoutManager */ private void addInlineArea(LayoutContext context, LineBreakPosition lbp, boolean isLastPosition) { - // the TLM which created the last KnuthElement in this line - LayoutManager lastLM = null; KnuthSequence seq = (KnuthSequence) knuthParagraphs.get(lbp.parIndex); int startElementIndex = lbp.startIndex; @@ -1456,15 +1455,16 @@ public class LineLayoutManager extends InlineStackingLayoutManager } } - // Remove trailing spaces if allowed so - if (whiteSpaceTreament == EN_IGNORE_IF_SURROUNDING_LINEFEED - || whiteSpaceTreament == EN_IGNORE - || whiteSpaceTreament == EN_IGNORE_IF_BEFORE_LINEFEED) { - // ignore the last element in the line if it is a KnuthGlue object - ListIterator seqIterator = seq.listIterator(endElementIndex); - KnuthElement lastElement = (KnuthElement) seqIterator.next(); - lastLM = lastElement.getLayoutManager(); - if (lastElement.isGlue()) { + // ignore the last element in the line if it is a KnuthGlue object + ListIterator seqIterator = seq.listIterator(endElementIndex); + KnuthElement lastElement = (KnuthElement) seqIterator.next(); + // the TLM which created the last KnuthElement in this line + LayoutManager lastLM = lastElement.getLayoutManager(); + if (lastElement.isGlue()) { + // Remove trailing spaces if allowed so + if (whiteSpaceTreament == EN_IGNORE_IF_SURROUNDING_LINEFEED + || whiteSpaceTreament == EN_IGNORE + || whiteSpaceTreament == EN_IGNORE_IF_BEFORE_LINEFEED) { endElementIndex--; // this returns the same KnuthElement seqIterator.previous(); @@ -1480,7 +1480,7 @@ public class LineLayoutManager extends InlineStackingLayoutManager || whiteSpaceTreament == EN_IGNORE_IF_AFTER_LINEFEED) { // ignore KnuthGlue and KnuthPenalty objects // at the beginning of the line - ListIterator seqIterator = seq.listIterator(startElementIndex); + seqIterator = seq.listIterator(startElementIndex); while (seqIterator.hasNext() && !((KnuthElement) seqIterator.next()).isBox()) { startElementIndex++; } diff --git a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java index cbe2e2639..05cf979de 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java @@ -165,7 +165,8 @@ public class TextLayoutManager extends LeafNodeLayoutManager { private int hyphIPD; private boolean hasChanged = false; - private int returnedIndex = 0; + private int[] returnedIndices = {0, 0}; + private int changeOffset = 0; private int thisStart = 0; private int tempStart = 0; private List changeList = new LinkedList(); @@ -811,19 +812,19 @@ public class TextLayoutManager extends LeafNodeLayoutManager { //TODO: add kern to wordIPD? } } - int iLetterSpaces = wordLength - 1; + int letterSpaces = wordLength - 1; // if there is a break opportunity and the next one // is not a space, it could be used as a line end; // add one more letter space, in case other text follows if (breakOpportunity && !TextLayoutManager.isSpace(ch)) { - iLetterSpaces++; + letterSpaces++; } - assert iLetterSpaces >= 0; - wordIPD = wordIPD.plus(letterSpaceIPD.mult(iLetterSpaces)); + assert letterSpaces >= 0; + wordIPD = wordIPD.plus(letterSpaceIPD.mult(letterSpaces)); // create the AreaInfo object AreaInfo areaInfo = new AreaInfo(thisStart, lastIndex, 0, - iLetterSpaces, wordIPD, + letterSpaces, wordIPD, endsWithHyphen, false, breakOpportunity, font); prevAreaInfo = areaInfo; @@ -903,11 +904,9 @@ public class TextLayoutManager extends LeafNodeLayoutManager { } } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ public void hyphenate(Position pos, HyphContext hyphContext) { - AreaInfo areaInfo = getAreaInfo(((LeafPosition) pos).getLeafPos()); + AreaInfo areaInfo = getAreaInfo(((LeafPosition) pos).getLeafPos() + changeOffset); int startIndex = areaInfo.startIndex; int stopIndex; boolean nothingChanged = true; @@ -962,7 +961,7 @@ public class TextLayoutManager extends LeafNodeLayoutManager { // the new AreaInfo object is not equal to the old one changeList.add(new PendingChange(new AreaInfo(startIndex, stopIndex, 0, letterSpaceCount, newIPD, hyphenFollows, false, false, font), - ((LeafPosition) pos).getLeafPos())); + ((LeafPosition) pos).getLeafPos() + changeOffset)); nothingChanged = false; } startIndex = stopIndex; @@ -972,11 +971,41 @@ public class TextLayoutManager extends LeafNodeLayoutManager { /** {@inheritDoc} */ public boolean applyChanges(final List oldList) { + + // make sure the LM appears unfinished in between this call + // and the next call to getChangedKnuthElements() setFinished(false); + if (oldList.isEmpty()) { + return false; + } + + // Find the first and last positions in oldList that point to an AreaInfo + // (i.e. getLeafPos() != -1) + LeafPosition startPos = null, endPos = null; + ListIterator oldListIter; + for (oldListIter = oldList.listIterator(); oldListIter.hasNext();) { + startPos = (LeafPosition) ((KnuthElement) oldListIter.next()).getPosition(); + if (startPos != null && startPos.getLeafPos() != -1) { + break; + } + } + for (oldListIter = oldList.listIterator(oldList.size()); oldListIter.hasPrevious();) { + endPos = (LeafPosition) ((KnuthElement) oldListIter.previous()).getPosition(); + if (endPos != null && endPos.getLeafPos() != -1) { + break; + } + } + + // set start/end index, taking into account any offset due to + // changes applied to previous paragraphs + returnedIndices[0] = (startPos != null ? startPos.getLeafPos() : -1) + changeOffset; + returnedIndices[1] = (endPos != null ? endPos.getLeafPos() : -1) + changeOffset; + + int areaInfosAdded = 0; + int areaInfosRemoved = 0; + if (!changeList.isEmpty()) { - int areaInfosAdded = 0; - int areaInfosRemoved = 0; int oldIndex = -1, changeIndex; PendingChange currChange; ListIterator changeListIterator = changeList.listIterator(); @@ -997,7 +1026,11 @@ public class TextLayoutManager extends LeafNodeLayoutManager { changeList.clear(); } - returnedIndex = 0; + // increase the end index for getChangedKnuthElements() + returnedIndices[1] += (areaInfosAdded - areaInfosRemoved); + // increase offset to use for subsequent paragraphs + changeOffset += (areaInfosAdded - areaInfosRemoved); + return hasChanged; } @@ -1009,27 +1042,24 @@ public class TextLayoutManager extends LeafNodeLayoutManager { final LinkedList returnList = new LinkedList(); - while (returnedIndex < areaInfos.size()) { - AreaInfo areaInfo = getAreaInfo(returnedIndex); + for (; returnedIndices[0] <= returnedIndices[1]; returnedIndices[0]++) { + AreaInfo areaInfo = getAreaInfo(returnedIndices[0]); if (areaInfo.wordSpaceCount == 0) { // areaInfo refers either to a word or a word fragment - addElementsForAWordFragment(returnList, alignment, areaInfo, returnedIndex); + addElementsForAWordFragment(returnList, alignment, areaInfo, returnedIndices[0]); } else { // areaInfo refers to a space - addElementsForASpace(returnList, alignment, areaInfo, returnedIndex); + addElementsForASpace(returnList, alignment, areaInfo, returnedIndices[0]); } - returnedIndex++; } - setFinished(true); + setFinished(returnedIndices[0] == areaInfos.size() - 1); //ElementListObserver.observe(returnList, "text-changed", null); return returnList; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ public String getWordChars(Position pos) { - int leafValue = ((LeafPosition) pos).getLeafPos(); + int leafValue = ((LeafPosition) pos).getLeafPos() + changeOffset; if (leafValue != -1) { AreaInfo areaInfo = getAreaInfo(leafValue); StringBuffer buffer = new StringBuffer(areaInfo.getCharLength()); diff --git a/status.xml b/status.xml index 69aff4921..d933ef686 100644 --- a/status.xml +++ b/status.xml @@ -58,6 +58,9 @@ documents. Example: the fix of marks layering will be such a case when it's done. --> + + Fixed behavior when combining hyphenation with preserved linefeeds or whitespace. + Replaced magic numbers with constants from UnitConv and GraphicsConstants. diff --git a/test/layoutengine/disabled-testcases.xml b/test/layoutengine/disabled-testcases.xml index 1fb4f2926..6c61ca747 100644 --- a/test/layoutengine/disabled-testcases.xml +++ b/test/layoutengine/disabled-testcases.xml @@ -38,12 +38,6 @@ block_font-stretch.xml Font-stretch is not implemented, yet. - - Hyphenation with preserved linefeeds - block_hyphenation_linefeed_preserve.xml - When hyphenation is enabled and linefeeds are preserved, - the text is output multiple times. - linefeed-treatment block_linefeed-treatment.xml diff --git a/test/layoutengine/hyphenation-testcases/block_hyphenation_linefeed_preserve.xml b/test/layoutengine/hyphenation-testcases/block_hyphenation_linefeed_preserve.xml index d1231892f..ac13e9875 100644 --- a/test/layoutengine/hyphenation-testcases/block_hyphenation_linefeed_preserve.xml +++ b/test/layoutengine/hyphenation-testcases/block_hyphenation_linefeed_preserve.xml @@ -19,7 +19,11 @@

- Check for bug: Duplicate content and linefeeds as "#". + Check for bug 38264: +

    +
  • duplication of content with linefeed-treatment="preserve" and hyphenate="true"
  • +
  • missing hyphens with white-space-treatment="preserve" and hyphenate="true"
  • +

@@ -31,21 +35,39 @@
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas semper. Proin at. - + line1 line2 -Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas semper. Proin at1. - +Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas semper. Proin at. +
- - + + + + + + + + + + + + + + + + + + + + + + + -- cgit v1.2.3 From 24e2fad7e1416bd1878e3474f710af2c15edd8fb Mon Sep 17 00:00:00 2001 From: Simon Pepping Date: Sat, 4 Dec 2010 08:30:47 +0000 Subject: Allow for words consisting of only soft hyphens; fixes bug 49837 git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1042115 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/fop/fo/FOTreeBuilder.java | 4 +- .../fop/layoutmgr/inline/TextLayoutManager.java | 25 +++--- .../standard-testcases/word_lonely_shy.xml | 98 ++++++++++++++++++++++ 3 files changed, 116 insertions(+), 11 deletions(-) create mode 100644 test/layoutengine/standard-testcases/word_lonely_shy.xml (limited to 'test') diff --git a/src/java/org/apache/fop/fo/FOTreeBuilder.java b/src/java/org/apache/fop/fo/FOTreeBuilder.java index c848eb4f1..451481eb8 100644 --- a/src/java/org/apache/fop/fo/FOTreeBuilder.java +++ b/src/java/org/apache/fop/fo/FOTreeBuilder.java @@ -398,7 +398,9 @@ public class FOTreeBuilder extends DefaultHandler { FOValidationEventProducer eventProducer = FOValidationEventProducer.Provider.get( userAgent.getEventBroadcaster()); - eventProducer.unknownFormattingObject(this, currentFObj.getName(), + String name = (currentFObj != null ? currentFObj.getName() + : "{" + namespaceURI + "}" + localName); + eventProducer.unknownFormattingObject(this, name, new QName(namespaceURI, localName), getEffectiveLocator()); } diff --git a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java index 05cf979de..498fd1265 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java @@ -770,11 +770,8 @@ public class TextLayoutManager extends LeafNodeLayoutManager { while (lastIndex > 0 && foText.charAt(lastIndex - 1) == CharUtilities.SOFT_HYPHEN) { lastIndex--; } - final boolean endsWithHyphen = checkEndsWithHyphen - && foText.charAt(lastIndex) == CharUtilities.SOFT_HYPHEN; Font font = FontSelector .selectFontForCharactersInText(foText, thisStart, lastIndex, foText, this); - int wordLength = lastIndex - thisStart; boolean kerning = font.hasKerning(); MinOptMax wordIPD = MinOptMax.ZERO; for (int i = thisStart; i < lastIndex; i++) { @@ -801,23 +798,31 @@ public class TextLayoutManager extends LeafNodeLayoutManager { } } } + boolean endsWithHyphen = checkEndsWithHyphen + && foText.charAt(lastIndex) == CharUtilities.SOFT_HYPHEN; if (kerning && breakOpportunity && !TextLayoutManager.isSpace(ch) && lastIndex > 0 && endsWithHyphen) { - final int kern = font.getKernValue(foText.charAt(lastIndex - 1), ch); + int kern = font.getKernValue(foText.charAt(lastIndex - 1), ch); if (kern != 0) { addToLetterAdjust(lastIndex, kern); //TODO: add kern to wordIPD? } } - int letterSpaces = wordLength - 1; - // if there is a break opportunity and the next one - // is not a space, it could be used as a line end; - // add one more letter space, in case other text follows - if (breakOpportunity && !TextLayoutManager.isSpace(ch)) { - letterSpaces++; + // shy+chars at start of word: wordLength == 0 && breakOpportunity + // shy only characters in word: wordLength == 0 && !breakOpportunity + int wordLength = lastIndex - thisStart; + int letterSpaces = 0; + if (wordLength != 0) { + letterSpaces = wordLength - 1; + // if there is a break opportunity and the next one + // is not a space, it could be used as a line end; + // add one more letter space, in case other text follows + if (breakOpportunity && !TextLayoutManager.isSpace(ch)) { + letterSpaces++; + } } assert letterSpaces >= 0; wordIPD = wordIPD.plus(letterSpaceIPD.mult(letterSpaces)); diff --git a/test/layoutengine/standard-testcases/word_lonely_shy.xml b/test/layoutengine/standard-testcases/word_lonely_shy.xml new file mode 100644 index 000000000..557ceea90 --- /dev/null +++ b/test/layoutengine/standard-testcases/word_lonely_shy.xml @@ -0,0 +1,98 @@ + + + + + +

+ This test checks that a word consisting of one or more Soft Hyphens is rendered as an empty word. +

+
+ + + + + + + + + + Name: hy (hyphen), Unicode: U+002D (45) + - + Name: shy (soft hyphen = discretionary hyphen), Unicode: U+00AD (173) + ­ ­ ­­ ­­­ ­­­­ a ­ b ­­ c ­­­ d ­­­­ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ -- cgit v1.2.3 From bc3a0d90c10f31bc683582f76d3a7adca3d83b12 Mon Sep 17 00:00:00 2001 From: Jeremias Maerki Date: Tue, 7 Dec 2010 08:34:39 +0000 Subject: Bugzilla #42034: Fixed adjustment of inline parent area for justified text containing a forward page reference. git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1042934 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/fop/area/LineArea.java | 18 ++++++-- .../org/apache/fop/area/inline/InlineArea.java | 5 ++ .../org/apache/fop/area/inline/InlineParent.java | 22 +++++---- status.xml | 3 ++ .../standard-testcases/basic-link_for_toc.xml | 53 ++++++++++++++++++++++ 5 files changed, 90 insertions(+), 11 deletions(-) create mode 100644 test/layoutengine/standard-testcases/basic-link_for_toc.xml (limited to 'test') diff --git a/src/java/org/apache/fop/area/LineArea.java b/src/java/org/apache/fop/area/LineArea.java index c89b5be5b..b33b5da14 100644 --- a/src/java/org/apache/fop/area/LineArea.java +++ b/src/java/org/apache/fop/area/LineArea.java @@ -19,13 +19,13 @@ package org.apache.fop.area; -import org.apache.fop.area.inline.InlineArea; -import org.apache.fop.fo.Constants; - import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import org.apache.fop.area.inline.InlineArea; +import org.apache.fop.fo.Constants; + /** * The line area. * This is a line area that contains inline areas. @@ -59,6 +59,15 @@ public class LineArea extends Area { variationFactor = 1.0; bAddedToAreaTree = false; } + + /** {@inheritDoc} */ + public String toString() { + return getClass().getSimpleName() + + ": diff=" + difference + + ", variation=" + variationFactor + + ", stretch=" + availableStretch + + ", shrink=" + availableShrink; + } } private LineAdjustingInfo adjustingInfo = null; @@ -199,6 +208,9 @@ public class LineArea extends Area { */ public void finalise() { if (adjustingInfo.lineAlignment == Constants.EN_JUSTIFY) { + if (log.isTraceEnabled()) { + log.trace("Applying variation factor to justified line: " + adjustingInfo); + } // justified line: apply the variation factor boolean bUnresolvedAreasPresent = false; // recursively apply variation factor to descendant areas diff --git a/src/java/org/apache/fop/area/inline/InlineArea.java b/src/java/org/apache/fop/area/inline/InlineArea.java index 0889d1dad..3450b99be 100644 --- a/src/java/org/apache/fop/area/inline/InlineArea.java +++ b/src/java/org/apache/fop/area/inline/InlineArea.java @@ -228,6 +228,11 @@ public class InlineArea extends Area { * @param ipdVariation the variation */ public void handleIPDVariation(int ipdVariation) { + if (log.isTraceEnabled()) { + log.trace("Handling IPD variation for " + getClass().getSimpleName() + + ": increase by " + ipdVariation + " mpt."); + } + increaseIPD(ipdVariation); notifyIPDVariation(ipdVariation); } diff --git a/src/java/org/apache/fop/area/inline/InlineParent.java b/src/java/org/apache/fop/area/inline/InlineParent.java index 5d4369103..86c9141e6 100644 --- a/src/java/org/apache/fop/area/inline/InlineParent.java +++ b/src/java/org/apache/fop/area/inline/InlineParent.java @@ -19,10 +19,9 @@ package org.apache.fop.area.inline; -import org.apache.fop.area.Area; - import java.util.List; -import java.util.ArrayList; + +import org.apache.fop.area.Area; /** * Inline parent area. @@ -35,7 +34,7 @@ public class InlineParent extends InlineArea { /** * The list of inline areas added to this inline parent. */ - protected List inlines = new ArrayList(); + protected List inlines = new java.util.ArrayList(); /** Controls whether the IPD is automatically adjusted based on the area's children. */ protected transient boolean autoSize; @@ -51,13 +50,14 @@ public class InlineParent extends InlineArea { * * @param childArea the child area to add */ + @Override public void addChildArea(Area childArea) { if (inlines.size() == 0) { autoSize = (getIPD() == 0); } if (childArea instanceof InlineArea) { InlineArea inlineChildArea = (InlineArea) childArea; - inlines.add(childArea); + inlines.add(inlineChildArea); // set the parent area for the child area inlineChildArea.setParentArea(this); if (autoSize) { @@ -71,7 +71,7 @@ public class InlineParent extends InlineArea { * * @return the list of child areas */ - public List getChildAreas() { + public List getChildAreas() { return inlines; } @@ -82,14 +82,20 @@ public class InlineParent extends InlineArea { * @param lineShrink the total shrink of the line * @return true if there is an UnresolvedArea descendant */ + @Override public boolean applyVariationFactor(double variationFactor, int lineStretch, int lineShrink) { boolean bUnresolvedAreasPresent = false; + int cumulativeIPD = 0; // recursively apply variation factor to descendant areas for (int i = 0, len = inlines.size(); i < len; i++) { - bUnresolvedAreasPresent |= ((InlineArea)inlines.get(i)) - .applyVariationFactor(variationFactor, lineStretch, lineShrink); + InlineArea inline = inlines.get(i); + bUnresolvedAreasPresent |= inline.applyVariationFactor( + variationFactor, lineStretch, lineShrink); + cumulativeIPD += inline.getIPD(); //Update this area's IPD based on changes to children } + setIPD(cumulativeIPD); + return bUnresolvedAreasPresent; } } diff --git a/status.xml b/status.xml index d933ef686..e6cd1589c 100644 --- a/status.xml +++ b/status.xml @@ -58,6 +58,9 @@ documents. Example: the fix of marks layering will be such a case when it's done. --> + + Fixed adjustment of inline parent area for justified text containing a forward page reference. + Fixed behavior when combining hyphenation with preserved linefeeds or whitespace. diff --git a/test/layoutengine/standard-testcases/basic-link_for_toc.xml b/test/layoutengine/standard-testcases/basic-link_for_toc.xml new file mode 100644 index 000000000..9966c54b1 --- /dev/null +++ b/test/layoutengine/standard-testcases/basic-link_for_toc.xml @@ -0,0 +1,53 @@ + + + + + +

+ This test checks fo:basic-link in conjunction with text-align="justify" and an + fo:page-number-citation. +

+
+ + + + + + + + + + + You can read about Apache FOP in + chapter 1 on page . + Apache FOP is open source, BTW. + + + + + + + + + + + + + +
-- cgit v1.2.3 From f4086dd275b290d9793b7e401be8f35d7c299938 Mon Sep 17 00:00:00 2001 From: Simon Pepping Date: Thu, 9 Dec 2010 09:00:24 +0000 Subject: Avoid an NPE in InlineStackingLM.applyChanges for Knuth elements with a null position; resolves bug 50276 git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1043871 13f79535-47bb-0310-9956-ffa450edef68 --- .../inline/InlineStackingLayoutManager.java | 5 ++- .../knuth_element-null_position.xml | 44 ++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 test/layoutengine/standard-testcases/knuth_element-null_position.xml (limited to 'test') diff --git a/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java index 4a6a59615..bcc03b956 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java @@ -285,8 +285,9 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager KnuthElement oldElement; while (oldListIterator.hasNext()) { oldElement = (KnuthElement) oldListIterator.next(); - oldElement.setPosition - (oldElement.getPosition().getPosition()); + if (oldElement.getPosition() != null) { + oldElement.setPosition(oldElement.getPosition().getPosition()); + } } // reset the iterator oldListIterator = oldList.listIterator(); diff --git a/test/layoutengine/standard-testcases/knuth_element-null_position.xml b/test/layoutengine/standard-testcases/knuth_element-null_position.xml new file mode 100644 index 000000000..cf964fdf5 --- /dev/null +++ b/test/layoutengine/standard-testcases/knuth_element-null_position.xml @@ -0,0 +1,44 @@ + + + + + +

This check tests that Knuth elements with a null position do +not cause a NPE (in InlineStackingLM.applyChanges)

+
+ + + + + + + + + + + + Abluftanlage + + + + + + + + +
-- cgit v1.2.3 From 6f9a59a3fdcae9116ae20927e7204c77ea7d40a2 Mon Sep 17 00:00:00 2001 From: Vincent Hennebert Date: Tue, 14 Dec 2010 19:39:28 +0000 Subject: Bugzilla #50089: Content after forced break in block-container is not rendered git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1049228 13f79535-47bb-0310-9956-ffa450edef68 --- .../fop/layoutmgr/BlockContainerLayoutManager.java | 2 +- status.xml | 3 ++ .../standard-testcases/block-container_break.xml | 47 ++++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 test/layoutengine/standard-testcases/block-container_break.xml (limited to 'test') diff --git a/src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java b/src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java index ee010efe5..877da13dd 100644 --- a/src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java @@ -323,7 +323,7 @@ public class BlockContainerLayoutManager extends BlockStackingLayoutManager } if (ElementListUtils.endsWithForcedBreak(returnedList)) { // a descendant of this block has break-after - if (curLM.isFinished()) { + if (curLM.isFinished() && !hasNextChildLM()) { // there is no other content in this block; // it's useless to add space after before a page break setFinished(true); diff --git a/status.xml b/status.xml index e6cd1589c..2f2608cfd 100644 --- a/status.xml +++ b/status.xml @@ -58,6 +58,9 @@ documents. Example: the fix of marks layering will be such a case when it's done. --> + + Bugfix: content after forced break in block-container is not rendered. + Fixed adjustment of inline parent area for justified text containing a forward page reference. diff --git a/test/layoutengine/standard-testcases/block-container_break.xml b/test/layoutengine/standard-testcases/block-container_break.xml new file mode 100644 index 000000000..352f755f0 --- /dev/null +++ b/test/layoutengine/standard-testcases/block-container_break.xml @@ -0,0 +1,47 @@ + + + + + +

+ This test checks that a forced break on a child element of an fo:block-container is honored. +

+
+ + + + + + + + + + + Before the break. + After the break. + + + + + + + + + +
-- cgit v1.2.3 From d4ec49dd8f220752be8a5ab0cf6d6f4e30a1e685 Mon Sep 17 00:00:00 2001 From: Simon Pepping Date: Fri, 17 Dec 2010 10:57:18 +0000 Subject: Auxiliary positions do not have an index value; fixing this in InlineStackingLM.applyChanges, rewrapping positions; fixed bug 49870 git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1050342 13f79535-47bb-0310-9956-ffa450edef68 --- .../inline/InlineStackingLayoutManager.java | 7 +++- .../inline_hyphenation_border.xml | 49 ++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 test/layoutengine/standard-testcases/inline_hyphenation_border.xml (limited to 'test') diff --git a/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java index bcc03b956..8d8de3d22 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java @@ -339,8 +339,11 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager oldListIterator = oldList.listIterator(); while (oldListIterator.hasNext()) { oldElement = (KnuthElement) oldListIterator.next(); - oldElement.setPosition - (notifyPos(new NonLeafPosition(this, oldElement.getPosition()))); + NonLeafPosition newPos = new NonLeafPosition(this, oldElement.getPosition()); + if (newPos.generatesAreas()) { + notifyPos(newPos); + } + oldElement.setPosition(newPos); } return bSomethingChanged; } diff --git a/test/layoutengine/standard-testcases/inline_hyphenation_border.xml b/test/layoutengine/standard-testcases/inline_hyphenation_border.xml new file mode 100644 index 000000000..f3c133e6e --- /dev/null +++ b/test/layoutengine/standard-testcases/inline_hyphenation_border.xml @@ -0,0 +1,49 @@ + + + + + +

+ This test checks whether the border is properly rendered with + hyphenation. I effectively checks whether + InlineStackingLM.applyChanges rewraps the positions properly. +

+
+ + + + + + + + + + + Test + + + + + + + + + + + +
-- cgit v1.2.3 From e058f4d959c3135516348affa098598fd835da50 Mon Sep 17 00:00:00 2001 From: Simon Pepping Date: Fri, 24 Dec 2010 19:28:11 +0000 Subject: Avoid unwrapping and rewrapping of Positions; use inspection instead. Remove unused method removeWordSpace git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1052561 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/fop/layoutmgr/Position.java | 29 +++- .../fop/layoutmgr/inline/ContentLayoutManager.java | 25 ++-- .../layoutmgr/inline/FootnoteLayoutManager.java | 5 +- .../fop/layoutmgr/inline/InlineLayoutManager.java | 4 +- .../layoutmgr/inline/InlineLevelLayoutManager.java | 30 ++++- .../inline/InlineStackingLayoutManager.java | 150 ++++++++++----------- .../layoutmgr/inline/LeafNodeLayoutManager.java | 29 ++-- .../fop/layoutmgr/inline/LineLayoutManager.java | 5 + .../fop/layoutmgr/inline/TextLayoutManager.java | 54 +++----- .../standard-testcases/inline_letter-spacing_3.xml | 2 +- 10 files changed, 188 insertions(+), 145 deletions(-) (limited to 'test') diff --git a/src/java/org/apache/fop/layoutmgr/Position.java b/src/java/org/apache/fop/layoutmgr/Position.java index 5cf6a893f..8230e64f0 100644 --- a/src/java/org/apache/fop/layoutmgr/Position.java +++ b/src/java/org/apache/fop/layoutmgr/Position.java @@ -48,14 +48,39 @@ public class Position { } /** - * Overridden by NonLeafPosition to return the Position of its - * child LM. + * @param depth the depth at which the LM in this position is found + * @return associated layout manager + */ + public LayoutManager getLM(int depth) { + Position subPos = getPosition(depth); + if (subPos == null) { + return null; + } else { + return subPos.getLM(); + } + } + + /** + * Overridden by NonLeafPosition to return the Position of its child LM. * @return a position or null */ public Position getPosition() { return null; } + /** + * Overridden by NonLeafPosition to return the Position of its child LM. + * @param depth the depth at which the position in this position is found + * @return a position or null + */ + public Position getPosition(int depth) { + Position subPos = this; + for (int i = 0; i < depth && subPos != null; ++i, subPos = subPos.getPosition()) { + // no-op + } + return subPos; + } + /** @return true if generates areas */ public boolean generatesAreas() { return false; diff --git a/src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java index 598a641d5..c7eaa1820 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java @@ -292,14 +292,9 @@ public class ContentLayoutManager extends AbstractBaseLayoutManager return oldList; } - /** - * Remove the word space represented by the given elements - * - * @param oldList the elements representing the word space - */ - public void removeWordSpace(List oldList) { - // do nothing - log.warn(this.getClass().getName() + " should not receive a call to removeWordSpace(list)"); + /** {@inheritDoc} */ + public List addALetterSpaceTo(List oldList, int depth) { + return addALetterSpaceTo(oldList); } /** {@inheritDoc} */ @@ -317,12 +312,20 @@ public class ContentLayoutManager extends AbstractBaseLayoutManager } /** {@inheritDoc} */ - public List getChangedKnuthElements(List oldList, - /*int flaggedPenalty,*/ - int alignment) { + public boolean applyChanges(List oldList, int depth) { + return applyChanges(oldList); + } + + /** {@inheritDoc} */ + public List getChangedKnuthElements(List oldList, int alignment) { return null; } + /** {@inheritDoc} */ + public List getChangedKnuthElements(List oldList, int alignment, int depth) { + return getChangedKnuthElements(oldList, alignment); + } + /** {@inheritDoc} */ public PageSequenceLayoutManager getPSLM() { return parentLM.getPSLM(); diff --git a/src/java/org/apache/fop/layoutmgr/inline/FootnoteLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/FootnoteLayoutManager.java index 2cdc7a6fc..efa6f880a 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/FootnoteLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/FootnoteLayoutManager.java @@ -122,9 +122,8 @@ public class FootnoteLayoutManager extends InlineStackingLayoutManager { /** * {@inheritDoc} */ - public List getChangedKnuthElements(List oldList, - int alignment) { - List returnedList = super.getChangedKnuthElements(oldList, alignment); + public List getChangedKnuthElements(List oldList, int alignment, int depth) { + List returnedList = super.getChangedKnuthElements(oldList, alignment, depth); addAnchor(returnedList); return returnedList; } diff --git a/src/java/org/apache/fop/layoutmgr/inline/InlineLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/InlineLayoutManager.java index 82285d106..1d3233112 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/InlineLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/InlineLayoutManager.java @@ -532,10 +532,10 @@ public class InlineLayoutManager extends InlineStackingLayoutManager { } /** {@inheritDoc} */ - public List getChangedKnuthElements(List oldList, int alignment) { + public List getChangedKnuthElements(List oldList, int alignment, int depth) { List returnedList = new LinkedList(); addKnuthElementsForBorderPaddingStart(returnedList); - returnedList.addAll(super.getChangedKnuthElements(oldList, alignment)); + returnedList.addAll(super.getChangedKnuthElements(oldList, alignment, depth)); addKnuthElementsForBorderPaddingEnd(returnedList); return returnedList; } diff --git a/src/java/org/apache/fop/layoutmgr/inline/InlineLevelLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/InlineLevelLayoutManager.java index 11f2ea000..ac829a2fc 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/InlineLevelLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/InlineLevelLayoutManager.java @@ -40,12 +40,15 @@ public interface InlineLevelLayoutManager extends LayoutManager { List addALetterSpaceTo(List oldList); /** - * Tell the LM to modify its data, removing the word space - * represented by the given elements + * Tell the LM to modify its data, adding a letter space + * to the word fragment represented by the given elements, + * and returning the corrected elements * - * @param oldList the elements representing the word space + * @param oldList the elements which must be given one more letter space + * @param depth the depth at which the Positions for this LM in oldList are found + * @return the new elements replacing the old ones */ - void removeWordSpace(List oldList); +List addALetterSpaceTo(List oldList, int depth); /** * Get the word chars corresponding to the given position. @@ -71,4 +74,23 @@ public interface InlineLevelLayoutManager extends LayoutManager { */ boolean applyChanges(List oldList); + /** + * Tell the LM to apply the changes due to hyphenation + * + * @param oldList the list of the old elements the changes refer to + * @param depth the depth at which the Positions for this LM in oldList are found + * @return true if the LM had to change its data, false otherwise + */ + boolean applyChanges(List oldList, int depth); + + /** + * Get a sequence of KnuthElements representing the content + * of the node assigned to the LM, after changes have been applied + * @param oldList the elements to replace + * @param alignment the desired text alignment + * @param depth the depth at which the Positions for this LM in oldList are found + * @return the updated list of KnuthElements + **/ + List getChangedKnuthElements(List oldList, int alignment, int depth); + } diff --git a/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java index 8d8de3d22..d8c4966d0 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/InlineStackingLayoutManager.java @@ -217,54 +217,48 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager /** {@inheritDoc} */ public List addALetterSpaceTo(List oldList) { + return addALetterSpaceTo(oldList, 0); + } + + /** {@inheritDoc} */ + public List addALetterSpaceTo(List oldList, int thisDepth) { // old list contains only a box, or the sequence: box penalty glue box - ListIterator oldListIterator = oldList.listIterator(); - KnuthElement element = null; - // "unwrap" the Position stored in each element of oldList - while (oldListIterator.hasNext()) { - element = (KnuthElement) oldListIterator.next(); - element.setPosition(element.getPosition().getPosition()); - } + ListIterator oldListIterator = oldList.listIterator(oldList.size()); + KnuthElement element = (KnuthElement) oldListIterator.previous(); + int depth = thisDepth + 1; // The last element may not have a layout manager (its position == null); // this may happen if it is a padding box; see bug 39571. - InlineLevelLayoutManager lm - = (InlineLevelLayoutManager) element.getLayoutManager(); - if (lm != null) { - oldList = lm.addALetterSpaceTo(oldList); + Position pos = element.getPosition(); + InlineLevelLayoutManager lm = null; + if (pos != null) { + lm = (InlineLevelLayoutManager) pos.getLM(depth); + } + if (lm == null) { + return oldList; } - // "wrap" again the Position stored in each element of oldList + oldList = lm.addALetterSpaceTo(oldList, depth); + // "wrap" the Position stored in new elements of oldList oldListIterator = oldList.listIterator(); while (oldListIterator.hasNext()) { element = (KnuthElement) oldListIterator.next(); - element.setPosition(notifyPos(new NonLeafPosition(this, element.getPosition()))); + pos = element.getPosition(); + lm = null; + if (pos != null) { + lm = (InlineLevelLayoutManager) pos.getLM(thisDepth); + } + // in old elements the position at thisDepth is a position for this LM + // only wrap new elements + if (lm != this) { + // new element, wrap position + element.setPosition(notifyPos(new NonLeafPosition(this, element.getPosition()))); + } } return oldList; } - /** - * remove the AreaInfo object represented by the given elements, - * so that it won't generate any element when getChangedKnuthElements - * will be called - * - * @param oldList the elements representing the word space - */ - public void removeWordSpace(List oldList) { - ListIterator oldListIterator = oldList.listIterator(); - KnuthElement element = null; - // "unwrap" the Position stored in each element of oldList - while (oldListIterator.hasNext()) { - element = (KnuthElement) oldListIterator.next(); - element.setPosition(element.getPosition().getPosition()); - } - - ((InlineLevelLayoutManager) - element.getLayoutManager()).removeWordSpace(oldList); - - } - /** {@inheritDoc} */ public String getWordChars(Position pos) { Position newPos = pos.getPosition(); @@ -280,17 +274,14 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager /** {@inheritDoc} */ public boolean applyChanges(List oldList) { - // "unwrap" the Positions stored in the elements + return applyChanges(oldList, 0); + } + + /** {@inheritDoc} */ + public boolean applyChanges(List oldList, int depth) { ListIterator oldListIterator = oldList.listIterator(); KnuthElement oldElement; - while (oldListIterator.hasNext()) { - oldElement = (KnuthElement) oldListIterator.next(); - if (oldElement.getPosition() != null) { - oldElement.setPosition(oldElement.getPosition().getPosition()); - } - } - // reset the iterator - oldListIterator = oldList.listIterator(); + depth += 1; InlineLevelLayoutManager prevLM = null; InlineLevelLayoutManager currLM; @@ -299,7 +290,12 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager boolean bSomethingChanged = false; while (oldListIterator.hasNext()) { oldElement = (KnuthElement) oldListIterator.next(); - currLM = (InlineLevelLayoutManager) oldElement.getLayoutManager(); + Position pos = oldElement.getPosition(); + if (pos == null) { + currLM = null; + } else { + currLM = (InlineLevelLayoutManager) pos.getLM(depth); + } // initialize prevLM if (prevLM == null) { prevLM = currLM; @@ -310,41 +306,34 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager prevLM = currLM; } else if (oldListIterator.hasNext()) { bSomethingChanged - = prevLM.applyChanges(oldList.subList(fromIndex - , oldListIterator.previousIndex())) + = prevLM.applyChanges(oldList.subList(fromIndex, + oldListIterator.previousIndex()), + depth) || bSomethingChanged; prevLM = currLM; fromIndex = oldListIterator.previousIndex(); } else if (currLM == prevLM) { bSomethingChanged = (prevLM != null) - && prevLM.applyChanges(oldList.subList(fromIndex, oldList.size())) + && prevLM.applyChanges(oldList.subList(fromIndex, + oldList.size()), depth) || bSomethingChanged; } else { bSomethingChanged - = prevLM.applyChanges(oldList.subList(fromIndex - , oldListIterator.previousIndex())) + = prevLM.applyChanges(oldList.subList(fromIndex, + oldListIterator.previousIndex()), + depth) || bSomethingChanged; if (currLM != null) { bSomethingChanged - = currLM.applyChanges(oldList.subList(oldListIterator.previousIndex() - , oldList.size())) + = currLM.applyChanges(oldList.subList(oldListIterator.previousIndex(), + oldList.size()), depth) || bSomethingChanged; } } } } - // "wrap" again the Positions stored in the elements - oldListIterator = oldList.listIterator(); - while (oldListIterator.hasNext()) { - oldElement = (KnuthElement) oldListIterator.next(); - NonLeafPosition newPos = new NonLeafPosition(this, oldElement.getPosition()); - if (newPos.generatesAreas()) { - notifyPos(newPos); - } - oldElement.setPosition(newPos); - } return bSomethingChanged; } @@ -352,16 +341,15 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager * {@inheritDoc} */ public List getChangedKnuthElements(List oldList, int alignment) { + return getChangedKnuthElements(oldList, alignment, 0); + } + + /** {@inheritDoc} */ + public List getChangedKnuthElements(List oldList, int alignment, int depth) { // "unwrap" the Positions stored in the elements ListIterator oldListIterator = oldList.listIterator(); KnuthElement oldElement; - while (oldListIterator.hasNext()) { - oldElement = (KnuthElement) oldListIterator.next(); - oldElement.setPosition - (oldElement.getPosition().getPosition()); - } - // reset the iterator - oldListIterator = oldList.listIterator(); + depth += 1; KnuthElement returnedElement; LinkedList returnedList = new LinkedList(); @@ -372,7 +360,12 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager while (oldListIterator.hasNext()) { oldElement = (KnuthElement) oldListIterator.next(); - currLM = (InlineLevelLayoutManager) oldElement.getLayoutManager(); + Position pos = oldElement.getPosition(); + if (pos == null) { + currLM = null; + } else { + currLM = (InlineLevelLayoutManager) pos.getLM(depth); + } if (prevLM == null) { prevLM = currLM; } @@ -381,33 +374,31 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager if (oldListIterator.hasNext()) { returnedList.addAll (prevLM.getChangedKnuthElements - (oldList.subList(fromIndex, - oldListIterator.previousIndex()), - /*flaggedPenalty,*/ alignment)); + (oldList.subList(fromIndex, oldListIterator.previousIndex()), + alignment, depth)); prevLM = currLM; fromIndex = oldListIterator.previousIndex(); } else if (currLM == prevLM) { returnedList.addAll (prevLM.getChangedKnuthElements (oldList.subList(fromIndex, oldList.size()), - /*flaggedPenalty,*/ alignment)); + alignment, depth)); } else { returnedList.addAll (prevLM.getChangedKnuthElements - (oldList.subList(fromIndex, - oldListIterator.previousIndex()), - /*flaggedPenalty,*/ alignment)); + (oldList.subList(fromIndex, oldListIterator.previousIndex()), + alignment, depth)); if (currLM != null) { returnedList.addAll (currLM.getChangedKnuthElements - (oldList.subList(oldListIterator.previousIndex(), - oldList.size()), - /*flaggedPenalty,*/ alignment)); + (oldList.subList(oldListIterator.previousIndex(), oldList.size()), + alignment, depth)); } } } } + // this is a new list // "wrap" the Position stored in each element of returnedList ListIterator listIter = returnedList.listIterator(); while (listIter.hasNext()) { @@ -416,6 +407,7 @@ public abstract class InlineStackingLayoutManager extends AbstractLayoutManager (notifyPos(new NonLeafPosition(this, returnedElement.getPosition()))); returnList.add(returnedElement); } + return returnList; } } diff --git a/src/java/org/apache/fop/layoutmgr/inline/LeafNodeLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/LeafNodeLayoutManager.java index 458110a89..f3749f2ed 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/LeafNodeLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/LeafNodeLayoutManager.java @@ -297,13 +297,11 @@ public abstract class LeafNodeLayoutManager extends AbstractLayoutManager } /** - * Remove the word space represented by the given elements - * - * @param oldList the elements representing the word space + * {@inheritDoc} + * Only TextLM has a meaningful implementation of this method */ - public void removeWordSpace(List oldList) { - // do nothing - log.warn(this.getClass().getName() + " should not receive a call to removeWordSpace(list)"); + public List addALetterSpaceTo(List oldList, int depth) { + return addALetterSpaceTo(oldList); } /** {@inheritDoc} */ @@ -321,9 +319,24 @@ public abstract class LeafNodeLayoutManager extends AbstractLayoutManager return false; } + /** + * {@inheritDoc} + * Only TextLM has a meaningful implementation of this method + */ + public boolean applyChanges(List oldList, int depth) { + return applyChanges(oldList); + } + + /** + * {@inheritDoc} + * No subclass has a meaningful implementation of this method + */ + public List getChangedKnuthElements(List oldList, int alignment, int depth) { + return getChangedKnuthElements(oldList, alignment); + } + /** {@inheritDoc} */ - public List getChangedKnuthElements(List oldList, - int alignment) { + public List getChangedKnuthElements(List oldList, int alignment) { if (isFinished()) { return null; } diff --git a/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java index 43276b630..2611a8cd5 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java @@ -1167,6 +1167,11 @@ public class LineLayoutManager extends InlineStackingLayoutManager /** {@inheritDoc} */ @Override + public List getChangedKnuthElements(List oldList, int alignment, int depth) { + return getChangedKnuthElements(oldList, alignment); + } + + /** {@inheritDoc} */ public List getChangedKnuthElements(List oldList, int alignment) { List returnList = new LinkedList(); for (int p = 0; p < knuthParagraphs.size(); p++) { diff --git a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java index 498fd1265..3f5ed329a 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java @@ -844,14 +844,20 @@ public class TextLayoutManager extends LeafNodeLayoutManager { } /** {@inheritDoc} */ - public List addALetterSpaceTo(final List oldList) { + public List addALetterSpaceTo(List oldList) { + return addALetterSpaceTo(oldList, 0); + } + + /** {@inheritDoc} */ + public List addALetterSpaceTo(final List oldList, int depth) { // old list contains only a box, or the sequence: box penalty glue box; // look at the Position stored in the first element in oldList // which is always a box ListIterator oldListIterator = oldList.listIterator(); KnuthElement knuthElement = (KnuthElement) oldListIterator.next(); - LeafPosition pos = (LeafPosition) ((KnuthBox) knuthElement).getPosition(); - int index = pos.getLeafPos(); + Position pos = knuthElement.getPosition(); + LeafPosition leafPos = (LeafPosition) pos.getPosition(depth); + int index = leafPos.getLeafPos(); //element could refer to '-1' position, for non-collapsed spaces (?) if (index > -1) { AreaInfo areaInfo = getAreaInfo(index); @@ -866,6 +872,7 @@ public class TextLayoutManager extends LeafNodeLayoutManager { oldListIterator.add(new KnuthGlue(letterSpaceIPD, auxiliaryPosition, false)); } else if (letterSpaceIPD.isStiff()) { // constant letter space: replace the box + // give it the unwrapped position of the replaced element oldListIterator.set(new KnuthInlineBox(areaInfo.areaIPD.getOpt(), alignmentContext, pos, false)); } else { @@ -879,36 +886,6 @@ public class TextLayoutManager extends LeafNodeLayoutManager { return oldList; } - /** - * Removes the AreaInfo object represented by the given elements, so that it won't - * generate any element when getChangedKnuthElements is called. - * - * @param oldList the elements representing the word space - */ - public void removeWordSpace(final List oldList) { - // find the element storing the Position whose value - // points to the AreaInfo object - final ListIterator oldListIterator = oldList.listIterator(); - if (((KnuthElement) ((LinkedList) oldList).getFirst()).isPenalty()) { - // non breaking space: oldList starts with a penalty - oldListIterator.next(); - } - if (oldList.size() > 2) { - // alignment is either center, start or end: - // the first two elements does not store the needed Position - oldListIterator.next(); - oldListIterator.next(); - } - KnuthElement knuthElement = (KnuthElement) oldListIterator.next(); - int leafValue = ((LeafPosition) knuthElement.getPosition()).getLeafPos(); - // only the last word space can be a trailing space! - if (leafValue == areaInfos.size() - 1) { - areaInfos.remove(leafValue); - } else { - TextLayoutManager.LOG.error("trying to remove a non-trailing word space"); - } - } - /** {@inheritDoc} */ public void hyphenate(Position pos, HyphContext hyphContext) { AreaInfo areaInfo = getAreaInfo(((LeafPosition) pos).getLeafPos() + changeOffset); @@ -976,6 +953,11 @@ public class TextLayoutManager extends LeafNodeLayoutManager { /** {@inheritDoc} */ public boolean applyChanges(final List oldList) { + return applyChanges(oldList, 0); + } + + /** {@inheritDoc} */ + public boolean applyChanges(final List oldList, int depth) { // make sure the LM appears unfinished in between this call // and the next call to getChangedKnuthElements() @@ -990,13 +972,15 @@ public class TextLayoutManager extends LeafNodeLayoutManager { LeafPosition startPos = null, endPos = null; ListIterator oldListIter; for (oldListIter = oldList.listIterator(); oldListIter.hasNext();) { - startPos = (LeafPosition) ((KnuthElement) oldListIter.next()).getPosition(); + Position pos = ((KnuthElement) oldListIter.next()).getPosition(); + startPos = (LeafPosition) pos.getPosition(depth); if (startPos != null && startPos.getLeafPos() != -1) { break; } } for (oldListIter = oldList.listIterator(oldList.size()); oldListIter.hasPrevious();) { - endPos = (LeafPosition) ((KnuthElement) oldListIter.previous()).getPosition(); + Position pos = ((KnuthElement) oldListIter.previous()).getPosition(); + endPos = (LeafPosition) pos.getPosition(depth); if (endPos != null && endPos.getLeafPos() != -1) { break; } diff --git a/test/layoutengine/standard-testcases/inline_letter-spacing_3.xml b/test/layoutengine/standard-testcases/inline_letter-spacing_3.xml index b86162ac1..39eac6d40 100644 --- a/test/layoutengine/standard-testcases/inline_letter-spacing_3.xml +++ b/test/layoutengine/standard-testcases/inline_letter-spacing_3.xml @@ -48,7 +48,7 @@
- Date: Tue, 4 Jan 2011 13:36:10 +0000 Subject: Add type-safe parameters to collections; replace XGC jar to benefit from new type-safe methods git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1055034 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/fop/plan/PlanElementMapping.java | 2 +- lib/xmlgraphics-commons-1.5svn.jar | Bin 743264 -> 765844 bytes src/java/org/apache/fop/fo/ElementMapping.java | 8 ++++---- .../org/apache/fop/fo/ElementMappingRegistry.java | 16 +++++++++------- src/java/org/apache/fop/fo/FOElementMapping.java | 2 +- .../fop/fo/extensions/ExtensionElementMapping.java | 6 +++--- .../fop/fo/extensions/InternalElementMapping.java | 4 ++-- .../fo/extensions/OldExtensionElementMapping.java | 2 +- .../svg/BatikExtensionElementMapping.java | 2 +- .../fop/fo/extensions/svg/SVGElementMapping.java | 2 +- .../fop/fo/extensions/xmp/RDFElementMapping.java | 2 +- .../fop/fo/extensions/xmp/XMPElementMapping.java | 2 +- .../org/apache/fop/render/XMLHandlerRegistry.java | 20 ++++++++++---------- .../render/afp/extensions/AFPElementMapping.java | 2 +- .../render/pcl/extensions/PCLElementMapping.java | 2 +- .../render/pdf/extensions/PDFElementMapping.java | 2 +- .../ps/extensions/PSExtensionElementMapping.java | 2 +- .../fop/fotreetest/ext/TestElementMapping.java | 2 +- 18 files changed, 40 insertions(+), 38 deletions(-) (limited to 'test') diff --git a/examples/plan/src/org/apache/fop/plan/PlanElementMapping.java b/examples/plan/src/org/apache/fop/plan/PlanElementMapping.java index 781fd8371..5b8a0b5bb 100644 --- a/examples/plan/src/org/apache/fop/plan/PlanElementMapping.java +++ b/examples/plan/src/org/apache/fop/plan/PlanElementMapping.java @@ -45,7 +45,7 @@ public class PlanElementMapping extends ElementMapping { /** {@inheritDoc} */ protected void initialize() { if (foObjs == null) { - foObjs = new java.util.HashMap(); + foObjs = new java.util.HashMap(); foObjs.put("plan", new PE()); foObjs.put(DEFAULT, new PlanMaker()); } diff --git a/lib/xmlgraphics-commons-1.5svn.jar b/lib/xmlgraphics-commons-1.5svn.jar index c152d2d5b..b11bfd2d2 100644 Binary files a/lib/xmlgraphics-commons-1.5svn.jar and b/lib/xmlgraphics-commons-1.5svn.jar differ diff --git a/src/java/org/apache/fop/fo/ElementMapping.java b/src/java/org/apache/fop/fo/ElementMapping.java index 1651f23a6..5417586e0 100644 --- a/src/java/org/apache/fop/fo/ElementMapping.java +++ b/src/java/org/apache/fop/fo/ElementMapping.java @@ -19,7 +19,7 @@ package org.apache.fop.fo; -import java.util.HashMap; +import java.util.Map; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -30,7 +30,7 @@ import org.apache.xmlgraphics.util.QName; /** * Abstract base class for Element Mappings (including FO Element Mappings) - * which provide the framework of valid elements and attibutes for a given + * which provide the framework of valid elements and attributes for a given * namespace. */ public abstract class ElementMapping { @@ -38,7 +38,7 @@ public abstract class ElementMapping { public static final String DEFAULT = ""; /** The HashMap table of formatting objects defined by the ElementMapping */ - protected HashMap foObjs = null; + protected Map foObjs = null; //Please don't change that to java.util.Map as that can break extensions. /** The namespace for the ElementMapping */ @@ -49,7 +49,7 @@ public abstract class ElementMapping { * * @return Table of Maker objects for this ElementMapping */ - public HashMap getTable() { + public Map getTable() { if (foObjs == null) { initialize(); } diff --git a/src/java/org/apache/fop/fo/ElementMappingRegistry.java b/src/java/org/apache/fop/fo/ElementMappingRegistry.java index 4a6904f73..cf14fa281 100644 --- a/src/java/org/apache/fop/fo/ElementMappingRegistry.java +++ b/src/java/org/apache/fop/fo/ElementMappingRegistry.java @@ -48,12 +48,14 @@ public class ElementMappingRegistry { * Table mapping element names to the makers of objects * representing formatting objects. */ - protected Map fobjTable = new java.util.HashMap(); + protected Map> fobjTable + = new java.util.HashMap>(); /** * Map of mapped namespaces and their associated ElementMapping instances. */ - protected Map namespaces = new java.util.HashMap(); + protected Map namespaces + = new java.util.HashMap(); /** * Main constructor. Adds all default element mapping as well as detects ElementMapping @@ -70,10 +72,10 @@ public class ElementMappingRegistry { */ private void setupDefaultMappings() { // add mappings from available services - Iterator providers = Service.providers(ElementMapping.class, false); + Iterator providers = Service.providerNames(ElementMapping.class); if (providers != null) { while (providers.hasNext()) { - String mapping = (String)providers.next(); + String mapping = providers.next(); try { addElementMapping(mapping); } catch (IllegalArgumentException e) { @@ -129,13 +131,13 @@ public class ElementMappingRegistry { */ public Maker findFOMaker(String namespaceURI, String localName, Locator locator) throws FOPException { - Map table = (Map)fobjTable.get(namespaceURI); + Map table = fobjTable.get(namespaceURI); Maker fobjMaker = null; if (table != null) { - fobjMaker = (Maker)table.get(localName); + fobjMaker = table.get(localName); // try default if (fobjMaker == null) { - fobjMaker = (Maker)table.get(ElementMapping.DEFAULT); + fobjMaker = table.get(ElementMapping.DEFAULT); } } diff --git a/src/java/org/apache/fop/fo/FOElementMapping.java b/src/java/org/apache/fop/fo/FOElementMapping.java index 0a7e40955..8069880c6 100644 --- a/src/java/org/apache/fop/fo/FOElementMapping.java +++ b/src/java/org/apache/fop/fo/FOElementMapping.java @@ -44,7 +44,7 @@ public class FOElementMapping extends ElementMapping { */ protected void initialize() { if (foObjs == null) { - foObjs = new HashMap(); + foObjs = new HashMap(); // Declarations and Pagination and Layout Formatting Objects foObjs.put("root", new RootMaker()); diff --git a/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java b/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java index a12bed0fa..80a569c90 100644 --- a/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java +++ b/src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java @@ -37,8 +37,8 @@ public class ExtensionElementMapping extends ElementMapping { /** The FOP extension namespace URI */ public static final String URI = "http://xmlgraphics.apache.org/fop/extensions"; - private static final Set PROPERTY_ATTRIBUTES - = new java.util.HashSet(); + private static final Set PROPERTY_ATTRIBUTES + = new java.util.HashSet(); static { //These are FOP's standard extension properties (fox:*) @@ -63,7 +63,7 @@ public class ExtensionElementMapping extends ElementMapping { */ protected void initialize() { if (foObjs == null) { - foObjs = new HashMap(); + foObjs = new HashMap(); foObjs.put("outline", new UnknownXMLObj.Maker(URI)); foObjs.put("label", new UnknownXMLObj.Maker(URI)); foObjs.put("destination", new DestinationMaker()); diff --git a/src/java/org/apache/fop/fo/extensions/InternalElementMapping.java b/src/java/org/apache/fop/fo/extensions/InternalElementMapping.java index 7704c8de7..4798f5500 100644 --- a/src/java/org/apache/fop/fo/extensions/InternalElementMapping.java +++ b/src/java/org/apache/fop/fo/extensions/InternalElementMapping.java @@ -34,7 +34,7 @@ public class InternalElementMapping extends ElementMapping { /** The FOP extension namespace URI */ public static final String URI = "http://xmlgraphics.apache.org/fop/internal"; - private static final Set PROPERTY_ATTRIBUTES = new java.util.HashSet(); + private static final Set PROPERTY_ATTRIBUTES = new java.util.HashSet(); static { //These are FOP's extension properties for accessibility @@ -53,7 +53,7 @@ public class InternalElementMapping extends ElementMapping { */ protected void initialize() { if (foObjs == null) { - foObjs = new HashMap(); + foObjs = new HashMap(); } } diff --git a/src/java/org/apache/fop/fo/extensions/OldExtensionElementMapping.java b/src/java/org/apache/fop/fo/extensions/OldExtensionElementMapping.java index e5ab93c35..d1c671dbe 100644 --- a/src/java/org/apache/fop/fo/extensions/OldExtensionElementMapping.java +++ b/src/java/org/apache/fop/fo/extensions/OldExtensionElementMapping.java @@ -44,7 +44,7 @@ public class OldExtensionElementMapping extends ElementMapping { */ protected void initialize() { if (foObjs == null) { - foObjs = new HashMap(); + foObjs = new HashMap(); foObjs.put("outline", new UnknownXMLObj.Maker(URI)); foObjs.put("label", new UnknownXMLObj.Maker(URI)); } diff --git a/src/java/org/apache/fop/fo/extensions/svg/BatikExtensionElementMapping.java b/src/java/org/apache/fop/fo/extensions/svg/BatikExtensionElementMapping.java index 449258525..6103345cf 100644 --- a/src/java/org/apache/fop/fo/extensions/svg/BatikExtensionElementMapping.java +++ b/src/java/org/apache/fop/fo/extensions/svg/BatikExtensionElementMapping.java @@ -73,7 +73,7 @@ public class BatikExtensionElementMapping extends ElementMapping { XMLResourceDescriptor.setXMLParserClassName( getAParserClassName()); - foObjs = new HashMap(); + foObjs = new HashMap(); foObjs.put("batik", new SE()); foObjs.put(DEFAULT, new SVGMaker()); } catch (Throwable t) { diff --git a/src/java/org/apache/fop/fo/extensions/svg/SVGElementMapping.java b/src/java/org/apache/fop/fo/extensions/svg/SVGElementMapping.java index 167baf723..7120dbb59 100644 --- a/src/java/org/apache/fop/fo/extensions/svg/SVGElementMapping.java +++ b/src/java/org/apache/fop/fo/extensions/svg/SVGElementMapping.java @@ -80,7 +80,7 @@ public class SVGElementMapping extends ElementMapping { XMLResourceDescriptor.setXMLParserClassName( getAParserClassName()); - foObjs = new HashMap(); + foObjs = new HashMap(); foObjs.put("svg", new SE()); foObjs.put(DEFAULT, new SVGMaker()); } catch (Throwable t) { diff --git a/src/java/org/apache/fop/fo/extensions/xmp/RDFElementMapping.java b/src/java/org/apache/fop/fo/extensions/xmp/RDFElementMapping.java index ff84ee11f..a6befd710 100644 --- a/src/java/org/apache/fop/fo/extensions/xmp/RDFElementMapping.java +++ b/src/java/org/apache/fop/fo/extensions/xmp/RDFElementMapping.java @@ -45,7 +45,7 @@ public class RDFElementMapping extends ElementMapping { /** {@inheritDoc} */ protected void initialize() { if (foObjs == null) { - foObjs = new HashMap(); + foObjs = new HashMap(); foObjs.put("RDF", new RDFElementMaker()); } } diff --git a/src/java/org/apache/fop/fo/extensions/xmp/XMPElementMapping.java b/src/java/org/apache/fop/fo/extensions/xmp/XMPElementMapping.java index b2b3570f2..d934dc2b1 100644 --- a/src/java/org/apache/fop/fo/extensions/xmp/XMPElementMapping.java +++ b/src/java/org/apache/fop/fo/extensions/xmp/XMPElementMapping.java @@ -45,7 +45,7 @@ public class XMPElementMapping extends ElementMapping { /** {@inheritDoc} */ protected void initialize() { if (foObjs == null) { - foObjs = new HashMap(); + foObjs = new HashMap(); foObjs.put("xmpmeta", new XMPMetaElementMaker()); } } diff --git a/src/java/org/apache/fop/render/XMLHandlerRegistry.java b/src/java/org/apache/fop/render/XMLHandlerRegistry.java index 81d9fcc93..cad09bff9 100644 --- a/src/java/org/apache/fop/render/XMLHandlerRegistry.java +++ b/src/java/org/apache/fop/render/XMLHandlerRegistry.java @@ -39,7 +39,8 @@ public class XMLHandlerRegistry { private static Log log = LogFactory.getLog(XMLHandlerRegistry.class); /** Map containing XML handlers for various document types */ - private Map handlers = new java.util.HashMap(); + private Map> handlers + = new java.util.HashMap>(); /** * Default constructor. @@ -98,11 +99,10 @@ public class XMLHandlerRegistry { * @param ns Namespace URI * @param handler XMLHandler to use */ - private void addXMLHandler(String ns, - XMLHandler handler) { - List lst = (List)handlers.get(ns); + private void addXMLHandler(String ns, XMLHandler handler) { + List lst = handlers.get(ns); if (lst == null) { - lst = new java.util.ArrayList(); + lst = new java.util.ArrayList(); handlers.put(ns, lst); } lst.add(handler); @@ -118,21 +118,21 @@ public class XMLHandlerRegistry { public XMLHandler getXMLHandler(Renderer renderer, String ns) { XMLHandler handler; - List lst = (List)handlers.get(ns); + List lst = handlers.get(ns); handler = getXMLHandler(renderer, lst); if (handler == null) { - lst = (List)handlers.get(XMLHandler.HANDLE_ALL); + lst = handlers.get(XMLHandler.HANDLE_ALL); handler = getXMLHandler(renderer, lst); } return handler; } - private XMLHandler getXMLHandler(Renderer renderer, List lst) { + private XMLHandler getXMLHandler(Renderer renderer, List lst) { XMLHandler handler; if (lst != null) { for (int i = 0, c = lst.size(); i < c; i++) { //TODO Maybe add priorities later - handler = (XMLHandler)lst.get(i); + handler = lst.get(i); if (handler.supportsRenderer(renderer)) { return handler; } @@ -147,7 +147,7 @@ public class XMLHandlerRegistry { */ private void discoverXMLHandlers() { // add mappings from available services - Iterator providers = Service.providers(XMLHandler.class); + Iterator providers = Service.providers(XMLHandler.class); if (providers != null) { while (providers.hasNext()) { XMLHandler handler = (XMLHandler)providers.next(); diff --git a/src/java/org/apache/fop/render/afp/extensions/AFPElementMapping.java b/src/java/org/apache/fop/render/afp/extensions/AFPElementMapping.java index 580e9f800..4e4100bc7 100644 --- a/src/java/org/apache/fop/render/afp/extensions/AFPElementMapping.java +++ b/src/java/org/apache/fop/render/afp/extensions/AFPElementMapping.java @@ -73,7 +73,7 @@ public class AFPElementMapping extends ElementMapping { protected void initialize() { if (foObjs == null) { - super.foObjs = new java.util.HashMap(); + super.foObjs = new java.util.HashMap(); foObjs.put( TAG_LOGICAL_ELEMENT, new AFPTagLogicalElementMaker()); diff --git a/src/java/org/apache/fop/render/pcl/extensions/PCLElementMapping.java b/src/java/org/apache/fop/render/pcl/extensions/PCLElementMapping.java index 700a95c65..08f3a5f44 100644 --- a/src/java/org/apache/fop/render/pcl/extensions/PCLElementMapping.java +++ b/src/java/org/apache/fop/render/pcl/extensions/PCLElementMapping.java @@ -57,7 +57,7 @@ public class PCLElementMapping extends ElementMapping { protected void initialize() { if (foObjs == null) { - foObjs = new HashMap(); + foObjs = new HashMap(); //No extension elements, yet, only attributes } 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 55795f4fa..c70ed3635 100644 --- a/src/java/org/apache/fop/render/pdf/extensions/PDFElementMapping.java +++ b/src/java/org/apache/fop/render/pdf/extensions/PDFElementMapping.java @@ -38,7 +38,7 @@ public class PDFElementMapping extends ElementMapping { /** {@inheritDoc} */ protected void initialize() { if (foObjs == null) { - foObjs = new java.util.HashMap(); + foObjs = new java.util.HashMap(); foObjs.put(PDFEmbeddedFileElement.ELEMENT, new PDFEmbeddedFileMaker()); } } diff --git a/src/java/org/apache/fop/render/ps/extensions/PSExtensionElementMapping.java b/src/java/org/apache/fop/render/ps/extensions/PSExtensionElementMapping.java index 2044385a8..54806d047 100644 --- a/src/java/org/apache/fop/render/ps/extensions/PSExtensionElementMapping.java +++ b/src/java/org/apache/fop/render/ps/extensions/PSExtensionElementMapping.java @@ -38,7 +38,7 @@ public class PSExtensionElementMapping extends ElementMapping { /** {@inheritDoc} */ protected void initialize() { if (foObjs == null) { - foObjs = new java.util.HashMap(); + foObjs = new java.util.HashMap(); foObjs.put(PSSetupCodeElement.ELEMENT, new PSSetupCodeMaker()); foObjs.put(PSPageSetupCodeElement.ELEMENT, new PSPageSetupCodeMaker()); foObjs.put(PSSetPageDeviceElement.ELEMENT, new PSSetPageDeviceMaker()); diff --git a/test/java/org/apache/fop/fotreetest/ext/TestElementMapping.java b/test/java/org/apache/fop/fotreetest/ext/TestElementMapping.java index 1d9127d0c..eee0efac4 100644 --- a/test/java/org/apache/fop/fotreetest/ext/TestElementMapping.java +++ b/test/java/org/apache/fop/fotreetest/ext/TestElementMapping.java @@ -40,7 +40,7 @@ public class TestElementMapping extends ElementMapping { /** @see org.apache.fop.fo.ElementMapping#initialize() */ protected void initialize() { if (foObjs == null) { - foObjs = new java.util.HashMap(); + foObjs = new java.util.HashMap(); foObjs.put("assert", new AssertMaker()); } } -- cgit v1.2.3 From 4de3abbc235c7e7d8efa0bc9bfd2bfa701e1767b Mon Sep 17 00:00:00 2001 From: "Andreas L. Delmelle" Date: Fri, 7 Jan 2011 21:14:33 +0000 Subject: Bugzilla 48380: Avoid ClassCastException when using fox:widow-content-limit git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1056513 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/fop/layoutmgr/ElementListUtils.java | 80 +++++++++------------- status.xml | 3 + .../fox_widow-content-limit_bug48380.xml | 61 +++++++++++++++++ 3 files changed, 97 insertions(+), 47 deletions(-) create mode 100644 test/layoutengine/standard-testcases/fox_widow-content-limit_bug48380.xml (limited to 'test') diff --git a/src/java/org/apache/fop/layoutmgr/ElementListUtils.java b/src/java/org/apache/fop/layoutmgr/ElementListUtils.java index 6a843ac63..2bd6f429a 100644 --- a/src/java/org/apache/fop/layoutmgr/ElementListUtils.java +++ b/src/java/org/apache/fop/layoutmgr/ElementListUtils.java @@ -55,43 +55,7 @@ public final class ElementListUtils { * @return true if the constraint is bigger than the list contents */ public static boolean removeLegalBreaks(List elements, int constraint) { - int len = 0; - ListIterator iter = elements.listIterator(); - while (iter.hasNext()) { - ListElement el = (ListElement)iter.next(); - if (el.isPenalty()) { - KnuthPenalty penalty = (KnuthPenalty)el; - //Convert all penalties to break inhibitors - if (penalty.getPenalty() < KnuthPenalty.INFINITE) { - iter.set(new KnuthPenalty(penalty.getWidth(), KnuthPenalty.INFINITE, - penalty.isPenaltyFlagged(), penalty.getPosition(), - penalty.isAuxiliary())); - } - } else if (el.isGlue()) { - KnuthGlue glue = (KnuthGlue)el; - len += glue.getWidth(); - iter.previous(); - el = (ListElement)iter.previous(); - iter.next(); - if (el.isBox()) { - iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, - null, false)); - } - iter.next(); - } else if (el instanceof BreakElement) { - BreakElement breakEl = (BreakElement)el; - if (breakEl.getPenaltyValue() < KnuthPenalty.INFINITE) { - breakEl.setPenaltyValue(KnuthPenalty.INFINITE); - } - } else { - KnuthElement kel = (KnuthElement)el; - len += kel.getWidth(); - } - if (len >= constraint) { - return false; - } - } - return true; + return removeLegalBreaks(elements, constraint, false); } /** @@ -103,27 +67,48 @@ public final class ElementListUtils { * @return true if the constraint is bigger than the list contents */ public static boolean removeLegalBreaksFromEnd(List elements, int constraint) { + return removeLegalBreaks(elements, constraint, true); + } + + private static boolean removeLegalBreaks(List elements, int constraint, boolean fromEnd) { + int len = 0; - ListIterator i = elements.listIterator(elements.size()); - while (i.hasPrevious()) { - ListElement el = (ListElement)i.previous(); + ListElement el; + + for (ListIterator iter = elements.listIterator(fromEnd ? elements.size() : 0); + (fromEnd ? iter.hasPrevious() : iter.hasNext());) { + + if (fromEnd) { + el = (ListElement) iter.previous(); + } else { + el = (ListElement) iter.next(); + } + if (el.isPenalty()) { KnuthPenalty penalty = (KnuthPenalty)el; - //Convert all penalties to break inhibitors + //Convert penalty to break inhibitor if (penalty.getPenalty() < KnuthPenalty.INFINITE) { - i.set(new KnuthPenalty(penalty.getWidth(), KnuthPenalty.INFINITE, + iter.set(new KnuthPenalty(penalty.getWidth(), KnuthPenalty.INFINITE, penalty.isPenaltyFlagged(), penalty.getPosition(), penalty.isAuxiliary())); } } else if (el.isGlue()) { KnuthGlue glue = (KnuthGlue)el; len += glue.getWidth(); - el = (ListElement)i.previous(); - i.next(); + //check if previous is a box + if (!fromEnd) { + iter.previous(); + } + el = (ListElement)iter.previous(); + iter.next(); if (el.isBox()) { - i.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, + //add break inhibitor + iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, null, false)); } + if (!fromEnd) { + iter.next(); + } } else if (el.isUnresolvedElement()) { if (el instanceof BreakElement) { BreakElement breakEl = (BreakElement)el; @@ -138,10 +123,12 @@ public final class ElementListUtils { KnuthElement kel = (KnuthElement)el; len += kel.getWidth(); } + if (len >= constraint) { return false; } } + return true; } @@ -191,8 +178,7 @@ public final class ElementListUtils { * @return true if the list ends with a forced break */ public static boolean endsWithForcedBreak(List elems) { - ListElement last = (ListElement) ListUtil.getLast(elems); - return last.isForcedBreak(); + return ((ListElement) ListUtil.getLast(elems)).isForcedBreak(); } /** diff --git a/status.xml b/status.xml index 2f2608cfd..16ef4dfe6 100644 --- a/status.xml +++ b/status.xml @@ -58,6 +58,9 @@ documents. Example: the fix of marks layering will be such a case when it's done. --> + + Bugfix: avoid ClassCastException when using fox:widow-content-limit + Bugfix: content after forced break in block-container is not rendered. diff --git a/test/layoutengine/standard-testcases/fox_widow-content-limit_bug48380.xml b/test/layoutengine/standard-testcases/fox_widow-content-limit_bug48380.xml new file mode 100644 index 000000000..7dab0b3af --- /dev/null +++ b/test/layoutengine/standard-testcases/fox_widow-content-limit_bug48380.xml @@ -0,0 +1,61 @@ + + + + + +

+ Check for bug 48380: ClassCastException when using fox:widow-content-limit. +

+
+ + + + + + + + + + + + + + + + + + . + + + test + + + + + + + + + + + + + + + +
\ No newline at end of file -- cgit v1.2.3 From dfa4c54704d8c10499557fd6dc2ab4312aa84a2c Mon Sep 17 00:00:00 2001 From: "Andreas L. Delmelle" Date: Fri, 7 Jan 2011 21:22:40 +0000 Subject: Bugzilla 50471: Avoid ArrayIndexOutOfBoundsException for codepoints without a linebreak class git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1056518 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/fop/text/linebreak/LineBreakStatus.java | 1 + status.xml | 3 +++ test/java/org/apache/fop/text/linebreak/LineBreakStatusTest.java | 6 ++++++ test/java/org/apache/fop/text/linebreak/LineBreakUtilsTest.java | 1 + 4 files changed, 11 insertions(+) (limited to 'test') diff --git a/src/java/org/apache/fop/text/linebreak/LineBreakStatus.java b/src/java/org/apache/fop/text/linebreak/LineBreakStatus.java index df5027373..157a480cc 100644 --- a/src/java/org/apache/fop/text/linebreak/LineBreakStatus.java +++ b/src/java/org/apache/fop/text/linebreak/LineBreakStatus.java @@ -87,6 +87,7 @@ public class LineBreakStatus { /* Initial conversions */ switch (currentClass) { + case 0: // Unassigned codepoint: same treatment as AI case LineBreakUtils.LINE_BREAK_PROPERTY_AI: case LineBreakUtils.LINE_BREAK_PROPERTY_SG: case LineBreakUtils.LINE_BREAK_PROPERTY_XX: diff --git a/status.xml b/status.xml index 16ef4dfe6..7af44400e 100644 --- a/status.xml +++ b/status.xml @@ -58,6 +58,9 @@ documents. Example: the fix of marks layering will be such a case when it's done. --> + + Bugfix: avoid ArrayIndexOutOfBoundsException for codepoints without a linebreak class + Bugfix: avoid ClassCastException when using fox:widow-content-limit diff --git a/test/java/org/apache/fop/text/linebreak/LineBreakStatusTest.java b/test/java/org/apache/fop/text/linebreak/LineBreakStatusTest.java index 8d2936127..e9b2ff90d 100644 --- a/test/java/org/apache/fop/text/linebreak/LineBreakStatusTest.java +++ b/test/java/org/apache/fop/text/linebreak/LineBreakStatusTest.java @@ -320,6 +320,12 @@ public class LineBreakStatusTest extends TestCase { "^^^^^^" + "^" + "_^^^^" )); + // Unassigned codepoint: should yield same result as AL + assertTrue(testBreak( + "No" + "\u1F7E" + "break", + "^^" + "^" + "^^^^^" + )); + } /** diff --git a/test/java/org/apache/fop/text/linebreak/LineBreakUtilsTest.java b/test/java/org/apache/fop/text/linebreak/LineBreakUtilsTest.java index 31ad950c7..bb6d209c2 100644 --- a/test/java/org/apache/fop/text/linebreak/LineBreakUtilsTest.java +++ b/test/java/org/apache/fop/text/linebreak/LineBreakUtilsTest.java @@ -41,6 +41,7 @@ public class LineBreakUtilsTest extends TestCase { assertEquals(LineBreakUtils.getLineBreakProperty('\n'), LineBreakUtils.LINE_BREAK_PROPERTY_LF); assertEquals(LineBreakUtils.getLineBreakProperty('\r'), LineBreakUtils.LINE_BREAK_PROPERTY_CR); assertEquals(LineBreakUtils.getLineBreakProperty('('), LineBreakUtils.LINE_BREAK_PROPERTY_OP); + assertEquals(LineBreakUtils.getLineBreakProperty('\u1F7E'), 0); } public void testLineBreakPair() { -- cgit v1.2.3 From 23e1125a2bc0b1ede23e66384fef96eb7e6631d4 Mon Sep 17 00:00:00 2001 From: "Andreas L. Delmelle" Date: Sat, 8 Jan 2011 19:22:12 +0000 Subject: Property fixup git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1056772 13f79535-47bb-0310-9956-ffa450edef68 --- .../fox_widow-content-limit_bug48380.xml | 120 ++++++++++----------- 1 file changed, 60 insertions(+), 60 deletions(-) (limited to 'test') diff --git a/test/layoutengine/standard-testcases/fox_widow-content-limit_bug48380.xml b/test/layoutengine/standard-testcases/fox_widow-content-limit_bug48380.xml index 7dab0b3af..83d5bd499 100644 --- a/test/layoutengine/standard-testcases/fox_widow-content-limit_bug48380.xml +++ b/test/layoutengine/standard-testcases/fox_widow-content-limit_bug48380.xml @@ -1,61 +1,61 @@ - - - - - -

- Check for bug 48380: ClassCastException when using fox:widow-content-limit. -

-
- - - - - - - - - - - - - - - - - - . - - - test - - - - - - - - - - - - - - - + + + + + +

+ Check for bug 48380: ClassCastException when using fox:widow-content-limit. +

+
+ + + + + + + + + + + + + + + + + + . + + + test + + + + + + + + + + + + + + +
\ No newline at end of file -- cgit v1.2.3 From 092af3cf902f54c565b2e1780992c2ef09683d88 Mon Sep 17 00:00:00 2001 From: "Andreas L. Delmelle" Date: Sun, 9 Jan 2011 14:40:31 +0000 Subject: Bugzilla 49848: Correct behavior of keep-together.within-line in case of nested inlines git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1056945 13f79535-47bb-0310-9956-ffa450edef68 --- .../fop/layoutmgr/inline/TextLayoutManager.java | 2 +- status.xml | 3 +++ .../standard-testcases/inline_keep-together.xml | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) (limited to 'test') diff --git a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java index 3f5ed329a..81240dec0 100644 --- a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java +++ b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java @@ -705,7 +705,7 @@ public class TextLayoutManager extends LeafNodeLayoutManager { if (inWord) { processWord(alignment, sequence, prevAreaInfo, ch, false, false); } else if (inWhitespace) { - processWhitespace(alignment, sequence, true); + processWhitespace(alignment, sequence, !keepTogether); } else if (areaInfo != null) { processLeftoverAreaInfo(alignment, sequence, areaInfo, ch == CharUtilities.ZERO_WIDTH_SPACE); diff --git a/status.xml b/status.xml index 7af44400e..16054217d 100644 --- a/status.xml +++ b/status.xml @@ -58,6 +58,9 @@ documents. Example: the fix of marks layering will be such a case when it's done. --> + + Bugfix: correct behavior of keep-together.within-line in case there are nested inlines + Bugfix: avoid ArrayIndexOutOfBoundsException for codepoints without a linebreak class diff --git a/test/layoutengine/standard-testcases/inline_keep-together.xml b/test/layoutengine/standard-testcases/inline_keep-together.xml index 6ec4ce603..0c6ae682a 100644 --- a/test/layoutengine/standard-testcases/inline_keep-together.xml +++ b/test/layoutengine/standard-testcases/inline_keep-together.xml @@ -38,6 +38,22 @@ This is Blah blah blah blah! This is Blah blah blah blah! This is Blah blah blah blah! + + + This entire sentence + should be kept + together + on + one + very, + very, + very, + very, + long + line + + + @@ -54,6 +70,9 @@ + + +
-- cgit v1.2.3 From 5ebc03434135be54db61bd43b96c99d1519e4c7c Mon Sep 17 00:00:00 2001 From: Simon Pepping Date: Wed, 12 Jan 2011 09:40:10 +0000 Subject: move hyphenation-dependent testcase into hyphenation-testcases git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1058034 13f79535-47bb-0310-9956-ffa450edef68 --- .../inline_hyphenation_border.xml | 49 ++++++++++++++++++++++ .../inline_hyphenation_border.xml | 49 ---------------------- 2 files changed, 49 insertions(+), 49 deletions(-) create mode 100644 test/layoutengine/hyphenation-testcases/inline_hyphenation_border.xml delete mode 100644 test/layoutengine/standard-testcases/inline_hyphenation_border.xml (limited to 'test') diff --git a/test/layoutengine/hyphenation-testcases/inline_hyphenation_border.xml b/test/layoutengine/hyphenation-testcases/inline_hyphenation_border.xml new file mode 100644 index 000000000..f3c133e6e --- /dev/null +++ b/test/layoutengine/hyphenation-testcases/inline_hyphenation_border.xml @@ -0,0 +1,49 @@ + + + + + +

+ This test checks whether the border is properly rendered with + hyphenation. I effectively checks whether + InlineStackingLM.applyChanges rewraps the positions properly. +

+
+ + + + + + + + + + + Test + + + + + + + + + + + +
diff --git a/test/layoutengine/standard-testcases/inline_hyphenation_border.xml b/test/layoutengine/standard-testcases/inline_hyphenation_border.xml deleted file mode 100644 index f3c133e6e..000000000 --- a/test/layoutengine/standard-testcases/inline_hyphenation_border.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - -

- This test checks whether the border is properly rendered with - hyphenation. I effectively checks whether - InlineStackingLM.applyChanges rewraps the positions properly. -

-
- - - - - - - - - - - Test - - - - - - - - - - - -
-- cgit v1.2.3 From 4c8a18e4a5e33f473150b9e2f4a91461cb67cce9 Mon Sep 17 00:00:00 2001 From: Simon Pepping Date: Fri, 14 Jan 2011 11:15:16 +0000 Subject: Relative URIs in the configuration file are evaluated relative to the base URI of the configuration file git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1058945 13f79535-47bb-0310-9956-ffa450edef68 --- .../content/xdocs/trunk/configuration.xml | 3 ++ src/java/org/apache/fop/apps/FopFactory.java | 10 +++++ .../apache/fop/apps/FopFactoryConfigurator.java | 52 +++++++++++++++++++--- .../apache/fop/fonts/FontManagerConfigurator.java | 19 +++++++- status.xml | 4 ++ test/test-no-xml-metrics.xconf | 2 +- 6 files changed, 83 insertions(+), 7 deletions(-) (limited to 'test') diff --git a/src/documentation/content/xdocs/trunk/configuration.xml b/src/documentation/content/xdocs/trunk/configuration.xml index 3ef8795b7..26707edbf 100644 --- a/src/documentation/content/xdocs/trunk/configuration.xml +++ b/src/documentation/content/xdocs/trunk/configuration.xml @@ -89,6 +89,9 @@ disabled + + Relative URIs for the above three properties are evaluated relative to the base URI of the configuration file. If the configuration is provided programmatically, the base URI can be set with FopFactory.setUserConfigBaseURI; default is the current working directory. + hyphenation-pattern String, attribute lang, attribute country (optional) diff --git a/src/java/org/apache/fop/apps/FopFactory.java b/src/java/org/apache/fop/apps/FopFactory.java index b86c52cf6..181bc85da 100644 --- a/src/java/org/apache/fop/apps/FopFactory.java +++ b/src/java/org/apache/fop/apps/FopFactory.java @@ -24,6 +24,7 @@ import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; +import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -700,6 +701,15 @@ public class FopFactory implements ImageContext { config.setUserConfig(userConfig); } + /** + * Set the base URI for the user configuration + * Useful for programmatic configurations + * @param baseURI the base URI + */ + public void setUserConfigBaseURI(URI baseURI) { + config.setBaseURI(baseURI); + } + /** * Get the user configuration. * @return the user configuration diff --git a/src/java/org/apache/fop/apps/FopFactoryConfigurator.java b/src/java/org/apache/fop/apps/FopFactoryConfigurator.java index 161bd4a8f..6c1986cb2 100644 --- a/src/java/org/apache/fop/apps/FopFactoryConfigurator.java +++ b/src/java/org/apache/fop/apps/FopFactoryConfigurator.java @@ -22,6 +22,8 @@ package org.apache.fop.apps; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; @@ -78,6 +80,9 @@ public class FopFactoryConfigurator { /** Fop factory configuration */ private Configuration cfg = null; + /** The base URI of the configuration file **/ + private URI baseURI = null; + /** * Default constructor * @param factory fop factory @@ -130,17 +135,23 @@ public class FopFactoryConfigurator { // base definitions for relative path resolution if (cfg.getChild("base", false) != null) { + String path = cfg.getChild("base").getValue(null); + if (baseURI != null) { + path = baseURI.resolve(path).normalize().toString(); + } try { - factory.setBaseURL( - cfg.getChild("base").getValue(null)); + factory.setBaseURL(path); } catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); } } if (cfg.getChild("hyphenation-base", false) != null) { + String path = cfg.getChild("hyphenation-base").getValue(null); + if (baseURI != null) { + path = baseURI.resolve(path).normalize().toString(); + } try { - factory.setHyphenBaseURL( - cfg.getChild("hyphenation-base").getValue(null)); + factory.setHyphenBaseURL(path); } catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); } @@ -259,7 +270,7 @@ public class FopFactoryConfigurator { } // configure font manager - new FontManagerConfigurator(cfg).configure(factory.getFontManager(), strict); + new FontManagerConfigurator(cfg, baseURI).configure(factory.getFontManager(), strict); // configure image loader framework configureImageLoading(cfg.getChild("image-loading", false), strict); @@ -339,6 +350,7 @@ public class FopFactoryConfigurator { */ public void setUserConfig(Configuration cfg) throws FOPException { this.cfg = cfg; + setBaseURI(); configure(this.factory); } @@ -349,4 +361,34 @@ public class FopFactoryConfigurator { public Configuration getUserConfig() { return this.cfg; } + + /** + * @return the baseURI + */ + public URI getBaseURI() { + return baseURI; + } + + /** + * @param baseURI the baseURI to set + */ + public void setBaseURI(URI baseURI) { + this.baseURI = baseURI; + } + + private void setBaseURI() throws FOPException { + String[] locationParts = cfg.getLocation().split(":"); + try { + if (locationParts != null && locationParts.length >= 2 + && "file".equals(locationParts[0])) { + baseURI = new URI(locationParts[0], locationParts[1], null); + } + if (baseURI == null) { + baseURI = new File(System.getProperty("user.dir")).toURI(); + } + } catch (URISyntaxException e) { + throw new FOPException(e); + } + } + } diff --git a/src/java/org/apache/fop/fonts/FontManagerConfigurator.java b/src/java/org/apache/fop/fonts/FontManagerConfigurator.java index 421c99051..6935df7e3 100644 --- a/src/java/org/apache/fop/fonts/FontManagerConfigurator.java +++ b/src/java/org/apache/fop/fonts/FontManagerConfigurator.java @@ -21,6 +21,7 @@ package org.apache.fop.fonts; import java.io.File; import java.net.MalformedURLException; +import java.net.URI; import java.util.List; import java.util.regex.Pattern; @@ -43,6 +44,8 @@ public class FontManagerConfigurator { private final Configuration cfg; + private URI baseURI = null; + /** * Main constructor * @param cfg the font manager configuration object @@ -51,6 +54,16 @@ public class FontManagerConfigurator { this.cfg = cfg; } + /** + * Main constructor + * @param cfg the font manager configuration object + * @param baseURI the base URI of the configuration + */ + public FontManagerConfigurator(Configuration cfg, URI baseURI) { + this.cfg = cfg; + this.baseURI = baseURI; + } + /** * Initializes font settings from the user configuration * @param fontManager a font manager @@ -74,8 +87,12 @@ public class FontManagerConfigurator { } } if (cfg.getChild("font-base", false) != null) { + String path = cfg.getChild("font-base").getValue(null); + if (baseURI != null) { + path = baseURI.resolve(path).normalize().toString(); + } try { - fontManager.setFontBaseURL(cfg.getChild("font-base").getValue(null)); + fontManager.setFontBaseURL(path); } catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, true); } diff --git a/status.xml b/status.xml index 16054217d..c80ba0668 100644 --- a/status.xml +++ b/status.xml @@ -49,6 +49,7 @@ + @@ -58,6 +59,9 @@ documents. Example: the fix of marks layering will be such a case when it's done. --> + + Bugfix: relative URIs in the configuration file (base, font-base, hyphenation-base) are evaluated relative to the base URI of the configuration file. + Bugfix: correct behavior of keep-together.within-line in case there are nested inlines diff --git a/test/test-no-xml-metrics.xconf b/test/test-no-xml-metrics.xconf index beb24c0ef..6005eac94 100644 --- a/test/test-no-xml-metrics.xconf +++ b/test/test-no-xml-metrics.xconf @@ -7,7 +7,7 @@ ./ - ./test/resources/fonts + ./resources/fonts -- cgit v1.2.3 From 1eaae07e7db29a870d7dd037083a3e0fc9f7dc8c Mon Sep 17 00:00:00 2001 From: Simon Pepping Date: Fri, 14 Jan 2011 12:58:53 +0000 Subject: Fix deprecation warnings; add some type safety git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1058988 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/fop/events/Event.java | 13 ++-- .../apache/fop/events/EventExceptionManager.java | 11 ++-- .../fop/events/PropertyExceptionFactory.java | 2 +- .../UnsupportedOperationExceptionFactory.java | 2 +- .../fop/events/ValidationExceptionFactory.java | 2 +- .../fop/fo/pagination/PageProductionException.java | 2 +- .../org/apache/fop/layoutmgr/LayoutException.java | 2 +- .../fop/render/AbstractGraphics2DAdapter.java | 5 +- .../org/apache/fop/render/AbstractRenderer.java | 8 ++- .../apache/fop/render/pdf/PDFDocumentHandler.java | 4 +- src/java/org/apache/fop/util/ColorUtil.java | 11 ++-- .../fop/util/text/AdvancedMessageFormat.java | 73 +++++++++++----------- .../org/apache/fop/traits/BorderPropsTestCase.java | 3 +- .../org/apache/fop/util/ColorUtilTestCase.java | 10 +-- 14 files changed, 80 insertions(+), 68 deletions(-) (limited to 'test') diff --git a/src/java/org/apache/fop/events/Event.java b/src/java/org/apache/fop/events/Event.java index c48530c1c..ffec9473e 100644 --- a/src/java/org/apache/fop/events/Event.java +++ b/src/java/org/apache/fop/events/Event.java @@ -38,7 +38,7 @@ public class Event extends EventObject { private String eventKey; private EventSeverity severity; - private Map params; + private Map params; /** * Creates a new Event. @@ -47,7 +47,8 @@ public class Event extends EventObject { * @param severity the severity level * @param params the event parameters (a map of name/value pairs) */ - public Event(Object source, String eventID, EventSeverity severity, Map params) { + public Event(Object source, String eventID, EventSeverity severity, Map params) + { super(source); int pos = eventID.lastIndexOf('.'); if (pos < 0 || pos == eventID.length() - 1) { @@ -122,7 +123,7 @@ public class Event extends EventObject { * Returns an unmodifiable {@link java.util.Map} with all event parameters. * @return the parameter map */ - public Map getParams() { + public Map getParams() { return Collections.unmodifiableMap(this.params); } @@ -138,7 +139,7 @@ public class Event extends EventObject { * This class is a fluent builder class for building up the parameter map. */ public static class ParamsBuilder { - private Map params; + private Map params; /** * Adds a new parameter (a name/value pair). @@ -148,7 +149,7 @@ public class Event extends EventObject { */ public ParamsBuilder param(String name, Object value) { if (this.params == null) { - this.params = new java.util.HashMap(); + this.params = new java.util.HashMap(); } this.params.put(name, value); return this; @@ -158,7 +159,7 @@ public class Event extends EventObject { * Returns the accumulated parameter map. * @return the accumulated parameter map */ - public Map build() { + public Map build() { return this.params; } } diff --git a/src/java/org/apache/fop/events/EventExceptionManager.java b/src/java/org/apache/fop/events/EventExceptionManager.java index f7d679282..3494dc560 100644 --- a/src/java/org/apache/fop/events/EventExceptionManager.java +++ b/src/java/org/apache/fop/events/EventExceptionManager.java @@ -32,11 +32,12 @@ public final class EventExceptionManager { private EventExceptionManager() { } - private static final Map EXCEPTION_FACTORIES = new java.util.HashMap(); + private static final Map EXCEPTION_FACTORIES + = new java.util.HashMap(); static { - Iterator iter; - iter = Service.providers(ExceptionFactory.class, true); + Iterator iter; + iter = Service.providers(ExceptionFactory.class); while (iter.hasNext()) { ExceptionFactory factory = (ExceptionFactory)iter.next(); EXCEPTION_FACTORIES.put(factory.getExceptionClass().getName(), factory); @@ -63,7 +64,7 @@ public final class EventExceptionManager { String msg = EventFormatter.format(event); //Get original exception as cause if it is given as one of the parameters Throwable t = null; - Iterator iter = event.getParams().values().iterator(); + Iterator iter = event.getParams().values().iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof Throwable) { @@ -96,6 +97,6 @@ public final class EventExceptionManager { * Returns the {@link Exception} class created by this factory. * @return the exception class */ - Class getExceptionClass(); + Class getExceptionClass(); } } diff --git a/src/java/org/apache/fop/events/PropertyExceptionFactory.java b/src/java/org/apache/fop/events/PropertyExceptionFactory.java index 753019b31..d8c7f39fb 100644 --- a/src/java/org/apache/fop/events/PropertyExceptionFactory.java +++ b/src/java/org/apache/fop/events/PropertyExceptionFactory.java @@ -40,7 +40,7 @@ public class PropertyExceptionFactory implements ExceptionFactory { } /** {@inheritDoc} */ - public Class getExceptionClass() { + public Class getExceptionClass() { return PropertyException.class; } diff --git a/src/java/org/apache/fop/events/UnsupportedOperationExceptionFactory.java b/src/java/org/apache/fop/events/UnsupportedOperationExceptionFactory.java index 7ec9d19b2..570fcbd64 100644 --- a/src/java/org/apache/fop/events/UnsupportedOperationExceptionFactory.java +++ b/src/java/org/apache/fop/events/UnsupportedOperationExceptionFactory.java @@ -36,7 +36,7 @@ public class UnsupportedOperationExceptionFactory implements ExceptionFactory { } /** {@inheritDoc} */ - public Class getExceptionClass() { + public Class getExceptionClass() { return UnsupportedOperationException.class; } diff --git a/src/java/org/apache/fop/events/ValidationExceptionFactory.java b/src/java/org/apache/fop/events/ValidationExceptionFactory.java index 760c4ec58..2c7c69ce9 100644 --- a/src/java/org/apache/fop/events/ValidationExceptionFactory.java +++ b/src/java/org/apache/fop/events/ValidationExceptionFactory.java @@ -43,7 +43,7 @@ public class ValidationExceptionFactory implements ExceptionFactory { } /** {@inheritDoc} */ - public Class getExceptionClass() { + public Class getExceptionClass() { return ValidationException.class; } diff --git a/src/java/org/apache/fop/fo/pagination/PageProductionException.java b/src/java/org/apache/fop/fo/pagination/PageProductionException.java index bb09db6f4..39060f3d4 100644 --- a/src/java/org/apache/fop/fo/pagination/PageProductionException.java +++ b/src/java/org/apache/fop/fo/pagination/PageProductionException.java @@ -98,7 +98,7 @@ public class PageProductionException extends RuntimeException { } /** {@inheritDoc} */ - public Class getExceptionClass() { + public Class getExceptionClass() { return PageProductionException.class; } diff --git a/src/java/org/apache/fop/layoutmgr/LayoutException.java b/src/java/org/apache/fop/layoutmgr/LayoutException.java index 2638d0210..f22d34bd8 100644 --- a/src/java/org/apache/fop/layoutmgr/LayoutException.java +++ b/src/java/org/apache/fop/layoutmgr/LayoutException.java @@ -97,7 +97,7 @@ public class LayoutException extends RuntimeException { } /** {@inheritDoc} */ - public Class getExceptionClass() { + public Class getExceptionClass() { return LayoutException.class; } diff --git a/src/java/org/apache/fop/render/AbstractGraphics2DAdapter.java b/src/java/org/apache/fop/render/AbstractGraphics2DAdapter.java index f5a51b058..913a72b0d 100644 --- a/src/java/org/apache/fop/render/AbstractGraphics2DAdapter.java +++ b/src/java/org/apache/fop/render/AbstractGraphics2DAdapter.java @@ -148,7 +148,10 @@ public abstract class AbstractGraphics2DAdapter implements Graphics2DAdapter { RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + * @deprecated + */ public void paintImage(Graphics2DImagePainter painter, RendererContext context, int x, int y, int width, int height) throws IOException { diff --git a/src/java/org/apache/fop/render/AbstractRenderer.java b/src/java/org/apache/fop/render/AbstractRenderer.java index d70d8113f..273f0bc16 100644 --- a/src/java/org/apache/fop/render/AbstractRenderer.java +++ b/src/java/org/apache/fop/render/AbstractRenderer.java @@ -208,15 +208,17 @@ public abstract class AbstractRenderer return sb.toString(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + * @deprecated + */ public void startPageSequence(LineArea seqTitle) { //do nothing } /** {@inheritDoc} */ public void startPageSequence(PageSequence pageSequence) { - //TODO Discuss removing old deprecated method startPageSequence(LineArea) - startPageSequence(pageSequence.getTitle()); + // do nothing } // normally this would be overriden to create a page in the diff --git a/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java b/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java index 1cf291112..c1d959dd1 100644 --- a/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java +++ b/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java @@ -92,8 +92,8 @@ public class PDFDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { protected PageReference currentPageRef; /** Used for bookmarks/outlines. */ - protected Map pageReferences = - new java.util.HashMap(); + protected Map pageReferences + = new java.util.HashMap(); private final PDFDocumentNavigationHandler documentNavigationHandler = new PDFDocumentNavigationHandler(this); diff --git a/src/java/org/apache/fop/util/ColorUtil.java b/src/java/org/apache/fop/util/ColorUtil.java index 21277d60a..674079369 100644 --- a/src/java/org/apache/fop/util/ColorUtil.java +++ b/src/java/org/apache/fop/util/ColorUtil.java @@ -27,6 +27,7 @@ import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.xmlgraphics.java2d.color.ColorSpaces; import org.apache.xmlgraphics.java2d.color.DeviceCMYKColorSpace; import org.apache.fop.apps.FOUserAgent; @@ -50,7 +51,7 @@ public final class ColorUtil { * This map is used to predefine given colors, as well as speeding up * parsing of already parsed colors. */ - private static Map colorMap = null; + private static Map colorMap = null; /** Logger instance */ protected static final Log log = LogFactory.getLog(ColorUtil.class); @@ -328,7 +329,7 @@ public final class ColorUtil { String iccProfileSrc = null; if (isPseudoProfile(iccProfileName)) { if (CMYK_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) { - colorSpace = DeviceCMYKColorSpace.getInstance(); + colorSpace = ColorSpaces.getDeviceCMYKColorSpace(); } else { assert false : "Incomplete implementation"; } @@ -453,7 +454,7 @@ public final class ColorUtil { + "Arguments to cmyk() must be in the range [0%-100%] or [0.0-1.0]"); } float[] cmyk = new float[] {cyan, magenta, yellow, black}; - DeviceCMYKColorSpace cmykCs = DeviceCMYKColorSpace.getInstance(); + DeviceCMYKColorSpace cmykCs = ColorSpaces.getDeviceCMYKColorSpace(); float[] rgb = cmykCs.toRGB(cmyk); parsedColor = ColorExt.createFromFoRgbIcc(rgb[0], rgb[1], rgb[2], CMYK_PSEUDO_PROFILE, null, cmykCs, cmyk); @@ -521,7 +522,7 @@ public final class ColorUtil { * Initializes the colorMap with some predefined values. */ private static void initializeColorMap() { // CSOK: MethodLength - colorMap = Collections.synchronizedMap(new java.util.HashMap()); + colorMap = Collections.synchronizedMap(new java.util.HashMap()); colorMap.put("aliceblue", new Color(240, 248, 255)); colorMap.put("antiquewhite", new Color(250, 235, 215)); @@ -710,7 +711,7 @@ public final class ColorUtil { */ public static Color toCMYKGrayColor(float black) { float[] cmyk = new float[] {0f, 0f, 0f, 1.0f - black}; - DeviceCMYKColorSpace cmykCs = DeviceCMYKColorSpace.getInstance(); + DeviceCMYKColorSpace cmykCs = ColorSpaces.getDeviceCMYKColorSpace(); float[] rgb = cmykCs.toRGB(cmyk); return ColorExt.createFromFoRgbIcc(rgb[0], rgb[1], rgb[2], CMYK_PSEUDO_PROFILE, null, cmykCs, cmyk); diff --git a/src/java/org/apache/fop/util/text/AdvancedMessageFormat.java b/src/java/org/apache/fop/util/text/AdvancedMessageFormat.java index 002b3f95c..41b70046c 100644 --- a/src/java/org/apache/fop/util/text/AdvancedMessageFormat.java +++ b/src/java/org/apache/fop/util/text/AdvancedMessageFormat.java @@ -46,24 +46,27 @@ public class AdvancedMessageFormat { /** Regex that matches "," but not "\," (escaped comma) */ static final Pattern COMMA_SEPARATOR_REGEX = Pattern.compile("(? PART_FACTORIES + = new java.util.HashMap(); + private static final List OBJECT_FORMATTERS + = new java.util.ArrayList(); + private static final Map FUNCTIONS + = new java.util.HashMap(); private CompositePart rootPart; static { - Iterator iter; - iter = Service.providers(PartFactory.class, true); + Iterator iter; + iter = Service.providers(PartFactory.class); while (iter.hasNext()) { PartFactory factory = (PartFactory)iter.next(); PART_FACTORIES.put(factory.getFormat(), factory); } - iter = Service.providers(ObjectFormatter.class, true); + iter = Service.providers(ObjectFormatter.class); while (iter.hasNext()) { OBJECT_FORMATTERS.add((ObjectFormatter)iter.next()); } - iter = Service.providers(Function.class, true); + iter = Service.providers(Function.class); while (iter.hasNext()) { Function function = (Function)iter.next(); FUNCTIONS.put(function.getName(), function); @@ -189,7 +192,7 @@ public class AdvancedMessageFormat { * @param params a Map of named parameters (Contents: ) * @return the formatted message */ - public String format(Map params) { + public String format(Map params) { StringBuffer sb = new StringBuffer(); format(params, sb); return sb.toString(); @@ -200,7 +203,7 @@ public class AdvancedMessageFormat { * @param params a Map of named parameters (Contents: ) * @param target the target StringBuffer to write the formatted message to */ - public void format(Map params, StringBuffer target) { + public void format(Map params, StringBuffer target) { rootPart.write(target, params); } @@ -215,14 +218,14 @@ public class AdvancedMessageFormat { * @param sb the target string buffer * @param params the parameters to work with */ - void write(StringBuffer sb, Map params); + void write(StringBuffer sb, Map params); /** * Indicates whether there is any content that is generated by this message part. * @param params the parameters to work with * @return true if the part has content */ - boolean isGenerated(Map params); + boolean isGenerated(Map params); } /** @@ -277,7 +280,7 @@ public class AdvancedMessageFormat { * @param params the message parameters * @return the function result */ - Object evaluate(Map params); + Object evaluate(Map params); /** * Returns the name of the function. @@ -294,11 +297,11 @@ public class AdvancedMessageFormat { this.text = text; } - public void write(StringBuffer sb, Map params) { + public void write(StringBuffer sb, Map params) { sb.append(text); } - public boolean isGenerated(Map params) { + public boolean isGenerated(Map params) { return true; } @@ -316,7 +319,7 @@ public class AdvancedMessageFormat { this.fieldName = fieldName; } - public void write(StringBuffer sb, Map params) { + public void write(StringBuffer sb, Map params) { if (!params.containsKey(fieldName)) { throw new IllegalArgumentException( "Message pattern contains unsupported field name: " + fieldName); @@ -325,7 +328,7 @@ public class AdvancedMessageFormat { formatObject(obj, sb); } - public boolean isGenerated(Map params) { + public boolean isGenerated(Map params) { Object obj = params.get(fieldName); return obj != null; } @@ -349,9 +352,9 @@ public class AdvancedMessageFormat { target.append(obj); } else { boolean handled = false; - Iterator iter = OBJECT_FORMATTERS.iterator(); + Iterator iter = OBJECT_FORMATTERS.iterator(); while (iter.hasNext()) { - ObjectFormatter formatter = (ObjectFormatter)iter.next(); + ObjectFormatter formatter = iter.next(); if (formatter.supportsObject(obj)) { formatter.format(target, obj); handled = true; @@ -375,12 +378,12 @@ public class AdvancedMessageFormat { } } - public void write(StringBuffer sb, Map params) { + public void write(StringBuffer sb, Map params) { Object obj = this.function.evaluate(params); formatObject(obj, sb); } - public boolean isGenerated(Map params) { + public boolean isGenerated(Map params) { Object obj = this.function.evaluate(params); return obj != null; } @@ -393,7 +396,7 @@ public class AdvancedMessageFormat { private static class CompositePart implements Part { - protected List parts = new java.util.ArrayList(); + protected List parts = new java.util.ArrayList(); private boolean conditional; private boolean hasSections = false; @@ -401,7 +404,7 @@ public class AdvancedMessageFormat { this.conditional = conditional; } - private CompositePart(List parts) { + private CompositePart(List parts) { this.parts.addAll(parts); this.conditional = true; } @@ -411,7 +414,7 @@ public class AdvancedMessageFormat { throw new NullPointerException("part must not be null"); } if (hasSections) { - CompositePart composite = (CompositePart)this.parts.get(this.parts.size() - 1); + CompositePart composite = (CompositePart) this.parts.get(this.parts.size() - 1); composite.addChild(part); } else { this.parts.add(part); @@ -420,20 +423,20 @@ public class AdvancedMessageFormat { public void newSection() { if (!hasSections) { - List p = this.parts; + List p = this.parts; //Dropping into a different mode... - this.parts = new java.util.ArrayList(); + this.parts = new java.util.ArrayList(); this.parts.add(new CompositePart(p)); hasSections = true; } this.parts.add(new CompositePart(true)); } - public void write(StringBuffer sb, Map params) { + public void write(StringBuffer sb, Map params) { if (hasSections) { - Iterator iter = this.parts.iterator(); + Iterator iter = this.parts.iterator(); while (iter.hasNext()) { - CompositePart part = (CompositePart)iter.next(); + Part part = iter.next(); if (part.isGenerated(params)) { part.write(sb, params); break; @@ -441,20 +444,20 @@ public class AdvancedMessageFormat { } } else { if (isGenerated(params)) { - Iterator iter = this.parts.iterator(); + Iterator iter = this.parts.iterator(); while (iter.hasNext()) { - Part part = (Part)iter.next(); + Part part = iter.next(); part.write(sb, params); } } } } - public boolean isGenerated(Map params) { + public boolean isGenerated(Map params) { if (hasSections) { - Iterator iter = this.parts.iterator(); + Iterator iter = this.parts.iterator(); while (iter.hasNext()) { - Part part = (Part)iter.next(); + Part part = iter.next(); if (part.isGenerated(params)) { return true; } @@ -462,9 +465,9 @@ public class AdvancedMessageFormat { return false; } else { if (conditional) { - Iterator iter = this.parts.iterator(); + Iterator iter = this.parts.iterator(); while (iter.hasNext()) { - Part part = (Part)iter.next(); + Part part = iter.next(); if (!part.isGenerated(params)) { return false; } diff --git a/test/java/org/apache/fop/traits/BorderPropsTestCase.java b/test/java/org/apache/fop/traits/BorderPropsTestCase.java index be7714ba2..e142a4358 100644 --- a/test/java/org/apache/fop/traits/BorderPropsTestCase.java +++ b/test/java/org/apache/fop/traits/BorderPropsTestCase.java @@ -23,6 +23,7 @@ import java.awt.Color; import junit.framework.TestCase; +import org.apache.xmlgraphics.java2d.color.ColorSpaces; import org.apache.xmlgraphics.java2d.color.DeviceCMYKColorSpace; import org.apache.fop.fo.Constants; @@ -50,7 +51,7 @@ public class BorderPropsTestCase extends TestCase { assertEquals(b1, b2); float[] cmyk = new float[] {1.0f, 1.0f, 0.5f, 1.0f}; - DeviceCMYKColorSpace cmykCs = DeviceCMYKColorSpace.getInstance(); + DeviceCMYKColorSpace cmykCs = ColorSpaces.getDeviceCMYKColorSpace(); float[] rgb = cmykCs.toRGB(cmyk); col = ColorExt.createFromFoRgbIcc(rgb[0], rgb[1], rgb[2], "#CMYK", null, cmykCs, cmyk); diff --git a/test/java/org/apache/fop/util/ColorUtilTestCase.java b/test/java/org/apache/fop/util/ColorUtilTestCase.java index aefd2a76a..c2fb0fbc9 100644 --- a/test/java/org/apache/fop/util/ColorUtilTestCase.java +++ b/test/java/org/apache/fop/util/ColorUtilTestCase.java @@ -24,7 +24,7 @@ import java.awt.color.ColorSpace; import junit.framework.TestCase; -import org.apache.xmlgraphics.java2d.color.DeviceCMYKColorSpace; +import org.apache.xmlgraphics.java2d.color.ColorSpaces; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.FopFactory; @@ -156,7 +156,7 @@ public class ColorUtilTestCase extends TestCase { assertEquals(255, colActual.getRed()); assertEquals(255, colActual.getGreen()); assertEquals(0, colActual.getBlue()); - assertEquals(DeviceCMYKColorSpace.getInstance(), colActual.getColorSpace()); + assertEquals(ColorSpaces.getDeviceCMYKColorSpace(), colActual.getColorSpace()); float[] comps = colActual.getColorComponents(null); assertEquals(4, comps.length); assertEquals(0f, comps[0], 0); @@ -171,7 +171,7 @@ public class ColorUtilTestCase extends TestCase { assertEquals(248, colActual.getRed()); assertEquals(199, colActual.getGreen()); assertEquals(172, colActual.getBlue()); - assertEquals(DeviceCMYKColorSpace.getInstance(), colActual.getColorSpace()); + assertEquals(ColorSpaces.getDeviceCMYKColorSpace(), colActual.getColorSpace()); comps = colActual.getColorComponents(null); assertEquals(0.0274f, comps[0], 0.001); assertEquals(0.2196f, comps[1], 0.001); @@ -185,7 +185,7 @@ public class ColorUtilTestCase extends TestCase { assertEquals(255, colActual.getRed()); assertEquals(255, colActual.getGreen()); assertEquals(0, colActual.getBlue()); - assertEquals(DeviceCMYKColorSpace.getInstance(), colActual.getColorSpace()); + assertEquals(ColorSpaces.getDeviceCMYKColorSpace(), colActual.getColorSpace()); comps = colActual.getColorComponents(null); assertEquals(4, comps.length); assertEquals(0f, comps[0], 0); @@ -200,7 +200,7 @@ public class ColorUtilTestCase extends TestCase { assertEquals(127, colActual.getRed()); assertEquals(127, colActual.getGreen()); assertEquals(127, colActual.getBlue()); - assertEquals(DeviceCMYKColorSpace.getInstance(), colActual.getColorSpace()); + assertEquals(ColorSpaces.getDeviceCMYKColorSpace(), colActual.getColorSpace()); comps = colActual.getColorComponents(null); assertEquals(4, comps.length); assertEquals(0f, comps[0], 0); -- cgit v1.2.3 From 678138119f6087108d6ff94041796e5a6960ecf3 Mon Sep 17 00:00:00 2001 From: "Andreas L. Delmelle" Date: Sat, 15 Jan 2011 21:40:50 +0000 Subject: Add test/use-case for id on fo:root git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1059415 13f79535-47bb-0310-9956-ffa450edef68 --- .../page-number-citation-last_complex.xml | 30 ++++++++++++---------- 1 file changed, 16 insertions(+), 14 deletions(-) (limited to 'test') diff --git a/test/layoutengine/standard-testcases/page-number-citation-last_complex.xml b/test/layoutengine/standard-testcases/page-number-citation-last_complex.xml index 38728606c..a3f9256dc 100644 --- a/test/layoutengine/standard-testcases/page-number-citation-last_complex.xml +++ b/test/layoutengine/standard-testcases/page-number-citation-last_complex.xml @@ -28,7 +28,7 @@

- + @@ -79,6 +79,7 @@ + root= page-sequence= block= list= @@ -97,18 +98,19 @@ - - - - - - - - - - + + + + + + + + + + + -- cgit v1.2.3