xmlgraphics-fop-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jerem...@apache.org
Subject svn commit: r746664 [5/8] - in /xmlgraphics/fop/trunk: ./ examples/embedding/java/embedding/atxml/ examples/embedding/java/embedding/intermediate/ examples/embedding/xml/xslt/ examples/plan/src/org/apache/fop/plan/ lib/ src/documentation/content/xdocs/...
Date Sun, 22 Feb 2009 12:40:55 GMT
Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java Sun Feb 22 12:40:44 2009
@@ -27,6 +27,7 @@
 
 import org.apache.fop.afp.AFPResourceLevel;
 import org.apache.fop.afp.AFPResourceLevelDefaults;
+import org.apache.fop.afp.fonts.AFPFontCollection;
 import org.apache.fop.afp.fonts.AFPFontInfo;
 import org.apache.fop.afp.fonts.CharacterSet;
 import org.apache.fop.afp.fonts.FopCharacterSet;
@@ -34,17 +35,23 @@
 import org.apache.fop.afp.fonts.RasterFont;
 import org.apache.fop.apps.FOPException;
 import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.fonts.FontCollection;
+import org.apache.fop.fonts.FontInfo;
+import org.apache.fop.fonts.FontManager;
 import org.apache.fop.fonts.FontTriplet;
 import org.apache.fop.fonts.FontUtil;
 import org.apache.fop.fonts.Typeface;
 import org.apache.fop.render.PrintRendererConfigurator;
 import org.apache.fop.render.Renderer;
+import org.apache.fop.render.intermediate.IFDocumentHandler;
+import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator;
 import org.apache.fop.util.LogUtil;
 
 /**
  * AFP Renderer configurator
  */
-public class AFPRendererConfigurator extends PrintRendererConfigurator {
+public class AFPRendererConfigurator extends PrintRendererConfigurator
+            implements IFDocumentHandlerConfigurator {
 
     /**
      * Default constructor
@@ -233,6 +240,7 @@
         Configuration cfg = super.getRendererConfig(renderer);
         if (cfg != null) {
             AFPRenderer afpRenderer = (AFPRenderer)renderer;
+
             try {
                 List/*<AFPFontInfo>*/ fontList = buildFontListFromConfiguration(cfg);
                 afpRenderer.setFontList(fontList);
@@ -241,69 +249,109 @@
                         userAgent.getFactory().validateUserConfigStrictly());
             }
 
-            // image information
-            Configuration imagesCfg = cfg.getChild("images");
+            configure(afpRenderer, cfg);
+        }
+    }
 
-            // default to grayscale images
-            String imagesMode = imagesCfg.getAttribute("mode", IMAGES_MODE_GRAYSCALE);
-            if (IMAGES_MODE_COLOR.equals(imagesMode)) {
-                afpRenderer.setColorImages(true);
-            } else {
-                afpRenderer.setColorImages(false);
-                // default to 8 bits per pixel
-                int bitsPerPixel = imagesCfg.getAttributeAsInteger("bits-per-pixel", 8);
-                afpRenderer.setBitsPerPixel(bitsPerPixel);
-            }
+    private void configure(AFPCustomizable customizable, Configuration cfg) throws FOPException {
 
-            // native image support
-            boolean nativeImageSupport = imagesCfg.getAttributeAsBoolean("native", false);
-            afpRenderer.setNativeImagesSupported(nativeImageSupport);
-
-            // renderer resolution
-            Configuration rendererResolutionCfg = cfg.getChild("renderer-resolution", false);
-            if (rendererResolutionCfg != null) {
-                afpRenderer.setResolution(rendererResolutionCfg.getValueAsInteger(240));
+        // image information
+        Configuration imagesCfg = cfg.getChild("images");
+
+        // default to grayscale images
+        String imagesMode = imagesCfg.getAttribute("mode", IMAGES_MODE_GRAYSCALE);
+        if (IMAGES_MODE_COLOR.equals(imagesMode)) {
+            customizable.setColorImages(true);
+        } else {
+            customizable.setColorImages(false);
+            // default to 8 bits per pixel
+            int bitsPerPixel = imagesCfg.getAttributeAsInteger("bits-per-pixel", 8);
+            customizable.setBitsPerPixel(bitsPerPixel);
+        }
+
+        // native image support
+        boolean nativeImageSupport = imagesCfg.getAttributeAsBoolean("native", false);
+        customizable.setNativeImagesSupported(nativeImageSupport);
+
+        // renderer resolution
+        Configuration rendererResolutionCfg = cfg.getChild("renderer-resolution", false);
+        if (rendererResolutionCfg != null) {
+            customizable.setResolution(rendererResolutionCfg.getValueAsInteger(240));
+        }
+
+        // a default external resource group file setting
+        Configuration resourceGroupFileCfg
+            = cfg.getChild("resource-group-file", false);
+        if (resourceGroupFileCfg != null) {
+            String resourceGroupDest = null;
+            try {
+                resourceGroupDest = resourceGroupFileCfg.getValue();
+            } catch (ConfigurationException e) {
+                LogUtil.handleException(log, e,
+                        userAgent.getFactory().validateUserConfigStrictly());
             }
+            File resourceGroupFile = new File(resourceGroupDest);
+            if (resourceGroupFile.canWrite()) {
+                customizable.setDefaultResourceGroupFilePath(resourceGroupDest);
+            } else {
+                log.warn("Unable to write to default external resource group file '"
+                            + resourceGroupDest + "'");
+            }
+        }
 
-            // a default external resource group file setting
-            Configuration resourceGroupFileCfg
-                = cfg.getChild("resource-group-file", false);
-            if (resourceGroupFileCfg != null) {
-                String resourceGroupDest = null;
+        Configuration defaultResourceLevelCfg = cfg.getChild("default-resource-levels", false);
+        if (defaultResourceLevelCfg != null) {
+            AFPResourceLevelDefaults defaults = new AFPResourceLevelDefaults();
+            String[] types = defaultResourceLevelCfg.getAttributeNames();
+            for (int i = 0, c = types.length; i < c; i++) {
+                String type = types[i];
                 try {
-                    resourceGroupDest = resourceGroupFileCfg.getValue();
+                    String level = defaultResourceLevelCfg.getAttribute(type);
+                    defaults.setDefaultResourceLevel(type, AFPResourceLevel.valueOf(level));
+                } catch (IllegalArgumentException iae) {
+                    LogUtil.handleException(log, iae,
+                            userAgent.getFactory().validateUserConfigStrictly());
                 } catch (ConfigurationException e) {
                     LogUtil.handleException(log, e,
                             userAgent.getFactory().validateUserConfigStrictly());
                 }
-                File resourceGroupFile = new File(resourceGroupDest);
-                if (resourceGroupFile.canWrite()) {
-                    afpRenderer.setDefaultResourceGroupFilePath(resourceGroupDest);
-                } else {
-                    log.warn("Unable to write to default external resource group file '"
-                                + resourceGroupDest + "'");
-                }
             }
+            customizable.setResourceLevelDefaults(defaults);
+        }
+    }
 
-            Configuration defaultResourceLevelCfg = cfg.getChild("default-resource-levels", false);
-            if (defaultResourceLevelCfg != null) {
-                AFPResourceLevelDefaults defaults = new AFPResourceLevelDefaults();
-                String[] types = defaultResourceLevelCfg.getAttributeNames();
-                for (int i = 0, c = types.length; i < c; i++) {
-                    String type = types[i];
-                    try {
-                        String level = defaultResourceLevelCfg.getAttribute(type);
-                        defaults.setDefaultResourceLevel(type, AFPResourceLevel.valueOf(level));
-                    } catch (IllegalArgumentException iae) {
-                        LogUtil.handleException(log, iae,
-                                userAgent.getFactory().validateUserConfigStrictly());
-                    } catch (ConfigurationException e) {
-                        LogUtil.handleException(log, e,
-                                userAgent.getFactory().validateUserConfigStrictly());
-                    }
-                }
-                afpRenderer.setResourceLevelDefaults(defaults);
+    /** {@inheritDoc} */
+    public void configure(IFDocumentHandler documentHandler) throws FOPException {
+        Configuration cfg = super.getRendererConfig(documentHandler.getMimeType());
+        if (cfg != null) {
+            AFPDocumentHandler afpDocumentHandler = (AFPDocumentHandler)documentHandler;
+            configure(afpDocumentHandler, cfg);
+        }
+    }
+
+    /** {@inheritDoc} */
+    public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo)
+            throws FOPException {
+        FontManager fontManager = userAgent.getFactory().getFontManager();
+        List fontCollections = new java.util.ArrayList();
+
+        Configuration cfg = super.getRendererConfig(documentHandler.getMimeType());
+        if (cfg != null) {
+            try {
+                List fontList = buildFontListFromConfiguration(cfg);
+                fontCollections.add(new AFPFontCollection(
+                        userAgent.getEventBroadcaster(), fontList));
+            } catch (ConfigurationException e) {
+                LogUtil.handleException(log, e,
+                        userAgent.getFactory().validateUserConfigStrictly());
             }
+        } else {
+            fontCollections.add(new AFPFontCollection(userAgent.getEventBroadcaster(), null));
         }
+
+        fontManager.setup(fontInfo,
+                (FontCollection[])fontCollections.toArray(
+                        new FontCollection[fontCollections.size()]));
+        documentHandler.setFontInfo(fontInfo);
     }
 }

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererContext.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererContext.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererContext.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererContext.java Sun Feb 22 12:40:44 2009
@@ -28,9 +28,13 @@
 import org.apache.fop.afp.AFPResourceManager;
 import org.apache.fop.afp.modca.ResourceObject;
 import org.apache.fop.render.AbstractRenderer;
+import org.apache.fop.render.ImageHandlerUtil;
 import org.apache.fop.render.RendererContext;
 import org.apache.fop.render.RendererContextConstants;
 
+/**
+ * AFP-specific renderer context class.
+ */
 public class AFPRendererContext extends RendererContext {
 
     /**
@@ -65,8 +69,7 @@
 
         Map foreignAttributes = (Map)getProperty(RendererContextConstants.FOREIGN_ATTRIBUTES);
         if (foreignAttributes != null) {
-            String conversionMode = (String)foreignAttributes.get(CONVERSION_MODE);
-            boolean paintAsBitmap = BITMAP.equalsIgnoreCase(conversionMode);
+            boolean paintAsBitmap = ImageHandlerUtil.isConversionModeBitmap(foreignAttributes);
             info.setPaintAsBitmap(paintAsBitmap);
 
             AFPForeignAttributeReader foreignAttributeReader

Propchange: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererImageInfo.java
            ('svn:mergeinfo' removed)

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPSVGHandler.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPSVGHandler.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPSVGHandler.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPSVGHandler.java Sun Feb 22 12:40:44 2009
@@ -123,7 +123,7 @@
             = RendererContext.wrapRendererContext(rendererContext);
         Dimension imageSize = getImageSize(wrappedContext);
         Graphics2DImagePainter painter
-            = createGrapics2DImagePainter(bridgeContext, root, imageSize);
+            = createGraphics2DImagePainter(bridgeContext, root, imageSize);
 
         // Create AFPObjectAreaInfo
         RendererContextWrapper rctx = RendererContext.wrapRendererContext(rendererContext);
@@ -217,8 +217,8 @@
         context.setProperty(AFPRendererContextConstants.AFP_GRAYSCALE, Boolean.FALSE);
     }
 
-    /** {@inheritDoc} */
-    protected Graphics2DImagePainter createGrapics2DImagePainter(BridgeContext ctx, GraphicsNode root, Dimension imageSize) {
+    private Graphics2DImagePainter createGraphics2DImagePainter(BridgeContext ctx,
+            GraphicsNode root, Dimension imageSize) {
         Graphics2DImagePainter painter = null;
         if (paintAsBitmap()) {
             // paint as IOCA Image

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java Sun Feb 22 12:40:44 2009
@@ -19,12 +19,13 @@
 
 package org.apache.fop.render.afp;
 
+import java.awt.Rectangle;
 import java.io.IOException;
 import java.io.InputStream;
 
 import org.apache.commons.io.IOUtils;
 
-import org.apache.xmlgraphics.image.loader.ImageInfo;
+import org.apache.xmlgraphics.image.loader.Image;
 import org.apache.xmlgraphics.image.loader.ImageSize;
 import org.apache.xmlgraphics.image.loader.impl.ImageRawStream;
 
@@ -32,34 +33,53 @@
 import org.apache.fop.afp.AFPObjectAreaInfo;
 import org.apache.fop.afp.AFPPaintingState;
 import org.apache.fop.afp.AFPResourceInfo;
+import org.apache.fop.afp.AFPResourceManager;
 import org.apache.fop.afp.modca.ResourceObject;
+import org.apache.fop.render.ImageHandler;
+import org.apache.fop.render.RenderingContext;
 
 /**
  * A base abstract AFP raw stream image handler
  */
-public abstract class AbstractAFPImageHandlerRawStream extends AFPImageHandler {
+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();
 
-        ImageInfo imageInfo = rendererImageInfo.getImageInfo();
-        String mimeType = imageInfo.getMimeType();
-        if (mimeType != null) {
-            dataObjectInfo.setMimeType(mimeType);
-        }
+        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.
+     * @param imageObjectInfo the image object info being built
+     * @param image the image being processed
+     */
+    protected void setAdditionalParameters(AFPDataObjectInfo imageObjectInfo,
+            ImageRawStream image) {
+        //nop
+    }
+
+    private void updateDataObjectInfo(AFPDataObjectInfo dataObjectInfo,
+            ImageRawStream rawStream, AFPResourceManager resourceManager) throws IOException {
+        dataObjectInfo.setMimeType(rawStream.getFlavor().getMimeType());
 
         AFPResourceInfo resourceInfo = dataObjectInfo.getResourceInfo();
         if (!resourceInfo.levelChanged()) {
-            resourceInfo.setLevel(afpInfo.getResourceManager().getResourceLevelDefaults()
+            resourceInfo.setLevel(resourceManager.getResourceLevelDefaults()
                     .getDefaultResourceLevel(ResourceObject.TYPE_IMAGE));
         }
 
-        ImageRawStream rawStream = (ImageRawStream) rendererImageInfo.getImage();
         InputStream inputStream = rawStream.createInputStream();
         try {
             dataObjectInfo.setData(IOUtils.toByteArray(inputStream));
@@ -76,15 +96,38 @@
         ImageSize imageSize = rawStream.getSize();
         dataObjectInfo.setDataHeightRes((int) (imageSize.getDpiHorizontal() * 10));
         dataObjectInfo.setDataWidthRes((int) (imageSize.getDpiVertical() * 10));
+    }
+
+    /** {@inheritDoc} */
+    public void handleImage(RenderingContext context, Image image, Rectangle pos)
+            throws IOException {
+        AFPRenderingContext afpContext = (AFPRenderingContext)context;
+
+        AFPDataObjectInfo dataObjectInfo = createDataObjectInfo();
+
+        // set resource information
+        setResourceInformation(dataObjectInfo,
+                image.getInfo().getOriginalURI(),
+                afpContext.getForeignAttributes());
+
+        // Positioning
+        dataObjectInfo.setObjectAreaInfo(createObjectAreaInfo(afpContext.getPaintingState(), pos));
 
         // set object area info
-        AFPObjectAreaInfo objectAreaInfo = dataObjectInfo.getObjectAreaInfo();
-        AFPPaintingState paintingState = afpInfo.getPaintingState();
+        //AFPObjectAreaInfo objectAreaInfo = dataObjectInfo.getObjectAreaInfo();
+        AFPPaintingState paintingState = afpContext.getPaintingState();
         int resolution = paintingState.getResolution();
+        AFPObjectAreaInfo objectAreaInfo = dataObjectInfo.getObjectAreaInfo();
         objectAreaInfo.setWidthRes(resolution);
         objectAreaInfo.setHeightRes(resolution);
 
-        return dataObjectInfo;
+        // Image content
+        ImageRawStream imageStream = (ImageRawStream)image;
+        updateDataObjectInfo(dataObjectInfo, imageStream, afpContext.getResourceManager());
+        setAdditionalParameters(dataObjectInfo, imageStream);
+
+        // Create image
+        afpContext.getResourceManager().createObject(dataObjectInfo);
     }
 
 }

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/bitmap/TIFFRenderer.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/bitmap/TIFFRenderer.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/bitmap/TIFFRenderer.java Sun Feb 22 12:40:44 2009
@@ -43,7 +43,6 @@
 
 import org.apache.fop.apps.FOPException;
 import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.apps.MimeConstants;
 import org.apache.fop.render.java2d.Java2DRenderer;
 
 /**
@@ -67,19 +66,7 @@
  * <code>org.apache.fop.render.java2D.Java2DRenderer</code> and just encode
  * rendering results into TIFF format using Batik's image codec
  */
-public class TIFFRenderer extends Java2DRenderer {
-
-    /** The MIME type for tiff-Rendering */
-    public static final String MIME_TYPE = MimeConstants.MIME_TIFF;
-
-    //private static final String COMPRESSION_NONE = "NONE";
-    //private static final String COMPRESSION_JPEG = "JPEG";
-    public static final String COMPRESSION_PACKBITS = "PackBits";
-    //private static final String COMPRESSION_DEFLATE = "Deflate";
-    //private static final String COMPRESSION_LZW = "LZW";
-    //private static final String COMPRESSION_ZLIB = "ZLib";
-    public static final String COMPRESSION_CCITT_T6 = "CCITT T.6"; //CCITT Group 4
-    public static final String COMPRESSION_CCITT_T4 = "CCITT T.4"; //CCITT Group 3
+public class TIFFRenderer extends Java2DRenderer implements TIFFConstants {
 
     /** ImageWriter parameters */
     private ImageWriterParams writerParams;

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java Sun Feb 22 12:40:44 2009
@@ -19,18 +19,38 @@
 
 package org.apache.fop.render.bitmap;
 
+import java.awt.Color;
+import java.awt.Graphics2D;
 import java.awt.image.BufferedImage;
+import java.util.List;
 
 import org.apache.avalon.framework.configuration.Configuration;
+
 import org.apache.fop.apps.FOPException;
 import org.apache.fop.apps.FOUserAgent;
-import org.apache.fop.render.PrintRendererConfigurator;
+import org.apache.fop.fonts.FontCollection;
+import org.apache.fop.fonts.FontEventAdapter;
+import org.apache.fop.fonts.FontEventListener;
+import org.apache.fop.fonts.FontInfo;
+import org.apache.fop.fonts.FontManager;
+import org.apache.fop.fonts.FontResolver;
+import org.apache.fop.render.DefaultFontResolver;
 import org.apache.fop.render.Renderer;
+import org.apache.fop.render.intermediate.IFDocumentHandler;
+import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator;
+import org.apache.fop.render.java2d.Base14FontCollection;
+import org.apache.fop.render.java2d.ConfiguredFontCollection;
+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.java2d.Java2DRendererConfigurator;
+import org.apache.fop.util.ColorUtil;
 
 /**
  * TIFF Renderer configurator
  */
-public class TIFFRendererConfigurator extends PrintRendererConfigurator {
+public class TIFFRendererConfigurator extends Java2DRendererConfigurator
+            implements IFDocumentHandlerConfigurator {
 
     /**
      * Default constructor
@@ -52,15 +72,9 @@
         if (cfg != null) {
             TIFFRenderer tiffRenderer = (TIFFRenderer)renderer;
             //set compression
-            String name = cfg.getChild("compression").getValue(TIFFRenderer.COMPRESSION_PACKBITS);
+            String name = cfg.getChild("compression").getValue(TIFFConstants.COMPRESSION_PACKBITS);
             //Some compression formats need a special image format:
-            if (name.equalsIgnoreCase(TIFFRenderer.COMPRESSION_CCITT_T6)) {
-                tiffRenderer.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY);
-            } else if (name.equalsIgnoreCase(TIFFRenderer.COMPRESSION_CCITT_T4)) {
-                tiffRenderer.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY);
-            } else {
-                tiffRenderer.setBufferedImageType(BufferedImage.TYPE_INT_ARGB);
-            }
+            tiffRenderer.setBufferedImageType(getBufferedImageTypeFor(name));
             if (!"NONE".equalsIgnoreCase(name)) {
                 tiffRenderer.getWriterParams().setCompressionMethod(name);
             }
@@ -70,4 +84,104 @@
         }
         super.configure(renderer);
     }
+
+    private int getBufferedImageTypeFor(String compressionName) {
+        if (compressionName.equalsIgnoreCase(TIFFConstants.COMPRESSION_CCITT_T6)) {
+            return BufferedImage.TYPE_BYTE_BINARY;
+        } else if (compressionName.equalsIgnoreCase(TIFFConstants.COMPRESSION_CCITT_T4)) {
+            return BufferedImage.TYPE_BYTE_BINARY;
+        } else {
+            return BufferedImage.TYPE_INT_ARGB;
+        }
+    }
+
+    // ---=== IFDocumentHandler configuration ===---
+
+    /** {@inheritDoc} */
+    public void configure(IFDocumentHandler documentHandler) throws FOPException {
+        Configuration cfg = super.getRendererConfig(documentHandler.getMimeType());
+        if (cfg != null) {
+            TIFFDocumentHandler tiffHandler = (TIFFDocumentHandler)documentHandler;
+            BitmapRenderingSettings settings = tiffHandler.getSettings();
+            //set compression
+            String name = cfg.getChild("compression").getValue(TIFFConstants.COMPRESSION_PACKBITS);
+            //Some compression formats need a special image format:
+            settings.setBufferedImageType(getBufferedImageTypeFor(name));
+            if (!"NONE".equalsIgnoreCase(name)) {
+                settings.getWriterParams().setCompressionMethod(name);
+            }
+            if (log.isInfoEnabled()) {
+                log.info("TIFF compression set to " + name);
+            }
+
+            boolean transparent = cfg.getChild(
+                    Java2DRenderer.JAVA2D_TRANSPARENT_PAGE_BACKGROUND).getValueAsBoolean(
+                            settings.hasTransparentPageBackground());
+            if (transparent) {
+                settings.setPageBackgroundColor(null);
+            } else {
+                String background = cfg.getChild("background-color").getValue(null);
+                if (background != null) {
+                    settings.setPageBackgroundColor(
+                            ColorUtil.parseColorString(this.userAgent, background));
+                } else {
+                    settings.setPageBackgroundColor(Color.WHITE);
+                }
+            }
+
+            boolean antiAliasing = cfg.getChild("anti-aliasing").getValueAsBoolean(
+                    settings.isAntiAliasingEnabled());
+            settings.setAntiAliasing(antiAliasing);
+
+            String optimization = cfg.getChild("rendering").getValue(null);
+            if ("quality".equalsIgnoreCase(optimization)) {
+                settings.setQualityRendering(true);
+            } else if ("speed".equalsIgnoreCase(optimization)) {
+                settings.setQualityRendering(false);
+            }
+
+            String color = cfg.getChild("color-mode").getValue(null);
+            if (color != null) {
+                if ("rgba".equalsIgnoreCase(color)) {
+                    settings.setBufferedImageType(BufferedImage.TYPE_INT_ARGB);
+                } else if ("rgb".equalsIgnoreCase(color)) {
+                    settings.setBufferedImageType(BufferedImage.TYPE_INT_RGB);
+                } else if ("gray".equalsIgnoreCase(color)) {
+                    settings.setBufferedImageType(BufferedImage.TYPE_BYTE_GRAY);
+                } else if ("binary".equalsIgnoreCase(color)) {
+                    settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY);
+                } else {
+                    throw new FOPException("Invalid value for color-mode: " + color);
+                }
+            }
+        }
+    }
+
+    /** {@inheritDoc} */
+    public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo)
+            throws FOPException {
+        FontManager fontManager = userAgent.getFactory().getFontManager();
+
+        Graphics2D graphics2D = Java2DFontMetrics.createFontMetricsGraphics2D();
+
+        List fontCollections = new java.util.ArrayList();
+        fontCollections.add(new Base14FontCollection(graphics2D));
+        fontCollections.add(new InstalledFontCollection(graphics2D));
+
+        Configuration cfg = super.getRendererConfig(documentHandler.getMimeType());
+        if (cfg != null) {
+            FontResolver fontResolver = new DefaultFontResolver(userAgent);
+            FontEventListener listener = new FontEventAdapter(
+                    userAgent.getEventBroadcaster());
+            List fontList = buildFontList(cfg, fontResolver, listener);
+            fontCollections.add(new ConfiguredFontCollection(fontResolver, fontList));
+        }
+
+        fontManager.setup(fontInfo,
+                (FontCollection[])fontCollections.toArray(
+                        new FontCollection[fontCollections.size()]));
+        documentHandler.setFontInfo(fontInfo);
+    }
+
+
 }

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java Sun Feb 22 12:40:44 2009
@@ -88,7 +88,8 @@
                     font = new CustomFontMetricsMapper(fontMetrics, fontSource);
                 } else {
                     CustomFont fontMetrics = FontLoader.loadFont(
-                            fontFile, null, true, EncodingMode.AUTO, fontResolver);
+                            fontFile, null, true, EncodingMode.AUTO,
+                            configFontInfo.getKerning(), fontResolver);
                     font = new CustomFontMetricsMapper(fontMetrics);
                 }
 

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DFontMetrics.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DFontMetrics.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DFontMetrics.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DFontMetrics.java Sun Feb 22 12:40:44 2009
@@ -21,12 +21,14 @@
 
 // Java
 import java.awt.Font;
-import java.awt.Graphics2D;
-import java.awt.geom.Rectangle2D;
 import java.awt.FontMetrics;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
 import java.awt.font.LineMetrics;
 import java.awt.font.TextAttribute;
 import java.awt.font.TextLayout;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
 import java.util.Map;
 
 /**
@@ -110,6 +112,20 @@
     private Graphics2D graphics;
 
     /**
+     * Creates a Graphics2D object for the sole purpose of getting font metrics.
+     * @return a Graphics2D object
+     */
+    public static Graphics2D createFontMetricsGraphics2D() {
+        BufferedImage fontImage = new BufferedImage(100, 100,
+                BufferedImage.TYPE_INT_RGB);
+        Graphics2D graphics2D = fontImage.createGraphics();
+        //The next line is important to get accurate font metrics!
+        graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
+                RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+        return graphics2D;
+    }
+
+    /**
      * Constructs a new Font-metrics.
      * @param graphics a temp graphics object - this is needed  so
      * that we can get an instance of java.awt.FontMetrics

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DGraphicsState.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DGraphicsState.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DGraphicsState.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DGraphicsState.java Sun Feb 22 12:40:44 2009
@@ -222,7 +222,7 @@
                 getGraph().setPaint(p);
                 return true;
             }
-        } else if (p.equals(getGraph().getPaint())) {
+        } else if (!p.equals(getGraph().getPaint())) {
             getGraph().setPaint(p);
             return true;
         }
@@ -252,10 +252,12 @@
      * according to the rule last-specified-first-applied.
      * @see java.awt.Graphics2D#transform(AffineTransform)
      *
-     * @param tf the transform to concatonate to the current level transform
+     * @param tf the transform to concatenate to the current level transform
      */
     public void transform(AffineTransform tf) {
-        getGraph().transform(tf);
+        if (!tf.isIdentity()) {
+            getGraph().transform(tf);
+        }
     }
 
     /**
@@ -270,7 +272,7 @@
 
     /** {@inheritDoc} */
     public String toString() {
-        String s = "AWTGraphicsState " + currentGraphics.toString()
+        String s = "Java2DGraphicsState " + currentGraphics.toString()
                 + ", Stroke (width: " + currentStrokeWidth + " style: "
                 + currentStrokeStyle + "), " + getTransform();
         return s;

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DRenderer.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DRenderer.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DRenderer.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DRenderer.java Sun Feb 22 12:40:44 2009
@@ -123,7 +123,7 @@
     /** The 0-based current page number */
     private int currentPageNumber = 0;
 
-    /** true if antialiasing is set */
+    /** true if anti-aliasing is set */
     protected boolean antialiasing = true;
 
     /** true if qualityRendering is set */
@@ -167,12 +167,7 @@
         //Don't call super.setupFontInfo() here! Java2D needs a special font setup
         // create a temp Image to test font metrics on
         this.fontInfo = inFontInfo;
-        BufferedImage fontImage = new BufferedImage(100, 100,
-                BufferedImage.TYPE_INT_RGB);
-        Graphics2D graphics2D = fontImage.createGraphics();
-        //The next line is important to get accurate font metrics!
-        graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
-                RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+        Graphics2D graphics2D = Java2DFontMetrics.createFontMetricsGraphics2D();
 
         FontCollection[] fontCollections = new FontCollection[] {
                 new Base14FontCollection(graphics2D),

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java Sun Feb 22 12:40:44 2009
@@ -33,6 +33,7 @@
 
 import org.apache.fop.image.loader.batik.BatikUtil;
 import org.apache.fop.render.AbstractGenericSVGHandler;
+import org.apache.fop.render.ImageHandlerUtil;
 import org.apache.fop.render.Renderer;
 import org.apache.fop.render.RendererContext;
 import org.apache.fop.render.RendererContextConstants;
@@ -71,10 +72,7 @@
         pdfi.currentXPosition = ((Integer)context.getProperty(XPOS)).intValue();
         pdfi.currentYPosition = ((Integer)context.getProperty(YPOS)).intValue();
         Map foreign = (Map)context.getProperty(RendererContextConstants.FOREIGN_ATTRIBUTES);
-        if (foreign != null
-                && BITMAP.equalsIgnoreCase((String)foreign.get(CONVERSION_MODE))) {
-            pdfi.paintAsBitmap = true;
-        }
+        pdfi.paintAsBitmap = ImageHandlerUtil.isConversionModeBitmap(foreign);
         return pdfi;
     }
 

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLGenerator.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLGenerator.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLGenerator.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLGenerator.java Sun Feb 22 12:40:44 2009
@@ -22,16 +22,16 @@
 import java.awt.Color;
 import java.awt.Dimension;
 import java.awt.Graphics2D;
-import java.awt.color.ColorSpace;
 import java.awt.geom.AffineTransform;
 import java.awt.image.BufferedImage;
 import java.awt.image.BufferedImageOp;
 import java.awt.image.ByteLookupTable;
-import java.awt.image.ColorConvertOp;
 import java.awt.image.ColorModel;
 import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferByte;
 import java.awt.image.IndexColorModel;
 import java.awt.image.LookupOp;
+import java.awt.image.MultiPixelPackedSampleModel;
 import java.awt.image.Raster;
 import java.awt.image.RenderedImage;
 import java.awt.image.WritableRaster;
@@ -55,6 +55,10 @@
  */
 public class PCLGenerator {
 
+    private static final String US_ASCII = "US-ASCII";
+
+    private static final String ISO_8859_1 = "ISO-8859-1";
+
     /** The ESC (escape) character */
     public static final char ESC = '\033';
 
@@ -116,6 +120,14 @@
         return this.out;
     }
 
+    /**
+     * Returns the currently active text encoding.
+     * @return the text encoding
+     */
+    public String getTextEncoding() {
+        return ISO_8859_1;
+    }
+
     /** @return the maximum resolution to encode bitmap images at */
     public int getMaximumBitmapResolution() {
         return this.maxBitmapResolution;
@@ -128,7 +140,7 @@
      */
     public void writeCommand(String cmd) throws IOException {
         out.write(27); //ESC
-        out.write(cmd.getBytes("US-ASCII"));
+        out.write(cmd.getBytes(US_ASCII));
     }
 
     /**
@@ -137,7 +149,7 @@
      * @throws IOException In case of an I/O error
      */
     public void writeText(String s) throws IOException {
-        out.write(s.getBytes("ISO-8859-1"));
+        out.write(s.getBytes(ISO_8859_1));
     }
 
     /**
@@ -578,7 +590,7 @@
      */
     public static boolean isMonochromeImage(RenderedImage img) {
         return BitmapImageUtil.isMonochromeImage(img);
-    }
+        }
 
     /**
      * Indicates whether an image is a grayscale image.
@@ -589,6 +601,26 @@
         return BitmapImageUtil.isGrayscaleImage(img);
     }
 
+    private static int jaiAvailable = -1; //no synchronization necessary, not critical
+
+    /**
+     * Indicates whether JAI is available. JAI has shown to be reliable when dithering a
+     * grayscale or color image to monochrome bitmaps (1-bit).
+     * @return true if JAI is available
+     */
+    public static boolean isJAIAvailable() {
+        if (jaiAvailable < 0) {
+            try {
+                String clName = "javax.media.jai.JAI";
+                Class.forName(clName);
+                jaiAvailable = 1;
+            } catch (ClassNotFoundException cnfe) {
+                jaiAvailable = 0;
+            }
+        }
+        return (jaiAvailable > 0);
+    }
+
     private int calculatePCLResolution(int resolution) {
         return calculatePCLResolution(resolution, false);
     }
@@ -705,12 +737,22 @@
      */
     public void paintBitmap(RenderedImage img, Dimension targetDim, boolean sourceTransparency)
                 throws IOException {
-        double targetResolution = img.getWidth() / UnitConv.mpt2in(targetDim.width);
+        double targetHResolution = img.getWidth() / UnitConv.mpt2in(targetDim.width);
+        double targetVResolution = img.getHeight() / UnitConv.mpt2in(targetDim.height);
+        double targetResolution = Math.max(targetHResolution, targetVResolution);
         int resolution = (int)Math.round(targetResolution);
         int effResolution = calculatePCLResolution(resolution, true);
         Dimension orgDim = new Dimension(img.getWidth(), img.getHeight());
-        Dimension effDim = getAdjustedDimension(orgDim, targetResolution, effResolution);
+        Dimension effDim;
+        if (targetResolution == effResolution) {
+            effDim = orgDim; //avoid scaling side-effects
+        } else {
+            effDim = new Dimension(
+                    (int)Math.ceil(UnitConv.mpt2px(targetDim.width, effResolution)),
+                    (int)Math.ceil(UnitConv.mpt2px(targetDim.height, effResolution)));
+        }
         boolean scaled = !orgDim.equals(effDim);
+        //ImageWriterUtil.saveAsPNG(img, new java.io.File("D:/text-0-org.png"));
 
         boolean monochrome = isMonochromeImage(img);
         if (!monochrome) {
@@ -728,18 +770,26 @@
             BufferedImage src = null;
             if (img instanceof BufferedImage && !scaled) {
                 if (!isGrayscaleImage(img) || img.getColorModel().hasAlpha()) {
+                    /* Disabled as this doesn't work reliably, use the fallback below
                     src = new BufferedImage(effDim.width, effDim.height,
                             BufferedImage.TYPE_BYTE_GRAY);
+                    Graphics2D g2d = src.createGraphics();
+                    try {
+                        clearBackground(g2d, effDim);
+                    } finally {
+                        g2d.dispose();
+                    }
                     ColorConvertOp op = new ColorConvertOp(
                             ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
                     op.filter((BufferedImage)img, src);
+                    */
                 } else {
                     src = (BufferedImage)img;
                 }
             }
             if (src == null) {
                 src = BitmapImageUtil.convertToGrayscale(img, effDim);
-            }
+                }
             MonochromeBitmapConverter converter
                 = BitmapImageUtil.createDefaultMonochromeBitmapConverter();
             converter.setHint("quality", "false");
@@ -752,13 +802,29 @@
             RenderedImage effImg = img;
             if (scaled) {
                 effImg = BitmapImageUtil.convertToMonochrome(img, effDim);
-            }
+                }
             setSourceTransparencyMode(sourceTransparency);
             selectCurrentPattern(0, 0); //Solid black
             paintMonochromeBitmap(effImg, effResolution);
         }
     }
 
+    private void clearBackground(Graphics2D g2d, Dimension effDim) {
+        //white background
+        g2d.setBackground(Color.WHITE);
+        g2d.clearRect(0, 0, effDim.width, effDim.height);
+    }
+
+    private int toGray(int rgb) {
+        // see http://www.jguru.com/faq/view.jsp?EID=221919
+        double greyVal = 0.072169d * (rgb & 0xff);
+        rgb >>= 8;
+        greyVal += 0.715160d * (rgb & 0xff);
+        rgb >>= 8;
+        greyVal += 0.212671d * (rgb & 0xff);
+        return (int)greyVal;
+    }
+
     /**
      * Paint a bitmap at the current cursor position. The bitmap must be a monochrome
      * (1-bit) bitmap image.
@@ -770,79 +836,159 @@
         if (!isValidPCLResolution(resolution)) {
             throw new IllegalArgumentException("Invalid PCL resolution: " + resolution);
         }
-        setRasterGraphicsResolution(resolution);
-        writeCommand("*r0f" + img.getHeight() + "t" + img.getWidth() + "s1A");
-        Raster raster = img.getData();
         boolean monochrome = isMonochromeImage(img);
         if (!monochrome) {
             throw new IllegalArgumentException("img must be a monochrome image");
         }
 
-        int x = 0;
-        int y = 0;
-        int imgw = img.getWidth();
-        int imgh = img.getHeight();
-        int bytewidth = (imgw / 8);
-        if ((imgw % 8) != 0) {
-            bytewidth++;
-        }
-        byte ib;
-        byte[] rle = new byte[bytewidth * 2]; //compressed (RLE)
-        byte[] uncompressed = new byte[bytewidth]; //uncompressed
-        int lastcount = -1;
-        byte lastbyte = 0;
-        int rlewidth = 0;
+        setRasterGraphicsResolution(resolution);
+        writeCommand("*r0f" + img.getHeight() + "t" + img.getWidth() + "s1A");
+        Raster raster = img.getData();
 
+        Encoder encoder = new Encoder(img);
         // Transfer graphics data
-        for (y = 0; y < imgh; y++) {
-            ib = 0;
-            for (x = 0; x < imgw; x++) {
-                int sample = raster.getSample(x, y, 0);
-                //Set image bit for black
-                if ((sample == 0)) {
-                    ib |= (1 << (7 - (x % 8)));
-                }
-
-                //RLE encoding
-                if ((x % 8) == 7 || ((x + 1) == imgw)) {
-                    if (rlewidth < bytewidth) {
-                        if (lastcount >= 0) {
-                            if (ib == lastbyte) {
-                                lastcount++;
-                            } else {
-                                rle[rlewidth++] = (byte)(lastcount & 0xFF);
-                                rle[rlewidth++] = lastbyte;
-                                lastbyte = ib;
-                                lastcount = 0;
-                            }
+        int imgw = img.getWidth();
+        IndexColorModel cm = (IndexColorModel)img.getColorModel();
+        if (cm.getTransferType() == DataBuffer.TYPE_BYTE) {
+            DataBufferByte dataBuffer = (DataBufferByte)raster.getDataBuffer();
+            MultiPixelPackedSampleModel packedSampleModel = new MultiPixelPackedSampleModel(
+                    DataBuffer.TYPE_BYTE, img.getWidth(), img.getHeight(), 1);
+            if (img.getSampleModel().equals(packedSampleModel)
+                    && dataBuffer.getNumBanks() == 1) {
+                //Optimized packed encoding
+                byte[] buf = dataBuffer.getData();
+                int scanlineStride = packedSampleModel.getScanlineStride();
+                int idx = 0;
+                int c0 = toGray(cm.getRGB(0));
+                int c1 = toGray(cm.getRGB(1));
+                boolean zeroIsWhite = c0 > c1;
+                for (int y = 0, maxy = img.getHeight(); y < maxy; y++) {
+                    for (int x = 0, maxx = scanlineStride; x < maxx; x++) {
+                        if (zeroIsWhite) {
+                            encoder.add8Bits(buf[idx]);
                         } else {
-                            lastbyte = ib;
-                            lastcount = 0;
-                        }
-                        if (lastcount == 255 || ((x + 1) == imgw)) {
-                            rle[rlewidth++] = (byte)(lastcount & 0xFF);
-                            rle[rlewidth++] = lastbyte;
-                            lastbyte = 0;
-                            lastcount = -1;
+                            encoder.add8Bits((byte)~buf[idx]);
                         }
+                        idx++;
+                    }
+                    encoder.endLine();
+                }
+            } else {
+                //Optimized non-packed encoding
+                for (int y = 0, maxy = img.getHeight(); y < maxy; y++) {
+                    byte[] line = (byte[])raster.getDataElements(0, y, imgw, 1, null);
+                    for (int x = 0, maxx = imgw; x < maxx; x++) {
+                        encoder.addBit(line[x] == 0);
                     }
-                    uncompressed[x / 8] = ib;
-                    ib = 0;
+                    encoder.endLine();
                 }
             }
+        } else {
+            //Safe but slow fallback
+            for (int y = 0, maxy = img.getHeight(); y < maxy; y++) {
+                for (int x = 0, maxx = imgw; x < maxx; x++) {
+                    int sample = raster.getSample(x, y, 0);
+                    encoder.addBit(sample == 0);
+                }
+                encoder.endLine();
+            }
+        }
+
+        // End raster graphics
+        writeCommand("*rB");
+    }
+
+    private class Encoder {
+
+        private int imgw;
+        private int bytewidth;
+        private byte[] rle; //compressed (RLE)
+        private byte[] uncompressed; //uncompressed
+        private int lastcount = -1;
+        private byte lastbyte = 0;
+        private int rlewidth = 0;
+        private byte ib = 0; //current image bits
+        private int x = 0;
+        private boolean zeroRow = true;
+
+        public Encoder(RenderedImage img) {
+            imgw = img.getWidth();
+            bytewidth = (imgw / 8);
+            if ((imgw % 8) != 0) {
+                bytewidth++;
+            }
+            rle = new byte[bytewidth * 2];
+            uncompressed = new byte[bytewidth];
+        }
+
+        public void addBit(boolean bit) {
+            //Set image bit for black
+            if (bit) {
+                ib |= 1;
+            }
+
+            //RLE encoding
+            if ((x % 8) == 7 || ((x + 1) == imgw)) {
+                finishedByte();
+            } else {
+                ib <<= 1;
+            }
+            x++;
+        }
+
+        public void add8Bits(byte b) {
+            ib = b;
+            finishedByte();
+            x += 8;
+        }
+
+        private void finishedByte() {
             if (rlewidth < bytewidth) {
+                if (lastcount >= 0) {
+                    if (ib == lastbyte) {
+                        lastcount++;
+                    } else {
+                        rle[rlewidth++] = (byte)(lastcount & 0xFF);
+                        rle[rlewidth++] = lastbyte;
+                        lastbyte = ib;
+                        lastcount = 0;
+                    }
+                } else {
+                    lastbyte = ib;
+                    lastcount = 0;
+                }
+                if (lastcount == 255 || ((x + 1) == imgw)) {
+                    rle[rlewidth++] = (byte)(lastcount & 0xFF);
+                    rle[rlewidth++] = lastbyte;
+                    lastbyte = 0;
+                    lastcount = -1;
+                }
+            }
+            uncompressed[x / 8] = ib;
+            if (ib != 0) {
+                zeroRow = false;
+            }
+            ib = 0;
+        }
+
+        public void endLine() throws IOException {
+            if (zeroRow && PCLGenerator.this.currentSourceTransparency) {
+                writeCommand("*b1Y");
+            } else if (rlewidth < bytewidth) {
                 writeCommand("*b1m" + rlewidth + "W");
-                this.out.write(rle, 0, rlewidth);
+                out.write(rle, 0, rlewidth);
             } else {
                 writeCommand("*b0m" + bytewidth + "W");
-                this.out.write(uncompressed);
+                out.write(uncompressed);
             }
             lastcount = -1;
             rlewidth = 0;
+            ib = 0;
+            x = 0;
+            zeroRow = true;
         }
 
-        // End raster graphics
-        writeCommand("*rB");
+
     }
 
 }

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLPageDefinition.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLPageDefinition.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLPageDefinition.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLPageDefinition.java Sun Feb 22 12:40:44 2009
@@ -114,6 +114,22 @@
         return null;
     }
 
+    /**
+     * Returns a page definition based on a page format.
+     * @param name the name of the page format (ex. "A4" or "Letter")
+     * @return the page definition or null if no match was found
+     */
+    public static PCLPageDefinition getPageDefinition(String name) {
+        Iterator iter = pageDefinitions.iterator();
+        while (iter.hasNext()) {
+            PCLPageDefinition def = (PCLPageDefinition)iter.next();
+            if (def.getName().equalsIgnoreCase(name)) {
+                return def;
+            }
+        }
+        return null;
+    }
+
     /** @return the default page definition (letter) */
     public static PCLPageDefinition getDefaultPageDefinition() {
         return defaultPageDefinition;

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRenderer.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRenderer.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRenderer.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRenderer.java Sun Feb 22 12:40:44 2009
@@ -26,13 +26,11 @@
 import java.awt.Graphics2D;
 import java.awt.Point;
 import java.awt.Rectangle;
-import java.awt.RenderingHints;
 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.BufferedImage;
 import java.awt.image.RenderedImage;
 import java.io.FileNotFoundException;
 import java.io.IOException;
@@ -58,10 +56,10 @@
 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.QName;
 import org.apache.xmlgraphics.util.UnitConv;
 
 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;
@@ -82,12 +80,12 @@
 import org.apache.fop.area.inline.WordArea;
 import org.apache.fop.datatypes.URISpecification;
 import org.apache.fop.events.ResourceEventProducer;
-import org.apache.fop.fo.extensions.ExtensionElementMapping;
 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;
@@ -96,6 +94,7 @@
 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;
@@ -109,7 +108,7 @@
 /**
  * Renderer for the PCL 5 printer language. It also uses HP GL/2 for certain graphic elements.
  */
-public class PCLRenderer extends PrintRenderer {
+public class PCLRenderer extends PrintRenderer implements PCLConstants {
 
     /** logging instance */
     private static Log log = LogFactory.getLog(PCLRenderer.class);
@@ -117,11 +116,6 @@
     /** The MIME type for PCL */
     public static final String MIME_TYPE = MimeConstants.MIME_PCL_ALT;
 
-    private static final QName CONV_MODE
-            = new QName(ExtensionElementMapping.URI, null, "conversion-mode");
-    private static final QName SRC_TRANSPARENCY
-            = new QName(ExtensionElementMapping.URI, null, "source-transparency");
-
     /** The OutputStream to write the PCL stream to */
     protected OutputStream out;
 
@@ -138,28 +132,10 @@
     private java.awt.Color currentFillColor = null;
 
     /**
-     * Controls whether appearance is more important than speed. False can cause some FO feature
-     * to be ignored (like the advanced borders).
-     */
-    private boolean qualityBeforeSpeed = false;
-
-    /**
-     * Controls whether all text should be painted as text. This is a fallback setting in case
-     * the mixture of native and bitmapped text does not provide the necessary quality.
-     */
-    private boolean allTextAsBitmaps = false;
-
-    /**
-     * Controls whether an RGB canvas is used when converting Java2D graphics to bitmaps.
-     * This can be used to work around problems with Apache Batik, for example, but setting
-     * this to true will increase memory consumption.
-     */
-    private final boolean useColorCanvas = false;
-
-    /**
-     * Controls whether the generation of PJL commands gets disabled.
+     * Utility class which enables all sorts of features that are not directly connected to the
+     * normal rendering process.
      */
-    private boolean disabledPJL = false;
+    private PCLRenderingUtil pclUtil;
 
     /** contains the pageWith of the last printed page */
     private long pageWidth = 0;
@@ -172,13 +148,24 @@
     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) {
-        this.qualityBeforeSpeed = qualityBeforeSpeed;
+        pclUtil.setRenderingMode(qualityBeforeSpeed
+                ? PCLRenderingMode.QUALITY : PCLRenderingMode.SPEED);
     }
 
     /**
@@ -186,7 +173,7 @@
      * @param disable true to disable PJL commands
      */
     public void setPJLDisabled(boolean disable) {
-        this.disabledPJL = disable;
+        pclUtil.setPJLDisabled(disable);
     }
 
     /**
@@ -194,7 +181,16 @@
      * @return true if PJL generation is disabled.
      */
     public boolean isPJLDisabled() {
-        return this.disabledPJL;
+        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);
     }
 
     /**
@@ -205,12 +201,7 @@
         //The PCLRenderer uses the Java2D FontSetup which needs a special font setup
         //create a temp Image to test font metrics on
         fontInfo = inFontInfo;
-        BufferedImage fontImage = new BufferedImage(100, 100,
-                BufferedImage.TYPE_INT_RGB);
-        Graphics2D graphics2D = fontImage.createGraphics();
-        //The next line is important to get accurate font metrics!
-        graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
-                RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+        Graphics2D graphics2D = Java2DFontMetrics.createFontMetricsGraphics2D();
 
         FontCollection[] fontCollections = new FontCollection[] {
                 new Base14FontCollection(graphics2D),
@@ -254,125 +245,6 @@
         }
     }
 
-    /**
-     * Sets the current font (NOTE: Hard-coded font mappings ATM!)
-     * @param name the font name (internal F* names for now)
-     * @param size the font size
-     * @param text the text to be rendered (used to determine if there are non-printable chars)
-     * @return true if the font can be mapped to PCL
-     * @throws IOException if an I/O problem occurs
-     */
-    public boolean setFont(String name, float size, String text) throws IOException {
-        byte[] encoded = text.getBytes("ISO-8859-1");
-        for (int i = 0, c = encoded.length; i < c; i++) {
-            if (encoded[i] == 0x3F && text.charAt(i) != '?') {
-                return false;
-            }
-        }
-        int fontcode = 0;
-        if (name.length() > 1 && name.charAt(0) == 'F') {
-            try {
-                fontcode = Integer.parseInt(name.substring(1));
-            } catch (Exception e) {
-                log.error(e);
-            }
-        }
-        //Note "(ON" selects ISO 8859-1 symbol set as used by PCLGenerator
-        String formattedSize = gen.formatDouble2(size / 1000);
-        switch (fontcode) {
-        case 1:     // F1 = Helvetica
-            // gen.writeCommand("(8U");
-            // gen.writeCommand("(s1p" + formattedSize + "v0s0b24580T");
-            // Arial is more common among PCL5 printers than Helvetica - so use Arial
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s1p" + formattedSize + "v0s0b16602T");
-            break;
-        case 2:     // F2 = Helvetica Oblique
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s1p" + formattedSize + "v1s0b16602T");
-            break;
-        case 3:     // F3 = Helvetica Bold
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s1p" + formattedSize + "v0s3b16602T");
-            break;
-        case 4:     // F4 = Helvetica Bold Oblique
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s1p" + formattedSize + "v1s3b16602T");
-            break;
-        case 5:     // F5 = Times Roman
-            // gen.writeCommand("(8U");
-            // gen.writeCommand("(s1p" + formattedSize + "v0s0b25093T");
-            // Times New is more common among PCL5 printers than Times - so use Times New
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s1p" + formattedSize + "v0s0b16901T");
-            break;
-        case 6:     // F6 = Times Italic
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s1p" + formattedSize + "v1s0b16901T");
-            break;
-        case 7:     // F7 = Times Bold
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s1p" + formattedSize + "v0s3b16901T");
-            break;
-        case 8:     // F8 = Times Bold Italic
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s1p" + formattedSize + "v1s3b16901T");
-            break;
-        case 9:     // F9 = Courier
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f))
-                    + "h0s0b4099T");
-            break;
-        case 10:    // F10 = Courier Oblique
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f))
-                    + "h1s0b4099T");
-            break;
-        case 11:    // F11 = Courier Bold
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f))
-                    + "h0s3b4099T");
-            break;
-        case 12:    // F12 = Courier Bold Oblique
-
-            gen.writeCommand("(0N");
-            gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f))
-                    + "h1s3b4099T");
-            break;
-        case 13:    // F13 = Symbol
-
-            return false;
-            //gen.writeCommand("(19M");
-            //gen.writeCommand("(s1p" + formattedSize + "v0s0b16686T");
-            // ECMA Latin 1 Symbol Set in Times Roman???
-            // gen.writeCommand("(9U");
-            // gen.writeCommand("(s1p" + formattedSize + "v0s0b25093T");
-            //break;
-        case 14:    // F14 = Zapf Dingbats
-
-            return false;
-            //gen.writeCommand("(14L");
-            //gen.writeCommand("(s1p" + formattedSize + "v0s0b45101T");
-            //break;
-        default:
-            //gen.writeCommand("(0N");
-            //gen.writeCommand("(s" + formattedSize + "V");
-            return false;
-        }
-        return true;
-    }
-
     /** {@inheritDoc} */
     public void startRenderer(OutputStream outputStream) throws IOException {
         log.debug("Rendering areas to PCL...");
@@ -412,15 +284,13 @@
         saveGraphicsState();
 
         //Paper source
-        String paperSource = page.getForeignAttributeValue(
-                new QName(PCLElementMapping.NAMESPACE, null, "paper-source"));
+        String paperSource = page.getForeignAttributeValue(PCLElementMapping.PCL_PAPER_SOURCE);
         if (paperSource != null) {
             gen.selectPaperSource(Integer.parseInt(paperSource));
         }
 
         // Is Page duplex?
-        String pageDuplex = page.getForeignAttributeValue(
-                new QName(PCLElementMapping.NAMESPACE, null, "duplex-mode"));
+        String pageDuplex = page.getForeignAttributeValue(PCLElementMapping.PCL_DUPLEX_MODE);
         if (pageDuplex != null) {
             gen.selectDuplexMode(Integer.parseInt(pageDuplex));
         }
@@ -497,70 +367,15 @@
     }
 
     private Point2D transformedPoint(int x, int y) {
-        AffineTransform at = graphicContext.getTransform();
-        if (log.isTraceEnabled()) {
-            log.trace("Current transform: " + at);
-        }
-        Point2D.Float orgPoint = new Point2D.Float(x, y);
-        Point2D.Float transPoint = new Point2D.Float();
-        at.transform(orgPoint, transPoint);
-        //At this point we have the absolute position in FOP's coordinate system
-
-        //Now get PCL coordinates taking the current print direction and the logical page
-        //into account.
-        Dimension pageSize = currentPageDefinition.getPhysicalPageSize();
-        Rectangle logRect = currentPageDefinition.getLogicalPageRect();
-        switch (currentPrintDirection) {
-        case 0:
-            transPoint.x -= logRect.x;
-            transPoint.y -= logRect.y;
-            break;
-        case 90:
-            float ty = transPoint.x;
-            transPoint.x = pageSize.height - transPoint.y;
-            transPoint.y = ty;
-            transPoint.x -= logRect.y;
-            transPoint.y -= logRect.x;
-            break;
-        case 180:
-            transPoint.x = pageSize.width - transPoint.x;
-            transPoint.y = pageSize.height - transPoint.y;
-            transPoint.x -= pageSize.width - logRect.x - logRect.width;
-            transPoint.y -= pageSize.height - logRect.y - logRect.height;
-            //The next line is odd and is probably necessary due to the default value of the
-            //Text Length command: "1/2 inch less than maximum text length"
-            //I wonder why this isn't necessary for the 90 degree rotation. *shrug*
-            transPoint.y -= UnitConv.in2mpt(0.5);
-            break;
-        case 270:
-            float tx = transPoint.y;
-            transPoint.y = pageSize.width - transPoint.x;
-            transPoint.x = tx;
-            transPoint.x -= pageSize.height - logRect.y - logRect.height;
-            transPoint.y -= pageSize.width - logRect.x - logRect.width;
-            break;
-        default:
-            throw new IllegalStateException("Illegal print direction: " + currentPrintDirection);
-        }
-        return transPoint;
+        return PCLRenderingUtil.transformedPoint(x, y, graphicContext.getTransform(),
+                currentPageDefinition, currentPrintDirection);
     }
 
     private void changePrintDirection() {
         AffineTransform at = graphicContext.getTransform();
         int newDir;
         try {
-            if (at.getScaleX() == 0 && at.getScaleY() == 0
-                    && at.getShearX() == 1 && at.getShearY() == -1) {
-                newDir = 90;
-            } else if (at.getScaleX() == -1 && at.getScaleY() == -1
-                    && at.getShearX() == 0 && at.getShearY() == 0) {
-                newDir = 180;
-            } else if (at.getScaleX() == 0 && at.getScaleY() == 0
-                    && at.getShearX() == -1 && at.getShearY() == 1) {
-                newDir = 270;
-            } else {
-                newDir = 0;
-            }
+            newDir = PCLRenderingUtil.determinePrintDirection(at);
             if (newDir != this.currentPrintDirection) {
                 this.currentPrintDirection = newDir;
                 gen.changePrintDirection(this.currentPrintDirection);
@@ -657,9 +472,9 @@
         try {
 
             final Color col = (Color)text.getTrait(Trait.COLOR);
-            boolean pclFont = allTextAsBitmaps
+            boolean pclFont = pclUtil.isAllTextAsBitmaps()
                     ? false
-                    : setFont(fontname, fontsize, text.getText());
+                    : HardcodedFonts.setFont(gen, fontname, fontsize, text.getText());
             if (pclFont) {
                 //this.currentFill = col;
                 if (col != null) {
@@ -699,7 +514,7 @@
                 RendererContext rc = createRendererContext(paintRect.x, paintRect.y,
                         paintRect.width, paintRect.height, null);
                 Map atts = new java.util.HashMap();
-                atts.put(CONV_MODE, "bitmap");
+                atts.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP);
                 atts.put(SRC_TRANSPARENCY, "true");
                 rc.setProperty(RendererContextConstants.FOREIGN_ATTRIBUTES, atts);
 
@@ -717,7 +532,7 @@
                     public Dimension getImageSize() {
                         return paintRect.getSize();
                     }
-                    
+
                 };
                 g2a.paintImage(painter, rc,
                         paintRect.x, paintRect.y, paintRect.width, paintRect.height);
@@ -1149,7 +964,7 @@
         RendererContext context = super.createRendererContext(
                 x, y, width, height, foreignAttributes);
         context.setProperty(PCLRendererContextConstants.PCL_COLOR_CANVAS,
-                Boolean.valueOf(this.useColorCanvas));
+                Boolean.valueOf(pclUtil.isColorCanvasEnabled()));
         return context;
     }
 
@@ -1371,10 +1186,10 @@
         if (bpsBefore == null && bpsAfter == null && bpsStart == null && bpsEnd == null) {
             return; //no borders to paint
         }
-        if (qualityBeforeSpeed) {
-            drawQualityBorders(borderRect, bpsBefore, bpsAfter, bpsStart, bpsEnd);
-        } else {
+        if (PCLRenderingMode.SPEED == pclUtil.getRenderingMode()) {
             drawFastBorders(borderRect, bpsBefore, bpsAfter, bpsStart, bpsEnd);
+        } else {
+            drawQualityBorders(borderRect, bpsBefore, bpsAfter, bpsStart, bpsEnd);
         }
     }
 
@@ -1450,7 +1265,7 @@
         RendererContext rc = createRendererContext(paintRect.x, paintRect.y,
                 paintRect.width, paintRect.height, null);
         Map atts = new java.util.HashMap();
-        atts.put(CONV_MODE, "bitmap");
+        atts.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP);
         atts.put(SRC_TRANSPARENCY, "true");
         rc.setProperty(RendererContextConstants.FOREIGN_ATTRIBUTES, atts);
 
@@ -1690,15 +1505,4 @@
         super.renderLeader(area);
     }
 
-    /**
-     * 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) {
-        this.allTextAsBitmaps = allTextAsBitmaps;
-    }
-
-
-
 }

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java Sun Feb 22 12:40:44 2009
@@ -19,17 +19,34 @@
 
 package org.apache.fop.render.pcl;
 
+import java.awt.Graphics2D;
+import java.util.List;
+
 import org.apache.avalon.framework.configuration.Configuration;
 
 import org.apache.fop.apps.FOPException;
 import org.apache.fop.apps.FOUserAgent;
+import org.apache.fop.fonts.FontCollection;
+import org.apache.fop.fonts.FontEventAdapter;
+import org.apache.fop.fonts.FontEventListener;
+import org.apache.fop.fonts.FontInfo;
+import org.apache.fop.fonts.FontManager;
+import org.apache.fop.fonts.FontResolver;
+import org.apache.fop.render.DefaultFontResolver;
 import org.apache.fop.render.PrintRendererConfigurator;
 import org.apache.fop.render.Renderer;
+import org.apache.fop.render.intermediate.IFDocumentHandler;
+import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator;
+import org.apache.fop.render.java2d.Base14FontCollection;
+import org.apache.fop.render.java2d.ConfiguredFontCollection;
+import org.apache.fop.render.java2d.InstalledFontCollection;
+import org.apache.fop.render.java2d.Java2DFontMetrics;
 
 /**
  * PCL Renderer configurator
  */
-public class PCLRendererConfigurator extends PrintRendererConfigurator {
+public class PCLRendererConfigurator extends PrintRendererConfigurator
+            implements IFDocumentHandlerConfigurator {
 
     /**
      * Default constructor
@@ -50,30 +67,75 @@
         if (cfg != null) {
             PCLRenderer pclRenderer = (PCLRenderer)renderer;
 
-            String rendering = cfg.getChild("rendering").getValue(null);
-            if ("quality".equalsIgnoreCase(rendering)) {
-                pclRenderer.setQualityBeforeSpeed(true);
-            } else if ("speed".equalsIgnoreCase(rendering)) {
-                pclRenderer.setQualityBeforeSpeed(false);
-            } else if (rendering != null) {
-                throw new FOPException(
-                        "Valid values for 'rendering' are 'quality' and 'speed'. Value found: "
-                            + rendering);
-            }
+            PCLRenderingUtil pclUtil = pclRenderer.getPCLUtil();
+            configure(cfg, pclUtil);
+        }
+        super.configure(renderer);
+    }
 
-            String textRendering = cfg.getChild("text-rendering").getValue(null);
-            if ("bitmap".equalsIgnoreCase(textRendering)) {
-                pclRenderer.setAllTextAsBitmaps(true);
-            } else if ("auto".equalsIgnoreCase(textRendering)) {
-                pclRenderer.setAllTextAsBitmaps(false);
-            } else if (textRendering != null) {
+    private void configure(Configuration cfg, PCLRenderingUtil pclUtil) throws FOPException {
+        String rendering = cfg.getChild("rendering").getValue(null);
+        if (rendering != null) {
+            try {
+                pclUtil.setRenderingMode(PCLRenderingMode.valueOf(rendering));
+            } catch (IllegalArgumentException e) {
                 throw new FOPException(
-                        "Valid values for 'text-rendering' are 'auto' and 'bitmap'. Value found: "
-                            + textRendering);
+                    "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'."
+                        + " Value found: " + rendering);
             }
+        }
 
-            pclRenderer.setPJLDisabled(cfg.getChild("disable-pjl").getValueAsBoolean(false));
+        String textRendering = cfg.getChild("text-rendering").getValue(null);
+        if ("bitmap".equalsIgnoreCase(textRendering)) {
+            pclUtil.setAllTextAsBitmaps(true);
+        } else if ("auto".equalsIgnoreCase(textRendering)) {
+            pclUtil.setAllTextAsBitmaps(false);
+        } else if (textRendering != null) {
+            throw new FOPException(
+                    "Valid values for 'text-rendering' are 'auto' and 'bitmap'. Value found: "
+                        + textRendering);
+        }
+
+        pclUtil.setPJLDisabled(cfg.getChild("disable-pjl").getValueAsBoolean(false));
+    }
+
+    // ---=== IFDocumentHandler configuration ===---
+
+    /** {@inheritDoc} */
+    public void configure(IFDocumentHandler documentHandler) throws FOPException {
+        Configuration cfg = super.getRendererConfig(documentHandler.getMimeType());
+        if (cfg != null) {
+            PCLDocumentHandler pclDocumentHandler = (PCLDocumentHandler)documentHandler;
+            PCLRenderingUtil pclUtil = pclDocumentHandler.getPCLUtil();
+            configure(cfg, pclUtil);
         }
-        super.configure(renderer);
     }
+
+    /** {@inheritDoc} */
+    public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo)
+                throws FOPException {
+        FontManager fontManager = userAgent.getFactory().getFontManager();
+
+        Graphics2D graphics2D = Java2DFontMetrics.createFontMetricsGraphics2D();
+
+        List fontCollections = new java.util.ArrayList();
+        fontCollections.add(new Base14FontCollection(graphics2D));
+        fontCollections.add(new InstalledFontCollection(graphics2D));
+
+        Configuration cfg = super.getRendererConfig(documentHandler.getMimeType());
+        if (cfg != null) {
+            FontResolver fontResolver = new DefaultFontResolver(userAgent);
+            FontEventListener listener = new FontEventAdapter(
+                    userAgent.getEventBroadcaster());
+            List fontList = buildFontList(cfg, fontResolver, listener);
+            fontCollections.add(new ConfiguredFontCollection(fontResolver, fontList));
+        }
+
+        fontManager.setup(fontInfo,
+                (FontCollection[])fontCollections.toArray(
+                        new FontCollection[fontCollections.size()]));
+        documentHandler.setFontInfo(fontInfo);
+    }
+
+
 }

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRendererContext.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRendererContext.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRendererContext.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/PCLRendererContext.java Sun Feb 22 12:40:44 2009
@@ -22,6 +22,7 @@
 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;
 
 /**
@@ -51,16 +52,14 @@
 
     /** @return true if the SVG image should be rendered as a bitmap */
     public boolean paintAsBitmap() {
-        QName qName = new QName(ExtensionElementMapping.URI, null, "conversion-mode");
-        return getForeignAttributes() != null
-             && "bitmap".equalsIgnoreCase((String)getForeignAttributes().get(qName));
+        return ImageHandlerUtil.isConversionModeBitmap(getForeignAttributes());
     }
 
     /** @return true if clipping is disabled inside the PCLGraphics2D. */
     public boolean isClippingDisabled() {
-        QName qName = new QName(ExtensionElementMapping.URI, null, "disable-clipping");
         return getForeignAttributes() != null
-             && "true".equalsIgnoreCase((String)getForeignAttributes().get(qName));
+             && "true".equalsIgnoreCase((String)getForeignAttributes().get(
+                     PCLConstants.DISABLE_CLIPPING));
     }
 
     /**
@@ -68,9 +67,9 @@
      * @return true if the background shouldn't be erased
      */
     public boolean isSourceTransparency() {
-        QName qName = new QName(ExtensionElementMapping.URI, null, "source-transparency");
         return getForeignAttributes() != null
-             && "true".equalsIgnoreCase((String)getForeignAttributes().get(qName));
+             && "true".equalsIgnoreCase((String)getForeignAttributes().get(
+                     PCLConstants.SRC_TRANSPARENCY));
     }
 
     /**
@@ -80,11 +79,11 @@
      * @return true if an EGB canvas should be used
      */
     public boolean isColorCanvas() {
-        QName qName = new QName(ExtensionElementMapping.URI, null, "color-canvas");
         Boolean prop = (Boolean)context.getProperty(PCLRendererContextConstants.PCL_COLOR_CANVAS);
         return Boolean.TRUE.equals(prop)
             || (getForeignAttributes() != null
-                    && "true".equalsIgnoreCase((String)getForeignAttributes().get(qName)));
+                    && "true".equalsIgnoreCase((String)getForeignAttributes().get(
+                            PCLConstants.COLOR_CANVAS)));
     }
 
 }
\ No newline at end of file

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/extensions/PCLElementMapping.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/extensions/PCLElementMapping.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/extensions/PCLElementMapping.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pcl/extensions/PCLElementMapping.java Sun Feb 22 12:40:44 2009
@@ -21,6 +21,8 @@
 
 import java.util.HashMap;
 
+import org.apache.xmlgraphics.util.QName;
+
 import org.apache.fop.fo.ElementMapping;
 
 /**
@@ -34,6 +36,14 @@
     /** The usual namespace prefix used for PCL extensions */
     public static final String NAMESPACE_PREFIX = "pcl";
 
+    /** The extension attribute for the PCL paper source */
+    public static final QName PCL_PAPER_SOURCE
+        = new QName(PCLElementMapping.NAMESPACE, null, "paper-source");
+
+    /** The extension attribute for the PCL duplex mode */
+    public static final QName PCL_DUPLEX_MODE
+        = new QName(PCLElementMapping.NAMESPACE, null, "duplex-mode");
+
     /** Main constructor */
     public PCLElementMapping() {
         this.namespaceURI = NAMESPACE;

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/ImageRenderedAdapter.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/ImageRenderedAdapter.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/ImageRenderedAdapter.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/ImageRenderedAdapter.java Sun Feb 22 12:40:44 2009
@@ -75,6 +75,18 @@
         return ((ImageRendered)this.image);
     }
 
+    /** {@inheritDoc} */
+    public int getWidth() {
+        RenderedImage ri = getImage().getRenderedImage();
+        return ri.getWidth();
+    }
+
+    /** {@inheritDoc} */
+    public int getHeight() {
+        RenderedImage ri = getImage().getRenderedImage();
+        return ri.getHeight();
+    }
+
     private ColorModel getEffectiveColorModel() {
         return encodingHelper.getEncodedColorModel();
     }

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFEventProducer.xml
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFEventProducer.xml?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFEventProducer.xml (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFEventProducer.xml Sun Feb 22 12:40:44 2009
@@ -1,4 +1,3 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<catalogue xml:lang="en">
+<?xml version="1.0" encoding="UTF-8"?><catalogue xml:lang="en">
   <message key="org.apache.fop.render.pdf.PDFEventProducer.nonFullyResolvedLinkTargets">{count} link target{count,equals,1,,s} could not be fully resolved and now point{count,equals,1,,s} to the top of the page or {count,equals,1,is,are} dysfunctional.</message>
 </catalogue>

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFGraphics2DAdapter.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFGraphics2DAdapter.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFGraphics2DAdapter.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFGraphics2DAdapter.java Sun Feb 22 12:40:44 2009
@@ -55,6 +55,7 @@
             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;
@@ -69,16 +70,17 @@
         float sx = pdfInfo.paintAsBitmap ? 1.0f : (fwidth / (float)imw);
         float sy = pdfInfo.paintAsBitmap ? 1.0f : (fheight / (float)imh);
 
-        renderer.saveGraphicsState();
-        renderer.setColor(Color.black, false, null);
-        renderer.setColor(Color.black, true, null);
+        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.
-        renderer.currentStream.add(sx + " 0 0 " + sy + " " + fx + " "
+        generator.add(sx + " 0 0 " + sy + " " + fx + " "
                           + fy + " cm\n");
 
 
@@ -95,8 +97,8 @@
 
         AffineTransform transform = new AffineTransform();
         transform.translate(fx, fy);
-        pdfInfo.pdfPaintingState.concatenate(transform);
-        graphics.setPaintingState(pdfInfo.pdfPaintingState);
+        generator.getState().concatenate(transform);
+        graphics.setPaintingState(generator.getState());
         graphics.setOutputStream(pdfInfo.outputStream);
 
         if (pdfInfo.paintAsBitmap) {
@@ -113,8 +115,9 @@
             painter.paint(graphics, area);
         }
 
-        pdfInfo.currentStream.add(graphics.getString());
-        renderer.restoreGraphicsState();
+        generator.add(graphics.getString());
+        generator.restoreGraphicsState();
+        generator.comment("G2D end");
     }
 
     /** {@inheritDoc} */

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFImageHandler.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFImageHandler.java?rev=746664&r1=746663&r2=746664&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFImageHandler.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/pdf/PDFImageHandler.java Sun Feb 22 12:40:44 2009
@@ -23,15 +23,16 @@
 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.ImageHandler;
+import org.apache.fop.render.ImageHandlerBase;
 import org.apache.fop.render.RendererContext;
-import org.apache.xmlgraphics.image.loader.Image;
 
 /**
  * This interface is used for handling all sorts of image type for PDF output.
  */
-public interface PDFImageHandler extends ImageHandler {
+public interface PDFImageHandler extends ImageHandlerBase {
 
     /**
      * Generates the PDF objects for the given {@link Image} instance. If the handler generates



---------------------------------------------------------------------
To unsubscribe, e-mail: fop-commits-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-commits-help@xmlgraphics.apache.org


Mime
View raw message