diff options
author | Mehdi Houshmand <mehdi@apache.org> | 2012-07-03 09:46:41 +0000 |
---|---|---|
committer | Mehdi Houshmand <mehdi@apache.org> | 2012-07-03 09:46:41 +0000 |
commit | 4e47dc20363d4ee9afbde17db4f7d20c5d480158 (patch) | |
tree | 6f5c714e59c93795a4f4b7ceecd12e06008d7835 /src/java/org/apache/fop/render | |
parent | 2a7e60cb3390a91d428fb607c0e19eaa911ec5b9 (diff) | |
parent | ddf23aef5465ec7b939fb304b30d877bd5ec43be (diff) | |
download | xmlgraphics-fop-4e47dc20363d4ee9afbde17db4f7d20c5d480158.tar.gz xmlgraphics-fop-4e47dc20363d4ee9afbde17db4f7d20c5d480158.zip |
Merged Temp_URI_Unification branch back into trunk
git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/trunk@1356646 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'src/java/org/apache/fop/render')
100 files changed, 3456 insertions, 1877 deletions
diff --git a/src/java/org/apache/fop/render/AbstractConfigurator.java b/src/java/org/apache/fop/render/AbstractConfigurator.java index c3c6733b0..c890d0830 100644 --- a/src/java/org/apache/fop/render/AbstractConfigurator.java +++ b/src/java/org/apache/fop/render/AbstractConfigurator.java @@ -19,9 +19,6 @@ package org.apache.fop.render; -import org.apache.avalon.framework.configuration.Configuration; -import org.apache.avalon.framework.configuration.ConfigurationException; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -49,41 +46,6 @@ public abstract class AbstractConfigurator { } /** - * Returns the configuration subtree for a specific renderer. - * @param mimeType the MIME type of the renderer - * @return the requested configuration subtree, null if there's no configuration - */ - protected Configuration getConfig(String mimeType) { - Configuration cfg = userAgent.getFactory().getUserConfig(); - if (cfg == null) { - if (log.isDebugEnabled()) { - log.debug("userconfig is null"); - } - return null; - } - - Configuration userConfig = null; - - String type = getType(); - Configuration[] cfgs - = cfg.getChild(type + "s").getChildren(type); - for (int i = 0; i < cfgs.length; ++i) { - Configuration child = cfgs[i]; - try { - if (child.getAttribute(MIME).equals(mimeType)) { - userConfig = child; - break; - } - } catch (ConfigurationException e) { - // silently pass over configurations without mime type - } - } - log.debug((userConfig == null ? "No u" : "U") - + "ser configuration found for MIME type " + mimeType); - return userConfig; - } - - /** * Returns the configurator type * @return the configurator type */ diff --git a/src/java/org/apache/fop/render/AbstractRendererConfigurator.java b/src/java/org/apache/fop/render/AbstractRendererConfigurator.java index e1bc10440..799469353 100644 --- a/src/java/org/apache/fop/render/AbstractRendererConfigurator.java +++ b/src/java/org/apache/fop/render/AbstractRendererConfigurator.java @@ -19,49 +19,30 @@ package org.apache.fop.render; -import org.apache.avalon.framework.configuration.Configuration; - import org.apache.fop.apps.FOUserAgent; /** * Abstract base classes for renderer-related configurator classes. This class basically just * provides an accessor to the specific renderer configuration object. */ -public abstract class AbstractRendererConfigurator extends AbstractConfigurator { +public abstract class AbstractRendererConfigurator { - private static final String TYPE = "renderer"; + /** fop factory configuration */ + protected final FOUserAgent userAgent; /** * Default constructor * @param userAgent user agent */ public AbstractRendererConfigurator(FOUserAgent userAgent) { - super(userAgent); - } - - /** - * Returns the configuration subtree for a specific renderer. - * @param renderer the renderer - * @return the requested configuration subtree, null if there's no configuration - */ - protected Configuration getRendererConfig(Renderer renderer) { - return super.getConfig(renderer.getMimeType()); + this.userAgent = userAgent; } /** - * Returns the configuration subtree for a specific renderer. - * @param mimeType the MIME type of the renderer - * @return the requested configuration subtree, null if there's no configuration + * Returns the configurator type + * @return the configurator type */ - protected Configuration getRendererConfig(String mimeType) { - return super.getConfig(mimeType); + public static String getType() { + return "renderer"; } - - /** - * {@inheritDoc} - */ - public String getType() { - return TYPE; - } - } diff --git a/src/java/org/apache/fop/render/AbstractRendererMaker.java b/src/java/org/apache/fop/render/AbstractRendererMaker.java index fadfda94d..b4a281efa 100644 --- a/src/java/org/apache/fop/render/AbstractRendererMaker.java +++ b/src/java/org/apache/fop/render/AbstractRendererMaker.java @@ -19,6 +19,7 @@ package org.apache.fop.render; +import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; /** @@ -50,9 +51,8 @@ public abstract class AbstractRendererMaker { * @param userAgent user agent * @return a config object that can be used to configure the renderer */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return null; - } + public abstract void configureRenderer(FOUserAgent userAgent, Renderer renderer) + throws FOPException; /** * Indicates whether a specific MIME type is supported by this renderer. diff --git a/src/java/org/apache/fop/render/DefaultRendererConfigurator.java b/src/java/org/apache/fop/render/DefaultRendererConfigurator.java new file mode 100644 index 000000000..061c25709 --- /dev/null +++ b/src/java/org/apache/fop/render/DefaultRendererConfigurator.java @@ -0,0 +1,48 @@ +/* + * 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.ArrayList; +import java.util.List; + +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.fonts.FontCollection; +import org.apache.fop.fonts.FontManager; +import org.apache.fop.fonts.base14.Base14FontCollection; +import org.apache.fop.render.RendererConfig.RendererConfigParser; + +/** + * This object represents the default renderer configurator and contains the methods for most the + * RendererConfigurators. + */ +public class DefaultRendererConfigurator extends PrintRendererConfigurator { + + public DefaultRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + super(userAgent, rendererConfigParser); + } + + protected List<FontCollection> getDefaultFontCollection() { + FontManager fontManager = userAgent.getFontManager(); + List<FontCollection> fontCollection = new ArrayList<FontCollection>(); + fontCollection.add(new Base14FontCollection(fontManager.isBase14KerningEnabled())); + return fontCollection; + } + +} diff --git a/src/java/org/apache/fop/render/PrintRenderer.java b/src/java/org/apache/fop/render/PrintRenderer.java index 2017dbd88..5302975f6 100644 --- a/src/java/org/apache/fop/render/PrintRenderer.java +++ b/src/java/org/apache/fop/render/PrintRenderer.java @@ -36,10 +36,11 @@ 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.fonts.FontResolver; import org.apache.fop.fonts.FontTriplet; import org.apache.fop.fonts.base14.Base14FontCollection; +import sun.font.FontResolver; + /** Abstract base class of "Print" type renderers. */ public abstract class PrintRenderer extends AbstractRenderer { @@ -88,11 +89,11 @@ public abstract class PrintRenderer extends AbstractRenderer { /** {@inheritDoc} */ public void setupFontInfo(FontInfo inFontInfo) throws FOPException { this.fontInfo = inFontInfo; - FontManager fontManager = userAgent.getFactory().getFontManager(); + FontManager fontManager = userAgent.getFontManager(); FontCollection[] fontCollections = new FontCollection[] { new Base14FontCollection(fontManager.isBase14KerningEnabled()), - new CustomFontCollection(getFontResolver(), getFontList(), - userAgent.isComplexScriptFeaturesEnabled()) + new CustomFontCollection(fontManager.getResourceResolver(), getFontList(), + userAgent.isComplexScriptFeaturesEnabled()) }; fontManager.setup(getFontInfo(), fontCollections); } @@ -180,18 +181,6 @@ public abstract class PrintRenderer extends AbstractRenderer { } /** - * Get FontResolver - * - * @return FontResolver - */ - public FontResolver getFontResolver() { - if (this.fontResolver == null) { - this.fontResolver = new DefaultFontResolver(super.userAgent); - } - return this.fontResolver; - } - - /** * @return the font info */ public FontInfo getFontInfo() { diff --git a/src/java/org/apache/fop/render/PrintRendererConfigurator.java b/src/java/org/apache/fop/render/PrintRendererConfigurator.java index 93678b4f8..f36bd4c7f 100644 --- a/src/java/org/apache/fop/render/PrintRendererConfigurator.java +++ b/src/java/org/apache/fop/render/PrintRendererConfigurator.java @@ -19,124 +19,155 @@ package org.apache.fop.render; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import org.apache.avalon.framework.configuration.Configuration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.FopFactory; +import org.apache.fop.apps.io.InternalResourceResolver; import org.apache.fop.fonts.CustomFontCollection; +import org.apache.fop.fonts.DefaultFontConfigurator; import org.apache.fop.fonts.EmbedFontInfo; import org.apache.fop.fonts.FontCollection; +import org.apache.fop.fonts.FontConfigurator; import org.apache.fop.fonts.FontEventAdapter; -import org.apache.fop.fonts.FontEventListener; import org.apache.fop.fonts.FontInfo; -import org.apache.fop.fonts.FontInfoConfigurator; import org.apache.fop.fonts.FontManager; -import org.apache.fop.fonts.FontResolver; -import org.apache.fop.fonts.base14.Base14FontCollection; +import org.apache.fop.render.RendererConfig.RendererConfigParser; import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; /** * Base Print renderer configurator (mostly handles font configuration) */ -public class PrintRendererConfigurator extends AbstractRendererConfigurator - implements RendererConfigurator, IFDocumentHandlerConfigurator { +public abstract class PrintRendererConfigurator extends AbstractRendererConfigurator + implements IFDocumentHandlerConfigurator { /** logger instance */ - protected static final Log log = LogFactory.getLog(PrintRendererConfigurator.class); + private static Log LOG = LogFactory.getLog(PrintRendererConfigurator.class); + + private final RendererConfigParser rendererConfigParser; + + private final FontConfigurator<EmbedFontInfo> fontInfoConfigurator; /** * Default constructor * @param userAgent user agent */ - public PrintRendererConfigurator(FOUserAgent userAgent) { + public PrintRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + this(userAgent, rendererConfigParser, + new DefaultFontConfigurator(userAgent.getFontManager(), new FontEventAdapter( + userAgent.getEventBroadcaster()), userAgent.validateUserConfigStrictly())); + } + + /** + * Default constructor + * @param userAgent user agent + */ + public PrintRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser, + FontConfigurator<EmbedFontInfo> fontInfoConfigurator) { super(userAgent); + this.rendererConfigParser = rendererConfigParser; + this.fontInfoConfigurator = fontInfoConfigurator; } /** - * Builds a list of EmbedFontInfo objects for use with the setup() method. + * Returns the renderer configuration data for a specific renderer. * - * @param renderer print renderer - * @throws FOPException if something's wrong with the config data + * @param documentHandler the document handler + * @return the renderer configuration data + * @throws FOPException if an error occurs */ - public void configure(Renderer renderer) throws FOPException { - Configuration cfg = getRendererConfig(renderer); - if (cfg == null) { - log.trace("no configuration found for " + renderer); - return; - } - - PrintRenderer printRenderer = (PrintRenderer)renderer; - FontResolver fontResolver = printRenderer.getFontResolver(); + protected RendererConfig getRendererConfig(IFDocumentHandler documentHandler) throws FOPException { + return getRendererConfig(documentHandler.getMimeType()); + } - FontEventListener listener = new FontEventAdapter( - renderer.getUserAgent().getEventBroadcaster()); - List<EmbedFontInfo> embedFontInfoList = buildFontList(cfg, fontResolver, listener); - printRenderer.addFontList(embedFontInfoList); + /** + * gets the renderer configuration data for a specific renderer. + * + * @param mimeType the MIME type + * @return the renderer configuration data + * @throws FOPException if an error occurs + */ + protected RendererConfig getRendererConfig(String mimeType) throws FOPException { + return userAgent.getRendererConfig(mimeType, rendererConfigParser); } /** - * Builds the font list from configuration. - * @param cfg the configuration object - * @param fontResolver a font resolver - * @param listener the font event listener - * @return the list of {@link EmbedFontInfo} objects - * @throws FOPException if an error occurs while processing the configuration + * gets the renderer configuration data for a specific renderer. + * + * @param renderer the renderer + * @return the renderer configuration data + * @throws FOPException if an error occurs */ - protected List<EmbedFontInfo> buildFontList(Configuration cfg, FontResolver fontResolver, - FontEventListener listener) throws FOPException { - FopFactory factory = userAgent.getFactory(); - FontManager fontManager = factory.getFontManager(); - if (fontResolver == null) { - //Ensure that we have minimal font resolution capabilities - fontResolver - = FontManager.createMinimalFontResolver - ( userAgent.isComplexScriptFeaturesEnabled() ); - } + protected RendererConfig getRendererConfig(Renderer renderer) throws FOPException { + return getRendererConfig(renderer.getMimeType()); + } - boolean strict = factory.validateUserConfigStrictly(); - //Read font configuration - FontInfoConfigurator fontInfoConfigurator - = new FontInfoConfigurator(cfg, fontManager, fontResolver, listener, strict); - List<EmbedFontInfo> fontInfoList = new ArrayList<EmbedFontInfo>(); - fontInfoConfigurator.configure(fontInfoList); - return fontInfoList; + /** + * Builds a list of EmbedFontInfo objects for use with the setup() method. + * + * @param renderer print renderer + * @throws FOPException if something's wrong with the config data + */ + public void configure(Renderer renderer) throws FOPException { + PrintRenderer printRenderer = (PrintRenderer) renderer; + List<EmbedFontInfo> embedFontInfoList = buildFontList(renderer.getMimeType()); + printRenderer.addFontList(embedFontInfoList); } - // ---=== IFDocumentHandler configuration ===--- - /** {@inheritDoc} */ public void configure(IFDocumentHandler documentHandler) throws FOPException { //nop } /** {@inheritDoc} */ - public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) - throws FOPException { - FontManager fontManager = userAgent.getFactory().getFontManager(); - List<FontCollection> fontCollections = new ArrayList<FontCollection>(); - fontCollections.add(new Base14FontCollection(fontManager.isBase14KerningEnabled())); - - Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); - if (cfg != null) { - FontResolver fontResolver = new DefaultFontResolver(userAgent); - FontEventListener listener = new FontEventAdapter( - userAgent.getEventBroadcaster()); - List<EmbedFontInfo> fontList = buildFontList(cfg, fontResolver, listener); - fontCollections.add(new CustomFontCollection(fontResolver, fontList, - userAgent.isComplexScriptFeaturesEnabled())); + public void setupFontInfo(String mimeType, FontInfo fontInfo) throws FOPException { + FontManager fontManager = userAgent.getFontManager(); + List<FontCollection> fontCollections = getDefaultFontCollection(); + fontCollections.add(getCustomFontCollection(fontManager.getResourceResolver(), mimeType)); + fontManager.setup(fontInfo, fontCollections.toArray(new FontCollection[fontCollections.size()])); + } + + protected abstract List<FontCollection> getDefaultFontCollection(); + + /** + * Returns the font collection for custom configured fonts. + * + * @param resolver the resource resolver + * @param mimeType the renderer MIME type + * @return the font collection + * @throws FOPException if an error occurs + */ + protected FontCollection getCustomFontCollection(InternalResourceResolver resolver, String mimeType) + throws FOPException { + List<EmbedFontInfo> fontList; + if (rendererConfigParser == null) { + fontList = Collections.<EmbedFontInfo>emptyList(); + } else { + fontList = fontInfoConfigurator.configure(getRendererConfig(mimeType).getFontInfoConfig()); } + return createCollectionFromFontList(resolver, fontList); + } + + /*** + * Creates the font collection given a list of embedded font infomation. + * + * @param resolver the resource resolver + * @param fontList the embedded font infomation + * @return the font collection + */ + protected FontCollection createCollectionFromFontList(InternalResourceResolver resolver, + List<EmbedFontInfo> fontList) { + return new CustomFontCollection(resolver, fontList, + userAgent.isComplexScriptFeaturesEnabled()); + } - fontManager.setup(fontInfo, - (FontCollection[])fontCollections.toArray( - new FontCollection[fontCollections.size()])); - documentHandler.setFontInfo(fontInfo); + private List<EmbedFontInfo> buildFontList(String mimeType) throws FOPException { + return fontInfoConfigurator.configure(getRendererConfig(mimeType).getFontInfoConfig()); } } diff --git a/src/java/org/apache/fop/render/RendererConfig.java b/src/java/org/apache/fop/render/RendererConfig.java new file mode 100644 index 000000000..4b3b63a51 --- /dev/null +++ b/src/java/org/apache/fop/render/RendererConfig.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render; + +import org.apache.avalon.framework.configuration.Configuration; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.fonts.FontConfig; + +/** + * Implementations of this interface have all the renderer-specific configuration data found in the + * FOP-conf. This object is just a data object that is created by the {@link RendererConfigParser} + * when the FOP conf is parsed. + */ +public interface RendererConfig { + + /** + * Returns the render-specific font configuration information. + * @return the font config + */ + FontConfig getFontInfoConfig(); + + /** + * Implementations of this interface parse the relevant renderer-specific configuration data + * within the FOP-conf and create a {@link RendererConfig}. + */ + public interface RendererConfigParser { + + /** + * Builds the object that contains the renderer configuration data. + * + * @param userAgent the user agent + * @param rendererConfiguration the Avalon config object for parsing the data + * @return the configuration data object + * @throws FOPException if an error occurs while parsing the fop conf + */ + RendererConfig build(FOUserAgent userAgent, Configuration rendererConfiguration) throws FOPException; + + /** + * The MIME type of the renderer. + * + * @return the mime type + */ + String getMimeType(); + } +} diff --git a/src/java/org/apache/fop/render/RendererConfigurator.java b/src/java/org/apache/fop/render/RendererConfigOption.java index 6dceeb74d..5b670d07a 100644 --- a/src/java/org/apache/fop/render/RendererConfigurator.java +++ b/src/java/org/apache/fop/render/RendererConfigOption.java @@ -19,16 +19,11 @@ package org.apache.fop.render; -import org.apache.fop.apps.FOPException; - /** - * Renderer configurator interface + * Implementations of this interface enumerate the various renderer configuration options available + * to users in the FOP conf. */ -public interface RendererConfigurator { - /** - * Configures a renderer - * @param renderer renderer - * @throws FOPException fop exception - */ - void configure(Renderer renderer) throws FOPException; +public interface RendererConfigOption { + /** The name of the option. */ + String getName(); } diff --git a/src/java/org/apache/fop/render/RendererFactory.java b/src/java/org/apache/fop/render/RendererFactory.java index 3ceb27a8e..df5213dad 100644 --- a/src/java/org/apache/fop/render/RendererFactory.java +++ b/src/java/org/apache/fop/render/RendererFactory.java @@ -36,6 +36,7 @@ import org.apache.fop.area.AreaTreeHandler; import org.apache.fop.fo.FOEventHandler; import org.apache.fop.render.intermediate.AbstractIFDocumentHandlerMaker; import org.apache.fop.render.intermediate.EventProducingFilter; +import org.apache.fop.render.intermediate.IFContext; import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; import org.apache.fop.render.intermediate.IFRenderer; @@ -52,25 +53,19 @@ public class RendererFactory { private Map eventHandlerMakerMapping = new java.util.HashMap(); private Map documentHandlerMakerMapping = new java.util.HashMap(); - private boolean rendererPreferred = false; + private final boolean rendererPreferred; /** * Main constructor. + * @param rendererPreferred Controls whether a {@link Renderer} is preferred over a + * {@link IFDocumentHandler} if both are available for the same MIME type. True to prefer the + * {@link Renderer}, false to prefer the {@link IFDocumentHandler}. */ - public RendererFactory() { + public RendererFactory(boolean rendererPreferred) { discoverRenderers(); discoverFOEventHandlers(); discoverDocumentHandlers(); - } - - /** - * Controls whether a {@link Renderer} is preferred over a {@link IFDocumentHandler} if - * both are available for the same MIME type. - * @param value true to prefer the {@link Renderer}, - * false to prefer the {@link IFDocumentHandler}. - */ - public void setRendererPreferred(boolean value) { - this.rendererPreferred = value; + this.rendererPreferred = rendererPreferred; } /** @@ -239,7 +234,7 @@ public class RendererFactory { * @param mime the requested output format * @return the requested RendererMaker or null if none is available */ - public AbstractIFDocumentHandlerMaker getDocumentHandlerMaker(String mime) { + private AbstractIFDocumentHandlerMaker getDocumentHandlerMaker(String mime) { AbstractIFDocumentHandlerMaker maker = (AbstractIFDocumentHandlerMaker)documentHandlerMakerMapping.get(mime); return maker; @@ -299,10 +294,7 @@ public class RendererFactory { AbstractRendererMaker maker = getRendererMaker(outputFormat); if (maker != null) { Renderer rend = maker.makeRenderer(userAgent); - RendererConfigurator configurator = maker.getConfigurator(userAgent); - if (configurator != null) { - configurator.configure(rend); - } + maker.configureRenderer(userAgent, rend); return rend; } else { return null; @@ -383,7 +375,10 @@ public class RendererFactory { throw new UnsupportedOperationException( "No IF document handler for the requested format available: " + outputFormat); } - IFDocumentHandler documentHandler = maker.makeIFDocumentHandler(userAgent); + IFDocumentHandler documentHandler = maker.makeIFDocumentHandler(new IFContext(userAgent)); + // TODO: do all the configuration in the makeIfDocumentHandler method, that would beam when + // you ask for a document handler, a configured one is returned to you. Getting it and + // configuring it in two steps doesn't make sense. IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); if (configurator != null) { configurator.configure(documentHandler); @@ -398,15 +393,15 @@ public class RendererFactory { List lst = new java.util.ArrayList(); Iterator iter = this.rendererMakerMapping.keySet().iterator(); while (iter.hasNext()) { - lst.add(((String)iter.next())); + lst.add(iter.next()); } iter = this.eventHandlerMakerMapping.keySet().iterator(); while (iter.hasNext()) { - lst.add(((String)iter.next())); + lst.add(iter.next()); } iter = this.documentHandlerMakerMapping.keySet().iterator(); while (iter.hasNext()) { - lst.add(((String)iter.next())); + lst.add(iter.next()); } Collections.sort(lst); return (String[])lst.toArray(new String[lst.size()]); diff --git a/src/java/org/apache/fop/render/XMLHandlerConfigurator.java b/src/java/org/apache/fop/render/XMLHandlerConfigurator.java index 604fdb672..fbce59a07 100644 --- a/src/java/org/apache/fop/render/XMLHandlerConfigurator.java +++ b/src/java/org/apache/fop/render/XMLHandlerConfigurator.java @@ -83,7 +83,7 @@ public class XMLHandlerConfigurator extends AbstractRendererConfigurator { */ public void configure(RendererContext context, String ns) throws FOPException { //Optional XML handler configuration - Configuration cfg = getRendererConfig(context.getRenderer()); + Configuration cfg = userAgent.getRendererConfiguration(context.getRenderer().getMimeType()); if (cfg != null) { cfg = getHandlerConfig(cfg, ns); if (cfg != null) { diff --git a/src/java/org/apache/fop/render/afp/AFPCustomizable.java b/src/java/org/apache/fop/render/afp/AFPCustomizable.java index e0924c0d0..1bdb18cf2 100644 --- a/src/java/org/apache/fop/render/afp/AFPCustomizable.java +++ b/src/java/org/apache/fop/render/afp/AFPCustomizable.java @@ -19,6 +19,8 @@ package org.apache.fop.render.afp; +import java.net.URI; + import org.apache.fop.afp.AFPResourceLevelDefaults; /** @@ -152,10 +154,10 @@ public interface AFPCustomizable { boolean isStrokeGOCAText(); /** - * Sets the default resource group file path - * @param filePath the default resource group file path + * Sets the default resource group URI + * @param uri the default resource group URI */ - void setDefaultResourceGroupFilePath(String filePath); + void setDefaultResourceGroupUri(URI uri); /** * Sets the resource level defaults. The object passed in provides information which resource diff --git a/src/java/org/apache/fop/render/afp/AFPDocumentHandler.java b/src/java/org/apache/fop/render/afp/AFPDocumentHandler.java index 76de3f704..fb6c89ce4 100644 --- a/src/java/org/apache/fop/render/afp/AFPDocumentHandler.java +++ b/src/java/org/apache/fop/render/afp/AFPDocumentHandler.java @@ -23,6 +23,7 @@ import java.awt.Color; import java.awt.Dimension; import java.awt.geom.AffineTransform; import java.io.IOException; +import java.net.URI; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -38,13 +39,13 @@ import org.apache.fop.afp.DataStream; import org.apache.fop.afp.fonts.AFPFontCollection; import org.apache.fop.afp.fonts.AFPPageFonts; 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.afp.util.AFPResourceAccessor; import org.apache.fop.apps.MimeConstants; import org.apache.fop.fonts.FontCollection; import org.apache.fop.fonts.FontEventAdapter; import org.apache.fop.fonts.FontInfo; import org.apache.fop.fonts.FontManager; +import org.apache.fop.render.afp.AFPRendererConfig.AFPRendererConfigParser; import org.apache.fop.render.afp.extensions.AFPElementMapping; import org.apache.fop.render.afp.extensions.AFPIncludeFormMap; import org.apache.fop.render.afp.extensions.AFPInvokeMediumMap; @@ -53,6 +54,8 @@ import org.apache.fop.render.afp.extensions.AFPPageSegmentElement; import org.apache.fop.render.afp.extensions.AFPPageSetup; import org.apache.fop.render.afp.extensions.ExtensionPlacement; import org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler; +import org.apache.fop.render.intermediate.IFContext; +import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; import org.apache.fop.render.intermediate.IFException; import org.apache.fop.render.intermediate.IFPainter; @@ -99,8 +102,9 @@ public class AFPDocumentHandler extends AbstractBinaryWritingIFDocumentHandler /** * Default constructor. */ - public AFPDocumentHandler() { - this.resourceManager = new AFPResourceManager(); + public AFPDocumentHandler(IFContext context) { + super(context); + this.resourceManager = new AFPResourceManager(context.getUserAgent().getResourceResolver()); this.paintingState = new AFPPaintingState(); this.unitConv = paintingState.getUnitConverter(); } @@ -117,13 +121,13 @@ public class AFPDocumentHandler extends AbstractBinaryWritingIFDocumentHandler /** {@inheritDoc} */ public IFDocumentHandlerConfigurator getConfigurator() { - return new AFPRendererConfigurator(getUserAgent()); + return new AFPRendererConfigurator(getUserAgent(), new AFPRendererConfigParser()); } /** {@inheritDoc} */ @Override public void setDefaultFontInfo(FontInfo fontInfo) { - FontManager fontManager = getUserAgent().getFactory().getFontManager(); + FontManager fontManager = getUserAgent().getFontManager(); FontCollection[] fontCollections = new FontCollection[] { new AFPFontCollection(getUserAgent().getEventBroadcaster(), null) }; @@ -381,8 +385,8 @@ public class AFPDocumentHandler extends AbstractBinaryWritingIFDocumentHandler } } else if (extension instanceof AFPIncludeFormMap) { AFPIncludeFormMap formMap = (AFPIncludeFormMap)extension; - ResourceAccessor accessor = new DefaultFOPResourceAccessor( - getUserAgent(), null, null); + AFPResourceAccessor accessor = new AFPResourceAccessor( + getUserAgent().getResourceResolver()); try { getResourceManager().createIncludedResource(formMap.getName(), formMap.getSrc(), accessor, @@ -493,9 +497,8 @@ public class AFPDocumentHandler extends AbstractBinaryWritingIFDocumentHandler return paintingState.getFS45(); } - /** {@inheritDoc} */ - public void setDefaultResourceGroupFilePath(String filePath) { - resourceManager.setDefaultResourceGroupFilePath(filePath); + public void setDefaultResourceGroupUri(URI uri) { + resourceManager.setDefaultResourceGroupUri(uri); } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/afp/AFPDocumentHandlerMaker.java b/src/java/org/apache/fop/render/afp/AFPDocumentHandlerMaker.java index cbe6d0ca3..f83ede9f7 100644 --- a/src/java/org/apache/fop/render/afp/AFPDocumentHandlerMaker.java +++ b/src/java/org/apache/fop/render/afp/AFPDocumentHandlerMaker.java @@ -19,7 +19,6 @@ package org.apache.fop.render.afp; -import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.MimeConstants; import org.apache.fop.render.intermediate.AbstractIFDocumentHandlerMaker; import org.apache.fop.render.intermediate.IFContext; @@ -36,10 +35,8 @@ public class AFPDocumentHandlerMaker extends AbstractIFDocumentHandlerMaker { }; /** {@inheritDoc} */ - public IFDocumentHandler makeIFDocumentHandler(FOUserAgent ua) { - AFPDocumentHandler handler = new AFPDocumentHandler(); - handler.setContext(new IFContext(ua)); - return handler; + public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) { + return new AFPDocumentHandler(ifContext); } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/afp/AFPFontConfig.java b/src/java/org/apache/fop/render/afp/AFPFontConfig.java new file mode 100644 index 000000000..4b2ece440 --- /dev/null +++ b/src/java/org/apache/fop/render/afp/AFPFontConfig.java @@ -0,0 +1,439 @@ +/* + * 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.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.avalon.framework.configuration.Configuration; +import org.apache.avalon.framework.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.fop.afp.AFPEventProducer; +import org.apache.fop.afp.fonts.AFPFont; +import org.apache.fop.afp.fonts.AFPFontInfo; +import org.apache.fop.afp.fonts.CharacterSet; +import org.apache.fop.afp.fonts.CharacterSetBuilder; +import org.apache.fop.afp.fonts.CharacterSetType; +import org.apache.fop.afp.fonts.DoubleByteFont; +import org.apache.fop.afp.fonts.OutlineFont; +import org.apache.fop.afp.fonts.RasterFont; +import org.apache.fop.afp.util.AFPResourceAccessor; +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.io.InternalResourceResolver; +import org.apache.fop.events.EventProducer; +import org.apache.fop.fonts.FontConfig; +import org.apache.fop.fonts.FontManager; +import org.apache.fop.fonts.FontManagerConfigurator; +import org.apache.fop.fonts.FontTriplet; +import org.apache.fop.fonts.FontTriplet.Matcher; +import org.apache.fop.fonts.FontUtil; +import org.apache.fop.fonts.Typeface; + +/** + * The config object for AFP fonts, these differ from the the more generic fonts (TTF and Type1). + */ +public final class AFPFontConfig implements FontConfig { + + private static final Log LOG = LogFactory.getLog(AFPFontConfig.class); + + private final List<AFPFontConfigData> fontsConfig; + + private AFPFontConfig() { + fontsConfig = new ArrayList<AFPFontConfigData>(); + } + + /** + * Returns a list of AFP font configuration data. + * @return the AFP font config data + */ + public List<AFPFontConfigData> getFontConfig() { + return fontsConfig; + } + + /** + * The parser for AFP font data. + */ + static final class AFPFontInfoConfigParser implements FontConfigParser { + + /** {@inheritDoc}} */ + public AFPFontConfig parse(Configuration cfg, FontManager fontManager, boolean strict, + EventProducer eventProducer) throws FOPException { + try { + return new ParserHelper(cfg, fontManager, strict, + (AFPEventProducer) eventProducer).fontConfig; + } catch (ConfigurationException ce) { + throw new FOPException(ce); + } + } + + AFPFontConfig getEmptyConfig() { + return new AFPFontConfig(); + } + } + + private static final class AggregateMatcher implements Matcher { + + private final List<Matcher> matchers; + + private AggregateMatcher(Matcher... matchers) { + this.matchers = new ArrayList<Matcher>(); + for (Matcher matcher : matchers) { + if (matcher != null) { + this.matchers.add(matcher); + } + } + } + + public boolean matches(FontTriplet triplet) { + for (Matcher matcher : matchers) { + if (matcher.matches(triplet)) { + return true; + } + } + return false; + } + + } + + private static final class ParserHelper { + + private static final Log LOG = LogFactory.getLog(ParserHelper.class); + + private final AFPFontConfig fontConfig; + + private final Matcher matcher; + + private ParserHelper(Configuration cfg, FontManager fontManager, boolean strict, + AFPEventProducer eventProducer) throws FOPException, ConfigurationException { + Configuration fonts = cfg.getChild("fonts"); + Matcher localMatcher = null; + Configuration referencedFontsCfg = fonts.getChild("referenced-fonts", false); + if (referencedFontsCfg != null) { + localMatcher = FontManagerConfigurator.createFontsMatcher(referencedFontsCfg, strict); + } + matcher = new AggregateMatcher(fontManager.getReferencedFontsMatcher(), localMatcher); + fontConfig = new AFPFontConfig(); + for (Configuration font : fonts.getChildren("font")) { + buildFont(font, eventProducer); + } + } + + private void buildFont(Configuration fontCfg, AFPEventProducer eventProducer) + throws ConfigurationException { + //FontManager fontManager = this.userAgent.getFontManager(); + Configuration[] triplets = fontCfg.getChildren("font-triplet"); + List<FontTriplet> tripletList = new ArrayList<FontTriplet>(); + if (triplets.length == 0) { + eventProducer.fontConfigMissing(this, "<font-triplet...", fontCfg.getLocation()); + return; + } + for (Configuration triplet : triplets) { + int weight = FontUtil.parseCSS2FontWeight(triplet.getAttribute("weight")); + FontTriplet fontTriplet = new FontTriplet(triplet.getAttribute("name"), + triplet.getAttribute("style"), weight); + tripletList.add(fontTriplet); + } + //build the fonts + Configuration[] config = fontCfg.getChildren("afp-font"); + if (config.length == 0) { + eventProducer.fontConfigMissing(this, "<afp-font...", fontCfg.getLocation()); + return; + } + Configuration afpFontCfg = config[0]; + String uri = afpFontCfg.getAttribute("base-uri", null); + try { + String type = afpFontCfg.getAttribute("type"); + if (type == null) { + eventProducer.fontConfigMissing(this, "type attribute", fontCfg.getLocation()); + return; + } + String codepage = afpFontCfg.getAttribute("codepage"); + if (codepage == null) { + eventProducer.fontConfigMissing(this, "codepage attribute", + fontCfg.getLocation()); + return; + } + String encoding = afpFontCfg.getAttribute("encoding"); + if (encoding == null) { + eventProducer.fontConfigMissing(this, "encoding attribute", + fontCfg.getLocation()); + return; + } + + fontFromType(tripletList, type, codepage, encoding, afpFontCfg, eventProducer, uri); + } catch (ConfigurationException ce) { + eventProducer.invalidConfiguration(this, ce); + } + } + + private void fontFromType(List<FontTriplet> fontTriplets, String type, String codepage, + String encoding, Configuration cfg, AFPEventProducer eventProducer, String embedURI) + throws ConfigurationException { + AFPFontConfigData config = null; + if ("raster".equalsIgnoreCase(type)) { + config = getRasterFont(fontTriplets, type, codepage, encoding, cfg, eventProducer, + embedURI); + } else if ("outline".equalsIgnoreCase(type)) { + config = getOutlineFont(fontTriplets, type, codepage, encoding, cfg, eventProducer, + embedURI); + } else if ("CIDKeyed".equalsIgnoreCase(type)) { + config = getCIDKeyedFont(fontTriplets, type, codepage, encoding, cfg, + eventProducer, + embedURI); + } else { + LOG.error("No or incorrect type attribute: " + type); + } + if (config != null) { + fontConfig.fontsConfig.add(config); + } + } + + private CIDKeyedFontConfig getCIDKeyedFont(List<FontTriplet> fontTriplets, String type, + String codepage, String encoding, Configuration cfg, AFPEventProducer eventProducer, + String uri) throws ConfigurationException { + String characterset = cfg.getAttribute("characterset"); + if (characterset == null) { + eventProducer.fontConfigMissing(this, "characterset attribute", + cfg.getLocation()); + return null; + } + String name = cfg.getAttribute("name", characterset); + CharacterSetType charsetType = cfg.getAttributeAsBoolean("ebcdic-dbcs", false) + ? CharacterSetType.DOUBLE_BYTE_LINE_DATA : CharacterSetType.DOUBLE_BYTE; + return new CIDKeyedFontConfig(fontTriplets, type, codepage, encoding, characterset, + name, charsetType, isEmbbedable(fontTriplets), uri); + } + + private OutlineFontConfig getOutlineFont(List<FontTriplet> fontTriplets, String type, + String codepage, String encoding, Configuration cfg, + AFPEventProducer eventProducer, String uri) throws ConfigurationException { + String characterset = cfg.getAttribute("characterset"); + if (characterset == null) { + eventProducer.fontConfigMissing(this, "characterset attribute", + cfg.getLocation()); + return null; + } + String name = cfg.getAttribute("name", characterset); + String base14 = cfg.getAttribute("base14-font", null); + return new OutlineFontConfig(fontTriplets, type, codepage, encoding, characterset, + name, base14, isEmbbedable(fontTriplets), uri); + } + + private RasterFontConfig getRasterFont(List<FontTriplet> triplets, String type, + String codepage, String encoding, Configuration cfg, + AFPEventProducer eventProducer, String uri) + throws ConfigurationException { + String name = cfg.getAttribute("name", "Unknown"); + // Create a new font object + Configuration[] rasters = cfg.getChildren("afp-raster-font"); + if (rasters.length == 0) { + eventProducer.fontConfigMissing(this, "<afp-raster-font...", + cfg.getLocation()); + return null; + } + List<RasterCharactersetData> charsetData = new ArrayList<RasterCharactersetData>(); + for (Configuration rasterCfg : rasters) { + String characterset = rasterCfg.getAttribute("characterset"); + if (characterset == null) { + eventProducer.fontConfigMissing(this, "characterset attribute", + cfg.getLocation()); + return null; + } + float size = rasterCfg.getAttributeAsFloat("size"); + int sizeMpt = (int) (size * 1000); + String base14 = rasterCfg.getAttribute("base14-font", null); + charsetData.add(new RasterCharactersetData(characterset, sizeMpt, base14)); + } + return new RasterFontConfig(triplets, type, codepage, encoding, null, name, uri, charsetData, + isEmbbedable(triplets)); + } + + private boolean isEmbbedable(List<FontTriplet> triplets) { + for (FontTriplet triplet : triplets) { + if (matcher.matches(triplet)) { + return false; + } + } + return true; + } + + } + + abstract static class AFPFontConfigData { + private final List<FontTriplet> triplets; + private final String codePage; + private final String encoding; + private final String name; + private final boolean embeddable; + private final String uri; + + AFPFontConfigData(List<FontTriplet> triplets, String type, String codePage, + String encoding, String name, boolean embeddable, String uri) { + this.triplets = Collections.unmodifiableList(triplets); + this.codePage = codePage; + this.encoding = encoding; + this.name = name; + this.embeddable = embeddable; + this.uri = uri; + } + + static AFPFontInfo getFontInfo(AFPFont font, AFPFontConfigData config) { + return font != null ? new AFPFontInfo(font, config.triplets) : null; + } + + abstract AFPFontInfo getFontInfo(InternalResourceResolver resourceResolver, + AFPEventProducer eventProducer) throws IOException; + + AFPResourceAccessor getAccessor(InternalResourceResolver resourceResolver) { + return new AFPResourceAccessor(resourceResolver, uri); + } + } + + static final class CIDKeyedFontConfig extends AFPFontConfigData { + + private final CharacterSetType charsetType; + + private final String characterset; + + private CIDKeyedFontConfig(List<FontTriplet> triplets, String type, String codePage, + String encoding, String characterset, String name, CharacterSetType charsetType, boolean embeddable, String uri) { + super(triplets, type, codePage, encoding, name, embeddable, uri); + this.characterset = characterset; + this.charsetType = charsetType; + } + + @Override + AFPFontInfo getFontInfo(InternalResourceResolver resourceResolver, AFPEventProducer eventProducer) + throws IOException { + AFPResourceAccessor accessor = getAccessor(resourceResolver); + CharacterSet characterSet = CharacterSetBuilder.getDoubleByteInstance().buildDBCS( + characterset, super.codePage, super.encoding, charsetType, accessor, eventProducer); + return getFontInfo(new DoubleByteFont(super.codePage, super.embeddable, characterSet), + this); + } + } + + static final class OutlineFontConfig extends AFPFontConfigData { + private final String base14; + private final String characterset; + + private OutlineFontConfig(List<FontTriplet> triplets, String type, String codePage, + String encoding, String characterset, String name, String base14, boolean embeddable, String uri) { + super(triplets, type, codePage, encoding, name, embeddable, uri); + this.characterset = characterset; + this.base14 = base14; + } + + @Override + AFPFontInfo getFontInfo(InternalResourceResolver resourceResolver, AFPEventProducer eventProducer) + throws IOException { + CharacterSet characterSet = null; + if (base14 != null) { + try { + Class<? extends Typeface> clazz = Class.forName( + "org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); + try { + Typeface tf = clazz.newInstance(); + characterSet = CharacterSetBuilder.getSingleByteInstance() + .build(characterset, super.codePage, + super.encoding, + tf, eventProducer); + } catch (Exception ie) { + String msg = "The base 14 font class " + clazz.getName() + + " could not be instantiated"; + LOG.error(msg); + } + } catch (ClassNotFoundException cnfe) { + String msg = "The base 14 font class for " + characterset + + " could not be found"; + LOG.error(msg); + } + } else { + AFPResourceAccessor accessor = getAccessor(resourceResolver); + characterSet = CharacterSetBuilder.getSingleByteInstance().buildSBCS( + characterset, super.codePage, super.encoding, accessor, eventProducer); + } + return getFontInfo(new OutlineFont(super.name, super.embeddable, characterSet), this); + } + } + + static final class RasterFontConfig extends AFPFontConfigData { + private final List<RasterCharactersetData> charsets; + + private RasterFontConfig(List<FontTriplet> triplets, String type, String codePage, + String encoding, String characterset, String name, String uri, + List<RasterCharactersetData> csetData, boolean embeddable) { + super(triplets, type, codePage, encoding, name, embeddable, uri); + this.charsets = Collections.unmodifiableList(csetData); + } + + @Override + AFPFontInfo getFontInfo(InternalResourceResolver resourceResolver, AFPEventProducer eventProducer) + throws IOException { + RasterFont rasterFont = new RasterFont(super.name, super.embeddable); + for (RasterCharactersetData charset : charsets) { + if (charset.base14 != null) { + try { + Class<? extends Typeface> clazz = Class.forName( + "org.apache.fop.fonts.base14." + charset.base14).asSubclass( + Typeface.class); + try { + Typeface tf = clazz.newInstance(); + rasterFont.addCharacterSet(charset.size, + CharacterSetBuilder.getSingleByteInstance().build( + charset.characterset, super.codePage, super.encoding, + tf, eventProducer)); + } catch (Exception ie) { + String msg = "The base 14 font class " + clazz.getName() + + " could not be instantiated"; + LOG.error(msg); + } + } catch (ClassNotFoundException cnfe) { + String msg = "The base 14 font class for " + charset.characterset + + " could not be found"; + LOG.error(msg); + } + } else { + AFPResourceAccessor accessor = getAccessor(resourceResolver); + rasterFont.addCharacterSet(charset.size, + CharacterSetBuilder.getSingleByteInstance().buildSBCS(charset.characterset, + super.codePage, super.encoding, accessor, eventProducer)); + } + } + return getFontInfo(rasterFont, this); + } + } + + static final class RasterCharactersetData { + private final String characterset; + private final int size; + private final String base14; + + private RasterCharactersetData(String characterset, int size, String base14) { + this.characterset = characterset; + this.size = size; + this.base14 = base14; + } + } +} diff --git a/src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java b/src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java index a03aaf816..5f155e277 100644 --- a/src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java +++ b/src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java @@ -19,7 +19,7 @@ package org.apache.fop.render.afp; -import java.io.File; +import java.net.URI; import java.util.Map; import org.apache.commons.logging.Log; @@ -46,7 +46,7 @@ public class AFPForeignAttributeReader { AFPElementMapping.NAMESPACE, "afp:resource-level"); /** the resource-group-file attribute */ - public static final QName RESOURCE_GROUP_FILE = new QName( + public static final QName RESOURCE_GROUP_URI = new QName( AFPElementMapping.NAMESPACE, "afp:resource-group-file"); /** @@ -64,7 +64,7 @@ public class AFPForeignAttributeReader { public AFPResourceInfo getResourceInfo(Map/*<QName, String>*/ foreignAttributes) { AFPResourceInfo resourceInfo = new AFPResourceInfo(); if (foreignAttributes != null && !foreignAttributes.isEmpty()) { - String resourceName = (String)foreignAttributes.get(RESOURCE_NAME); + String resourceName = (String) foreignAttributes.get(RESOURCE_NAME); if (resourceName != null) { resourceInfo.setName(resourceName); } @@ -82,45 +82,20 @@ public class AFPForeignAttributeReader { * @param foreignAttributes the foreign attributes * @return the resource level */ - public AFPResourceLevel getResourceLevel(Map/*<QName, String>*/ foreignAttributes) { + public AFPResourceLevel getResourceLevel(Map<QName, String> foreignAttributes) { AFPResourceLevel resourceLevel = null; if (foreignAttributes != null && !foreignAttributes.isEmpty()) { if (foreignAttributes.containsKey(RESOURCE_LEVEL)) { - String levelString = (String)foreignAttributes.get(RESOURCE_LEVEL); + String levelString = foreignAttributes.get(RESOURCE_LEVEL); resourceLevel = AFPResourceLevel.valueOf(levelString); // if external get resource group file attributes if (resourceLevel != null && resourceLevel.isExternal()) { - String resourceGroupFile - = (String)foreignAttributes.get(RESOURCE_GROUP_FILE); - if (resourceGroupFile == null) { - String msg = RESOURCE_GROUP_FILE + " not specified"; - LOG.error(msg); + String resourceGroupUri = foreignAttributes.get(RESOURCE_GROUP_URI); + if (resourceGroupUri == null) { + String msg = RESOURCE_GROUP_URI + " not specified"; throw new UnsupportedOperationException(msg); } - File resourceExternalGroupFile = new File(resourceGroupFile); - SecurityManager security = System.getSecurityManager(); - try { - if (security != null) { - security.checkWrite(resourceExternalGroupFile.getPath()); - } - } catch (SecurityException ex) { - String msg = "unable to gain write access to external resource file: " - + resourceGroupFile; - LOG.error(msg); - } - - try { - boolean exists = resourceExternalGroupFile.exists(); - if (exists) { - 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); - } + resourceLevel.setExternalUri(URI.create(resourceGroupUri)); } } } diff --git a/src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java b/src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java index 834304f6b..68d806a1c 100644 --- a/src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java +++ b/src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java @@ -42,6 +42,7 @@ import org.apache.fop.afp.AFPObjectAreaInfo; import org.apache.fop.afp.AFPPaintingState; import org.apache.fop.afp.AFPResourceInfo; import org.apache.fop.afp.AFPResourceLevel; +import org.apache.fop.afp.AFPResourceLevel.ResourceType; import org.apache.fop.afp.AFPResourceManager; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.image.loader.batik.BatikImageFlavors; @@ -142,7 +143,7 @@ public class AFPImageHandlerSVG implements ImageHandler { //level not explicitly set/changed so default to inline for GOCA graphic objects // (due to a bug in the IBM AFP Workbench Viewer (2.04.01.07), hard copy works just fine) if (!resourceInfo.levelChanged()) { - resourceInfo.setLevel(new AFPResourceLevel(AFPResourceLevel.INLINE)); + resourceInfo.setLevel(new AFPResourceLevel(ResourceType.INLINE)); } } diff --git a/src/java/org/apache/fop/render/afp/AFPPainter.java b/src/java/org/apache/fop/render/afp/AFPPainter.java index 592b47eaa..7d659a8b4 100644 --- a/src/java/org/apache/fop/render/afp/AFPPainter.java +++ b/src/java/org/apache/fop/render/afp/AFPPainter.java @@ -51,8 +51,7 @@ import org.apache.fop.afp.modca.AbstractPageObject; import org.apache.fop.afp.modca.PresentationTextObject; import org.apache.fop.afp.ptoca.PtocaBuilder; import org.apache.fop.afp.ptoca.PtocaProducer; -import org.apache.fop.afp.util.DefaultFOPResourceAccessor; -import org.apache.fop.afp.util.ResourceAccessor; +import org.apache.fop.afp.util.AFPResourceAccessor; import org.apache.fop.fonts.Font; import org.apache.fop.fonts.FontTriplet; import org.apache.fop.fonts.Typeface; @@ -204,8 +203,8 @@ public class AFPPainter extends AbstractIFPainter<AFPDocumentHandler> { //Do we need to embed an external page segment? if (pageSegment.getURI() != null) { - ResourceAccessor accessor = new DefaultFOPResourceAccessor ( - getUserAgent(), null, null); + AFPResourceAccessor accessor = new AFPResourceAccessor( + getDocumentHandler().getUserAgent().getResourceResolver()); try { URI resourceUri = new URI(pageSegment.getURI()); getDocumentHandler().getResourceManager().createIncludedResourceFromExternal( diff --git a/src/java/org/apache/fop/render/afp/AFPRendererConfig.java b/src/java/org/apache/fop/render/afp/AFPRendererConfig.java new file mode 100644 index 000000000..6d210c0d0 --- /dev/null +++ b/src/java/org/apache/fop/render/afp/AFPRendererConfig.java @@ -0,0 +1,375 @@ +/* + * 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.net.URI; +import java.net.URISyntaxException; +import java.util.EnumMap; + +import org.apache.avalon.framework.configuration.Configuration; +import org.apache.avalon.framework.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.fop.afp.AFPConstants; +import org.apache.fop.afp.AFPDataObjectInfo; +import org.apache.fop.afp.AFPEventProducer; +import org.apache.fop.afp.AFPResourceLevel; +import org.apache.fop.afp.AFPResourceLevelDefaults; +import org.apache.fop.afp.modca.triplets.MappingOptionTriplet; +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.apps.MimeConstants; +import org.apache.fop.apps.io.InternalResourceResolver; +import org.apache.fop.fonts.FontManager; +import org.apache.fop.render.RendererConfig; +import org.apache.fop.render.afp.AFPFontConfig.AFPFontInfoConfigParser; +import org.apache.fop.util.LogUtil; + +import static org.apache.fop.render.afp.AFPRendererConfig.ImagesModeOptions.MODE_COLOR; +import static org.apache.fop.render.afp.AFPRendererConfig.ImagesModeOptions.MODE_GRAYSCALE; +import static org.apache.fop.render.afp.AFPRendererOption.DEFAULT_RESOURCE_LEVELS; +import static org.apache.fop.render.afp.AFPRendererOption.GOCA; +import static org.apache.fop.render.afp.AFPRendererOption.GOCA_TEXT; +import static org.apache.fop.render.afp.AFPRendererOption.IMAGES; +import static org.apache.fop.render.afp.AFPRendererOption.IMAGES_DITHERING_QUALITY; +import static org.apache.fop.render.afp.AFPRendererOption.IMAGES_FS45; +import static org.apache.fop.render.afp.AFPRendererOption.IMAGES_JPEG; +import static org.apache.fop.render.afp.AFPRendererOption.IMAGES_MAPPING_OPTION; +import static org.apache.fop.render.afp.AFPRendererOption.IMAGES_MODE; +import static org.apache.fop.render.afp.AFPRendererOption.IMAGES_NATIVE; +import static org.apache.fop.render.afp.AFPRendererOption.IMAGES_WRAP_PSEG; +import static org.apache.fop.render.afp.AFPRendererOption.JPEG_ALLOW_JPEG_EMBEDDING; +import static org.apache.fop.render.afp.AFPRendererOption.JPEG_BITMAP_ENCODING_QUALITY; +import static org.apache.fop.render.afp.AFPRendererOption.LINE_WIDTH_CORRECTION; +import static org.apache.fop.render.afp.AFPRendererOption.RENDERER_RESOLUTION; +import static org.apache.fop.render.afp.AFPRendererOption.RESOURCE_GROUP_URI; +import static org.apache.fop.render.afp.AFPRendererOption.SHADING; + +/** + * The AFP renderer config object. + */ +public final class AFPRendererConfig implements RendererConfig { + + /** + * An enumeration for the various images modes available to the AFP renderer. + */ + public enum ImagesModeOptions { + + MODE_GRAYSCALE("b+w", "bits-per-pixel"), + MODE_COLOR("color", "cmyk"); + + private final String name; + + private final String modeAttribute; + + private ImagesModeOptions(String name, String modeAttribute) { + this.name = name; + this.modeAttribute = modeAttribute; + } + + public String getName() { + return name; + } + + public String getModeAttribute() { + return modeAttribute; + } + + public static ImagesModeOptions forName(String name) { + for (ImagesModeOptions option : values()) { + if (option.name.equals(name)) { + return option; + } + } + throw new IllegalArgumentException(name); + } + } + + private final EnumMap<AFPRendererOption, Object> params = new EnumMap<AFPRendererOption, Object>(AFPRendererOption.class); + + private final EnumMap<ImagesModeOptions, Object> imageModeParams + = new EnumMap<ImagesModeOptions, Object>(ImagesModeOptions.class); + + private final AFPFontConfig fontConfig; + + private AFPRendererConfig(AFPFontConfig fontConfig) { + this.fontConfig = fontConfig; + } + + public AFPFontConfig getFontInfoConfig() { + return fontConfig; + } + + public Boolean isColorImages() { + return getParam(IMAGES_MODE, Boolean.class); + } + + public Boolean isCmykImagesSupported() { + if (!isColorImages()) { + throw new IllegalStateException(); + } + return Boolean.class.cast(imageModeParams.get(MODE_COLOR)); + } + + public Integer getBitsPerPixel() { + if (isColorImages()) { + throw new IllegalStateException(); + } + return Integer.class.cast(imageModeParams.get(MODE_GRAYSCALE)); + } + + public Float getDitheringQuality() { + return getParam(IMAGES_DITHERING_QUALITY, Float.class); + } + + public Boolean isNativeImagesSupported() { + return getParam(IMAGES_NATIVE, Boolean.class); + } + + public AFPShadingMode getShadingMode() { + return getParam(SHADING, AFPShadingMode.class); + } + + public Integer getResolution() { + return getParam(RENDERER_RESOLUTION, Integer.class); + } + + + public URI getDefaultResourceGroupUri() { + return getParam(RESOURCE_GROUP_URI, URI.class); + } + + public AFPResourceLevelDefaults getResourceLevelDefaults() { + return getParam(DEFAULT_RESOURCE_LEVELS, AFPResourceLevelDefaults.class); + } + + public Boolean isWrapPseg() { + return getParam(IMAGES_WRAP_PSEG, Boolean.class); + } + + public Boolean isFs45() { + return getParam(IMAGES_FS45, Boolean.class); + } + + public Boolean allowJpegEmbedding() { + return getParam(JPEG_ALLOW_JPEG_EMBEDDING, Boolean.class); + } + + public Float getBitmapEncodingQuality() { + return getParam(JPEG_BITMAP_ENCODING_QUALITY, Float.class); + } + + public Float getLineWidthCorrection() { + return getParam(LINE_WIDTH_CORRECTION, Float.class); + } + + public Boolean isGocaEnabled() { + return getParam(GOCA, Boolean.class); + } + + public Boolean isStrokeGocaText() { + return getParam(GOCA_TEXT, Boolean.class); + } + + private <T> T getParam(AFPRendererOption options, Class<T> type) { + assert options.getType().equals(type); + return type.cast(params.get(options)); + } + + private <T> void setParam(AFPRendererOption option, T value) { + assert option.getType().isInstance(value); + params.put(option, value); + } + + /** + * The parser for AFP renderer specific data in the FOP conf. + */ + public static final class AFPRendererConfigParser implements RendererConfigParser { + + private static final Log LOG = LogFactory.getLog(AFPRendererConfigParser.class); + + /** {@inheritDoc} */ + public AFPRendererConfig build(FOUserAgent userAgent, Configuration cfg) throws FOPException { + boolean strict = userAgent != null ? userAgent.validateUserConfigStrictly() : false; + AFPRendererConfig config = null; + AFPEventProducer eventProducer = AFPEventProducer.Provider.get(userAgent.getEventBroadcaster()); + try { + config = new ParserHelper(cfg, userAgent.getFontManager(), strict, eventProducer).config; + } catch (ConfigurationException e) { + LogUtil.handleException(LOG, e, strict); + } + return config; + } + + /** {@inheritDoc} */ + public String getMimeType() { + return MimeConstants.MIME_AFP; + } + } + + private static final class ParserHelper { + + private static final Log LOG = LogFactory.getLog(ParserHelper.class); + + private final AFPRendererConfig config; + + private final boolean strict; + + private final Configuration cfg; + + private ParserHelper(Configuration cfg, FontManager fontManager, boolean strict, + AFPEventProducer eventProducer) + throws ConfigurationException, FOPException { + this.cfg = cfg; + this.strict = strict; + if (cfg != null) { + config = new AFPRendererConfig(new AFPFontInfoConfigParser().parse(cfg, + fontManager, strict, eventProducer)); + configure(); + } else { + config = new AFPRendererConfig(new AFPFontInfoConfigParser().getEmptyConfig()); + } + } + + private void configure() throws ConfigurationException, FOPException { + configureImages(); + setParam(SHADING, AFPShadingMode.getValueOf( + cfg.getChild(SHADING.getName()).getValue(AFPShadingMode.COLOR.getName()))); + Configuration rendererResolutionCfg = cfg.getChild(RENDERER_RESOLUTION.getName(), false); + setParam(RENDERER_RESOLUTION, rendererResolutionCfg == null ? 240 + : rendererResolutionCfg.getValueAsInteger(240)); + Configuration lineWidthCorrectionCfg = cfg.getChild(LINE_WIDTH_CORRECTION.getName(), + false); + setParam(LINE_WIDTH_CORRECTION, lineWidthCorrectionCfg != null + ? lineWidthCorrectionCfg.getValueAsFloat() + : AFPConstants.LINE_WIDTH_CORRECTION); + Configuration gocaCfg = cfg.getChild(GOCA.getName()); + boolean gocaEnabled = gocaCfg.getAttributeAsBoolean("enabled", true); + setParam(GOCA, gocaEnabled); + String strokeGocaText = gocaCfg.getAttribute(GOCA_TEXT.getName(), "default"); + setParam(GOCA_TEXT, "stroke".equalsIgnoreCase(strokeGocaText) + || "shapes".equalsIgnoreCase(strokeGocaText)); + //TODO remove + createResourceGroupFile(); + createResourceLevel(); + } + + private void setParam(AFPRendererOption option, Object value) { + config.setParam(option, value); + } + + private void configureImages() throws ConfigurationException, FOPException { + Configuration imagesCfg = cfg.getChild(IMAGES.getName()); + ImagesModeOptions imagesMode = ImagesModeOptions.forName(imagesCfg.getAttribute( + IMAGES_MODE.getName(), MODE_GRAYSCALE.getName())); + boolean colorImages = MODE_COLOR == imagesMode; + setParam(IMAGES_MODE, colorImages); + if (colorImages) { + config.imageModeParams.put(MODE_COLOR, imagesCfg + .getAttributeAsBoolean(imagesMode.getModeAttribute(), false)); + } else { + config.imageModeParams.put(MODE_GRAYSCALE, + imagesCfg.getAttributeAsInteger(imagesMode.getModeAttribute(), 8)); + } + String dithering = imagesCfg.getAttribute(AFPRendererOption.IMAGES_DITHERING_QUALITY.getName(), "medium"); + float dq; + if (dithering.startsWith("min")) { + dq = 0.0f; + } else if (dithering.startsWith("max")) { + dq = 1.0f; + } else { + try { + dq = Float.parseFloat(dithering); + } catch (NumberFormatException nfe) { + //Default value + dq = 0.5f; + } + } + setParam(IMAGES_DITHERING_QUALITY, dq); + setParam(IMAGES_NATIVE, imagesCfg.getAttributeAsBoolean(IMAGES_NATIVE.getName(), false)); + setParam(IMAGES_WRAP_PSEG, + imagesCfg.getAttributeAsBoolean(IMAGES_WRAP_PSEG.getName(), false)); + setParam(IMAGES_FS45, imagesCfg.getAttributeAsBoolean(IMAGES_FS45.getName(), false)); + if ("scale-to-fit".equals(imagesCfg.getAttribute(IMAGES_MAPPING_OPTION.getName(), null))) { + setParam(IMAGES_MAPPING_OPTION, MappingOptionTriplet.SCALE_TO_FILL); + } else { + setParam(IMAGES_MAPPING_OPTION, AFPDataObjectInfo.DEFAULT_MAPPING_OPTION); + } + configureJpegImages(imagesCfg); + } + + private void configureJpegImages(Configuration imagesCfg) { + Configuration jpegConfig = imagesCfg.getChild(IMAGES_JPEG.getName()); + float bitmapEncodingQuality = 1.0f; + boolean allowJpegEmbedding = false; + if (jpegConfig != null) { + allowJpegEmbedding = jpegConfig.getAttributeAsBoolean( + JPEG_ALLOW_JPEG_EMBEDDING.getName(), + false); + String bitmapEncodingQualityStr = jpegConfig.getAttribute( + JPEG_BITMAP_ENCODING_QUALITY.getName(), null); + if (bitmapEncodingQualityStr != null) { + try { + bitmapEncodingQuality = Float.parseFloat(bitmapEncodingQualityStr); + } catch (NumberFormatException nfe) { + //ignore and leave the default above + } + } + } + setParam(JPEG_BITMAP_ENCODING_QUALITY, bitmapEncodingQuality); + setParam(JPEG_ALLOW_JPEG_EMBEDDING, allowJpegEmbedding); + } + + private void createResourceGroupFile() throws FOPException { + try { + Configuration resourceGroupUriCfg = cfg.getChild(RESOURCE_GROUP_URI.getName(), false); + if (resourceGroupUriCfg != null) { + URI resourceGroupUri = InternalResourceResolver.cleanURI(resourceGroupUriCfg.getValue()); + setParam(RESOURCE_GROUP_URI, resourceGroupUri); + } + } catch (ConfigurationException e) { + LogUtil.handleException(LOG, e, strict); + } catch (URISyntaxException use) { + LogUtil.handleException(LOG, use, strict); + } + } + + private void createResourceLevel() throws FOPException { + Configuration defaultResourceLevelCfg = cfg.getChild(DEFAULT_RESOURCE_LEVELS.getName(), 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, strict); + } catch (ConfigurationException e) { + LogUtil.handleException(LOG, e, strict); + } + } + setParam(DEFAULT_RESOURCE_LEVELS, defaults); + } + } + } +} diff --git a/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java b/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java index e93d8b6aa..92115bc92 100644 --- a/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java +++ b/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java @@ -19,42 +19,24 @@ package org.apache.fop.render.afp; -import java.io.File; import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; -import org.apache.avalon.framework.configuration.Configuration; -import org.apache.avalon.framework.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import org.apache.fop.afp.AFPConstants; import org.apache.fop.afp.AFPEventProducer; -import org.apache.fop.afp.AFPResourceLevel; import org.apache.fop.afp.AFPResourceLevelDefaults; -import org.apache.fop.afp.fonts.AFPFont; 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.CharacterSetBuilder; -import org.apache.fop.afp.fonts.CharacterSetType; -import org.apache.fop.afp.fonts.DoubleByteFont; -import org.apache.fop.afp.fonts.OutlineFont; -import org.apache.fop.afp.fonts.RasterFont; -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.io.InternalResourceResolver; import org.apache.fop.fonts.FontCollection; -import org.apache.fop.fonts.FontInfo; -import org.apache.fop.fonts.FontManager; -import org.apache.fop.fonts.FontManagerConfigurator; -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.RendererConfig.RendererConfigParser; +import org.apache.fop.render.afp.AFPFontConfig.AFPFontConfigData; import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; import org.apache.fop.util.LogUtil; @@ -62,8 +44,9 @@ import org.apache.fop.util.LogUtil; /** * AFP Renderer configurator */ -public class AFPRendererConfigurator extends PrintRendererConfigurator - implements IFDocumentHandlerConfigurator { +public class AFPRendererConfigurator extends PrintRendererConfigurator implements + IFDocumentHandlerConfigurator { + private static Log LOG = LogFactory.getLog(AFPRendererConfigurator.class); private final AFPEventProducer eventProducer; @@ -72,470 +55,104 @@ public class AFPRendererConfigurator extends PrintRendererConfigurator * * @param userAgent user agent */ - public AFPRendererConfigurator(FOUserAgent userAgent) { - super(userAgent); + public AFPRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + super(userAgent, rendererConfigParser); eventProducer = AFPEventProducer.Provider.get(userAgent.getEventBroadcaster()); } - private AFPFontInfo buildFont(Configuration fontCfg, String fontPath) - throws ConfigurationException { - FontManager fontManager = this.userAgent.getFactory().getFontManager(); - Configuration[] triple = fontCfg.getChildren("font-triplet"); - List<FontTriplet> tripletList = new ArrayList<FontTriplet>(); - if (triple.length == 0) { - eventProducer.fontConfigMissing(this, "<font-triplet...", fontCfg.getLocation()); - return null; - } - for (Configuration config : triple) { - int weight = FontUtil.parseCSS2FontWeight(config.getAttribute("weight")); - FontTriplet triplet = new FontTriplet(config.getAttribute("name"), - config.getAttribute("style"), - weight); - tripletList.add(triplet); - } - - //build the fonts - Configuration[] config = fontCfg.getChildren("afp-font"); - if (config.length == 0) { - eventProducer.fontConfigMissing(this, "<afp-font...", fontCfg.getLocation()); - return null; - } - Configuration afpFontCfg = config[0]; - - URI baseURI = null; - String uri = afpFontCfg.getAttribute("base-uri", fontPath); - if (uri == null) { - //Fallback for old attribute which only supports local filenames - String path = afpFontCfg.getAttribute("path", fontPath); - if (path != null) { - File f = new File(path); - baseURI = f.toURI(); - } - } else { - try { - baseURI = new URI(uri); - } catch (URISyntaxException e) { - eventProducer.invalidConfiguration(this, e); - return null; - } - } - ResourceAccessor accessor = new DefaultFOPResourceAccessor( - this.userAgent, - fontManager.getFontBaseURL(), - baseURI); - - AFPFont font = null; - try { - String type = afpFontCfg.getAttribute("type"); - if (type == null) { - eventProducer.fontConfigMissing(this, "type attribute", fontCfg.getLocation()); - return null; - } - String codepage = afpFontCfg.getAttribute("codepage"); - if (codepage == null) { - eventProducer.fontConfigMissing(this, "codepage attribute", - fontCfg.getLocation()); - return null; - } - String encoding = afpFontCfg.getAttribute("encoding"); - if (encoding == null) { - eventProducer.fontConfigMissing(this, "encoding attribute", - fontCfg.getLocation()); - return null; - } - - font = fontFromType(type, codepage, encoding, accessor, afpFontCfg); - } catch (ConfigurationException ce) { - eventProducer.invalidConfiguration(this, ce); - } catch (IOException ioe) { - eventProducer.invalidConfiguration(this, ioe); - } catch (IllegalArgumentException iae) { - eventProducer.invalidConfiguration(this, iae); + @Override + public void configure(IFDocumentHandler documentHandler) throws FOPException { + AFPRendererConfig config = (AFPRendererConfig) getRendererConfig(documentHandler); + if (config != null) { + AFPDocumentHandler afpDocumentHandler = (AFPDocumentHandler) documentHandler; + configure(afpDocumentHandler, config); } - - return font != null ? new AFPFontInfo(font, tripletList) : null; } - - /** - * Create the AFPFont based on type and type-dependent configuration. - * - * @param type font type e.g. 'raster', 'outline' - * @param codepage codepage file - * @param encoding character encoding e.g. 'Cp500', 'UnicodeBigUnmarked' - * @param accessor - * @param afpFontCfg - * @return the created AFPFont - * @throws ConfigurationException - */ - private AFPFont fontFromType(String type, String codepage, String encoding, - ResourceAccessor accessor, Configuration afpFontCfg) throws ConfigurationException, - IOException { - - if ("raster".equalsIgnoreCase(type)) { - - String name = afpFontCfg.getAttribute("name", "Unknown"); - - // Create a new font object - RasterFont font = new RasterFont(name); - - Configuration[] rasters = afpFontCfg.getChildren("afp-raster-font"); - if (rasters.length == 0) { - eventProducer.fontConfigMissing(this, "<afp-raster-font...", - afpFontCfg.getLocation()); - return null; - } - for (int j = 0; j < rasters.length; j++) { - Configuration rasterCfg = rasters[j]; - - String characterset = rasterCfg.getAttribute("characterset"); - - if (characterset == null) { - eventProducer.fontConfigMissing(this, "characterset attribute", - afpFontCfg.getLocation()); - return null; - } - float size = rasterCfg.getAttributeAsFloat("size"); - int sizeMpt = (int) (size * 1000); - String base14 = rasterCfg.getAttribute("base14-font", null); - - if (base14 != null) { - try { - Class<? extends Typeface> clazz = Class.forName( - "org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); - try { - Typeface tf = clazz.newInstance(); - font.addCharacterSet(sizeMpt, - CharacterSetBuilder.getSingleByteInstance() - .build(characterset, codepage, encoding, tf, - eventProducer)); - } catch (Exception ie) { - String msg = "The base 14 font class " + clazz.getName() - + " could not be instantiated"; - log.error(msg); - } - } catch (ClassNotFoundException cnfe) { - String msg = "The base 14 font class for " + characterset - + " could not be found"; - log.error(msg); - } - } else { - font.addCharacterSet(sizeMpt, CharacterSetBuilder.getSingleByteInstance() - .buildSBCS(characterset, codepage, encoding, accessor, eventProducer)); - } - } - return font; - - } else if ("outline".equalsIgnoreCase(type)) { - String characterset = afpFontCfg.getAttribute("characterset"); - if (characterset == null) { - eventProducer.fontConfigMissing(this, "characterset attribute", - afpFontCfg.getLocation()); - return null; - } - String name = afpFontCfg.getAttribute("name", characterset); - CharacterSet characterSet = null; - String base14 = afpFontCfg.getAttribute("base14-font", null); - if (base14 != null) { - try { - Class<? extends Typeface> clazz = Class.forName("org.apache.fop.fonts.base14." - + base14).asSubclass(Typeface.class); - try { - Typeface tf = clazz.newInstance(); - characterSet = CharacterSetBuilder.getSingleByteInstance() - .build(characterset, codepage, encoding, tf, eventProducer); - } catch (Exception ie) { - String msg = "The base 14 font class " + clazz.getName() - + " could not be instantiated"; - log.error(msg); - } - } catch (ClassNotFoundException cnfe) { - String msg = "The base 14 font class for " + characterset - + " could not be found"; - log.error(msg); - } + private void configure(AFPDocumentHandler documentHandler, AFPRendererConfig config) { + Boolean colorImages = config.isColorImages(); + if (colorImages != null) { + documentHandler.setColorImages(colorImages); + if (colorImages) { + documentHandler.setCMYKImagesSupported(config.isCmykImagesSupported()); } else { - characterSet = CharacterSetBuilder.getSingleByteInstance().buildSBCS( - characterset, codepage, encoding, accessor, eventProducer); + documentHandler.setBitsPerPixel(config.getBitsPerPixel()); } - // Return new font object - return new OutlineFont(name, characterSet); - - } else if ("CIDKeyed".equalsIgnoreCase(type)) { - String characterset = afpFontCfg.getAttribute("characterset"); - if (characterset == null) { - eventProducer.fontConfigMissing(this, "characterset attribute", - afpFontCfg.getLocation()); - return null; - } - String name = afpFontCfg.getAttribute("name", characterset); - CharacterSet characterSet = null; - CharacterSetType charsetType = afpFontCfg.getAttributeAsBoolean("ebcdic-dbcs", false) - ? CharacterSetType.DOUBLE_BYTE_LINE_DATA : CharacterSetType.DOUBLE_BYTE; - characterSet = CharacterSetBuilder.getDoubleByteInstance().buildDBCS(characterset, - codepage, encoding, charsetType, accessor, eventProducer); - - // Create a new font object - DoubleByteFont font = new DoubleByteFont(name, characterSet); - return font; - - } else { - log.error("No or incorrect type attribute: " + type); } - - return null; - } - - /** - * Builds a list of AFPFontInfo objects for use with the setup() method. - * - * @param cfg Configuration object - * @param eventProducer for AFP font related events - * @return List the newly created list of fonts - * @throws ConfigurationException if something's wrong with the config data - */ - private List<AFPFontInfo> buildFontListFromConfiguration(Configuration cfg, - AFPEventProducer eventProducer) throws FOPException, ConfigurationException { - - Configuration fonts = cfg.getChild("fonts"); - FontManager fontManager = this.userAgent.getFactory().getFontManager(); - - // General matcher - FontTriplet.Matcher referencedFontsMatcher = fontManager.getReferencedFontsMatcher(); - // Renderer-specific matcher - FontTriplet.Matcher localMatcher = null; - - // Renderer-specific referenced fonts - Configuration referencedFontsCfg = fonts.getChild("referenced-fonts", false); - if (referencedFontsCfg != null) { - localMatcher = FontManagerConfigurator.createFontsMatcher( - referencedFontsCfg, this.userAgent.getFactory().validateUserConfigStrictly()); + if (config.getDitheringQuality() != null) { + documentHandler.setDitheringQuality(config.getDitheringQuality()); } - - List<AFPFontInfo> fontList = new java.util.ArrayList<AFPFontInfo>(); - Configuration[] font = fonts.getChildren("font"); - final String fontPath = null; - for (int i = 0; i < font.length; i++) { - AFPFontInfo afi = buildFont(font[i], fontPath); - if (afi != null) { - if (log.isDebugEnabled()) { - log.debug("Adding font " + afi.getAFPFont().getFontName()); - } - List<FontTriplet> fontTriplets = afi.getFontTriplets(); - for (int j = 0; j < fontTriplets.size(); ++j) { - FontTriplet triplet = fontTriplets.get(j); - if (log.isDebugEnabled()) { - log.debug(" Font triplet " - + triplet.getName() + ", " - + triplet.getStyle() + ", " - + triplet.getWeight()); - } - - if ((referencedFontsMatcher != null && referencedFontsMatcher.matches(triplet)) - || (localMatcher != null && localMatcher.matches(triplet))) { - afi.getAFPFont().setEmbeddable(false); - break; - } - } - - fontList.add(afi); - } + if (config.isNativeImagesSupported() != null) { + documentHandler.setNativeImagesSupported(config.isNativeImagesSupported()); } - return fontList; - } - - /** images are converted to grayscale bitmapped IOCA */ - private static final String IMAGES_MODE_GRAYSCALE = "b+w"; - - /** images are converted to color bitmapped IOCA */ - private static final String IMAGES_MODE_COLOR = "color"; - - /** - * Throws an UnsupportedOperationException. - * - * @param renderer not used - */ - @Override - public void configure(Renderer renderer) { - throw new UnsupportedOperationException(); - } - - private void configure(AFPCustomizable customizable, Configuration cfg) throws FOPException { - - // 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); - - boolean cmyk = imagesCfg.getAttributeAsBoolean("cmyk", false); - customizable.setCMYKImagesSupported(cmyk); - } else { - customizable.setColorImages(false); - // default to 8 bits per pixel - int bitsPerPixel = imagesCfg.getAttributeAsInteger("bits-per-pixel", 8); - customizable.setBitsPerPixel(bitsPerPixel); + if (config.getShadingMode() != null) { + documentHandler.setShadingMode(config.getShadingMode()); } - - String dithering = imagesCfg.getAttribute("dithering-quality", "medium"); - float dq = 0.5f; - if (dithering.startsWith("min")) { - dq = 0.0f; - } else if (dithering.startsWith("max")) { - dq = 1.0f; - } else { - try { - dq = Float.parseFloat(dithering); - } catch (NumberFormatException nfe) { - //ignore and leave the default above - } + if (config.getResolution() != null) { + documentHandler.setResolution(config.getResolution()); } - customizable.setDitheringQuality(dq); - - // native image support - boolean nativeImageSupport = imagesCfg.getAttributeAsBoolean("native", false); - customizable.setNativeImagesSupported(nativeImageSupport); - - Configuration jpegConfig = imagesCfg.getChild("jpeg"); - boolean allowEmbedding = false; - float ieq = 1.0f; - if (jpegConfig != null) { - allowEmbedding = jpegConfig.getAttributeAsBoolean("allow-embedding", false); - String bitmapEncodingQuality = jpegConfig.getAttribute("bitmap-encoding-quality", null); - - if (bitmapEncodingQuality != null) { - try { - ieq = Float.parseFloat(bitmapEncodingQuality); - } catch (NumberFormatException nfe) { - //ignore and leave the default above - } - } + if (config.isWrapPseg() != null) { + documentHandler.setWrapPSeg(config.isWrapPseg()); } - customizable.canEmbedJpeg(allowEmbedding); - customizable.setBitmapEncodingQuality(ieq); - - //FS11 and FS45 page segment wrapping - boolean pSeg = imagesCfg.getAttributeAsBoolean("pseg", false); - customizable.setWrapPSeg(pSeg); - - //FS45 image forcing - boolean fs45 = imagesCfg.getAttributeAsBoolean("fs45", false); - customizable.setFS45(fs45); - - // shading (filled rectangles) - Configuration shadingCfg = cfg.getChild("shading"); - AFPShadingMode shadingMode = AFPShadingMode.valueOf( - shadingCfg.getValue(AFPShadingMode.COLOR.getName())); - customizable.setShadingMode(shadingMode); - - // GOCA Support - Configuration gocaCfg = cfg.getChild("goca"); - boolean gocaEnabled = gocaCfg.getAttributeAsBoolean( - "enabled", customizable.isGOCAEnabled()); - customizable.setGOCAEnabled(gocaEnabled); - String gocaText = gocaCfg.getAttribute( - "text", customizable.isStrokeGOCAText() ? "stroke" : "default"); - customizable.setStrokeGOCAText("stroke".equalsIgnoreCase(gocaText) - || "shapes".equalsIgnoreCase(gocaText)); - - // renderer resolution - Configuration rendererResolutionCfg = cfg.getChild("renderer-resolution", false); - if (rendererResolutionCfg != null) { - customizable.setResolution(rendererResolutionCfg.getValueAsInteger(240)); + if (config.isFs45() != null) { + documentHandler.setFS45(config.isFs45()); } - - // renderer resolution - Configuration lineWidthCorrectionCfg = cfg.getChild("line-width-correction", false); - if (lineWidthCorrectionCfg != null) { - customizable.setLineWidthCorrection(lineWidthCorrectionCfg - .getValueAsFloat(AFPConstants.LINE_WIDTH_CORRECTION)); + if (config.allowJpegEmbedding() != null) { + documentHandler.canEmbedJpeg(config.allowJpegEmbedding()); } - - // 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(); - if (resourceGroupDest != null) { - File resourceGroupFile = new File(resourceGroupDest); - boolean created = resourceGroupFile.createNewFile(); - if (created && resourceGroupFile.canWrite()) { - customizable.setDefaultResourceGroupFilePath(resourceGroupDest); - } else { - log.warn("Unable to write to default external resource group file '" - + resourceGroupDest + "'"); - } - } - } catch (ConfigurationException e) { - LogUtil.handleException(log, e, - userAgent.getFactory().validateUserConfigStrictly()); - } catch (IOException ioe) { - throw new FOPException("Could not create default external resource group file" - , ioe); - } + if (config.getBitmapEncodingQuality() != null) { + documentHandler.setBitmapEncodingQuality(config.getBitmapEncodingQuality()); } - - 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()); - } - } - customizable.setResourceLevelDefaults(defaults); + if (config.getLineWidthCorrection() != null) { + documentHandler.setLineWidthCorrection(config.getLineWidthCorrection()); + } + if (config.isGocaEnabled() != null) { + documentHandler.setGOCAEnabled(config.isGocaEnabled()); + } + if (config.isStrokeGocaText() != null) { + documentHandler.setStrokeGOCAText(config.isStrokeGocaText()); + } + if (config.getDefaultResourceGroupUri() != null) { + documentHandler.setDefaultResourceGroupUri(config.getDefaultResourceGroupUri()); + } + AFPResourceLevelDefaults resourceLevelDefaults = config.getResourceLevelDefaults(); + if (resourceLevelDefaults != null) { + documentHandler.setResourceLevelDefaults(resourceLevelDefaults); } } - /** {@inheritDoc} */ @Override - public void configure(IFDocumentHandler documentHandler) throws FOPException { - Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); - if (cfg != null) { - AFPDocumentHandler afpDocumentHandler = (AFPDocumentHandler) documentHandler; - configure(afpDocumentHandler, cfg); - } + protected List<FontCollection> getDefaultFontCollection() { + return new ArrayList<FontCollection>(); } - /** {@inheritDoc} */ @Override - public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) - throws FOPException { - FontManager fontManager = userAgent.getFactory().getFontManager(); - List<AFPFontCollection> fontCollections = new ArrayList<AFPFontCollection>(); - - Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); - if (cfg != null) { + protected FontCollection getCustomFontCollection(InternalResourceResolver uriResolverWrapper, + String mimeType) throws FOPException { + AFPRendererConfig config = (AFPRendererConfig) getRendererConfig(mimeType); + if (config != null) { try { - List<AFPFontInfo> fontList = buildFontListFromConfiguration(cfg, eventProducer); - fontCollections.add(new AFPFontCollection( - userAgent.getEventBroadcaster(), fontList)); - } catch (ConfigurationException e) { + return new AFPFontCollection(userAgent.getEventBroadcaster(), createFontsList( + config.getFontInfoConfig(), mimeType)); + } catch (IOException e) { eventProducer.invalidConfiguration(this, e); - LogUtil.handleException(log, e, - userAgent.getFactory().validateUserConfigStrictly()); + LogUtil.handleException(LOG, e, userAgent.validateUserConfigStrictly()); + } catch (IllegalArgumentException iae) { + eventProducer.invalidConfiguration(this, iae); + LogUtil.handleException(LOG, iae, userAgent.validateUserConfigStrictly()); } - } else { - fontCollections.add(new AFPFontCollection(userAgent.getEventBroadcaster(), null)); } + return new AFPFontCollection(userAgent.getEventBroadcaster(), null); + } - fontManager.setup(fontInfo, - fontCollections.toArray( - new FontCollection[fontCollections.size()])); - documentHandler.setFontInfo(fontInfo); + private List<AFPFontInfo> createFontsList(AFPFontConfig fontConfig, String mimeType) + throws FOPException, IOException { + List<AFPFontInfo> afpFonts = new ArrayList<AFPFontInfo>(); + for (AFPFontConfigData config : fontConfig.getFontConfig()) { + afpFonts.add(config.getFontInfo(userAgent.getFontManager().getResourceResolver(), + eventProducer)); + } + return afpFonts; } } diff --git a/src/java/org/apache/fop/render/afp/AFPRendererOption.java b/src/java/org/apache/fop/render/afp/AFPRendererOption.java new file mode 100644 index 000000000..d573570d0 --- /dev/null +++ b/src/java/org/apache/fop/render/afp/AFPRendererOption.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.afp; + +import java.net.URI; + +import org.apache.fop.afp.AFPResourceLevelDefaults; +import org.apache.fop.render.RendererConfigOption; + +/** + * An enumeration of the configuration options available for the AFP renderer. + */ +public enum AFPRendererOption implements RendererConfigOption { + DEFAULT_RESOURCE_LEVELS("default-resource-levels", AFPResourceLevelDefaults.class), + IMAGES("images", null), + IMAGES_JPEG("jpeg", null), + IMAGES_DITHERING_QUALITY("dithering-quality", Float.class), + IMAGES_FS45("fs45", Boolean.class), + IMAGES_MAPPING_OPTION("mapping_option", Byte.class), + IMAGES_MODE("mode", Boolean.class), + IMAGES_NATIVE("native", Boolean.class), + IMAGES_WRAP_PSEG("pseg", Boolean.class), + JPEG_ALLOW_JPEG_EMBEDDING("allow-embedding", Boolean.class), + JPEG_BITMAP_ENCODING_QUALITY("bitmap-encoding-quality", Float.class), + RENDERER_RESOLUTION("renderer-resolution", Integer.class), + RESOURCE_GROUP_URI("resource-group-file", URI.class), + SHADING("shading", AFPShadingMode.class), + LINE_WIDTH_CORRECTION("line-width-correction", Float.class), + GOCA("goca", Boolean.class), + GOCA_TEXT("text", Boolean.class); + + private final String name; + + private final Class<?> type; + + private AFPRendererOption(String name, Class<?> type) { + this.name = name; + this.type = type; + } + + /** {@inheritDoc}}*/ + public String getName() { + return name; + } + + public Class<?> getType() { + return type; + } +} diff --git a/src/java/org/apache/fop/render/afp/AFPSVGHandler.java b/src/java/org/apache/fop/render/afp/AFPSVGHandler.java index 48b82bbf3..b73e22d89 100644 --- a/src/java/org/apache/fop/render/afp/AFPSVGHandler.java +++ b/src/java/org/apache/fop/render/afp/AFPSVGHandler.java @@ -195,7 +195,7 @@ public class AFPSVGHandler extends AbstractGenericSVGHandler { * @return a bridge context */ public static BridgeContext createBridgeContext(FOUserAgent userAgent, AFPGraphics2D g2d) { - ImageManager imageManager = userAgent.getFactory().getImageManager(); + ImageManager imageManager = userAgent.getImageManager(); SVGUserAgent svgUserAgent = new SVGUserAgent(userAgent, new AffineTransform()); diff --git a/src/java/org/apache/fop/render/afp/AFPShadingMode.java b/src/java/org/apache/fop/render/afp/AFPShadingMode.java index b45c33a8e..c2ae21f74 100644 --- a/src/java/org/apache/fop/render/afp/AFPShadingMode.java +++ b/src/java/org/apache/fop/render/afp/AFPShadingMode.java @@ -22,15 +22,12 @@ package org.apache.fop.render.afp; import java.io.ObjectStreamException; import java.io.Serializable; -/** Enumeration class for the AFP shading mode. */ -public final class AFPShadingMode implements Serializable { - - private static final long serialVersionUID = 8579867898716480779L; - +/** Enumeration of the AFP shading modes. */ +public enum AFPShadingMode implements Serializable { /** the color mode (the default) */ - public static final AFPShadingMode COLOR = new AFPShadingMode("COLOR"); + COLOR("COLOR"), /** the dithered mode */ - public static final AFPShadingMode DITHERED = new AFPShadingMode("DITHERED"); + DITHERED("DITHERED"); private String name; @@ -52,7 +49,7 @@ public final class AFPShadingMode implements Serializable { * @param name the name of the enumeration value * @return the enumeration object */ - public static AFPShadingMode valueOf(String name) { + public static AFPShadingMode getValueOf(String name) { if (COLOR.getName().equalsIgnoreCase(name)) { return COLOR; } else if (DITHERED.getName().equalsIgnoreCase(name)) { @@ -70,5 +67,4 @@ public final class AFPShadingMode implements Serializable { public String toString() { return getClass().getName() + ":" + name; } - } diff --git a/src/java/org/apache/fop/render/awt/AWTRenderer.java b/src/java/org/apache/fop/render/awt/AWTRenderer.java index 826dde233..0651975fd 100644 --- a/src/java/org/apache/fop/render/awt/AWTRenderer.java +++ b/src/java/org/apache/fop/render/awt/AWTRenderer.java @@ -41,7 +41,7 @@ import org.apache.xmlgraphics.util.UnitConv; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.FopFactoryConfigurator; +import org.apache.fop.apps.FopFactoryConfig; import org.apache.fop.apps.MimeConstants; import org.apache.fop.area.Area; import org.apache.fop.area.PageViewport; @@ -131,13 +131,13 @@ public class AWTRenderer extends Java2DRenderer implements Pageable { pageWidth = (int) Math.round(bounds.getWidth() / 1000f); pageHeight = (int) Math.round(bounds.getHeight() / 1000f); double scaleX = scaleFactor - * (UnitConv.IN2MM / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION) + * (UnitConv.IN2MM / FopFactoryConfig.DEFAULT_TARGET_RESOLUTION) / userAgent.getTargetPixelUnitToMillimeter(); double scaleY = scaleFactor - * (UnitConv.IN2MM / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION) + * (UnitConv.IN2MM / FopFactoryConfig.DEFAULT_TARGET_RESOLUTION) / userAgent.getTargetPixelUnitToMillimeter(); if (getPageViewport(pageNum).getForeignAttributes() != null) { - String scale = (String) getPageViewport(pageNum).getForeignAttributes().get( + String scale = getPageViewport(pageNum).getForeignAttributes().get( PageScale.EXT_PAGE_SCALE); Point2D scales = PageScale.getScale(scale); if (scales != null) { diff --git a/src/java/org/apache/fop/render/awt/AWTRendererMaker.java b/src/java/org/apache/fop/render/awt/AWTRendererMaker.java index d65a550d4..5efa49a99 100644 --- a/src/java/org/apache/fop/render/awt/AWTRendererMaker.java +++ b/src/java/org/apache/fop/render/awt/AWTRendererMaker.java @@ -31,20 +31,23 @@ public class AWTRendererMaker extends AbstractRendererMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_FOP_AWT_PREVIEW}; - - /** {@inheritDoc} */ + @Override public Renderer makeRenderer(FOUserAgent ua) { return new AWTRenderer(ua); } - /** {@inheritDoc} */ + @Override public boolean needsOutputStream() { return false; } - /** {@inheritDoc} */ + @Override public String[] getSupportedMimeTypes() { return MIMES; } + @Override + public void configureRenderer(FOUserAgent userAgent, Renderer renderer) { + // No-Op + } } diff --git a/src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java b/src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java index 0c6ebde56..262caa53b 100644 --- a/src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java +++ b/src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java @@ -36,7 +36,7 @@ import org.apache.xmlgraphics.image.writer.ImageWriter; import org.apache.xmlgraphics.image.writer.ImageWriterRegistry; import org.apache.xmlgraphics.image.writer.MultiImageWriter; -import org.apache.fop.apps.FopFactoryConfigurator; +import org.apache.fop.apps.FopFactoryConfig; import org.apache.fop.fonts.FontInfo; import org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler; import org.apache.fop.render.intermediate.IFContext; @@ -80,7 +80,14 @@ public abstract class AbstractBitmapDocumentHandler extends AbstractBinaryWritin /** * Default constructor. */ - public AbstractBitmapDocumentHandler() { + public AbstractBitmapDocumentHandler(IFContext context) { + super(context); + //Set target resolution + int dpi = Math.round(context.getUserAgent().getTargetResolution()); + getSettings().getWriterParams().setResolution(dpi); + + Map renderingOptions = getUserAgent().getRendererOptions(); + setTargetBitmapSize((Dimension)renderingOptions.get(TARGET_BITMAP_SIZE)); } /** {@inheritDoc} */ @@ -98,18 +105,6 @@ public abstract class AbstractBitmapDocumentHandler extends AbstractBinaryWritin public abstract String getDefaultExtension(); /** {@inheritDoc} */ - public void setContext(IFContext context) { - super.setContext(context); - - //Set target resolution - int dpi = Math.round(context.getUserAgent().getTargetResolution()); - getSettings().getWriterParams().setResolution(dpi); - - Map renderingOptions = getUserAgent().getRendererOptions(); - setTargetBitmapSize((Dimension)renderingOptions.get(TARGET_BITMAP_SIZE)); - } - - /** {@inheritDoc} */ public abstract IFDocumentHandlerConfigurator getConfigurator(); /** @@ -228,7 +223,7 @@ public abstract class AbstractBitmapDocumentHandler extends AbstractBinaryWritin //Normal case: just scale according to the target resolution scale = scaleFactor * getUserAgent().getTargetResolution() - / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION; + / FopFactoryConfig.DEFAULT_TARGET_RESOLUTION; bitmapWidth = (int) ((this.currentPageDimensions.width * scale / 1000f) + 0.5f); bitmapHeight = (int) ((this.currentPageDimensions.height * scale / 1000f) + 0.5f); } diff --git a/src/java/org/apache/fop/render/bitmap/BitmapRendererConfig.java b/src/java/org/apache/fop/render/bitmap/BitmapRendererConfig.java new file mode 100644 index 000000000..828f41d34 --- /dev/null +++ b/src/java/org/apache/fop/render/bitmap/BitmapRendererConfig.java @@ -0,0 +1,178 @@ +/* + * 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.bitmap; + +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.util.EnumMap; + +import org.apache.avalon.framework.configuration.Configuration; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.fonts.DefaultFontConfig; +import org.apache.fop.fonts.DefaultFontConfig.DefaultFontConfigParser; +import org.apache.fop.render.RendererConfig; +import org.apache.fop.render.java2d.Java2DRendererConfig; +import org.apache.fop.render.java2d.Java2DRendererConfig.Java2DRendererConfigParser; +import org.apache.fop.util.ColorUtil; + +import static org.apache.fop.render.bitmap.BitmapRendererOption.ANTI_ALIASING; +import static org.apache.fop.render.bitmap.BitmapRendererOption.BACKGROUND_COLOR; +import static org.apache.fop.render.bitmap.BitmapRendererOption.COLOR_MODE; +import static org.apache.fop.render.bitmap.BitmapRendererOption.JAVA2D_TRANSPARENT_PAGE_BACKGROUND; +import static org.apache.fop.render.bitmap.BitmapRendererOption.RENDERING_QUALITY; +import static org.apache.fop.render.bitmap.BitmapRendererOption.RENDERING_QUALITY_ELEMENT; +import static org.apache.fop.render.bitmap.BitmapRendererOption.RENDERING_SPEED; + +/** + * The Bitmap renderer config data object. + */ +public class BitmapRendererConfig implements RendererConfig { + + private final EnumMap<BitmapRendererOption, Object> params + = new EnumMap<BitmapRendererOption, Object>(BitmapRendererOption.class); + + private final DefaultFontConfig fontConfig; + + BitmapRendererConfig(DefaultFontConfig fontConfig) { + this.fontConfig = fontConfig; + } + + public DefaultFontConfig getFontInfoConfig() { + return fontConfig; + } + + public Color getBackgroundColor() { + return (Color) get(BACKGROUND_COLOR); + } + + public Boolean hasAntiAliasing() { + return (Boolean) get(ANTI_ALIASING); + } + + public Boolean isRenderHighQuality() { + return (Boolean) get(RENDERING_QUALITY); + } + + public Integer getColorMode() { + return (Integer) get(COLOR_MODE); + } + + public boolean hasTransparentBackround() { + Object result = get(JAVA2D_TRANSPARENT_PAGE_BACKGROUND); + return (Boolean) (result != null ? result + : JAVA2D_TRANSPARENT_PAGE_BACKGROUND.getDefaultValue()); + } + + private Object get(BitmapRendererOption option) { + return params.get(option); + } + + /** + * The parser for the Bitmap renderer configuration data. + */ + public static class BitmapRendererConfigParser implements RendererConfigParser { + + private final String mimeType; + + public BitmapRendererConfigParser(String mimeType) { + this.mimeType = mimeType; + } + + private void setParam(BitmapRendererConfig config, BitmapRendererOption option, + Object value) { + config.params.put(option, value != null ? value : option.getDefaultValue()); + } + + void build(BitmapRendererConfig config, FOUserAgent userAgent, + Configuration cfg) throws FOPException { + if (cfg != null) { + Java2DRendererConfig j2dConfig = new Java2DRendererConfigParser(null).build( + userAgent, cfg); + Boolean isTransparent = j2dConfig.isPageBackgroundTransparent(); + isTransparent = isTransparent == null + ? (Boolean) JAVA2D_TRANSPARENT_PAGE_BACKGROUND.getDefaultValue() + : isTransparent; + setParam(config, JAVA2D_TRANSPARENT_PAGE_BACKGROUND, isTransparent); + + String background = getValue(cfg, BACKGROUND_COLOR); + if (isTransparent) { + // We don't use setParam here because we want to force a null value + config.params.put(BACKGROUND_COLOR, null); + } else { + setParam(config, BACKGROUND_COLOR, + ColorUtil.parseColorString(userAgent, background)); + } + + setParam(config, BitmapRendererOption.ANTI_ALIASING, + getChild(cfg, ANTI_ALIASING).getValueAsBoolean( + (Boolean) ANTI_ALIASING.getDefaultValue())); + + String optimization = getValue(cfg, RENDERING_QUALITY_ELEMENT); + setParam(config, RENDERING_QUALITY, + !(BitmapRendererOption.getValue(optimization) == RENDERING_SPEED)); + + String color = getValue(cfg, COLOR_MODE); + setParam(config, COLOR_MODE, + getBufferedImageIntegerFromColor(BitmapRendererOption.getValue(color))); + } + } + + public BitmapRendererConfig build(FOUserAgent userAgent, Configuration cfg) + throws FOPException { + BitmapRendererConfig config = new BitmapRendererConfig(new DefaultFontConfigParser() + .parse(cfg, userAgent.validateStrictly())); + build(config, userAgent, cfg); + return config; + } + + private Integer getBufferedImageIntegerFromColor(BitmapRendererOption option) { + if (option == null) { + return null; + } + switch (option) { + case COLOR_MODE_RGBA: + return BufferedImage.TYPE_INT_ARGB; + case COLOR_MODE_RGB: + return BufferedImage.TYPE_INT_RGB; + case COLOR_MODE_GRAY: + return BufferedImage.TYPE_BYTE_GRAY; + case COLOR_MODE_BINARY: + case COLOR_MODE_BILEVEL: + return BufferedImage.TYPE_BYTE_BINARY; + default: + return null; + } + } + + private Configuration getChild(Configuration cfg, BitmapRendererOption option) { + return cfg.getChild(option.getName()); + } + + private String getValue(Configuration cfg, BitmapRendererOption option) { + return cfg.getChild(option.getName()).getValue(null); + } + + public String getMimeType() { + return mimeType; + } + } +} diff --git a/src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java b/src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java index 2ca0a172b..f0e32a9d7 100644 --- a/src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java +++ b/src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java @@ -19,123 +19,84 @@ package org.apache.fop.render.bitmap; -import java.awt.image.BufferedImage; +import java.util.ArrayList; 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.apps.MimeConstants; +import org.apache.fop.apps.io.InternalResourceResolver; +import org.apache.fop.fonts.EmbedFontInfo; 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.RendererConfig.RendererConfigParser; +import org.apache.fop.render.bitmap.BitmapRendererConfig.BitmapRendererConfigParser; 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; /** * Configurator for bitmap output. */ -public class BitmapRendererConfigurator extends Java2DRendererConfigurator - implements IFDocumentHandlerConfigurator { +public class BitmapRendererConfigurator extends Java2DRendererConfigurator { /** * Default constructor * @param userAgent user agent */ - public BitmapRendererConfigurator(FOUserAgent userAgent) { - super(userAgent); + public BitmapRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + super(userAgent, rendererConfigParser); } // ---=== IFDocumentHandler configuration ===--- /** {@inheritDoc} */ public void configure(IFDocumentHandler documentHandler) throws FOPException { - super.configure(documentHandler); - Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); - if (cfg != null) { - AbstractBitmapDocumentHandler bitmapHandler - = (AbstractBitmapDocumentHandler)documentHandler; - BitmapRenderingSettings settings = bitmapHandler.getSettings(); - - 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)); - } - } - - 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); - } + AbstractBitmapDocumentHandler bitmapHandler = (AbstractBitmapDocumentHandler) documentHandler; + BitmapRenderingSettings settings = bitmapHandler.getSettings(); + configure(documentHandler, settings, + new BitmapRendererConfigParser(MimeConstants.MIME_BITMAP)); + } - 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 if ("bi-level".equalsIgnoreCase(color)) { - settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); - } else { - throw new FOPException("Invalid value for color-mode: " + color); - } - } - } + void configure(IFDocumentHandler documentHandler, BitmapRenderingSettings settings, + BitmapRendererConfigParser parser) throws FOPException { + BitmapRendererConfig config = (BitmapRendererConfig) userAgent.getRendererConfig( + documentHandler.getMimeType(), parser); + configure(config, settings); } - /** {@inheritDoc} */ - public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) + private void configure(BitmapRendererConfig config, BitmapRenderingSettings settings) throws FOPException { - final FontManager fontManager = userAgent.getFactory().getFontManager(); - - final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics(); - - final List fontCollections = new java.util.ArrayList(); - fontCollections.add(new Base14FontCollection(java2DFontMetrics)); - fontCollections.add(new InstalledFontCollection(java2DFontMetrics)); - - 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, - userAgent.isComplexScriptFeaturesEnabled())); + if (config.hasTransparentBackround()) { + settings.setPageBackgroundColor(null); + } else if (config.getBackgroundColor() != null) { + settings.setPageBackgroundColor(config.getBackgroundColor()); + } + if (config.hasAntiAliasing() != null) { + settings.setAntiAliasing(config.hasAntiAliasing()); + } + if (config.isRenderHighQuality() != null) { + settings.setQualityRendering(config.isRenderHighQuality()); } + if (config.getColorMode() != null) { + settings.setBufferedImageType(config.getColorMode()); + } + } - fontManager.setup(fontInfo, - (FontCollection[])fontCollections.toArray( - new FontCollection[fontCollections.size()])); - documentHandler.setFontInfo(fontInfo); + @Override + protected FontCollection createCollectionFromFontList(InternalResourceResolver resourceResolver, + List<EmbedFontInfo> fontList) { + return new ConfiguredFontCollection(resourceResolver, fontList, userAgent.isComplexScriptFeaturesEnabled()); } + @Override + protected List<FontCollection> getDefaultFontCollection() { + final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics(); + final List<FontCollection> fontCollection = new ArrayList<FontCollection>(); + fontCollection.add(new Base14FontCollection(java2DFontMetrics)); + fontCollection.add(new InstalledFontCollection(java2DFontMetrics)); + return fontCollection; + } } diff --git a/src/java/org/apache/fop/render/bitmap/BitmapRendererOption.java b/src/java/org/apache/fop/render/bitmap/BitmapRendererOption.java new file mode 100644 index 000000000..d6030b5ac --- /dev/null +++ b/src/java/org/apache/fop/render/bitmap/BitmapRendererOption.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* $Id$ */ + +package org.apache.fop.render.bitmap; + +import java.awt.Color; +import java.awt.image.BufferedImage; + +import org.apache.fop.render.RendererConfigOption; + +/** + * An enumeration of the Bitmap renderer configuration opetions available to the user via the FOP + * conf. + */ +public enum BitmapRendererOption implements RendererConfigOption { + JAVA2D_TRANSPARENT_PAGE_BACKGROUND("transparent-page-background", false), + BACKGROUND_COLOR("background-color", Color.WHITE), + ANTI_ALIASING("anti-aliasing", true), + RENDERING_QUALITY_ELEMENT("rendering"), + RENDERING_QUALITY("quality", true), + RENDERING_SPEED("speed"), + COLOR_MODE("color-mode", BufferedImage.TYPE_INT_ARGB), + COLOR_MODE_RGBA("rgba"), + COLOR_MODE_RGB("rgb"), + COLOR_MODE_GRAY("gray"), + COLOR_MODE_BINARY("binary"), + COLOR_MODE_BILEVEL("bi-level"); + + private final String name; + private final Object defaultValue; + + private BitmapRendererOption(String name, Object defaultValue) { + this.name = name; + this.defaultValue = defaultValue; + } + + private BitmapRendererOption(String name) { + this(name, null); + } + + /** {@inheritDoc} */ + public String getName() { + return name; + } + + public Object getDefaultValue() { + return defaultValue; + } + + public static BitmapRendererOption getValue(String str) { + for (BitmapRendererOption opt : BitmapRendererOption.values()) { + if (opt.getName().equalsIgnoreCase(str)) { + return opt; + } + } + return null; + } +} diff --git a/src/java/org/apache/fop/render/bitmap/BitmapRenderingSettings.java b/src/java/org/apache/fop/render/bitmap/BitmapRenderingSettings.java index 278cd6c48..d239fe0fd 100644 --- a/src/java/org/apache/fop/render/bitmap/BitmapRenderingSettings.java +++ b/src/java/org/apache/fop/render/bitmap/BitmapRenderingSettings.java @@ -19,28 +19,30 @@ package org.apache.fop.render.bitmap; -import java.awt.image.BufferedImage; - import org.apache.xmlgraphics.image.writer.ImageWriterParams; import org.apache.fop.render.java2d.Java2DRenderingSettings; +import static org.apache.fop.render.bitmap.BitmapRendererOption.ANTI_ALIASING; +import static org.apache.fop.render.bitmap.BitmapRendererOption.COLOR_MODE; +import static org.apache.fop.render.bitmap.BitmapRendererOption.RENDERING_QUALITY; + /** * This class holds settings used when rendering to bitmaps. */ -public class BitmapRenderingSettings extends Java2DRenderingSettings implements TIFFConstants { +public class BitmapRenderingSettings extends Java2DRenderingSettings { /** ImageWriter parameters */ private ImageWriterParams writerParams; /** Image Type as parameter for the BufferedImage constructor (see BufferedImage.TYPE_*) */ - private int bufferedImageType = BufferedImage.TYPE_INT_ARGB; + private int bufferedImageType = (Integer) COLOR_MODE.getDefaultValue(); /** true if anti-aliasing is set */ - private boolean antialiasing = true; + private boolean antialiasing = (Boolean) ANTI_ALIASING.getDefaultValue(); /** true if qualityRendering is set */ - private boolean qualityRendering = true; + private boolean qualityRendering = (Boolean) RENDERING_QUALITY.getDefaultValue(); /** * Default constructor. Initializes the settings to their default values. diff --git a/src/java/org/apache/fop/render/bitmap/PNGDocumentHandler.java b/src/java/org/apache/fop/render/bitmap/PNGDocumentHandler.java index ed92b852f..68f6bac05 100644 --- a/src/java/org/apache/fop/render/bitmap/PNGDocumentHandler.java +++ b/src/java/org/apache/fop/render/bitmap/PNGDocumentHandler.java @@ -20,6 +20,9 @@ package org.apache.fop.render.bitmap; import org.apache.fop.apps.MimeConstants; +import org.apache.fop.render.bitmap.PNGRendererConfig.PNGRendererConfigParser; +import org.apache.fop.render.intermediate.IFContext; +import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; /** @@ -28,6 +31,11 @@ import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; */ public class PNGDocumentHandler extends AbstractBitmapDocumentHandler { + + PNGDocumentHandler(IFContext context) { + super(context); + } + /** {@inheritDoc} */ public String getMimeType() { return MimeConstants.MIME_PNG; @@ -40,7 +48,7 @@ public class PNGDocumentHandler extends AbstractBitmapDocumentHandler { /** {@inheritDoc} */ public IFDocumentHandlerConfigurator getConfigurator() { - return new BitmapRendererConfigurator(getUserAgent()); + return new BitmapRendererConfigurator(getUserAgent(), new PNGRendererConfigParser()); } } diff --git a/src/java/org/apache/fop/render/bitmap/PNGDocumentHandlerMaker.java b/src/java/org/apache/fop/render/bitmap/PNGDocumentHandlerMaker.java index d5a299528..7f820f71e 100644 --- a/src/java/org/apache/fop/render/bitmap/PNGDocumentHandlerMaker.java +++ b/src/java/org/apache/fop/render/bitmap/PNGDocumentHandlerMaker.java @@ -19,7 +19,6 @@ package org.apache.fop.render.bitmap; -import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.MimeConstants; import org.apache.fop.render.intermediate.AbstractIFDocumentHandlerMaker; import org.apache.fop.render.intermediate.IFContext; @@ -33,10 +32,8 @@ public class PNGDocumentHandlerMaker extends AbstractIFDocumentHandlerMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_PNG}; /** {@inheritDoc} */ - public IFDocumentHandler makeIFDocumentHandler(FOUserAgent ua) { - PNGDocumentHandler handler = new PNGDocumentHandler(); - handler.setContext(new IFContext(ua)); - return handler; + public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) { + return new PNGDocumentHandler(ifContext); } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/bitmap/PNGRendererConfig.java b/src/java/org/apache/fop/render/bitmap/PNGRendererConfig.java new file mode 100644 index 000000000..699faea51 --- /dev/null +++ b/src/java/org/apache/fop/render/bitmap/PNGRendererConfig.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fop.render.bitmap; + +import org.apache.avalon.framework.configuration.Configuration; + +import org.apache.xmlgraphics.util.MimeConstants; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.fonts.DefaultFontConfig; +import org.apache.fop.fonts.DefaultFontConfig.DefaultFontConfigParser; + +/** + * The PNG renderer configuration data object. + */ +public final class PNGRendererConfig extends BitmapRendererConfig { + + private PNGRendererConfig(DefaultFontConfig fontConfig) { + super(fontConfig); + } + + /** + * The PNG renderer configuration parser. + */ + public static class PNGRendererConfigParser implements RendererConfigParser { + + public PNGRendererConfig build(FOUserAgent userAgent, Configuration cfg) + throws FOPException { + return new PNGRendererConfig(new DefaultFontConfigParser().parse(cfg, + userAgent.validateStrictly())); + } + + /** {@inheritDoc} */ + public String getMimeType() { + return MimeConstants.MIME_PNG; + } + } +} diff --git a/src/java/org/apache/fop/render/bitmap/PNGRendererMaker.java b/src/java/org/apache/fop/render/bitmap/PNGRendererMaker.java index da19b2986..fb38b61f6 100644 --- a/src/java/org/apache/fop/render/bitmap/PNGRendererMaker.java +++ b/src/java/org/apache/fop/render/bitmap/PNGRendererMaker.java @@ -19,11 +19,12 @@ package org.apache.fop.render.bitmap; +import org.apache.fop.apps.FOPException; 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; +import org.apache.fop.render.bitmap.PNGRendererConfig.PNGRendererConfigParser; import org.apache.fop.render.java2d.Java2DRendererConfigurator; /** @@ -33,23 +34,22 @@ public class PNGRendererMaker extends AbstractRendererMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_PNG}; - - /** {@inheritDoc} */ + @Override public Renderer makeRenderer(FOUserAgent ua) { return new PNGRenderer(ua); } - /** {@inheritDoc} */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return new Java2DRendererConfigurator(userAgent); + @Override + public void configureRenderer(FOUserAgent userAgent, Renderer renderer) throws FOPException { + new Java2DRendererConfigurator(userAgent, new PNGRendererConfigParser()).configure(renderer); } - /** {@inheritDoc} */ + @Override public boolean needsOutputStream() { return true; } - /** {@inheritDoc} */ + @Override public String[] getSupportedMimeTypes() { return MIMES; } diff --git a/src/java/org/apache/fop/render/bitmap/TIFFConstants.java b/src/java/org/apache/fop/render/bitmap/TIFFCompressionValues.java index 437cf536a..71649022e 100644 --- a/src/java/org/apache/fop/render/bitmap/TIFFConstants.java +++ b/src/java/org/apache/fop/render/bitmap/TIFFCompressionValues.java @@ -19,31 +19,43 @@ package org.apache.fop.render.bitmap; -import org.apache.fop.apps.MimeConstants; - /** * Constants for TIFF output. */ -public interface TIFFConstants { - - /** The MIME type for tiff-Rendering */ - String MIME_TYPE = MimeConstants.MIME_TIFF; - +public enum TIFFCompressionValues { /** No compression */ - String COMPRESSION_NONE = "NONE"; + NONE("NONE"), /** JPEG compression */ - String COMPRESSION_JPEG = "JPEG"; + JPEG("JPEG"), /** Packbits (RLE) compression */ - String COMPRESSION_PACKBITS = "PackBits"; + PACKBITS("PackBits"), /** Deflate compression */ - String COMPRESSION_DEFLATE = "Deflate"; + DEFLATE("Deflate"), /** LZW compression */ - String COMPRESSION_LZW = "LZW"; + LZW("LZW"), /** ZLib compression */ - String COMPRESSION_ZLIB = "ZLib"; + ZLIB("ZLib"), /** CCITT Group 4 (T.6) compression */ - String COMPRESSION_CCITT_T6 = "CCITT T.6"; //CCITT Group 4 + CCITT_T6("CCITT T.6"), //CCITT Group 4 /** CCITT Group 3 (T.4) compression */ - String COMPRESSION_CCITT_T4 = "CCITT T.4"; //CCITT Group 3 + CCITT_T4("CCITT T.4"); //CCITT Group 3 + + private final String name; + + private TIFFCompressionValues(String name) { + this.name = name; + } + + public String getName() { + return name; + } + public static TIFFCompressionValues getValue(String name) { + for (TIFFCompressionValues tiffConst : TIFFCompressionValues.values()) { + if (tiffConst.name.equalsIgnoreCase(name)) { + return tiffConst; + } + } + return null; + } } diff --git a/src/java/org/apache/fop/render/bitmap/TIFFDocumentHandler.java b/src/java/org/apache/fop/render/bitmap/TIFFDocumentHandler.java index 1c9a39bbe..b147f497b 100644 --- a/src/java/org/apache/fop/render/bitmap/TIFFDocumentHandler.java +++ b/src/java/org/apache/fop/render/bitmap/TIFFDocumentHandler.java @@ -20,6 +20,9 @@ package org.apache.fop.render.bitmap; import org.apache.fop.apps.MimeConstants; +import org.apache.fop.render.bitmap.TIFFRendererConfig.TIFFRendererConfigParser; +import org.apache.fop.render.intermediate.IFContext; +import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; /** @@ -28,11 +31,16 @@ import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; */ public class TIFFDocumentHandler extends AbstractBitmapDocumentHandler { + TIFFDocumentHandler(IFContext context) { + super(context); + } + /** {@inheritDoc} */ public String getMimeType() { return MimeConstants.MIME_TIFF; } + /** {@inheritDoc} */ public String getDefaultExtension() { return "tif"; @@ -40,7 +48,6 @@ public class TIFFDocumentHandler extends AbstractBitmapDocumentHandler { /** {@inheritDoc} */ public IFDocumentHandlerConfigurator getConfigurator() { - return new TIFFRendererConfigurator(getUserAgent()); + return new TIFFRendererConfigurator(getUserAgent(), new TIFFRendererConfigParser()); } - } diff --git a/src/java/org/apache/fop/render/bitmap/TIFFDocumentHandlerMaker.java b/src/java/org/apache/fop/render/bitmap/TIFFDocumentHandlerMaker.java index b14ba3c18..ab8c7306a 100644 --- a/src/java/org/apache/fop/render/bitmap/TIFFDocumentHandlerMaker.java +++ b/src/java/org/apache/fop/render/bitmap/TIFFDocumentHandlerMaker.java @@ -19,7 +19,6 @@ package org.apache.fop.render.bitmap; -import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.MimeConstants; import org.apache.fop.render.intermediate.AbstractIFDocumentHandlerMaker; import org.apache.fop.render.intermediate.IFContext; @@ -33,10 +32,8 @@ public class TIFFDocumentHandlerMaker extends AbstractIFDocumentHandlerMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_TIFF}; /** {@inheritDoc} */ - public IFDocumentHandler makeIFDocumentHandler(FOUserAgent ua) { - TIFFDocumentHandler handler = new TIFFDocumentHandler(); - handler.setContext(new IFContext(ua)); - return handler; + public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) { + return new TIFFDocumentHandler(ifContext); } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/bitmap/TIFFRenderer.java b/src/java/org/apache/fop/render/bitmap/TIFFRenderer.java index 3cdcf2cdc..5b75a372c 100644 --- a/src/java/org/apache/fop/render/bitmap/TIFFRenderer.java +++ b/src/java/org/apache/fop/render/bitmap/TIFFRenderer.java @@ -44,8 +44,13 @@ import org.apache.xmlgraphics.image.writer.MultiImageWriter; 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; +import static org.apache.fop.render.bitmap.TIFFCompressionValues.CCITT_T4; +import static org.apache.fop.render.bitmap.TIFFCompressionValues.CCITT_T6; +import static org.apache.fop.render.bitmap.TIFFCompressionValues.PACKBITS; + /** * <p> * This class represents renderer to TIFF (Tagged Image File Format) format. It @@ -67,7 +72,7 @@ import org.apache.fop.render.java2d.Java2DRenderer; * <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 implements TIFFConstants { +public class TIFFRenderer extends Java2DRenderer { /** ImageWriter parameters */ private ImageWriterParams writerParams; @@ -79,7 +84,7 @@ public class TIFFRenderer extends Java2DRenderer implements TIFFConstants { /** {@inheritDoc} */ public String getMimeType() { - return MIME_TYPE; + return MimeConstants.MIME_TIFF; } /** @@ -90,7 +95,7 @@ public class TIFFRenderer extends Java2DRenderer implements TIFFConstants { public TIFFRenderer(FOUserAgent userAgent) { super(userAgent); writerParams = new ImageWriterParams(); - writerParams.setCompressionMethod(COMPRESSION_PACKBITS); + writerParams.setCompressionMethod(PACKBITS.getName()); int dpi = Math.round(userAgent.getTargetResolution()); writerParams.setResolution(dpi); @@ -190,8 +195,8 @@ public class TIFFRenderer extends Java2DRenderer implements TIFFConstants { throw new NoSuchElementException(e.getMessage()); } - if (COMPRESSION_CCITT_T4.equalsIgnoreCase(writerParams.getCompressionMethod()) - || COMPRESSION_CCITT_T6.equalsIgnoreCase(writerParams.getCompressionMethod())) { + TIFFCompressionValues compression = TIFFCompressionValues.getValue(writerParams.getCompressionMethod()); + if (compression == CCITT_T4 || compression == CCITT_T6) { return pageImage; } else { //Decorate the image with a packed sample model for encoding by the codec diff --git a/src/java/org/apache/fop/render/bitmap/TIFFRendererConfig.java b/src/java/org/apache/fop/render/bitmap/TIFFRendererConfig.java new file mode 100644 index 000000000..5417ecc1e --- /dev/null +++ b/src/java/org/apache/fop/render/bitmap/TIFFRendererConfig.java @@ -0,0 +1,102 @@ +/* + * 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.bitmap; + +import java.util.EnumMap; + +import org.apache.avalon.framework.configuration.Configuration; + +import org.apache.xmlgraphics.util.MimeConstants; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.fonts.DefaultFontConfig; +import org.apache.fop.fonts.DefaultFontConfig.DefaultFontConfigParser; +import org.apache.fop.render.RendererConfigOption; + +/** + * The renderer configuration object for the TIFF renderer. + */ +public final class TIFFRendererConfig extends BitmapRendererConfig { + + public enum TIFFRendererOption implements RendererConfigOption { + COMPRESSION("compression", TIFFCompressionValues.PACKBITS); + + private final String name; + private final Object defaultValue; + + private TIFFRendererOption(String name, Object defaultValue) { + this.name = name; + this.defaultValue = defaultValue; + } + + public String getName() { + return name; + } + + public Object getDefaultValue() { + return defaultValue; + } + } + + private final EnumMap<TIFFRendererOption, Object> params + = new EnumMap<TIFFRendererOption, Object>(TIFFRendererOption.class); + + private TIFFRendererConfig(DefaultFontConfig fontConfig) { + super(fontConfig); + } + + public TIFFCompressionValues getCompressionType() { + return (TIFFCompressionValues) params.get(TIFFRendererOption.COMPRESSION); + } + + /** + * The TIFF renderer configuration parser. + */ + public static final class TIFFRendererConfigParser extends BitmapRendererConfigParser { + + public TIFFRendererConfigParser() { + super(MimeConstants.MIME_TIFF); + } + + private TIFFRendererConfig config; + + private void setParam(TIFFRendererOption option, Object value) { + config.params.put(option, value != null ? value : option.getDefaultValue()); + } + + private String getValue(Configuration cfg, TIFFRendererOption option) { + return cfg.getChild(option.getName()).getValue(null); + } + + /** {@inheritDoc} */ + public TIFFRendererConfig build(FOUserAgent userAgent, Configuration cfg) throws FOPException { + config = new TIFFRendererConfig(new DefaultFontConfigParser() + .parse(cfg, userAgent.validateStrictly())); + super.build(config, userAgent, cfg); + if (cfg != null) { + setParam(TIFFRendererOption.COMPRESSION, + TIFFCompressionValues.getValue(getValue(cfg, + TIFFRendererOption.COMPRESSION))); + } + return config; + } + } +} diff --git a/src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java b/src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java index f78605a15..b10f2a381 100644 --- a/src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java +++ b/src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java @@ -21,24 +21,34 @@ package org.apache.fop.render.bitmap; import java.awt.image.BufferedImage; -import org.apache.avalon.framework.configuration.Configuration; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.xmlgraphics.image.writer.ImageWriterParams; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.render.Renderer; +import org.apache.fop.render.RendererConfig.RendererConfigParser; +import org.apache.fop.render.bitmap.TIFFRendererConfig.TIFFRendererConfigParser; import org.apache.fop.render.intermediate.IFDocumentHandler; +import static org.apache.fop.render.bitmap.TIFFCompressionValues.CCITT_T4; +import static org.apache.fop.render.bitmap.TIFFCompressionValues.CCITT_T6; +import static org.apache.fop.render.bitmap.TIFFCompressionValues.NONE; + /** * TIFF Renderer configurator */ public class TIFFRendererConfigurator extends BitmapRendererConfigurator { + private static final Log LOG = LogFactory.getLog(TIFFRendererConfigurator.class); /** * Default constructor * @param userAgent user agent */ - public TIFFRendererConfigurator(FOUserAgent userAgent) { - super(userAgent); + public TIFFRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + super(userAgent, rendererConfigParser); } /** @@ -49,58 +59,46 @@ public class TIFFRendererConfigurator extends BitmapRendererConfigurator { * {@inheritDoc} */ public void configure(Renderer renderer) throws FOPException { - Configuration cfg = super.getRendererConfig(renderer); - if (cfg != null) { - TIFFRenderer tiffRenderer = (TIFFRenderer)renderer; + final TIFFRendererConfig config = (TIFFRendererConfig) getRendererConfig(renderer); + if (config != null) { + TIFFRenderer tiffRenderer = (TIFFRenderer) renderer; //set compression - String name = cfg.getChild("compression").getValue(TIFFConstants.COMPRESSION_PACKBITS); - //Some compression formats need a special image format: - tiffRenderer.setBufferedImageType(getBufferedImageTypeFor(name)); - if (!"NONE".equalsIgnoreCase(name)) { - tiffRenderer.getWriterParams().setCompressionMethod(name); + tiffRenderer.setBufferedImageType(getCompressionType(config, tiffRenderer.getWriterParams())); + } + super.configure(renderer); + } + + private int getCompressionType(TIFFRendererConfig config, ImageWriterParams writerParms) + throws FOPException { + //Some compression formats need a special image format: + TIFFCompressionValues compression = config.getCompressionType(); + if (compression != null) { + if (compression != NONE) { + writerParms.setCompressionMethod(compression.getName()); } - if (log.isInfoEnabled()) { - log.info("TIFF compression set to " + name); + if (LOG.isInfoEnabled()) { + LOG.info("TIFF compression set to " + compression.getName()); } } - super.configure(renderer); + return getBufferedImageTypeFor(compression); } - /** - * Determines the type value for the BufferedImage to be produced for rendering - * the bitmap image. - * @param compressionName the compression name - * @return a value from the {@link BufferedImage}.TYPE_* constants - */ - 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)) { + private int getBufferedImageTypeFor(TIFFCompressionValues compressionType) { + if (compressionType == CCITT_T6 || compressionType == CCITT_T4) { return BufferedImage.TYPE_BYTE_BINARY; } else { return BufferedImage.TYPE_INT_ARGB; } } - // ---=== IFDocumentHandler configuration ===--- - /** {@inheritDoc} */ public void configure(IFDocumentHandler documentHandler) throws FOPException { - super.configure(documentHandler); - Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); - if (cfg != null) { - TIFFDocumentHandler tiffHandler = (TIFFDocumentHandler)documentHandler; + final TIFFRendererConfig tiffConfig = (TIFFRendererConfig) getRendererConfig(documentHandler); + if (tiffConfig != 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); - } + configure(documentHandler, settings, new TIFFRendererConfigParser()); + settings.setBufferedImageType(getCompressionType(tiffConfig, settings.getWriterParams())); } } diff --git a/src/java/org/apache/fop/render/bitmap/TIFFRendererMaker.java b/src/java/org/apache/fop/render/bitmap/TIFFRendererMaker.java index 852e6ba04..f4cb78285 100644 --- a/src/java/org/apache/fop/render/bitmap/TIFFRendererMaker.java +++ b/src/java/org/apache/fop/render/bitmap/TIFFRendererMaker.java @@ -19,11 +19,12 @@ package org.apache.fop.render.bitmap; +import org.apache.fop.apps.FOPException; 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; +import org.apache.fop.render.bitmap.TIFFRendererConfig.TIFFRendererConfigParser; /** * RendererMaker for the TIFF Renderer. @@ -32,24 +33,24 @@ public class TIFFRendererMaker extends AbstractRendererMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_TIFF}; - /** {@inheritDoc} */ + @Override public Renderer makeRenderer(FOUserAgent userAgent) { return new TIFFRenderer(userAgent); } - /** {@inheritDoc} */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return new TIFFRendererConfigurator(userAgent); - } - - /** {@inheritDoc} */ + @Override public boolean needsOutputStream() { return true; } - /** {@inheritDoc} */ + @Override public String[] getSupportedMimeTypes() { return MIMES; } + @Override + public void configureRenderer(FOUserAgent userAgent, Renderer renderer) throws FOPException { + new TIFFRendererConfigurator(userAgent, new TIFFRendererConfigParser()).configure(renderer); + } + } diff --git a/src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java b/src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java index cc5406acf..e0ee5b3b3 100644 --- a/src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java +++ b/src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java @@ -19,15 +19,14 @@ package org.apache.fop.render.intermediate; -import java.io.File; +import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.net.URL; +import java.net.URI; import javax.xml.transform.Result; import javax.xml.transform.stream.StreamResult; -import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.fop.fonts.FontCollection; @@ -49,10 +48,14 @@ public abstract class AbstractBinaryWritingIFDocumentHandler extends AbstractIFD /** Font configuration */ protected FontInfo fontInfo; + public AbstractBinaryWritingIFDocumentHandler(IFContext ifContext) { + super(ifContext); + } + /** {@inheritDoc} */ public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { - StreamResult streamResult = (StreamResult)result; + StreamResult streamResult = (StreamResult) result; OutputStream out = streamResult.getOutputStream(); if (out == null) { if (streamResult.getWriter() != null) { @@ -60,22 +63,13 @@ public abstract class AbstractBinaryWritingIFDocumentHandler extends AbstractIFD "FOP cannot use a Writer. Please supply an OutputStream!"); } try { - URL url = new URL(streamResult.getSystemId()); - File f = FileUtils.toFile(url); - if (f != null) { - out = new java.io.FileOutputStream(f); - } else { - out = url.openConnection().getOutputStream(); - } + URI resultURI = URI.create(streamResult.getSystemId()); + out = new BufferedOutputStream(getUserAgent().getResourceResolver().getOutputStream(resultURI)); } catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); } - out = new java.io.BufferedOutputStream(out); this.ownOutputStream = true; } - if (out == null) { - throw new IllegalArgumentException("Need a StreamResult with an OutputStream"); - } this.outputStream = out; } else { throw new UnsupportedOperationException( @@ -95,7 +89,7 @@ public abstract class AbstractBinaryWritingIFDocumentHandler extends AbstractIFD /** {@inheritDoc} */ public void setDefaultFontInfo(FontInfo fontInfo) { - FontManager fontManager = getUserAgent().getFactory().getFontManager(); + FontManager fontManager = getUserAgent().getFontManager(); FontCollection[] fontCollections = new FontCollection[] { new Base14FontCollection(fontManager.isBase14KerningEnabled()) }; diff --git a/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java b/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java index 2b90e4a7b..72ff9a1ac 100644 --- a/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java +++ b/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java @@ -21,6 +21,9 @@ package org.apache.fop.render.intermediate; import java.util.Locale; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + import org.apache.fop.accessibility.DummyStructureTreeEventHandler; import org.apache.fop.accessibility.StructureTreeEventHandler; import org.apache.fop.apps.FOUserAgent; @@ -30,19 +33,19 @@ import org.apache.fop.apps.FOUserAgent; */ public abstract class AbstractIFDocumentHandler implements IFDocumentHandler { - private IFContext ifContext; + /** logging instance */ + private static Log log = LogFactory.getLog(AbstractIFDocumentHandler.class); + + private final IFContext ifContext; /** * Default constructor. */ - public AbstractIFDocumentHandler() { - } - - /** {@inheritDoc} */ - public void setContext(IFContext context) { + protected AbstractIFDocumentHandler(IFContext context) { this.ifContext = context; } + /** {@inheritDoc} */ public IFContext getContext() { return this.ifContext; diff --git a/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandlerMaker.java b/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandlerMaker.java index 204faad00..610f522c2 100644 --- a/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandlerMaker.java +++ b/src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandlerMaker.java @@ -19,7 +19,6 @@ package org.apache.fop.render.intermediate; -import org.apache.fop.apps.FOUserAgent; /** * Base class for factory classes which instantiate {@link IFDocumentHandler}s and provide @@ -29,10 +28,10 @@ public abstract class AbstractIFDocumentHandlerMaker { /** * Instantiates a new {@link IFDocumentHandler}. - * @param userAgent the user agent + * @param ifContext the user agent * @return the newly instantiated document handler */ - public abstract IFDocumentHandler makeIFDocumentHandler(FOUserAgent userAgent); + public abstract IFDocumentHandler makeIFDocumentHandler(IFContext ifContext); /** * @return Indicates whether this document handler requires an OutputStream to work with. diff --git a/src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java b/src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java index 327eca14e..147b6d54b 100644 --- a/src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java +++ b/src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java @@ -45,7 +45,6 @@ import org.apache.xmlgraphics.image.loader.util.ImageUtil; import org.apache.fop.ResourceEventProducer; import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.apps.FopFactory; import org.apache.fop.fo.Constants; import org.apache.fop.fonts.FontInfo; import org.apache.fop.fonts.FontTriplet; @@ -112,14 +111,6 @@ public abstract class AbstractIFPainter<T extends IFDocumentHandler> implements return getContext().getUserAgent(); } - /** - * Returns the FOP factory. - * @return the FOP factory. - */ - protected FopFactory getFopFactory() { - return getUserAgent().getFactory(); - } - private AffineTransform combine(AffineTransform[] transforms) { AffineTransform at = new AffineTransform(); for (int i = 0, c = transforms.length; i < c; i++) { @@ -154,9 +145,9 @@ public abstract class AbstractIFPainter<T extends IFDocumentHandler> implements */ protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect) throws ImageException, IOException { - ImageManager manager = getFopFactory().getImageManager(); + ImageManager manager = getUserAgent().getImageManager(); ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); - ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); + ImageHandlerRegistry imageHandlerRegistry = getUserAgent().getImageHandlerRegistry(); //Load and convert the image to a supported format RenderingContext context = createRenderingContext(); @@ -220,8 +211,8 @@ public abstract class AbstractIFPainter<T extends IFDocumentHandler> implements protected void drawImage(Image image, Rectangle rect, RenderingContext context, boolean convert, Map additionalHints) throws IOException, ImageException { - ImageManager manager = getFopFactory().getImageManager(); - ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); + ImageManager manager = getUserAgent().getImageManager(); + ImageHandlerRegistry imageHandlerRegistry = getUserAgent().getImageHandlerRegistry(); Image effImage; context.putHints(additionalHints); @@ -259,7 +250,7 @@ public abstract class AbstractIFPainter<T extends IFDocumentHandler> implements * @return the ImageInfo instance or null if there has been an error. */ protected ImageInfo getImageInfo(String uri) { - ImageManager manager = getFopFactory().getImageManager(); + ImageManager manager = getUserAgent().getImageManager(); try { ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); return manager.getImageInfo(uri, sessionContext); @@ -285,7 +276,7 @@ public abstract class AbstractIFPainter<T extends IFDocumentHandler> implements * @param rect the rectangle in which to paint the image */ protected void drawImageUsingURI(String uri, Rectangle rect) { - ImageManager manager = getFopFactory().getImageManager(); + ImageManager manager = getUserAgent().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); @@ -313,7 +304,7 @@ public abstract class AbstractIFPainter<T extends IFDocumentHandler> implements * @param rect the rectangle in which to paint the image */ protected void drawImageUsingDocument(Document doc, Rectangle rect) { - ImageManager manager = getFopFactory().getImageManager(); + ImageManager manager = getUserAgent().getImageManager(); ImageInfo info = null; try { info = manager.preloadImage(null, new DOMSource(doc)); diff --git a/src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java b/src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java index be65e1317..fcf8554a6 100644 --- a/src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java +++ b/src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java @@ -45,6 +45,10 @@ public abstract class AbstractXMLWritingIFDocumentHandler extends AbstractIFDocu /** Main SAX ContentHandler to receive the generated SAX events. */ protected GenerationHelperContentHandler handler; + protected AbstractXMLWritingIFDocumentHandler(IFContext context) { + super(context); + } + /** {@inheritDoc} */ public void setResult(Result result) throws IFException { if (result instanceof SAXResult) { diff --git a/src/java/org/apache/fop/render/intermediate/IFDocumentHandler.java b/src/java/org/apache/fop/render/intermediate/IFDocumentHandler.java index 6cb8f2795..5342f09aa 100644 --- a/src/java/org/apache/fop/render/intermediate/IFDocumentHandler.java +++ b/src/java/org/apache/fop/render/intermediate/IFDocumentHandler.java @@ -78,12 +78,6 @@ import org.apache.fop.fonts.FontInfo; public interface IFDocumentHandler { /** - * Sets the intermediate format context object. - * @param context the context object - */ - void setContext(IFContext context); - - /** * Returns the associated intermediate format context object. * @return the context object */ @@ -274,4 +268,5 @@ public interface IFDocumentHandler { * @throws IFException if an error occurs while handling this event */ void handleExtensionObject(Object extension) throws IFException; + } diff --git a/src/java/org/apache/fop/render/intermediate/IFDocumentHandlerConfigurator.java b/src/java/org/apache/fop/render/intermediate/IFDocumentHandlerConfigurator.java index 3a42918f3..c00ebe29e 100644 --- a/src/java/org/apache/fop/render/intermediate/IFDocumentHandlerConfigurator.java +++ b/src/java/org/apache/fop/render/intermediate/IFDocumentHandlerConfigurator.java @@ -40,6 +40,6 @@ public interface IFDocumentHandlerConfigurator { * @param fontInfo the font info object to set up * @throws FOPException if an error occurs while configuring the object */ - void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException; + void setupFontInfo(String mimeType, FontInfo fontInfo) throws FOPException; } diff --git a/src/java/org/apache/fop/render/intermediate/IFParser.java b/src/java/org/apache/fop/render/intermediate/IFParser.java index 827eec820..d1fa50737 100644 --- a/src/java/org/apache/fop/render/intermediate/IFParser.java +++ b/src/java/org/apache/fop/render/intermediate/IFParser.java @@ -130,7 +130,7 @@ public class IFParser implements IFConstants { public ContentHandler getContentHandler(IFDocumentHandler documentHandler, FOUserAgent userAgent) { ElementMappingRegistry elementMappingRegistry - = userAgent.getFactory().getElementMappingRegistry(); + = userAgent.getElementMappingRegistry(); return new Handler(documentHandler, userAgent, elementMappingRegistry); } @@ -306,7 +306,7 @@ public class IFParser implements IFConstants { delegate.startElement(uri, localName, qName, attributes); } else { ContentHandlerFactoryRegistry registry - = userAgent.getFactory().getContentHandlerFactoryRegistry(); + = userAgent.getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory == null) { DOMImplementation domImplementation diff --git a/src/java/org/apache/fop/render/intermediate/IFRenderer.java b/src/java/org/apache/fop/render/intermediate/IFRenderer.java index e5c1f98c7..57f13ac07 100644 --- a/src/java/org/apache/fop/render/intermediate/IFRenderer.java +++ b/src/java/org/apache/fop/render/intermediate/IFRenderer.java @@ -232,9 +232,8 @@ public class IFRenderer extends AbstractPathOrientedRenderer { * @return the default IFDocumentHandler */ protected IFDocumentHandler createDefaultDocumentHandler() { - IFSerializer serializer = new IFSerializer(); FOUserAgent userAgent = getUserAgent(); - serializer.setContext(new IFContext(userAgent)); + IFSerializer serializer = new IFSerializer(new IFContext(userAgent)); if (userAgent.isAccessibilityEnabled()) { userAgent.setStructureTreeEventHandler(serializer.getStructureTreeEventHandler()); } diff --git a/src/java/org/apache/fop/render/intermediate/IFRendererConfig.java b/src/java/org/apache/fop/render/intermediate/IFRendererConfig.java new file mode 100644 index 000000000..753d9ff30 --- /dev/null +++ b/src/java/org/apache/fop/render/intermediate/IFRendererConfig.java @@ -0,0 +1,63 @@ +/* + * 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.intermediate; + +import org.apache.avalon.framework.configuration.Configuration; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.fonts.DefaultFontConfig; +import org.apache.fop.fonts.DefaultFontConfig.DefaultFontConfigParser; +import org.apache.fop.fonts.FontConfig; +import org.apache.fop.render.RendererConfig; + +/** + * The Intermediate Format renderer configuration data object. + */ +public final class IFRendererConfig implements RendererConfig { + + private final DefaultFontConfig fontConfig; + + private IFRendererConfig(DefaultFontConfig fontConfig) { + this.fontConfig = fontConfig; + } + + public FontConfig getFontInfoConfig() { + return fontConfig; + } + + /** + * The Intermediate Format configuration data parser. + */ + public static final class IFRendererConfigParser implements RendererConfigParser { + + /** {@inheritDoc} */ + public RendererConfig build(FOUserAgent userAgent, Configuration cfg) + throws FOPException { + return new IFRendererConfig(new DefaultFontConfigParser().parse(cfg, + userAgent.validateStrictly())); + } + + /** {@inheritDoc} */ + public String getMimeType() { + return "application/X-fop-intermediate-format"; + } + } +} diff --git a/src/java/org/apache/fop/render/intermediate/IFSerializer.java b/src/java/org/apache/fop/render/intermediate/IFSerializer.java index 7114f51e3..41d1b01ef 100644 --- a/src/java/org/apache/fop/render/intermediate/IFSerializer.java +++ b/src/java/org/apache/fop/render/intermediate/IFSerializer.java @@ -40,8 +40,9 @@ import org.apache.xmlgraphics.util.XMLizable; import org.apache.fop.accessibility.StructureTreeEventHandler; import org.apache.fop.fo.extensions.InternalElementMapping; import org.apache.fop.fonts.FontInfo; -import org.apache.fop.render.PrintRendererConfigurator; +import org.apache.fop.render.DefaultRendererConfigurator; import org.apache.fop.render.RenderingContext; +import org.apache.fop.render.intermediate.IFRendererConfig.IFRendererConfigParser; import org.apache.fop.render.intermediate.IFStructureTreeBuilder.IFStructureTreeElement; import org.apache.fop.render.intermediate.extensions.AbstractAction; import org.apache.fop.render.intermediate.extensions.Bookmark; @@ -62,7 +63,7 @@ import org.apache.fop.util.XMLUtil; * IFPainter implementation that serializes the intermediate format to XML. */ public class IFSerializer extends AbstractXMLWritingIFDocumentHandler - implements IFConstants, IFPainter, IFDocumentNavigationHandler { +implements IFConstants, IFPainter, IFDocumentNavigationHandler { /** * Intermediate Format (IF) version, used to express an @version attribute @@ -83,6 +84,10 @@ public class IFSerializer extends AbstractXMLWritingIFDocumentHandler private IFStructureTreeBuilder structureTreeBuilder; + public IFSerializer(IFContext context) { + super(context); + } + /** {@inheritDoc} */ @Override protected String getMainNamespace() { @@ -106,7 +111,7 @@ public class IFSerializer extends AbstractXMLWritingIFDocumentHandler if (this.mimicHandler != null) { return getMimickedDocumentHandler().getConfigurator(); } else { - return new PrintRendererConfigurator(getUserAgent()); + return new DefaultRendererConfigurator(getUserAgent(), new IFRendererConfigParser()); } } @@ -284,7 +289,7 @@ public class IFSerializer extends AbstractXMLWritingIFDocumentHandler /** {@inheritDoc} */ public void startPage(int index, String name, String pageMasterName, Dimension size) - throws IFException { + throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "index", Integer.toString(index)); @@ -386,7 +391,7 @@ public class IFSerializer extends AbstractXMLWritingIFDocumentHandler } private void startViewport(String transform, Dimension size, Rectangle clipRect) - throws IFException { + throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { @@ -684,7 +689,7 @@ public class IFSerializer extends AbstractXMLWritingIFDocumentHandler } else { throw new UnsupportedOperationException( "Extension must implement XMLizable: " - + extension + " (" + extension.getClass().getName() + ")"); + + extension + " (" + extension.getClass().getName() + ")"); } } diff --git a/src/java/org/apache/fop/render/intermediate/IFSerializerMaker.java b/src/java/org/apache/fop/render/intermediate/IFSerializerMaker.java index c0060ab8e..fa375fb94 100644 --- a/src/java/org/apache/fop/render/intermediate/IFSerializerMaker.java +++ b/src/java/org/apache/fop/render/intermediate/IFSerializerMaker.java @@ -28,9 +28,9 @@ import org.apache.fop.apps.MimeConstants; public class IFSerializerMaker extends AbstractIFDocumentHandlerMaker { /** {@inheritDoc} */ - public IFDocumentHandler makeIFDocumentHandler(FOUserAgent ua) { - IFSerializer handler = new IFSerializer(); - handler.setContext(new IFContext(ua)); + public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) { + IFSerializer handler = new IFSerializer(ifContext); + FOUserAgent ua = ifContext.getUserAgent(); if (ua.isAccessibilityEnabled()) { ua.setStructureTreeEventHandler(handler.getStructureTreeEventHandler()); } diff --git a/src/java/org/apache/fop/render/intermediate/IFUtil.java b/src/java/org/apache/fop/render/intermediate/IFUtil.java index c4f681936..bdd7eb8a0 100644 --- a/src/java/org/apache/fop/render/intermediate/IFUtil.java +++ b/src/java/org/apache/fop/render/intermediate/IFUtil.java @@ -167,7 +167,8 @@ public final class IFUtil { } IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); if (configurator != null) { - configurator.setupFontInfo(documentHandler, fontInfo); + configurator.setupFontInfo(documentHandler.getMimeType(), fontInfo); + documentHandler.setFontInfo(fontInfo); } else { documentHandler.setDefaultFontInfo(fontInfo); } diff --git a/src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java b/src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java index dde744180..b88e75206 100644 --- a/src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java +++ b/src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java @@ -61,11 +61,6 @@ public class IFDocumentHandlerProxy implements IFDocumentHandler { } /** {@inheritDoc} */ - public void setContext(IFContext context) { - this.delegate.setContext(context); - } - - /** {@inheritDoc} */ public IFContext getContext() { return this.delegate.getContext(); } diff --git a/src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java b/src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java index 9c404be3e..0b410873b 100644 --- a/src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java +++ b/src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java @@ -19,21 +19,19 @@ package org.apache.fop.render.java2d; +import java.io.InputStream; +import java.net.URI; import java.util.List; -import javax.xml.transform.Source; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.fop.apps.io.InternalResourceResolver; import org.apache.fop.fonts.CustomFont; import org.apache.fop.fonts.EmbedFontInfo; -import org.apache.fop.fonts.EncodingMode; import org.apache.fop.fonts.FontCollection; import org.apache.fop.fonts.FontInfo; import org.apache.fop.fonts.FontLoader; -import org.apache.fop.fonts.FontManager; -import org.apache.fop.fonts.FontResolver; import org.apache.fop.fonts.FontTriplet; import org.apache.fop.fonts.LazyFont; @@ -44,23 +42,21 @@ public class ConfiguredFontCollection implements FontCollection { private static Log log = LogFactory.getLog(ConfiguredFontCollection.class); - private FontResolver fontResolver; - private List/*<EmbedFontInfo>*/ embedFontInfoList; + private final InternalResourceResolver resourceResolver; + private final List<EmbedFontInfo> embedFontInfoList; + private final boolean useComplexScripts; /** * Main constructor - * @param fontResolver a font resolver + * @param resourceResolver a font resolver * @param customFonts the list of custom fonts * @param useComplexScriptFeatures true if complex script features enabled */ - public ConfiguredFontCollection(FontResolver fontResolver, - List/*<EmbedFontInfo>*/ customFonts, boolean useComplexScriptFeatures) { - this.fontResolver = fontResolver; - if (this.fontResolver == null) { - //Ensure that we have minimal font resolution capabilities - this.fontResolver = FontManager.createMinimalFontResolver(useComplexScriptFeatures); - } + public ConfiguredFontCollection(InternalResourceResolver resourceResolver, + List<EmbedFontInfo> customFonts, boolean useComplexScriptFeatures) { + this.resourceResolver = resourceResolver; this.embedFontInfoList = customFonts; + this.useComplexScripts = useComplexScriptFeatures; } /** {@inheritDoc} */ @@ -72,43 +68,37 @@ public class ConfiguredFontCollection implements FontCollection { } String internalName = null; - for (int i = 0; i < embedFontInfoList.size(); i++) { - - EmbedFontInfo configFontInfo = (EmbedFontInfo) embedFontInfoList.get(i); - String fontFile = configFontInfo.getEmbedFile(); - internalName = "F" + num; - num++; + for (EmbedFontInfo configFontInfo : embedFontInfoList) { + internalName = "F" + num++; try { + URI fontURI = configFontInfo.getEmbedURI(); FontMetricsMapper font = null; - String metricsUrl = configFontInfo.getMetricsFile(); + URI metricsURI = configFontInfo.getMetricsURI(); // If the user specified an XML-based metrics file, we'll use it // Otherwise, calculate metrics directly from the font file. - if (metricsUrl != null) { - LazyFont fontMetrics = new LazyFont(configFontInfo, fontResolver); - Source fontSource = fontResolver.resolve(configFontInfo.getEmbedFile()); + if (metricsURI != null) { + LazyFont fontMetrics = new LazyFont(configFontInfo, resourceResolver, useComplexScripts); + InputStream fontSource = resourceResolver.getResource(fontURI); font = new CustomFontMetricsMapper(fontMetrics, fontSource); } else { - CustomFont fontMetrics = FontLoader.loadFont( - fontFile, null, true, configFontInfo.getEmbeddingMode(), - EncodingMode.AUTO, - configFontInfo.getKerning(), - configFontInfo.getAdvanced(), fontResolver); + CustomFont fontMetrics = FontLoader.loadFont(fontURI, null, true, + configFontInfo.getEmbeddingMode(), configFontInfo.getEncodingMode(), + configFontInfo.getKerning(), configFontInfo.getAdvanced(), + resourceResolver); font = new CustomFontMetricsMapper(fontMetrics); } fontInfo.addMetrics(internalName, font); - List<FontTriplet> triplets = configFontInfo.getFontTriplets(); - for (int c = 0; c < triplets.size(); c++) { - FontTriplet triplet = (FontTriplet) triplets.get(c); - + for (FontTriplet triplet : configFontInfo.getFontTriplets()) { if (log.isDebugEnabled()) { log.debug("Registering: " + triplet + " under " + internalName); } fontInfo.addFontProperties(internalName, triplet); } } catch (Exception e) { - log.warn("Unable to load custom font from file '" + fontFile + "'", e); + log.warn("Unable to load custom font from file '" + configFontInfo.getEmbedURI() + + "'", e); } } return num; diff --git a/src/java/org/apache/fop/render/java2d/CustomFontMetricsMapper.java b/src/java/org/apache/fop/render/java2d/CustomFontMetricsMapper.java index 36df00f20..e821e635d 100644 --- a/src/java/org/apache/fop/render/java2d/CustomFontMetricsMapper.java +++ b/src/java/org/apache/fop/render/java2d/CustomFontMetricsMapper.java @@ -26,9 +26,6 @@ import java.io.InputStream; import java.util.Map; import java.util.Set; -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; - import org.apache.fop.fonts.CustomFont; import org.apache.fop.fonts.FontType; import org.apache.fop.fonts.LazyFont; @@ -67,7 +64,7 @@ public class CustomFontMetricsMapper extends Typeface implements FontMetricsMapp public CustomFontMetricsMapper(final CustomFont fontMetrics) throws FontFormatException, IOException { this.typeface = fontMetrics; - initialize(fontMetrics.getEmbedFileSource()); + initialize(fontMetrics.getInputStream()); } /** @@ -78,7 +75,7 @@ public class CustomFontMetricsMapper extends Typeface implements FontMetricsMapp * @throws FontFormatException if a bad font is loaded * @throws IOException if an I/O error occurs */ - public CustomFontMetricsMapper(final LazyFont fontMetrics, final Source fontSource) + public CustomFontMetricsMapper(final LazyFont fontMetrics, final InputStream fontSource) throws FontFormatException, IOException { this.typeface = fontMetrics; initialize(fontSource); @@ -88,29 +85,18 @@ public class CustomFontMetricsMapper extends Typeface implements FontMetricsMapp /** * Loads the java.awt.Font - * @param source + * @param inStream * @throws FontFormatException * @throws IOException */ - private void initialize(final Source source) + private void initialize(final InputStream inStream) throws FontFormatException, IOException { int type = Font.TRUETYPE_FONT; if (FontType.TYPE1.equals(typeface.getFontType())) { type = TYPE1_FONT; //Font.TYPE1_FONT; only available in Java 1.5 } - - InputStream is = null; - if (source instanceof StreamSource) { - is = ((StreamSource) source).getInputStream(); - } else if (source.getSystemId() != null) { - is = new java.net.URL(source.getSystemId()).openStream(); - } else { - throw new IllegalArgumentException("No font source provided."); - } - - this.font = Font.createFont(type, is); - is.close(); - + this.font = Font.createFont(type, inStream); + inStream.close(); } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/java2d/Java2DGraphicsState.java b/src/java/org/apache/fop/render/java2d/Java2DGraphicsState.java index b0c003b91..70fe0b449 100644 --- a/src/java/org/apache/fop/render/java2d/Java2DGraphicsState.java +++ b/src/java/org/apache/fop/render/java2d/Java2DGraphicsState.java @@ -130,7 +130,7 @@ public class Java2DGraphicsState { */ public boolean updateFont(String name, int size) { - FontMetricsMapper mapper = (FontMetricsMapper)fontInfo.getMetricsFor(name); + FontMetricsMapper mapper = (FontMetricsMapper) fontInfo.getMetricsFor(name); boolean updateName = (!mapper.getFontName().equals( getGraph().getFont().getFontName())); boolean updateSize = (size != (getGraph().getFont().getSize() * 1000)); diff --git a/src/java/org/apache/fop/render/java2d/Java2DRenderer.java b/src/java/org/apache/fop/render/java2d/Java2DRenderer.java index 8b60df746..91d38675d 100644 --- a/src/java/org/apache/fop/render/java2d/Java2DRenderer.java +++ b/src/java/org/apache/fop/render/java2d/Java2DRenderer.java @@ -58,7 +58,7 @@ 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.FopFactoryConfigurator; +import org.apache.fop.apps.FopFactoryConfig; import org.apache.fop.area.CTM; import org.apache.fop.area.PageViewport; import org.apache.fop.area.Trait; @@ -73,6 +73,7 @@ import org.apache.fop.fo.Constants; 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.fonts.Typeface; import org.apache.fop.render.AbstractPathOrientedRenderer; import org.apache.fop.render.Graphics2DAdapter; @@ -83,6 +84,8 @@ import org.apache.fop.render.pdf.CTMHelper; import org.apache.fop.util.CharUtilities; import org.apache.fop.util.ColorUtil; +import static org.apache.fop.render.java2d.Java2DRendererOption.JAVA2D_TRANSPARENT_PAGE_BACKGROUND; + /** * The <code>Java2DRenderer</code> class provides the abstract technical * foundation for all rendering with the Java2D API. Renderers like @@ -109,9 +112,6 @@ import org.apache.fop.util.ColorUtil; */ public abstract class Java2DRenderer extends AbstractPathOrientedRenderer implements Printable { - /** Rendering Options key for the controlling the transparent page background option. */ - public static final String JAVA2D_TRANSPARENT_PAGE_BACKGROUND = "transparent-page-background"; - /** The scale factor for the image size, values: ]0 ; 1] */ protected double scaleFactor = 1; @@ -157,7 +157,7 @@ public abstract class Java2DRenderer extends AbstractPathOrientedRenderer implem // MH: necessary? the caller has access to FOUserAgent userAgent.setRendererOverride(this); // for document regeneration - String s = (String) userAgent.getRendererOptions().get(JAVA2D_TRANSPARENT_PAGE_BACKGROUND); + String s = (String) userAgent.getRendererOption(JAVA2D_TRANSPARENT_PAGE_BACKGROUND); if (s != null) { this.transparentPageBackground = "true".equalsIgnoreCase(s); } @@ -175,14 +175,15 @@ public abstract class Java2DRenderer extends AbstractPathOrientedRenderer implem this.fontInfo = inFontInfo; final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics(); + FontManager fontManager = userAgent.getFontManager(); + FontCollection[] fontCollections = new FontCollection[] { new Base14FontCollection(java2DFontMetrics), new InstalledFontCollection(java2DFontMetrics), - new ConfiguredFontCollection(getFontResolver(), getFontList(), - userAgent.isComplexScriptFeaturesEnabled()) + new ConfiguredFontCollection(fontManager.getResourceResolver(), getFontList(), + userAgent.isComplexScriptFeaturesEnabled()) }; - userAgent.getFactory().getFontManager().setup( - getFontInfo(), fontCollections); + fontManager.setup(getFontInfo(), fontCollections); } /** {@inheritDoc} */ @@ -317,7 +318,7 @@ public abstract class Java2DRenderer extends AbstractPathOrientedRenderer implem // set scale factor double scaleX = scaleFactor; double scaleY = scaleFactor; - String scale = (String) currentPageViewport.getForeignAttributes().get( + String scale = currentPageViewport.getForeignAttributes().get( PageScale.EXT_PAGE_SCALE); Point2D scales = PageScale.getScale(scale); if (scales != null) { @@ -326,10 +327,10 @@ public abstract class Java2DRenderer extends AbstractPathOrientedRenderer implem } scaleX = scaleX - * (UnitConv.IN2MM / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION) + * (UnitConv.IN2MM / FopFactoryConfig.DEFAULT_TARGET_RESOLUTION) / userAgent.getTargetPixelUnitToMillimeter(); scaleY = scaleY - * (UnitConv.IN2MM / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION) + * (UnitConv.IN2MM / FopFactoryConfig.DEFAULT_TARGET_RESOLUTION) / userAgent.getTargetPixelUnitToMillimeter(); int bitmapWidth = (int) ((pageWidth * scaleX) + 0.5); int bitmapHeight = (int) ((pageHeight * scaleY) + 0.5); @@ -737,7 +738,7 @@ public abstract class Java2DRenderer extends AbstractPathOrientedRenderer implem //super.renderText(text); // rendering text decorations - Typeface tf = (Typeface) fontInfo.getFonts().get(font.getFontName()); + Typeface tf = fontInfo.getFonts().get(font.getFontName()); int fontsize = text.getTraitAsInteger(Trait.FONT_SIZE); renderTextDecoration(tf, fontsize, text, bl, rx); } @@ -918,7 +919,7 @@ public abstract class Java2DRenderer extends AbstractPathOrientedRenderer implem int y = currentBPPosition + (int)Math.round(pos.getY()); uri = URISpecification.getURL(uri); - ImageManager manager = getUserAgent().getFactory().getImageManager(); + ImageManager manager = getUserAgent().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); diff --git a/src/java/org/apache/fop/render/java2d/Java2DRendererConfig.java b/src/java/org/apache/fop/render/java2d/Java2DRendererConfig.java new file mode 100644 index 000000000..1ed0aec96 --- /dev/null +++ b/src/java/org/apache/fop/render/java2d/Java2DRendererConfig.java @@ -0,0 +1,83 @@ +/* + * 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.java2d; + +import java.util.EnumMap; + +import org.apache.avalon.framework.configuration.Configuration; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.fonts.DefaultFontConfig; +import org.apache.fop.fonts.DefaultFontConfig.DefaultFontConfigParser; +import org.apache.fop.render.RendererConfig; + +import static org.apache.fop.render.java2d.Java2DRendererOption.JAVA2D_TRANSPARENT_PAGE_BACKGROUND; + +/** + * The Java2D renderer configuration data object. + */ +public final class Java2DRendererConfig implements RendererConfig { + + private final EnumMap<Java2DRendererOption, Object> params + = new EnumMap<Java2DRendererOption, Object>(Java2DRendererOption.class); + + private final DefaultFontConfig fontConfig; + + private Java2DRendererConfig(DefaultFontConfig fontConfig) { + this.fontConfig = fontConfig; + } + + public DefaultFontConfig getFontInfoConfig() { + return fontConfig; + } + + public Boolean isPageBackgroundTransparent() { + return Boolean.class.cast(params.get(JAVA2D_TRANSPARENT_PAGE_BACKGROUND)); + } + + /** + * The Java2D renderer configuration data parser. + */ + public static class Java2DRendererConfigParser implements RendererConfigParser { + + private final String mimeType; + + public Java2DRendererConfigParser(String mimeType) { + this.mimeType = mimeType; + } + + /** {@inheritDoc} */ + public Java2DRendererConfig build(FOUserAgent userAgent, Configuration cfg) + throws FOPException { + Java2DRendererConfig config = new Java2DRendererConfig(new DefaultFontConfigParser() + .parse(cfg, userAgent.validateStrictly())); + boolean value = cfg.getChild( + JAVA2D_TRANSPARENT_PAGE_BACKGROUND.getName(), true).getValueAsBoolean(false); + config.params.put(JAVA2D_TRANSPARENT_PAGE_BACKGROUND, value); + return config; + } + + /** {@inheritDoc} */ + public String getMimeType() { + return mimeType; + } + } +} diff --git a/src/java/org/apache/fop/render/java2d/Java2DRendererConfigurator.java b/src/java/org/apache/fop/render/java2d/Java2DRendererConfigurator.java index a12cb3898..9ff2ccdbd 100644 --- a/src/java/org/apache/fop/render/java2d/Java2DRendererConfigurator.java +++ b/src/java/org/apache/fop/render/java2d/Java2DRendererConfigurator.java @@ -19,24 +19,23 @@ package org.apache.fop.render.java2d; -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.render.DefaultRendererConfigurator; import org.apache.fop.render.Renderer; +import org.apache.fop.render.RendererConfig.RendererConfigParser; /** * Configurerer for Java 2D renderer */ -public class Java2DRendererConfigurator extends PrintRendererConfigurator { +public class Java2DRendererConfigurator extends DefaultRendererConfigurator { /** * Default constructor * @param userAgent user agent */ - public Java2DRendererConfigurator(FOUserAgent userAgent) { - super(userAgent); + public Java2DRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + super(userAgent, rendererConfigParser); } /** @@ -45,15 +44,14 @@ public class Java2DRendererConfigurator extends PrintRendererConfigurator { * @throws FOPException fop exception */ public void configure(Renderer renderer) throws FOPException { - Configuration cfg = super.getRendererConfig(renderer); - if (cfg != null) { - Java2DRenderer java2dRenderer = (Java2DRenderer)renderer; - String value = cfg.getChild( - Java2DRenderer.JAVA2D_TRANSPARENT_PAGE_BACKGROUND, true).getValue(null); - if (value != null) { - java2dRenderer.setTransparentPageBackground("true".equalsIgnoreCase(value)); + Java2DRendererConfig config = (Java2DRendererConfig) getRendererConfig(renderer); + if (config != null) { + Java2DRenderer java2dRenderer = (Java2DRenderer) renderer; + // new Java2DRendererConfigParser(renderer.getMimeType())); + if (config.isPageBackgroundTransparent() != null) { + java2dRenderer.setTransparentPageBackground(config.isPageBackgroundTransparent()); } + super.configure(renderer); } - super.configure(renderer); } } diff --git a/src/java/org/apache/fop/render/ps/PSConfigurationConstants.java b/src/java/org/apache/fop/render/java2d/Java2DRendererOption.java index 6b3550f57..b25f05889 100644 --- a/src/java/org/apache/fop/render/ps/PSConfigurationConstants.java +++ b/src/java/org/apache/fop/render/java2d/Java2DRendererOption.java @@ -17,17 +17,21 @@ /* $Id$ */ -package org.apache.fop.render.ps; +package org.apache.fop.render.java2d; -/** - * Constants used for configuring PostScript output. - */ -public interface PSConfigurationConstants { +import org.apache.fop.render.RendererConfigOption; + +public enum Java2DRendererOption implements RendererConfigOption { + /** Rendering Options key for the controlling the transparent page background option. */ + JAVA2D_TRANSPARENT_PAGE_BACKGROUND("transparent-page-background"); + + private final String name; + + private Java2DRendererOption(String name) { + this.name = name; + } - /** Controls the behaviour for landscape pages */ - String AUTO_ROTATE_LANDSCAPE = "auto-rotate-landscape"; - /** Controls whether resources are optimized (rather than inlined) */ - String OPTIMIZE_RESOURCES = "optimize-resources"; - /** Determines the PostScript language level to be generated */ - String LANGUAGE_LEVEL = "language-level"; + public String getName() { + return name; + } } diff --git a/src/java/org/apache/fop/render/java2d/Java2DRenderingSettings.java b/src/java/org/apache/fop/render/java2d/Java2DRenderingSettings.java index f7bad64a7..06ea8a3cf 100644 --- a/src/java/org/apache/fop/render/java2d/Java2DRenderingSettings.java +++ b/src/java/org/apache/fop/render/java2d/Java2DRenderingSettings.java @@ -53,6 +53,4 @@ public class Java2DRenderingSettings { public boolean hasTransparentPageBackground() { return this.pageBackgroundColor == null; } - - } diff --git a/src/java/org/apache/fop/render/java2d/Java2DUtil.java b/src/java/org/apache/fop/render/java2d/Java2DUtil.java index 924460bd8..c17ad2994 100644 --- a/src/java/org/apache/fop/render/java2d/Java2DUtil.java +++ b/src/java/org/apache/fop/render/java2d/Java2DUtil.java @@ -44,7 +44,7 @@ public final class Java2DUtil { FontInfo fontInfo, FOUserAgent userAgent) { Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics(); - FontManager fontManager = userAgent.getFactory().getFontManager(); + FontManager fontManager = userAgent.getFontManager(); FontCollection[] fontCollections = new FontCollection[] { new org.apache.fop.render.java2d.Base14FontCollection(java2DFontMetrics), new InstalledFontCollection(java2DFontMetrics) diff --git a/src/java/org/apache/fop/render/DefaultFontResolver.java b/src/java/org/apache/fop/render/pcl/Java2DRendererOption.java index 0642537c4..cb23f7191 100644 --- a/src/java/org/apache/fop/render/DefaultFontResolver.java +++ b/src/java/org/apache/fop/render/pcl/Java2DRendererOption.java @@ -15,38 +15,35 @@ * limitations under the License. */ -/* $Id$ */ +package org.apache.fop.render.pcl; -package org.apache.fop.render; - -import javax.xml.transform.Source; - -import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.fonts.FontResolver; +import org.apache.fop.render.RendererConfigOption; /** - * Default FontResolver implementation which uses the FOUserAgent to resolve font URIs. + * An enumeration of the renderer configuration options available to the Java2D renderer via the + * FOP conf. */ -public class DefaultFontResolver implements FontResolver { +public enum Java2DRendererOption implements RendererConfigOption { - private FOUserAgent userAgent; + RENDERING_MODE("rendering", PCLRenderingMode.class), + TEXT_RENDERING("text-rendering", Boolean.class), + DISABLE_PJL("disable-pjl", Boolean.class); - /** - * Main constructor. - * @param userAgent the user agent - */ - public DefaultFontResolver(FOUserAgent userAgent) { - this.userAgent = userAgent; - } + private final String name; - /** {@inheritDoc} */ - public Source resolve(String href) { - return userAgent.resolveURI(href, userAgent.getFactory().getFontManager().getFontBaseURL()); + private final Class<?> type; + + private Java2DRendererOption(String name, Class<?> type) { + this.name = name; + this.type = type; } /** {@inheritDoc} */ - public boolean isComplexScriptFeaturesEnabled() { - return userAgent.isComplexScriptFeaturesEnabled(); + public String getName() { + return name; } + Class<?> getType() { + return type; + } } diff --git a/src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java b/src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java index 332b4a77d..d2e06d76f 100644 --- a/src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java +++ b/src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java @@ -32,18 +32,21 @@ import org.apache.commons.logging.LogFactory; import org.apache.xmlgraphics.util.UnitConv; -import org.apache.fop.apps.FopFactoryConfigurator; +import org.apache.fop.apps.FopFactoryConfig; import org.apache.fop.apps.MimeConstants; import org.apache.fop.fonts.FontInfo; import org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler; import org.apache.fop.render.intermediate.IFContext; +import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; import org.apache.fop.render.intermediate.IFException; import org.apache.fop.render.intermediate.IFPainter; import org.apache.fop.render.java2d.Java2DPainter; import org.apache.fop.render.java2d.Java2DUtil; +import org.apache.fop.render.pcl.PCLRendererConfig.PCLRendererConfigParser; import org.apache.fop.render.pcl.extensions.PCLElementMapping; + /** * {@link org.apache.fop.render.intermediate.IFDocumentHandler} implementation * that produces PCL 5. @@ -74,7 +77,9 @@ public class PCLDocumentHandler extends AbstractBinaryWritingIFDocumentHandler /** * Default constructor. */ - public PCLDocumentHandler() { + public PCLDocumentHandler(IFContext context) { + super(context); + this.pclUtil = new PCLRenderingUtil(context.getUserAgent()); } /** {@inheritDoc} */ @@ -88,15 +93,8 @@ public class PCLDocumentHandler extends AbstractBinaryWritingIFDocumentHandler } /** {@inheritDoc} */ - @Override - public void setContext(IFContext context) { - super.setContext(context); - this.pclUtil = new PCLRenderingUtil(context.getUserAgent()); - } - - /** {@inheritDoc} */ public IFDocumentHandlerConfigurator getConfigurator() { - return new PCLRendererConfigurator(getUserAgent()); + return new PCLRendererConfigurator(getUserAgent(), new PCLRendererConfigParser()); } /** {@inheritDoc} */ @@ -227,7 +225,7 @@ public class PCLDocumentHandler extends AbstractBinaryWritingIFDocumentHandler private IFPainter createAllBitmapPainter() { double scale = gen.getMaximumBitmapResolution() - / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION; + / FopFactoryConfig.DEFAULT_TARGET_RESOLUTION; Rectangle printArea = this.currentPageDefinition.getLogicalPageRect(); int bitmapWidth = (int)Math.ceil( UnitConv.mpt2px(printArea.width, gen.getMaximumBitmapResolution())); @@ -276,7 +274,6 @@ public class PCLDocumentHandler extends AbstractBinaryWritingIFDocumentHandler public void endPageContent() throws IFException { if (this.currentImage != null) { try { - //ImageWriterUtil.saveAsPNG(this.currentImage, new java.io.File("D:/page.png")); Rectangle printArea = this.currentPageDefinition.getLogicalPageRect(); gen.setCursorPos(0, 0); gen.paintBitmap(this.currentImage, printArea.getSize(), true); diff --git a/src/java/org/apache/fop/render/pcl/PCLDocumentHandlerMaker.java b/src/java/org/apache/fop/render/pcl/PCLDocumentHandlerMaker.java index 85653e423..affe2abae 100644 --- a/src/java/org/apache/fop/render/pcl/PCLDocumentHandlerMaker.java +++ b/src/java/org/apache/fop/render/pcl/PCLDocumentHandlerMaker.java @@ -19,7 +19,6 @@ package org.apache.fop.render.pcl; -import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.MimeConstants; import org.apache.fop.render.intermediate.AbstractIFDocumentHandlerMaker; import org.apache.fop.render.intermediate.IFContext; @@ -36,10 +35,8 @@ public class PCLDocumentHandlerMaker extends AbstractIFDocumentHandlerMaker { }; /** {@inheritDoc} */ - public IFDocumentHandler makeIFDocumentHandler(FOUserAgent ua) { - PCLDocumentHandler handler = new PCLDocumentHandler(); - handler.setContext(new IFContext(ua)); - return handler; + public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) { + return new PCLDocumentHandler(ifContext); } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/pcl/PCLGenerator.java b/src/java/org/apache/fop/render/pcl/PCLGenerator.java index 29fe77323..0db295a5a 100644 --- a/src/java/org/apache/fop/render/pcl/PCLGenerator.java +++ b/src/java/org/apache/fop/render/pcl/PCLGenerator.java @@ -677,13 +677,6 @@ public class PCLGenerator { } finally { g2d.dispose(); } - /* - try { - BatchDiffer.saveAsPNG(alpha, new java.io.File("D:/out-alpha.png")); - BatchDiffer.saveAsPNG(mask, new java.io.File("D:/out-mask.png")); - } catch (IOException e) { - e.printStackTrace(); - }*/ return mask; } else { return null; @@ -715,7 +708,6 @@ public class PCLGenerator { (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) { diff --git a/src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java b/src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java index 25249caf6..014bc47a1 100644 --- a/src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java +++ b/src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java @@ -127,7 +127,7 @@ public class PCLImageHandlerGraphics2D implements ImageHandler { if (!painted) { //Fallback solution: Paint to a BufferedImage FOUserAgent ua = context.getUserAgent(); - ImageManager imageManager = ua.getFactory().getImageManager(); + ImageManager imageManager = ua.getImageManager(); ImageRendered imgRend; try { imgRend = (ImageRendered)imageManager.convertImage( diff --git a/src/java/org/apache/fop/render/pcl/PCLPainter.java b/src/java/org/apache/fop/render/pcl/PCLPainter.java index f0d87d542..614ebf1d2 100644 --- a/src/java/org/apache/fop/render/pcl/PCLPainter.java +++ b/src/java/org/apache/fop/render/pcl/PCLPainter.java @@ -431,8 +431,12 @@ public class PCLPainter extends AbstractIFPainter<PCLDocumentHandler> implements final Font font = getFontInfo().getFontInstance(triplet, state.getFontSize()); //for cursive fonts, so the text isn't clipped - final FontMetricsMapper mapper = (FontMetricsMapper) getFontInfo().getMetricsFor( - font.getFontName()); + FontMetricsMapper mapper; + try { + mapper = (FontMetricsMapper) getFontInfo().getMetricsFor(font.getFontName()); + } catch (Exception t) { + throw new RuntimeException(t); + } final int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000; final int ascent = mapper.getAscender(font.getFontSize()) / 1000; final int descent = mapper.getDescender(font.getFontSize()) / 1000; diff --git a/src/java/org/apache/fop/render/pcl/PCLRendererConfig.java b/src/java/org/apache/fop/render/pcl/PCLRendererConfig.java new file mode 100644 index 000000000..29fccc2c8 --- /dev/null +++ b/src/java/org/apache/fop/render/pcl/PCLRendererConfig.java @@ -0,0 +1,123 @@ +/* + * 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.util.EnumMap; +import java.util.Map; + +import org.apache.avalon.framework.configuration.Configuration; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.apps.MimeConstants; +import org.apache.fop.fonts.DefaultFontConfig; +import org.apache.fop.fonts.DefaultFontConfig.DefaultFontConfigParser; +import org.apache.fop.render.RendererConfig; + +import static org.apache.fop.render.pcl.Java2DRendererOption.DISABLE_PJL; +import static org.apache.fop.render.pcl.Java2DRendererOption.RENDERING_MODE; +import static org.apache.fop.render.pcl.Java2DRendererOption.TEXT_RENDERING; + +/** + * The PCL renderer configuration data object. + */ +public final class PCLRendererConfig implements RendererConfig { + + private final Map<Java2DRendererOption, Object> params + = new EnumMap<Java2DRendererOption, Object>(Java2DRendererOption.class); + + private final DefaultFontConfig fontConfig; + + private PCLRendererConfig(DefaultFontConfig fontConfig) { + this.fontConfig = fontConfig; + } + + public DefaultFontConfig getFontInfoConfig() { + return fontConfig; + } + + public PCLRenderingMode getRenderingMode() { + return getParam(RENDERING_MODE, PCLRenderingMode.class); + } + + public Boolean isTextRendering() { + return getParam(TEXT_RENDERING, Boolean.class); + } + + public Boolean isDisablePjl() { + return getParam(DISABLE_PJL, Boolean.class); + } + + private <T> T getParam(Java2DRendererOption option, Class<T> type) { + assert option.getType().equals(type); + return type.cast(params.get(option)); + } + + private <T> void setParam(Java2DRendererOption option, T value) { + assert option.getType().isInstance(value); + params.put(option, value); + } + + /** + * The PCL renderer configuration data parser. + */ + public static final class PCLRendererConfigParser implements RendererConfigParser { + + /** {@inheritDoc} */ + public PCLRendererConfig build(FOUserAgent userAgent, Configuration cfg) throws FOPException { + PCLRendererConfig config = new PCLRendererConfig(new DefaultFontConfigParser() + .parse(cfg, userAgent.validateStrictly())); + configure(cfg, config); + return config; + } + + private void configure(Configuration cfg, PCLRendererConfig config) throws FOPException { + if (cfg != null) { + String rendering = cfg.getChild(RENDERING_MODE.getName()).getValue(null); + if (rendering != null) { + try { + config.setParam(RENDERING_MODE, PCLRenderingMode.getValueOf(rendering)); + } catch (IllegalArgumentException e) { + throw new FOPException("Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + + " Value found: " + rendering); + } + } + String textRendering = cfg.getChild(TEXT_RENDERING.getName()).getValue(null); + if ("bitmap".equalsIgnoreCase(textRendering)) { + config.setParam(TEXT_RENDERING, true); + } else if (textRendering == null || "auto".equalsIgnoreCase(textRendering)) { + config.setParam(TEXT_RENDERING, false); + } else { + throw new FOPException( + "Valid values for 'text-rendering' are 'auto' and 'bitmap'. Value found: " + + textRendering); + } + config.setParam(DISABLE_PJL, + cfg.getChild(DISABLE_PJL.getName()).getValueAsBoolean(false)); + } + } + + /** {@inheritDoc} */ + public String getMimeType() { + return MimeConstants.MIME_PCL; + } + } + +} diff --git a/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java b/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java index bc4cdc567..d103b4796 100644 --- a/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java +++ b/src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java @@ -21,19 +21,13 @@ package org.apache.fop.render.pcl; 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.apps.io.InternalResourceResolver; +import org.apache.fop.fonts.EmbedFontInfo; 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.RendererConfig.RendererConfigParser; import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; import org.apache.fop.render.java2d.Base14FontCollection; @@ -45,88 +39,52 @@ import org.apache.fop.render.java2d.Java2DFontMetrics; * PCL Renderer configurator */ public class PCLRendererConfigurator extends PrintRendererConfigurator - implements IFDocumentHandlerConfigurator { + implements IFDocumentHandlerConfigurator { /** * Default constructor * @param userAgent user agent */ - public PCLRendererConfigurator(FOUserAgent userAgent) { - super(userAgent); - } - - /** - * Throws an UnsupportedOperationException. - * - * @param renderer not used - */ - public void configure(Renderer renderer) { - throw new UnsupportedOperationException(); - } - - 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 'rendering' are 'quality', 'speed' and 'bitmap'." - + " Value found: " + rendering); - } - } - - 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)); + public PCLRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + super(userAgent, rendererConfigParser); } - // ---=== IFDocumentHandler configuration ===--- - /** {@inheritDoc} */ public void configure(IFDocumentHandler documentHandler) throws FOPException { - Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); - if (cfg != null) { - PCLDocumentHandler pclDocumentHandler = (PCLDocumentHandler)documentHandler; + PCLRendererConfig pdfConfig = (PCLRendererConfig) getRendererConfig(documentHandler); + if (pdfConfig != null) { + PCLDocumentHandler pclDocumentHandler = (PCLDocumentHandler) documentHandler; PCLRenderingUtil pclUtil = pclDocumentHandler.getPCLUtil(); - configure(cfg, pclUtil); + configure(pdfConfig, pclUtil); } } - /** {@inheritDoc} */ - public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) - throws FOPException { - FontManager fontManager = userAgent.getFactory().getFontManager(); + private void configure(PCLRendererConfig config, PCLRenderingUtil pclUtil) throws FOPException { + if (config.getRenderingMode() != null) { + pclUtil.setRenderingMode(config.getRenderingMode()); + } + if (config.isDisablePjl() != null) { + pclUtil.setPJLDisabled(config.isDisablePjl()); + } + if (config.isTextRendering() != null) { + pclUtil.setAllTextAsBitmaps(config.isTextRendering()); + } + } + @Override + protected List<FontCollection> getDefaultFontCollection() { + final List<FontCollection> fontCollections = new java.util.ArrayList<FontCollection>(); final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics(); - final List fontCollections = new java.util.ArrayList(); fontCollections.add(new Base14FontCollection(java2DFontMetrics)); fontCollections.add(new InstalledFontCollection(java2DFontMetrics)); - - 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, - userAgent.isComplexScriptFeaturesEnabled())); - } - - fontManager.setup(fontInfo, - (FontCollection[])fontCollections.toArray( - new FontCollection[fontCollections.size()])); - documentHandler.setFontInfo(fontInfo); + return fontCollections; } + @Override + protected FontCollection createCollectionFromFontList(InternalResourceResolver resourceResolver, + List<EmbedFontInfo> fontList) { + return new ConfiguredFontCollection(resourceResolver, fontList, + userAgent.isComplexScriptFeaturesEnabled()); + } } diff --git a/src/java/org/apache/fop/render/pcl/PCLRenderingMode.java b/src/java/org/apache/fop/render/pcl/PCLRenderingMode.java index 6201197cf..9b8213948 100644 --- a/src/java/org/apache/fop/render/pcl/PCLRenderingMode.java +++ b/src/java/org/apache/fop/render/pcl/PCLRenderingMode.java @@ -25,20 +25,18 @@ import java.io.Serializable; /** * Enumeration class for PCL rendering modes. */ -public final class PCLRenderingMode implements Serializable { - - private static final long serialVersionUID = 6359884255324755026L; - +public enum PCLRenderingMode implements Serializable { /** "Quality" rendering (mixed native and bitmap for improved quality) */ - public static final PCLRenderingMode QUALITY = new PCLRenderingMode("quality", 1.0f); + QUALITY("quality", 1.0f), /** "Speed" rendering (maximum speed with native rendering, reduced visual quality) */ - public static final PCLRenderingMode SPEED = new PCLRenderingMode("speed", 0.25f); + SPEED("speed", 0.25f), /** * "Bitmap" rendering (pages are painted entirely as bitmaps, maximum quality, * reduced performance) */ - public static final PCLRenderingMode BITMAP = new PCLRenderingMode("bitmap", 1.0f); + BITMAP("bitmap", 1.0f); + private static final long serialVersionUID = 6359884255324755026L; private String name; private float defaultDitheringQuality; @@ -70,20 +68,17 @@ public final class PCLRenderingMode implements Serializable { * @param name the name of the enumeration value * @return the enumeration object */ - public static PCLRenderingMode valueOf(String name) { - if (QUALITY.getName().equalsIgnoreCase(name)) { - return QUALITY; - } else if (SPEED.getName().equalsIgnoreCase(name)) { - return SPEED; - } else if (BITMAP.getName().equalsIgnoreCase(name)) { - return BITMAP; - } else { - throw new IllegalArgumentException("Illegal value for enumeration: " + name); + public static PCLRenderingMode getValueOf(String name) { + for (PCLRenderingMode mode : PCLRenderingMode.values()) { + if (mode.getName().equalsIgnoreCase(name)) { + return mode; + } } + throw new IllegalArgumentException("Illegal value for enumeration: " + name); } private Object readResolve() throws ObjectStreamException { - return valueOf(getName()); + return getValueOf(getName()); } /** {@inheritDoc} */ diff --git a/src/java/org/apache/fop/render/pdf/PDFConfigurationConstants.java b/src/java/org/apache/fop/render/pdf/PDFConfigurationConstants.java deleted file mode 100644 index 4a8a03b27..000000000 --- a/src/java/org/apache/fop/render/pdf/PDFConfigurationConstants.java +++ /dev/null @@ -1,84 +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; - -/** - * Constants used for configuring PDF output. - */ -public interface PDFConfigurationConstants { - - /** PDF encryption parameter: all parameters as object, datatype: PDFEncryptionParams */ - String ENCRYPTION_PARAMS = "encryption-params"; - /** PDF encryption parameter: user password, datatype: String */ - String USER_PASSWORD = "user-password"; - /** PDF encryption parameter: owner password, datatype: String */ - String OWNER_PASSWORD = "owner-password"; - /** PDF encryption parameter: Forbids printing, datatype: Boolean or "true"/"false" */ - String NO_PRINT = "noprint"; - /** PDF encryption parameter: Forbids copying content, datatype: Boolean or "true"/"false" */ - String NO_COPY_CONTENT = "nocopy"; - /** PDF encryption parameter: Forbids editing content, datatype: Boolean or "true"/"false" */ - String NO_EDIT_CONTENT = "noedit"; - /** PDF encryption parameter: Forbids annotations, datatype: Boolean or "true"/"false" */ - String NO_ANNOTATIONS = "noannotations"; - - /** - * PDF encryption parameter: Forbids filling in existing interactive forms, datatype: - * Boolean or "true"/"false" - */ - String NO_FILLINFORMS = "nofillinforms"; - - /** - * PDF encryption parameter: Forbids extracting text and graphics, datatype: Boolean - * or "true"/"false" - */ - String NO_ACCESSCONTENT = "noaccesscontent"; - - /** - * PDF encryption parameter: Forbids assembling document, datatype: Boolean or - * "true"/"false" - */ - String NO_ASSEMBLEDOC = "noassembledoc"; - - /** - * PDF encryption parameter: Forbids printing to high quality, datatype: Boolean or - * "true"/"false" - */ - String NO_PRINTHQ = "noprinthq"; - - /** - * PDF encryption length parameter: must be a multiple of 8 between 40 and 128, - * default value 40, datatype: int. - */ - String ENCRYPTION_LENGTH = "encryption-length"; - /** Rendering Options key for the PDF/A mode. */ - String PDF_A_MODE = "pdf-a-mode"; - /** Rendering Options key for the PDF/X mode. */ - String PDF_X_MODE = "pdf-x-mode"; - /** Rendering Options key for the ICC profile for the output intent. */ - String KEY_OUTPUT_PROFILE = "output-profile"; - /** PDF version entry: specify the version of the PDF document created, datatype: String */ - String PDF_VERSION = "version"; - /** - * Rendering Options key for disabling the sRGB color space (only possible if no PDF/A or - * PDF/X profile is active). - */ - String KEY_DISABLE_SRGB_COLORSPACE = "disable-srgb-colorspace"; -} diff --git a/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java b/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java index c56bce218..dd9320571 100644 --- a/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java +++ b/src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java @@ -49,6 +49,7 @@ import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; import org.apache.fop.render.intermediate.IFDocumentNavigationHandler; import org.apache.fop.render.intermediate.IFException; import org.apache.fop.render.intermediate.IFPainter; +import org.apache.fop.render.pdf.PDFRendererConfig.PDFRendererConfigParser; import org.apache.fop.render.pdf.extensions.PDFEmbeddedFileExtensionAttachment; /** @@ -72,7 +73,7 @@ public class PDFDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { * Utility class which enables all sorts of features that are not directly connected to the * normal rendering process. */ - private PDFRenderingUtil pdfUtil; + private final PDFRenderingUtil pdfUtil; /** the /Resources object of the PDF document being created */ private PDFResources pdfResources; @@ -95,7 +96,9 @@ public class PDFDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { /** * Default constructor. */ - public PDFDocumentHandler() { + public PDFDocumentHandler(IFContext context) { + super(context); + this.pdfUtil = new PDFRenderingUtil(context.getUserAgent()); } /** {@inheritDoc} */ @@ -109,14 +112,8 @@ public class PDFDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { } /** {@inheritDoc} */ - public void setContext(IFContext context) { - super.setContext(context); - this.pdfUtil = new PDFRenderingUtil(context.getUserAgent()); - } - - /** {@inheritDoc} */ public IFDocumentHandlerConfigurator getConfigurator() { - return new PDFRendererConfigurator(getUserAgent()); + return new PDFRendererConfigurator(getUserAgent(), new PDFRendererConfigParser()); } /** {@inheritDoc} */ @@ -124,8 +121,8 @@ public class PDFDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { return this.documentNavigationHandler; } - PDFRenderingUtil getPDFUtil() { - return this.pdfUtil; + void mergeRendererOptionsConfig(PDFRendererOptionsConfig config) { + pdfUtil.mergeRendererOptionsConfig(config); } PDFLogicalStructureHandler getLogicalStructureHandler() { diff --git a/src/java/org/apache/fop/render/pdf/PDFDocumentHandlerMaker.java b/src/java/org/apache/fop/render/pdf/PDFDocumentHandlerMaker.java index 1186db3ae..ceab6f54a 100644 --- a/src/java/org/apache/fop/render/pdf/PDFDocumentHandlerMaker.java +++ b/src/java/org/apache/fop/render/pdf/PDFDocumentHandlerMaker.java @@ -32,10 +32,10 @@ public class PDFDocumentHandlerMaker extends AbstractIFDocumentHandlerMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_PDF}; - /** {@inheritDoc} */ - public IFDocumentHandler makeIFDocumentHandler(FOUserAgent ua) { - PDFDocumentHandler handler = new PDFDocumentHandler(); - handler.setContext(new IFContext(ua)); + @Override + public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) { + PDFDocumentHandler handler = new PDFDocumentHandler(ifContext); + FOUserAgent ua = ifContext.getUserAgent(); if (ua.isAccessibilityEnabled()) { ua.setStructureTreeEventHandler(handler.getStructureTreeEventHandler()); } diff --git a/src/java/org/apache/fop/render/pdf/PDFEncryptionOption.java b/src/java/org/apache/fop/render/pdf/PDFEncryptionOption.java new file mode 100644 index 000000000..3d94e236b --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/PDFEncryptionOption.java @@ -0,0 +1,100 @@ +/* + * 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.pdf.PDFAMode; +import org.apache.fop.pdf.PDFXMode; +import org.apache.fop.render.RendererConfigOption; + +public enum PDFEncryptionOption implements RendererConfigOption { + + /** + * PDF encryption length parameter: must be a multiple of 8 between 40 and 128, + * default value 40, datatype: int, default: 40 + */ + ENCRYPTION_LENGTH("encryption-length", 40), + /** + * PDF encryption parameter: Forbids printing to high quality, datatype: Boolean or + * "true"/"false", default: false + */ + NO_PRINTHQ("noprinthq", 40), + /** + * PDF encryption parameter: Forbids assembling document, datatype: Boolean or + * "true"/"false", default: false + */ + NO_ASSEMBLEDOC("noassembledoc", false), + /** + * PDF encryption parameter: Forbids extracting text and graphics, datatype: Boolean + * or "true"/"false", default: false + */ + NO_ACCESSCONTENT("noaccesscontent", false), + /** + * PDF encryption parameter: Forbids filling in existing interactive forms, datatype: + * Boolean or "true"/"false", default: false + */ + NO_FILLINFORMS("nofillinforms", false), + /** + * PDF encryption parameter: Forbids annotations, datatype: Boolean or "true"/"false", + * default: false + */ + NO_ANNOTATIONS("noannotations", false), + /** + * PDF encryption parameter: Forbids printing, datatype: Boolean or "true"/"false", + * default: false + */ + NO_PRINT("noprint", false), + /** + * PDF encryption parameter: Forbids copying content, datatype: Boolean or "true"/"false", + * default: false + */ + NO_COPY_CONTENT("nocopy", false), + /** + * PDF encryption parameter: Forbids editing content, datatype: Boolean or "true"/"false", + * default: false + */ + NO_EDIT_CONTENT("noedit", false), + /** PDF encryption parameter: user password, datatype: String, default: "" */ + USER_PASSWORD("user-password", ""), + /** PDF encryption parameter: owner password, datatype: String, default: "" */ + OWNER_PASSWORD("owner-password", ""); + + public static final String ENCRYPTION_PARAMS = "encryption-params"; + + private final String name; + + private final Object defaultValue; + + private PDFEncryptionOption(String name, Object defaultValue) { + this.name = name; + this.defaultValue = defaultValue; + } + + private PDFEncryptionOption(String name) { + this(name, null); + } + + public String getName() { + return name; + } + + public Object getDefaultValue() { + return defaultValue; + } +} diff --git a/src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java b/src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java index bc3b66ece..8eaac923c 100644 --- a/src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java +++ b/src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java @@ -86,7 +86,7 @@ public class PDFImageHandlerSVG implements ImageHandler { BridgeContext ctx = new PDFBridgeContext(ua, (strokeText ? null : pdfContext.getFontInfo()), - userAgent.getFactory().getImageManager(), + userAgent.getImageManager(), userAgent.getImageSessionContext(), new AffineTransform()); diff --git a/src/java/org/apache/fop/render/pdf/PDFRendererConfig.java b/src/java/org/apache/fop/render/pdf/PDFRendererConfig.java new file mode 100644 index 000000000..049345609 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/PDFRendererConfig.java @@ -0,0 +1,227 @@ +/* + * 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.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.avalon.framework.configuration.Configuration; +import org.apache.avalon.framework.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.apps.MimeConstants; +import org.apache.fop.fonts.DefaultFontConfig; +import org.apache.fop.fonts.DefaultFontConfig.DefaultFontConfigParser; +import org.apache.fop.pdf.PDFEncryptionParams; +import org.apache.fop.pdf.PDFFilterList; +import org.apache.fop.render.RendererConfig; +import org.apache.fop.render.RendererConfigOption; +import org.apache.fop.util.LogUtil; + +import static org.apache.fop.render.pdf.PDFEncryptionOption.ENCRYPTION_LENGTH; +import static org.apache.fop.render.pdf.PDFEncryptionOption.ENCRYPTION_PARAMS; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_ACCESSCONTENT; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_ANNOTATIONS; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_ASSEMBLEDOC; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_COPY_CONTENT; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_EDIT_CONTENT; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_FILLINFORMS; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_PRINT; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_PRINTHQ; +import static org.apache.fop.render.pdf.PDFEncryptionOption.OWNER_PASSWORD; +import static org.apache.fop.render.pdf.PDFEncryptionOption.USER_PASSWORD; +import static org.apache.fop.render.pdf.PDFRendererOption.DISABLE_SRGB_COLORSPACE; +import static org.apache.fop.render.pdf.PDFRendererOption.FILTER_LIST; +import static org.apache.fop.render.pdf.PDFRendererOption.OUTPUT_PROFILE; +import static org.apache.fop.render.pdf.PDFRendererOption.PDF_A_MODE; +import static org.apache.fop.render.pdf.PDFRendererOption.PDF_X_MODE; +import static org.apache.fop.render.pdf.PDFRendererOption.VERSION; + +/** + * The PDF renderer configuration data object. + */ +public final class PDFRendererConfig implements RendererConfig { + + private static final Log LOG = LogFactory.getLog(PDFRendererConfig.class); + + private final PDFRendererOptionsConfig configOption; + + private final DefaultFontConfig fontConfig; + + private PDFRendererConfig(DefaultFontConfig fontConfig, PDFRendererOptionsConfig config) { + this.fontConfig = fontConfig; + this.configOption = config; + } + + public PDFRendererOptionsConfig getConfigOptions() { + return configOption; + } + + public DefaultFontConfig getFontInfoConfig() { + return fontConfig; + } + + /** + * The PDF renderer configuration data parser. + */ + public static final class PDFRendererConfigParser implements RendererConfigParser { + + public PDFRendererConfig build(FOUserAgent userAgent, Configuration cfg) throws FOPException { + boolean strict = userAgent != null ? userAgent.validateUserConfigStrictly() : false; + return new ParserHelper(cfg, userAgent, strict).pdfConfig; + } + + public String getMimeType() { + return MimeConstants.MIME_PDF; + } + } + + private static final class ParserHelper { + + private final Map<PDFRendererOption, Object> configOptions + = new EnumMap<PDFRendererOption, Object>(PDFRendererOption.class); + + private PDFEncryptionParams encryptionConfig; + + private PDFRendererConfig pdfConfig; + + private ParserHelper(Configuration cfg, FOUserAgent userAgent, boolean strict) throws FOPException { + if (cfg != null) { + configure(cfg, userAgent, strict); + } + pdfConfig = new PDFRendererConfig(new DefaultFontConfigParser().parse(cfg, strict), + new PDFRendererOptionsConfig(configOptions, encryptionConfig)); + } + + private void parseAndPut(PDFRendererOption option, Configuration cfg) { + put(option, option.parse(parseConfig(cfg, option))); + } + + private void put(PDFRendererOption option, Object value) { + if (value != null && !value.equals(option.getDefaultValue())) { + configOptions.put(option, value); + } + } + + private void configure(Configuration cfg, FOUserAgent userAgent, boolean strict) throws FOPException { + try { + buildFilterMapFromConfiguration(cfg); + parseAndPut(PDF_A_MODE, cfg); + parseAndPut(PDF_X_MODE, cfg); + configureEncryptionParams(cfg, userAgent, strict); + parseAndPut(OUTPUT_PROFILE, cfg); + parseAndPut(DISABLE_SRGB_COLORSPACE, cfg); + + parseAndPut(VERSION, cfg); + } catch (ConfigurationException e) { + LogUtil.handleException(LOG, e, strict); + } + } + + private void configureEncryptionParams(Configuration cfg, FOUserAgent userAgent, boolean strict) { + Configuration encryptCfg = cfg.getChild(ENCRYPTION_PARAMS, false); + if (encryptCfg != null) { + encryptionConfig = new PDFEncryptionParams(); + encryptionConfig.setOwnerPassword(parseConfig(encryptCfg, OWNER_PASSWORD)); + encryptionConfig.setUserPassword(parseConfig(encryptCfg, USER_PASSWORD)); + encryptionConfig.setAllowPrint(!doesValueExist(encryptCfg, NO_PRINT)); + encryptionConfig.setAllowCopyContent(!doesValueExist(encryptCfg, NO_COPY_CONTENT)); + encryptionConfig.setAllowEditContent(!doesValueExist(encryptCfg, NO_EDIT_CONTENT)); + encryptionConfig.setAllowEditAnnotations(!doesValueExist(encryptCfg, NO_ANNOTATIONS)); + encryptionConfig.setAllowFillInForms(!doesValueExist(encryptCfg, NO_FILLINFORMS)); + encryptionConfig.setAllowAccessContent(!doesValueExist(encryptCfg, NO_ACCESSCONTENT)); + encryptionConfig.setAllowAssembleDocument(!doesValueExist(encryptCfg, NO_ASSEMBLEDOC)); + encryptionConfig.setAllowPrintHq(!doesValueExist(encryptCfg, NO_PRINTHQ)); + String encryptionLength = parseConfig(encryptCfg, ENCRYPTION_LENGTH); + if (encryptionLength != null) { + int validatedLength = checkEncryptionLength(Integer.parseInt(encryptionLength), userAgent); + encryptionConfig.setEncryptionLengthInBits(validatedLength); + } + } + } + + private void buildFilterMapFromConfiguration(Configuration cfg) throws ConfigurationException, + FOPException { + Configuration[] filterLists = cfg.getChildren(FILTER_LIST.getName()); + Map<String, List<String>> filterMap = new HashMap<String, List<String>>(); + for (Configuration filters : filterLists) { + String type = filters.getAttribute("type", PDFFilterList.DEFAULT_FILTER); + List<String> filterList = new ArrayList<String>(); + for (Configuration nameCfg : filters.getChildren("value")) { + filterList.add(nameCfg.getValue()); + } + if (!filterList.isEmpty() && LOG.isDebugEnabled()) { + StringBuffer debug = new StringBuffer("Adding PDF filter"); + if (filterList.size() != 1) { + debug.append("s"); + } + debug.append(" for type ").append(type).append(": "); + for (int j = 0; j < filterList.size(); j++) { + if (j != 0) { + debug.append(", "); + } + debug.append(filterList.get(j)); + } + LogUtil.handleError(LOG, debug.toString(), true); + } + + if (filterMap.get(type) != null) { + throw new ConfigurationException("A filterList of type '" + + type + "' has already been defined"); + } + filterMap.put(type, filterList); + } + put(FILTER_LIST, filterMap); + } + + private String parseConfig(Configuration cfg, RendererConfigOption option) { + Configuration child = cfg.getChild(option.getName()); + return child.getValue(null); + } + + private boolean doesValueExist(Configuration cfg, RendererConfigOption option) { + return cfg.getChild(option.getName(), false) != null; + } + + private int checkEncryptionLength(int encryptionLength, FOUserAgent userAgent) { + int correctEncryptionLength = encryptionLength; + if (encryptionLength < 40) { + correctEncryptionLength = 40; + } else if (encryptionLength > 128) { + correctEncryptionLength = 128; + } else if (encryptionLength % 8 != 0) { + correctEncryptionLength = Math.round(encryptionLength / 8.0f) * 8; + } + if (correctEncryptionLength != encryptionLength && userAgent != null) { + PDFEventProducer.Provider.get(userAgent.getEventBroadcaster()) + .incorrectEncryptionLength(this, encryptionLength, + correctEncryptionLength); + } + return correctEncryptionLength; + } + } + +} diff --git a/src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java b/src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java index df5224c04..96a19db6a 100644 --- a/src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java +++ b/src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java @@ -19,239 +19,30 @@ package org.apache.fop.render.pdf; -import java.util.List; -import java.util.Map; - -import org.apache.avalon.framework.configuration.Configuration; -import org.apache.avalon.framework.configuration.ConfigurationException; - import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.pdf.PDFAMode; -import org.apache.fop.pdf.PDFEncryptionParams; -import org.apache.fop.pdf.PDFFilterList; -import org.apache.fop.pdf.PDFXMode; -import org.apache.fop.render.PrintRendererConfigurator; -import org.apache.fop.render.Renderer; +import org.apache.fop.render.DefaultRendererConfigurator; +import org.apache.fop.render.RendererConfig.RendererConfigParser; import org.apache.fop.render.intermediate.IFDocumentHandler; -import org.apache.fop.util.LogUtil; /** * PDF renderer configurator. */ -public class PDFRendererConfigurator extends PrintRendererConfigurator { +public class PDFRendererConfigurator extends DefaultRendererConfigurator { /** * Default constructor * * @param userAgent user agent */ - public PDFRendererConfigurator(FOUserAgent userAgent) { - super(userAgent); - } - - /** - * Throws an UnsupportedOperationException. - * - * @param renderer not used - */ - public void configure(Renderer renderer) { - throw new UnsupportedOperationException(); + public PDFRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + super(userAgent, rendererConfigParser); } - private void configure(Configuration cfg, PDFRenderingUtil pdfUtil) throws FOPException { - //PDF filters - try { - Map filterMap = buildFilterMapFromConfiguration(cfg); - if (filterMap != null) { - pdfUtil.setFilterMap(filterMap); - } - } catch (ConfigurationException e) { - LogUtil.handleException(log, e, false); - } - - String s = cfg.getChild(PDFConfigurationConstants.PDF_A_MODE, true).getValue(null); - if (s != null) { - pdfUtil.setAMode(PDFAMode.valueOf(s)); - } - s = cfg.getChild(PDFConfigurationConstants.PDF_X_MODE, true).getValue(null); - if (s != null) { - pdfUtil.setXMode(PDFXMode.valueOf(s)); - } - Configuration encryptionParamsConfig - = cfg.getChild(PDFConfigurationConstants.ENCRYPTION_PARAMS, false); - if (encryptionParamsConfig != null) { - PDFEncryptionParams encryptionParams = pdfUtil.getEncryptionParams(); - Configuration ownerPasswordConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.OWNER_PASSWORD, false); - if (ownerPasswordConfig != null) { - String ownerPassword = ownerPasswordConfig.getValue(null); - if (ownerPassword != null) { - encryptionParams.setOwnerPassword(ownerPassword); - } - } - Configuration userPasswordConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.USER_PASSWORD, false); - if (userPasswordConfig != null) { - String userPassword = userPasswordConfig.getValue(null); - if (userPassword != null) { - encryptionParams.setUserPassword(userPassword); - } - } - Configuration noPrintConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.NO_PRINT, false); - if (noPrintConfig != null) { - encryptionParams.setAllowPrint(false); - } - Configuration noCopyContentConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.NO_COPY_CONTENT, false); - if (noCopyContentConfig != null) { - encryptionParams.setAllowCopyContent(false); - } - Configuration noEditContentConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.NO_EDIT_CONTENT, false); - if (noEditContentConfig != null) { - encryptionParams.setAllowEditContent(false); - } - Configuration noAnnotationsConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.NO_ANNOTATIONS, false); - if (noAnnotationsConfig != null) { - encryptionParams.setAllowEditAnnotations(false); - } - Configuration noFillInForms = encryptionParamsConfig.getChild( - PDFConfigurationConstants.NO_FILLINFORMS, false); - if (noFillInForms != null) { - encryptionParams.setAllowFillInForms(false); - } - Configuration noAccessContentConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.NO_ACCESSCONTENT, false); - if (noAccessContentConfig != null) { - encryptionParams.setAllowAccessContent(false); - } - Configuration noAssembleDocConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.NO_ASSEMBLEDOC, false); - if (noAssembleDocConfig != null) { - encryptionParams.setAllowAssembleDocument(false); - } - Configuration noPrintHqConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.NO_PRINTHQ, false); - if (noPrintHqConfig != null) { - encryptionParams.setAllowPrintHq(false); - } - Configuration encryptionLengthConfig = encryptionParamsConfig.getChild( - PDFConfigurationConstants.ENCRYPTION_LENGTH, false); - if (encryptionLengthConfig != null) { - int encryptionLength = checkEncryptionLength( - Integer.parseInt(encryptionLengthConfig.getValue(null))); - encryptionParams.setEncryptionLengthInBits(encryptionLength); - } - } - - s = cfg.getChild(PDFConfigurationConstants.KEY_OUTPUT_PROFILE, true).getValue(null); - if (s != null) { - pdfUtil.setOutputProfileURI(s); - } - Configuration disableColorSpaceConfig = cfg.getChild( - PDFConfigurationConstants.KEY_DISABLE_SRGB_COLORSPACE, false); - if (disableColorSpaceConfig != null) { - pdfUtil.setDisableSRGBColorSpace( - disableColorSpaceConfig.getValueAsBoolean(false)); - } - - setPDFDocVersion(cfg, pdfUtil); - } - - private int checkEncryptionLength(int encryptionLength) { - int correctEncryptionLength = encryptionLength; - if (encryptionLength < 40) { - correctEncryptionLength = 40; - } else if (encryptionLength > 128) { - correctEncryptionLength = 128; - } else if (encryptionLength % 8 != 0) { - correctEncryptionLength = ((int) Math.round(encryptionLength / 8.0f)) * 8; - } - if (correctEncryptionLength != encryptionLength) { - PDFEventProducer.Provider.get(userAgent.getEventBroadcaster()) - .incorrectEncryptionLength(this, encryptionLength, correctEncryptionLength); - } - return correctEncryptionLength; - } - - private void setPDFDocVersion(Configuration cfg, PDFRenderingUtil pdfUtil) throws FOPException { - Configuration pdfVersion = cfg.getChild(PDFConfigurationConstants.PDF_VERSION, false); - if (pdfVersion != null) { - String version = pdfVersion.getValue(null); - if (version != null && version.length() != 0) { - try { - pdfUtil.setPDFVersion(version); - } catch (IllegalArgumentException e) { - throw new FOPException(e.getMessage()); - } - } else { - throw new FOPException("The PDF version has not been set."); - } - } - } - - /** - * Builds a filter map from an Avalon Configuration object. - * - * @param cfg the Configuration object - * @return Map the newly built filter map - * @throws ConfigurationException if a filter list is defined twice - */ - public static Map buildFilterMapFromConfiguration(Configuration cfg) - throws ConfigurationException { - Map filterMap = new java.util.HashMap(); - Configuration[] filterLists = cfg.getChildren("filterList"); - for (int i = 0; i < filterLists.length; i++) { - Configuration filters = filterLists[i]; - String type = filters.getAttribute("type", null); - Configuration[] filt = filters.getChildren("value"); - List filterList = new java.util.ArrayList(); - for (int j = 0; j < filt.length; j++) { - String name = filt[j].getValue(); - filterList.add(name); - } - - if (type == null) { - type = PDFFilterList.DEFAULT_FILTER; - } - - if (!filterList.isEmpty() && log.isDebugEnabled()) { - StringBuffer debug = new StringBuffer("Adding PDF filter"); - if (filterList.size() != 1) { - debug.append("s"); - } - debug.append(" for type ").append(type).append(": "); - for (int j = 0; j < filterList.size(); j++) { - if (j != 0) { - debug.append(", "); - } - debug.append(filterList.get(j)); - } - log.debug(debug.toString()); - } - - if (filterMap.get(type) != null) { - throw new ConfigurationException("A filterList of type '" - + type + "' has already been defined"); - } - filterMap.put(type, filterList); - } - return filterMap; - } - - // ---=== IFDocumentHandler configuration ===--- - /** {@inheritDoc} */ public void configure(IFDocumentHandler documentHandler) throws FOPException { - Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); - if (cfg != null) { - PDFDocumentHandler pdfDocumentHandler = (PDFDocumentHandler)documentHandler; - PDFRenderingUtil pdfUtil = pdfDocumentHandler.getPDFUtil(); - configure(cfg, pdfUtil); - } + ((PDFDocumentHandler) documentHandler).mergeRendererOptionsConfig( + ((PDFRendererConfig) getRendererConfig(documentHandler)).getConfigOptions()); } } diff --git a/src/java/org/apache/fop/render/pdf/PDFRendererOption.java b/src/java/org/apache/fop/render/pdf/PDFRendererOption.java new file mode 100644 index 000000000..7305b9646 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/PDFRendererOption.java @@ -0,0 +1,112 @@ +/* + * 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.net.URI; +import java.net.URISyntaxException; + +import org.apache.fop.apps.io.InternalResourceResolver; +import org.apache.fop.pdf.PDFAMode; +import org.apache.fop.pdf.PDFXMode; +import org.apache.fop.pdf.Version; +import org.apache.fop.render.RendererConfigOption; + +public enum PDFRendererOption implements RendererConfigOption { + FILTER_LIST("filterList", null) { + @Override + Object deserialize(String value) { + throw new UnsupportedOperationException(); + } + }, + /** Rendering Options key for the PDF/A mode, default: {@link PDFAMode#DISABLED} */ + PDF_A_MODE("pdf-a-mode", PDFAMode.DISABLED){ + @Override + PDFAMode deserialize(String value) { + return PDFAMode.getValueOf(value); + } + }, + /** Rendering Options key for the PDF/X mode, default: {@link PDFXMode#DISABLED} */ + PDF_X_MODE("pdf-x-mode", PDFXMode.DISABLED){ + @Override + PDFXMode deserialize(String value) { + return PDFXMode.getValueOf(value); + } + }, + /** PDF version entry: specify the version of the PDF document created, datatype: String */ + VERSION("version") { + @Override + Version deserialize(String value) { + return Version.getValueOf(value); + } + }, + /** + * Rendering Options key for disabling the sRGB color space (only possible if no PDF/A or + * PDF/X profile is active), default: false + */ + DISABLE_SRGB_COLORSPACE("disable-srgb-colorspace", false) { + @Override + Boolean deserialize(String value) { + return Boolean.valueOf(value); + } + }, + /** Rendering Options key for the ICC profile for the output intent. */ + OUTPUT_PROFILE("output-profile") { + @Override + URI deserialize(String value) { + try { + return InternalResourceResolver.cleanURI(value); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + }; + + private final String name; + + private final Object defaultValue; + + private PDFRendererOption(String name, Object defaultValue) { + this.name = name; + this.defaultValue = defaultValue; + } + + private PDFRendererOption(String name) { + this(name, null); + } + + public String getName() { + return name; + } + + public Object getDefaultValue() { + return defaultValue; + } + + public Object parse(Object object) { + if (object instanceof String) { + return deserialize((String) object); + } else { + return object; + } + } + + abstract Object deserialize(String value); + +} diff --git a/src/java/org/apache/fop/render/pdf/PDFRendererOptionsConfig.java b/src/java/org/apache/fop/render/pdf/PDFRendererOptionsConfig.java new file mode 100644 index 000000000..e8b068647 --- /dev/null +++ b/src/java/org/apache/fop/render/pdf/PDFRendererOptionsConfig.java @@ -0,0 +1,123 @@ +/* + * 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.net.URI; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +import org.apache.fop.pdf.PDFAMode; +import org.apache.fop.pdf.PDFEncryptionParams; +import org.apache.fop.pdf.PDFXMode; +import org.apache.fop.pdf.Version; + +import static org.apache.fop.render.pdf.PDFRendererOption.DISABLE_SRGB_COLORSPACE; +import static org.apache.fop.render.pdf.PDFRendererOption.FILTER_LIST; +import static org.apache.fop.render.pdf.PDFRendererOption.OUTPUT_PROFILE; +import static org.apache.fop.render.pdf.PDFRendererOption.PDF_A_MODE; +import static org.apache.fop.render.pdf.PDFRendererOption.PDF_X_MODE; +import static org.apache.fop.render.pdf.PDFRendererOption.VERSION; + +/** + * The renderer options configuration data. + */ +public final class PDFRendererOptionsConfig { + + static final PDFRendererOptionsConfig DEFAULT; + + static { + final EnumMap<PDFRendererOption, Object> props + = new EnumMap<PDFRendererOption, Object>(PDFRendererOption.class); + for(PDFRendererOption option : PDFRendererOption.values()) { + props.put(option, option.getDefaultValue()); + } + DEFAULT = new PDFRendererOptionsConfig(props, null); + } + + private final Map<PDFRendererOption, Object> properties + = new EnumMap<PDFRendererOption, Object>(PDFRendererOption.class); + + private final PDFEncryptionParams encryptionConfig; + + PDFRendererOptionsConfig(Map<PDFRendererOption, Object> props, + PDFEncryptionParams encryptionParams) { + properties.putAll(props); + this.encryptionConfig = copyPDFEncryptionParams(encryptionParams); + } + + private static PDFEncryptionParams copyPDFEncryptionParams(PDFEncryptionParams source) { + return source == null ? null : new PDFEncryptionParams(source); + } + + PDFRendererOptionsConfig merge(PDFRendererOptionsConfig config) { + if (config == null) { + return this; + } else { + return new PDFRendererOptionsConfig(merge(this.properties, config.properties), + config.getEncryptionParameters() == null + ? copyPDFEncryptionParams(this.encryptionConfig) + : copyPDFEncryptionParams(config.getEncryptionParameters())); + } + } + + private static Map<PDFRendererOption, Object> merge( + Map<PDFRendererOption, Object> first, Map<PDFRendererOption, Object> second) { + final EnumMap<PDFRendererOption, Object> merged + = new EnumMap<PDFRendererOption, Object>(PDFRendererOption.class); + for (PDFRendererOption option : PDFRendererOption.values()) { + Object value = second.get(option); + if (value != null) { + merged.put(option, value); + } else { + merged.put(option, first.get(option)); + } + } + return merged; + } + + public Map<String, List<String>> getFilterMap() { + return (Map<String, List<String>>) properties.get(FILTER_LIST); + } + + public PDFAMode getPDFAMode() { + return (PDFAMode) properties.get(PDF_A_MODE); + } + + public PDFXMode getPDFXMode() { + return (PDFXMode) properties.get(PDF_X_MODE); + } + + public PDFEncryptionParams getEncryptionParameters() { + return encryptionConfig; + } + + public URI getOutputProfileURI() { + return (URI) properties.get(OUTPUT_PROFILE); + } + + public Boolean getDisableSRGBColorSpace() { + return (Boolean) properties.get(DISABLE_SRGB_COLORSPACE); + } + + public Version getPDFVersion() { + return (Version) properties.get(VERSION); + } +} diff --git a/src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java b/src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java index 53d259677..fba9d922f 100644 --- a/src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java +++ b/src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java @@ -24,17 +24,15 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.net.URL; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.EnumMap; import java.util.Map; -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; - import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.xmlgraphics.image.loader.util.ImageUtil; import org.apache.xmlgraphics.java2d.color.profile.ColorProfileUtil; import org.apache.xmlgraphics.xmp.Metadata; import org.apache.xmlgraphics.xmp.schemas.XMPBasicAdapter; @@ -42,6 +40,7 @@ import org.apache.xmlgraphics.xmp.schemas.XMPBasicSchema; import org.apache.fop.accessibility.Accessibility; import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.apps.io.InternalResourceResolver; import org.apache.fop.fo.extensions.xmp.XMPMetadata; import org.apache.fop.pdf.PDFAMode; import org.apache.fop.pdf.PDFArray; @@ -68,11 +67,24 @@ import org.apache.fop.pdf.Version; import org.apache.fop.pdf.VersionController; import org.apache.fop.render.pdf.extensions.PDFEmbeddedFileExtensionAttachment; +import static org.apache.fop.render.pdf.PDFEncryptionOption.ENCRYPTION_PARAMS; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_ACCESSCONTENT; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_ANNOTATIONS; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_ASSEMBLEDOC; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_COPY_CONTENT; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_EDIT_CONTENT; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_FILLINFORMS; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_PRINT; +import static org.apache.fop.render.pdf.PDFEncryptionOption.NO_PRINTHQ; +import static org.apache.fop.render.pdf.PDFEncryptionOption.OWNER_PASSWORD; +import static org.apache.fop.render.pdf.PDFEncryptionOption.USER_PASSWORD; + + /** * Utility class which enables all sorts of features that are not directly connected to the * normal rendering process. */ -class PDFRenderingUtil implements PDFConfigurationConstants { +class PDFRenderingUtil { /** logging instance */ private static Log log = LogFactory.getLog(PDFRenderingUtil.class); @@ -80,171 +92,42 @@ class PDFRenderingUtil implements PDFConfigurationConstants { private FOUserAgent userAgent; /** the PDF Document being created */ - protected PDFDocument pdfDoc; - - /** the PDF/A mode (Default: disabled) */ - protected PDFAMode pdfAMode = PDFAMode.DISABLED; - - /** the PDF/X mode (Default: disabled) */ - protected PDFXMode pdfXMode = PDFXMode.DISABLED; - - /** the (optional) encryption parameters */ - protected PDFEncryptionParams encryptionParams; + private PDFDocument pdfDoc; - /** Registry of PDF filters */ - protected Map filterMap; + private PDFRendererOptionsConfig rendererConfig; /** the ICC stream used as output profile by this document for PDF/A and PDF/X functionality. */ - protected PDFICCStream outputProfile; - /** the default sRGB color space. */ - protected PDFICCBasedColorSpace sRGBColorSpace; - /** controls whether the sRGB color space should be installed */ - protected boolean disableSRGBColorSpace = false; - - /** Optional URI to an output profile to be used. */ - protected String outputProfileURI; - - protected Version maxPDFVersion; + private PDFICCStream outputProfile; + /** the default sRGB color space. */ + private PDFICCBasedColorSpace sRGBColorSpace; PDFRenderingUtil(FOUserAgent userAgent) { this.userAgent = userAgent; initialize(); } - private static boolean booleanValueOf(Object obj) { - if (obj instanceof Boolean) { - return ((Boolean)obj).booleanValue(); - } else if (obj instanceof String) { - return Boolean.valueOf((String)obj).booleanValue(); - } else { - throw new IllegalArgumentException("Boolean or \"true\" or \"false\" expected."); - } - } - private void initialize() { - PDFEncryptionParams params - = (PDFEncryptionParams)userAgent.getRendererOptions().get(ENCRYPTION_PARAMS); - if (params != null) { - this.encryptionParams = params; //overwrite if available - } - String userPassword = (String)userAgent.getRendererOptions().get(USER_PASSWORD); - if (userPassword != null) { - getEncryptionParams().setUserPassword(userPassword); - } - String ownerPassword = (String)userAgent.getRendererOptions().get(OWNER_PASSWORD); - if (ownerPassword != null) { - getEncryptionParams().setOwnerPassword(ownerPassword); - } - Object noPrint = userAgent.getRendererOptions().get(NO_PRINT); - if (noPrint != null) { - getEncryptionParams().setAllowPrint(!booleanValueOf(noPrint)); - } - Object noCopyContent = userAgent.getRendererOptions().get(NO_COPY_CONTENT); - if (noCopyContent != null) { - getEncryptionParams().setAllowCopyContent(!booleanValueOf(noCopyContent)); - } - Object noEditContent = userAgent.getRendererOptions().get(NO_EDIT_CONTENT); - if (noEditContent != null) { - getEncryptionParams().setAllowEditContent(!booleanValueOf(noEditContent)); - } - Object noAnnotations = userAgent.getRendererOptions().get(NO_ANNOTATIONS); - if (noAnnotations != null) { - getEncryptionParams().setAllowEditAnnotations(!booleanValueOf(noAnnotations)); - } - Object noFillInForms = userAgent.getRendererOptions().get(NO_FILLINFORMS); - if (noFillInForms != null) { - getEncryptionParams().setAllowFillInForms(!booleanValueOf(noFillInForms)); - } - Object noAccessContent = userAgent.getRendererOptions().get(NO_ACCESSCONTENT); - if (noAccessContent != null) { - getEncryptionParams().setAllowAccessContent(!booleanValueOf(noAccessContent)); - } - Object noAssembleDoc = userAgent.getRendererOptions().get(NO_ASSEMBLEDOC); - if (noAssembleDoc != null) { - getEncryptionParams().setAllowAssembleDocument(!booleanValueOf(noAssembleDoc)); - } - Object noPrintHQ = userAgent.getRendererOptions().get(NO_PRINTHQ); - if (noPrintHQ != null) { - getEncryptionParams().setAllowPrintHq(!booleanValueOf(noPrintHQ)); - } - String s = (String)userAgent.getRendererOptions().get(PDF_A_MODE); - if (s != null) { - this.pdfAMode = PDFAMode.valueOf(s); - } - if (this.pdfAMode.isPDFA1LevelA()) { + rendererConfig = PDFRendererOptionsConfig.DEFAULT.merge(createFromUserAgent(userAgent)); + if (rendererConfig.getPDFAMode().isPDFA1LevelA()) { //Enable accessibility if PDF/A-1a is enabled because it requires tagged PDF. userAgent.getRendererOptions().put(Accessibility.ACCESSIBILITY, Boolean.TRUE); } - s = (String)userAgent.getRendererOptions().get(PDF_X_MODE); - if (s != null) { - this.pdfXMode = PDFXMode.valueOf(s); - } - s = (String)userAgent.getRendererOptions().get(KEY_OUTPUT_PROFILE); - if (s != null) { - this.outputProfileURI = s; - } - Object disableSRGBColorSpace = userAgent.getRendererOptions().get( - KEY_DISABLE_SRGB_COLORSPACE); - if (disableSRGBColorSpace != null) { - this.disableSRGBColorSpace = booleanValueOf(disableSRGBColorSpace); - } - } - - public FOUserAgent getUserAgent() { - return this.userAgent; - } - - /** - * Sets the PDF/A mode for the PDF renderer. - * @param mode the PDF/A mode - */ - public void setAMode(PDFAMode mode) { - this.pdfAMode = mode; - } - - /** - * Sets the PDF/X mode for the PDF renderer. - * @param mode the PDF/X mode - */ - public void setXMode(PDFXMode mode) { - this.pdfXMode = 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.outputProfileURI = outputProfileURI; } - /** - * Enables or disables the default sRGB color space needed for the PDF document to preserve - * the sRGB colors used in XSL-FO. - * @param disable true to disable, false to enable - */ - public void setDisableSRGBColorSpace(boolean disable) { - this.disableSRGBColorSpace = disable; + private static PDFRendererOptionsConfig createFromUserAgent(FOUserAgent userAgent) { + Map<PDFRendererOption, Object> properties + = new EnumMap<PDFRendererOption, Object>(PDFRendererOption.class); + for (PDFRendererOption option : PDFRendererOption.values()) { + Object value = userAgent.getRendererOption(option); + properties.put(option, option.parse(value)); + } + PDFEncryptionParams encryptionConfig = new EncryptionParamsBuilder().createParams(userAgent); + return new PDFRendererOptionsConfig(properties, encryptionConfig); } - /** - * Sets the filter map to be used by the PDF renderer. - * @param filterMap the filter map - */ - public void setFilterMap(Map filterMap) { - this.filterMap = filterMap; - } - - /** - * Gets the encryption parameters used by the PDF renderer. - * @return encryptionParams the encryption parameters - */ - PDFEncryptionParams getEncryptionParams() { - if (this.encryptionParams == null) { - this.encryptionParams = new PDFEncryptionParams(); - } - return this.encryptionParams; + void mergeRendererOptionsConfig(PDFRendererOptionsConfig config) { + rendererConfig = rendererConfig.merge(config); } private void updateInfo() { @@ -258,15 +141,15 @@ class PDFRenderingUtil implements PDFConfigurationConstants { } private void updatePDFProfiles() { - pdfDoc.getProfile().setPDFAMode(this.pdfAMode); - pdfDoc.getProfile().setPDFXMode(this.pdfXMode); + pdfDoc.getProfile().setPDFAMode(rendererConfig.getPDFAMode()); + pdfDoc.getProfile().setPDFXMode(rendererConfig.getPDFXMode()); } private void addsRGBColorSpace() throws IOException { - if (disableSRGBColorSpace) { - if (this.pdfAMode != PDFAMode.DISABLED - || this.pdfXMode != PDFXMode.DISABLED - || this.outputProfileURI != null) { + if (rendererConfig.getDisableSRGBColorSpace()) { + if (rendererConfig.getPDFAMode() != PDFAMode.DISABLED + || rendererConfig.getPDFXMode() != PDFXMode.DISABLED + || rendererConfig.getOutputProfileURI() != null) { throw new IllegalStateException("It is not possible to disable the sRGB color" + " space if PDF/A or PDF/X functionality is enabled or an" + " output profile is set!"); @@ -286,17 +169,10 @@ class PDFRenderingUtil implements PDFConfigurationConstants { } ICC_Profile profile; InputStream in = null; - if (this.outputProfileURI != null) { + URI outputProfileUri = rendererConfig.getOutputProfileURI(); + if (outputProfileUri != null) { this.outputProfile = pdfDoc.getFactory().makePDFICCStream(); - Source src = getUserAgent().resolveURI(this.outputProfileURI); - if (src == null) { - throw new IOException("Output profile not found: " + this.outputProfileURI); - } - if (src instanceof StreamSource) { - in = ((StreamSource)src).getInputStream(); - } else { - in = new URL(src.getSystemId()).openStream(); - } + in = userAgent.getResourceResolver().getResource(rendererConfig.getOutputProfileURI()); try { profile = ColorProfileUtil.getICC_Profile(in); } finally { @@ -381,7 +257,7 @@ class PDFRenderingUtil implements PDFConfigurationConstants { } String producer = userAgent.getProducer() != null ? userAgent.getProducer() : ""; - + final Version maxPDFVersion = rendererConfig.getPDFVersion(); if (maxPDFVersion == null) { this.pdfDoc = new PDFDocument(producer); } else { @@ -391,22 +267,24 @@ class PDFRenderingUtil implements PDFConfigurationConstants { } updateInfo(); updatePDFProfiles(); - pdfDoc.setFilterMap(filterMap); + pdfDoc.setFilterMap(rendererConfig.getFilterMap()); pdfDoc.outputHeader(out); //Setup encryption if necessary - PDFEncryptionManager.setupPDFEncryption(encryptionParams, pdfDoc); + PDFEncryptionManager.setupPDFEncryption(rendererConfig.getEncryptionParameters(), pdfDoc); addsRGBColorSpace(); - if (this.outputProfileURI != null) { + if (rendererConfig.getOutputProfileURI() != null) { addDefaultOutputProfile(); } + PDFXMode pdfXMode = rendererConfig.getPDFXMode(); if (pdfXMode != PDFXMode.DISABLED) { log.debug(pdfXMode + " is active."); log.warn("Note: " + pdfXMode + " support is work-in-progress and not fully implemented, yet!"); addPDFXOutputIntent(); } + PDFAMode pdfAMode = rendererConfig.getPDFAMode(); if (pdfAMode.isPDFA1LevelB()) { log.debug("PDF/A is active. Conformance Level: " + pdfAMode); addPDFA1OutputIntent(); @@ -456,8 +334,13 @@ class PDFRenderingUtil implements PDFConfigurationConstants { //Create embedded file PDFEmbeddedFile file = new PDFEmbeddedFile(); this.pdfDoc.registerObject(file); - Source src = getUserAgent().resolveURI(embeddedFile.getSrc()); - InputStream in = ImageUtil.getInputStream(src); + URI srcURI; + try { + srcURI = InternalResourceResolver.cleanURI(embeddedFile.getSrc()); + } catch (URISyntaxException use) { + throw new RuntimeException(use); + } + InputStream in = userAgent.getResourceResolver().getResource(srcURI); if (in == null) { throw new FileNotFoundException(embeddedFile.getSrc()); } @@ -497,14 +380,72 @@ class PDFRenderingUtil implements PDFConfigurationConstants { nameArray.add(new PDFReference(fileSpec)); } - /** - * Sets the PDF version of the output document. See {@link Version} for the format of - * <code>version</code>. - * @param version the PDF version - * @throws IllegalArgumentException if the format of version doesn't conform to that specified - * by {@link Version} - */ - public void setPDFVersion(String version) { - maxPDFVersion = Version.getValueOf(version); + private static final class EncryptionParamsBuilder { + private PDFEncryptionParams params; + + private EncryptionParamsBuilder() { + } + + private PDFEncryptionParams createParams(FOUserAgent userAgent) { + params = (PDFEncryptionParams) userAgent.getRendererOptions().get(ENCRYPTION_PARAMS); + String userPassword = (String) userAgent.getRendererOption(USER_PASSWORD); + if (userPassword != null) { + getEncryptionParams().setUserPassword(userPassword); + } + String ownerPassword = (String) userAgent.getRendererOption(OWNER_PASSWORD); + if (ownerPassword != null) { + getEncryptionParams().setOwnerPassword(ownerPassword); + } + Object noPrint = userAgent.getRendererOption(NO_PRINT); + if (noPrint != null) { + getEncryptionParams().setAllowPrint(!booleanValueOf(noPrint)); + } + Object noCopyContent = userAgent.getRendererOption(NO_COPY_CONTENT); + if (noCopyContent != null) { + getEncryptionParams().setAllowCopyContent(!booleanValueOf(noCopyContent)); + } + Object noEditContent = userAgent.getRendererOption(NO_EDIT_CONTENT); + if (noEditContent != null) { + getEncryptionParams().setAllowEditContent(!booleanValueOf(noEditContent)); + } + Object noAnnotations = userAgent.getRendererOption(NO_ANNOTATIONS); + if (noAnnotations != null) { + getEncryptionParams().setAllowEditAnnotations(!booleanValueOf(noAnnotations)); + } + Object noFillInForms = userAgent.getRendererOption(NO_FILLINFORMS); + if (noFillInForms != null) { + getEncryptionParams().setAllowFillInForms(!booleanValueOf(noFillInForms)); + } + Object noAccessContent = userAgent.getRendererOption(NO_ACCESSCONTENT); + if (noAccessContent != null) { + getEncryptionParams().setAllowAccessContent(!booleanValueOf(noAccessContent)); + } + Object noAssembleDoc = userAgent.getRendererOption(NO_ASSEMBLEDOC); + if (noAssembleDoc != null) { + getEncryptionParams().setAllowAssembleDocument(!booleanValueOf(noAssembleDoc)); + } + Object noPrintHQ = userAgent.getRendererOption(NO_PRINTHQ); + if (noPrintHQ != null) { + getEncryptionParams().setAllowPrintHq(!booleanValueOf(noPrintHQ)); + } + return params; + } + + private PDFEncryptionParams getEncryptionParams() { + if (params == null) { + params = new PDFEncryptionParams(); + } + return params; + } + + private static boolean booleanValueOf(Object obj) { + if (obj instanceof Boolean) { + return ((Boolean)obj).booleanValue(); + } else if (obj instanceof String) { + return Boolean.valueOf((String)obj).booleanValue(); + } else { + throw new IllegalArgumentException("Boolean or \"true\" or \"false\" expected."); + } + } } } diff --git a/src/java/org/apache/fop/render/print/PrintRendererMaker.java b/src/java/org/apache/fop/render/print/PrintRendererMaker.java index 63444a628..66eb4b108 100644 --- a/src/java/org/apache/fop/render/print/PrintRendererMaker.java +++ b/src/java/org/apache/fop/render/print/PrintRendererMaker.java @@ -19,12 +19,15 @@ package org.apache.fop.render.print; +import java.util.List; + +import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.MimeConstants; +import org.apache.fop.fonts.FontCollection; import org.apache.fop.render.AbstractRendererMaker; import org.apache.fop.render.PrintRendererConfigurator; import org.apache.fop.render.Renderer; -import org.apache.fop.render.RendererConfigurator; /** * RendererMaker for the Print Renderer. @@ -33,22 +36,28 @@ public class PrintRendererMaker extends AbstractRendererMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_FOP_PRINT}; - /**{@inheritDoc} */ + @Override public Renderer makeRenderer(FOUserAgent userAgent) { return new PrintRenderer(userAgent); } - /** {@inheritDoc} */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return new PrintRendererConfigurator(userAgent); + @Override + public void configureRenderer(FOUserAgent userAgent, Renderer renderer) throws FOPException { + // TODO what constructor params? + new PrintRendererConfigurator(userAgent, null) { + @Override + protected List<FontCollection> getDefaultFontCollection() { + throw new UnsupportedOperationException(); + } + } .configure(renderer); } - /** {@inheritDoc} */ + @Override public boolean needsOutputStream() { return false; } - /** {@inheritDoc} */ + @Override public String[] getSupportedMimeTypes() { return MIMES; } diff --git a/src/java/org/apache/fop/render/ps/PSDocumentHandler.java b/src/java/org/apache/fop/render/ps/PSDocumentHandler.java index bf2d95c1d..d73beb759 100644 --- a/src/java/org/apache/fop/render/ps/PSDocumentHandler.java +++ b/src/java/org/apache/fop/render/ps/PSDocumentHandler.java @@ -22,10 +22,12 @@ package org.apache.fop.render.ps; import java.awt.Dimension; import java.awt.geom.Dimension2D; import java.awt.geom.Rectangle2D; -import java.io.File; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -50,20 +52,22 @@ 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.apps.FOUserAgent; import org.apache.fop.apps.MimeConstants; +import org.apache.fop.apps.io.TempResourceURIGenerator; import org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler; import org.apache.fop.render.intermediate.IFContext; import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; import org.apache.fop.render.intermediate.IFException; import org.apache.fop.render.intermediate.IFPainter; +import org.apache.fop.render.ps.PSRendererConfig.PSRendererConfigParser; import org.apache.fop.render.ps.extensions.PSCommentAfter; import org.apache.fop.render.ps.extensions.PSCommentBefore; import org.apache.fop.render.ps.extensions.PSPageTrailerCodeBefore; import org.apache.fop.render.ps.extensions.PSSetPageDevice; import org.apache.fop.render.ps.extensions.PSSetupCode; + /** * {@link org.apache.fop.render.intermediate.IFDocumentHandler} implementation * that produces PostScript. @@ -83,7 +87,9 @@ public class PSDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { PSGenerator gen; /** the temporary file in case of two-pass processing */ - private File tempFile; + private URI tempURI; + private static final TempResourceURIGenerator TEMP_URI_GENERATOR + = new TempResourceURIGenerator("ps-optimize"); private int currentPageNumber = 0; private PageDefinition currentPageDefinition; @@ -114,7 +120,9 @@ public class PSDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { /** * Default constructor. */ - public PSDocumentHandler() { + public PSDocumentHandler(IFContext context) { + super(context); + this.psUtil = new PSRenderingUtil(context.getUserAgent()); } /** {@inheritDoc} */ @@ -132,16 +140,8 @@ public class PSDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { } /** {@inheritDoc} */ - public void setContext(IFContext context) { - super.setContext(context); - FOUserAgent userAgent = context.getUserAgent(); - this.psUtil = new PSRenderingUtil(userAgent); - eventProducer = PSEventProducer.Provider.get(userAgent.getEventBroadcaster()); - } - - /** {@inheritDoc} */ public IFDocumentHandlerConfigurator getConfigurator() { - return new PSRendererConfigurator(getUserAgent()); + return new PSRendererConfigurator(getUserAgent(), new PSRendererConfigParser()); } PSRenderingUtil getPSUtil() { @@ -153,11 +153,10 @@ public class PSDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { super.startDocument(); this.fontResources = new FontResourceCache(getFontInfo()); try { - OutputStream out; + final OutputStream out; if (psUtil.isOptimizeResources()) { - this.tempFile = File.createTempFile("fop", ".ps"); - out = new java.io.FileOutputStream(this.tempFile); - out = new java.io.BufferedOutputStream(out); + tempURI = TEMP_URI_GENERATOR.generate(); + out = new BufferedOutputStream(getUserAgent().getResourceResolver().getOutputStream(tempURI)); } else { out = this.outputStream; } @@ -264,8 +263,7 @@ public class PSDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { 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); + InputStream in = new BufferedInputStream(getUserAgent().getResourceResolver().getResource(tempURI)); try { try { ResourceHandler handler = new ResourceHandler(getUserAgent(), eventProducer, @@ -278,10 +276,6 @@ public class PSDocumentHandler extends AbstractBinaryWritingIFDocumentHandler { } } 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; diff --git a/src/java/org/apache/fop/render/ps/PSDocumentHandlerMaker.java b/src/java/org/apache/fop/render/ps/PSDocumentHandlerMaker.java index c581f9e02..1c31c4906 100644 --- a/src/java/org/apache/fop/render/ps/PSDocumentHandlerMaker.java +++ b/src/java/org/apache/fop/render/ps/PSDocumentHandlerMaker.java @@ -19,7 +19,6 @@ package org.apache.fop.render.ps; -import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.MimeConstants; import org.apache.fop.render.intermediate.AbstractIFDocumentHandlerMaker; import org.apache.fop.render.intermediate.IFContext; @@ -33,19 +32,17 @@ public class PSDocumentHandlerMaker extends AbstractIFDocumentHandlerMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_POSTSCRIPT}; - /** {@inheritDoc} */ - public IFDocumentHandler makeIFDocumentHandler(FOUserAgent ua) { - PSDocumentHandler handler = new PSDocumentHandler(); - handler.setContext(new IFContext(ua)); - return handler; + @Override + public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) { + return new PSDocumentHandler(ifContext); } - /** {@inheritDoc} */ + @Override public boolean needsOutputStream() { return true; } - /** {@inheritDoc} */ + @Override public String[] getSupportedMimeTypes() { return MIMES; } diff --git a/src/java/org/apache/fop/render/ps/PSFontUtils.java b/src/java/org/apache/fop/render/ps/PSFontUtils.java index d0d75744f..c99bb21e1 100644 --- a/src/java/org/apache/fop/render/ps/PSFontUtils.java +++ b/src/java/org/apache/fop/render/ps/PSFontUtils.java @@ -19,19 +19,14 @@ package org.apache.fop.render.ps; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.net.MalformedURLException; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -526,27 +521,7 @@ public class PSFontUtils extends org.apache.xmlgraphics.ps.PSFontUtils { private static InputStream getInputStreamOnFont(PSGenerator gen, CustomFont font) throws IOException { if (isEmbeddable(font)) { - Source source = font.getEmbedFileSource(); - if (source == null && font.getEmbedResourceName() != null) { - source = new StreamSource(PSFontUtils.class - .getResourceAsStream(font.getEmbedResourceName())); - } - if (source == null) { - return null; - } - InputStream in = null; - if (source instanceof StreamSource) { - in = ((StreamSource) source).getInputStream(); - } - if (in == null && source.getSystemId() != null) { - try { - in = new java.net.URL(source.getSystemId()).openStream(); - } catch (MalformedURLException e) { - new FileNotFoundException( - "File not found. URL could not be resolved: " - + e.getMessage()); - } - } + InputStream in = font.getInputStream(); if (in == null) { return null; } diff --git a/src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java b/src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java index 839a0cab6..3ade34522 100644 --- a/src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java +++ b/src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java @@ -70,7 +70,7 @@ public class PSImageHandlerSVG implements ImageHandler { BridgeContext ctx = new PSBridgeContext(ua, (strokeText ? null : psContext.getFontInfo()), - context.getUserAgent().getFactory().getImageManager(), + context.getUserAgent().getImageManager(), context.getUserAgent().getImageSessionContext()); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) diff --git a/src/java/org/apache/fop/render/ps/PSImageUtils.java b/src/java/org/apache/fop/render/ps/PSImageUtils.java index 431071701..962f19d10 100644 --- a/src/java/org/apache/fop/render/ps/PSImageUtils.java +++ b/src/java/org/apache/fop/render/ps/PSImageUtils.java @@ -53,7 +53,7 @@ public class PSImageUtils extends org.apache.xmlgraphics.ps.PSImageUtils { } //Investigate choice for inline mode ImageFlavor[] inlineFlavors = determineSupportedImageFlavors(renderingContext); - ImageManager manager = renderingContext.getUserAgent().getFactory().getImageManager(); + ImageManager manager = renderingContext.getUserAgent().getImageManager(); ImageProviderPipeline[] inlineCandidates = manager.getPipelineFactory().determineCandidatePipelines( info, inlineFlavors); @@ -79,7 +79,7 @@ public class PSImageUtils extends org.apache.xmlgraphics.ps.PSImageUtils { private static ImageFlavor[] determineSupportedImageFlavors(RenderingContext renderingContext) { ImageFlavor[] inlineFlavors; ImageHandlerRegistry imageHandlerRegistry - = renderingContext.getUserAgent().getFactory().getImageHandlerRegistry(); + = renderingContext.getUserAgent().getImageHandlerRegistry(); inlineFlavors = imageHandlerRegistry.getSupportedFlavors(renderingContext); return inlineFlavors; } diff --git a/src/java/org/apache/fop/render/ps/PSRendererConfig.java b/src/java/org/apache/fop/render/ps/PSRendererConfig.java new file mode 100644 index 000000000..e26be11d0 --- /dev/null +++ b/src/java/org/apache/fop/render/ps/PSRendererConfig.java @@ -0,0 +1,147 @@ +/* + * 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 java.util.EnumMap; +import java.util.Locale; + +import org.apache.avalon.framework.configuration.Configuration; +import org.apache.avalon.framework.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.apps.MimeConstants; +import org.apache.fop.fonts.DefaultFontConfig; +import org.apache.fop.fonts.DefaultFontConfig.DefaultFontConfigParser; +import org.apache.fop.render.RendererConfig; +import org.apache.fop.util.LogUtil; + +import static org.apache.fop.render.ps.PSRendererOption.AUTO_ROTATE_LANDSCAPE; +import static org.apache.fop.render.ps.PSRendererOption.DSC_COMPLIANT; +import static org.apache.fop.render.ps.PSRendererOption.LANGUAGE_LEVEL; +import static org.apache.fop.render.ps.PSRendererOption.OPTIMIZE_RESOURCES; +import static org.apache.fop.render.ps.PSRendererOption.RENDERING_MODE; +import static org.apache.fop.render.ps.PSRendererOption.SAFE_SET_PAGE_DEVICE; + +/** + * The PostScript renderer configuration data object. + */ +public final class PSRendererConfig implements RendererConfig { + + private final EnumMap<PSRendererOption, Object> params + = new EnumMap<PSRendererOption, Object>(PSRendererOption.class); + + private final DefaultFontConfig fontConfig; + + private PSRendererConfig(DefaultFontConfig fontConfig) { + this.fontConfig = fontConfig; + } + + public DefaultFontConfig getFontInfoConfig() { + return fontConfig; + } + + public Boolean isAutoRotateLandscape() { + return (Boolean) params.get(AUTO_ROTATE_LANDSCAPE); + } + + public Integer getLanguageLevel() { + return (Integer) params.get(LANGUAGE_LEVEL); + } + + public Boolean isOptimizeResources() { + return (Boolean) params.get(OPTIMIZE_RESOURCES); + } + + public Boolean isSafeSetPageDevice() { + return (Boolean) params.get(SAFE_SET_PAGE_DEVICE); + } + + public Boolean isDscComplianceEnabled() { + return (Boolean) params.get(DSC_COMPLIANT); + } + + public PSRenderingMode getRenderingMode() { + return (PSRenderingMode) params.get(RENDERING_MODE); + } + + /** + * The PostScript renderer configuration data parser. + */ + public static final class PSRendererConfigParser implements RendererConfigParser { + + private static final Log LOG = LogFactory.getLog(PSRendererConfigParser.class); + + public PSRendererConfig build(FOUserAgent userAgent, Configuration cfg) throws FOPException { + PSRendererConfig config = null; + try { + config = new ParserHelper(cfg, userAgent).config; + } catch (ConfigurationException e) { + LogUtil.handleException(LOG, e, false); + } + return config; + } + + public String getMimeType() { + return MimeConstants.MIME_POSTSCRIPT; + } + } + + private static final class ParserHelper { + + private PSRendererConfig config; + + private ParserHelper(Configuration cfg, FOUserAgent userAgent) + throws ConfigurationException, FOPException { + config = new PSRendererConfig(new DefaultFontConfigParser().parse(cfg, + userAgent.validateStrictly())); + if (cfg != null) { + setBoolConfigParam(cfg, AUTO_ROTATE_LANDSCAPE); + setConfigParameter(LANGUAGE_LEVEL, + cfg.getChild(LANGUAGE_LEVEL.getName()) + .getValueAsInteger((Integer) LANGUAGE_LEVEL.getDefaultValue())); + setBoolConfigParam(cfg, OPTIMIZE_RESOURCES); + setBoolConfigParam(cfg, SAFE_SET_PAGE_DEVICE); + setBoolConfigParam(cfg, DSC_COMPLIANT); + Configuration child = cfg.getChild("rendering"); + if (child != null) { + config.params.put(RENDERING_MODE, + PSRenderingMode.valueOf(child.getValue( + RENDERING_MODE.getDefaultValue().toString()) + .toUpperCase(Locale.ENGLISH))); + } + } + } + + private void setConfigParameter(PSRendererOption option, + Object value) { + config.params.put(option, value != null ? value : option.getDefaultValue()); + } + + private void setBoolConfigParam(Configuration cfg, PSRendererOption option) { + setConfigParameter(option, cfg.getChild( + option.getName()).getValueAsBoolean((Boolean) option.getDefaultValue())); + } + + } + +} diff --git a/src/java/org/apache/fop/render/ps/PSRendererConfigurator.java b/src/java/org/apache/fop/render/ps/PSRendererConfigurator.java index 00f3fc154..b453de413 100644 --- a/src/java/org/apache/fop/render/ps/PSRendererConfigurator.java +++ b/src/java/org/apache/fop/render/ps/PSRendererConfigurator.java @@ -19,75 +19,56 @@ package org.apache.fop.render.ps; -import java.util.Locale; - -import org.apache.avalon.framework.configuration.Configuration; - -import org.apache.xmlgraphics.ps.PSGenerator; - import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; -import org.apache.fop.render.PrintRendererConfigurator; -import org.apache.fop.render.Renderer; +import org.apache.fop.render.DefaultRendererConfigurator; +import org.apache.fop.render.RendererConfig.RendererConfigParser; import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; + /** * Postscript renderer config */ -public class PSRendererConfigurator extends PrintRendererConfigurator - implements IFDocumentHandlerConfigurator { +public class PSRendererConfigurator extends DefaultRendererConfigurator + implements IFDocumentHandlerConfigurator { /** * Default constructor * @param userAgent user agent */ - public PSRendererConfigurator(FOUserAgent userAgent) { - super(userAgent); + public PSRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + super(userAgent, rendererConfigParser); } - /** - * Throws an UnsupportedOperationException. - * - * @param renderer not used - */ - public void configure(Renderer renderer) { - throw new UnsupportedOperationException(); - } - - private void configure(PSRenderingUtil psUtil, Configuration cfg) { - psUtil.setAutoRotateLandscape( - cfg.getChild("auto-rotate-landscape").getValueAsBoolean(false)); - Configuration child; - child = cfg.getChild("language-level"); - if (child != null) { - psUtil.setLanguageLevel(child.getValueAsInteger( - PSGenerator.DEFAULT_LANGUAGE_LEVEL)); + private void configure(PSRenderingUtil psUtil, PSRendererConfig psConfig) { + if (psConfig.isAutoRotateLandscape() != null) { + psUtil.setAutoRotateLandscape(psConfig.isAutoRotateLandscape()); + } + if (psConfig.getLanguageLevel() != null) { + psUtil.setLanguageLevel(psConfig.getLanguageLevel()); + } + if (psConfig.isOptimizeResources() != null) { + psUtil.setOptimizeResources(psConfig.isOptimizeResources()); } - child = cfg.getChild("optimize-resources"); - if (child != null) { - psUtil.setOptimizeResources(child.getValueAsBoolean(false)); + if (psConfig.isSafeSetPageDevice() != null) { + psUtil.setSafeSetPageDevice(psConfig.isSafeSetPageDevice()); } - child = cfg.getChild("rendering"); - if (child != null) { - psUtil.setRenderingMode(PSRenderingMode.valueOf( - child.getValue(psUtil.getRenderingMode().toString()) - .toUpperCase(Locale.ENGLISH))); + if (psConfig.isDscComplianceEnabled() != null) { + psUtil.setDSCComplianceEnabled(psConfig.isDscComplianceEnabled()); + } + if (psConfig.getRenderingMode() != null) { + psUtil.setRenderingMode(psConfig.getRenderingMode()); } - psUtil.setSafeSetPageDevice( - cfg.getChild("safe-set-page-device").getValueAsBoolean(false)); - psUtil.setDSCComplianceEnabled( - cfg.getChild("dsc-compliant").getValueAsBoolean(true)); } - /** {@inheritDoc} */ + @Override public void configure(IFDocumentHandler documentHandler) throws FOPException { - Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); - if (cfg != null) { - PSDocumentHandler psDocumentHandler = (PSDocumentHandler)documentHandler; - configure(psDocumentHandler.getPSUtil(), cfg); + PSRendererConfig psConfig = (PSRendererConfig) getRendererConfig(documentHandler); + if (psConfig != null) { + PSDocumentHandler psDocumentHandler = (PSDocumentHandler) documentHandler; + PSRenderingUtil psUtil = psDocumentHandler.getPSUtil(); + configure(psUtil, psConfig); } - } - } diff --git a/src/java/org/apache/fop/render/ps/PSRendererOption.java b/src/java/org/apache/fop/render/ps/PSRendererOption.java new file mode 100644 index 000000000..4c3396921 --- /dev/null +++ b/src/java/org/apache/fop/render/ps/PSRendererOption.java @@ -0,0 +1,57 @@ +/* + * 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.xmlgraphics.ps.PSGenerator; + +import org.apache.fop.render.RendererConfigOption; + +/** + * An enumeration of the PostScript renderer configuration options along with their default values. + */ +public enum PSRendererOption implements RendererConfigOption { + /** Indicates whether landscape pages should be rotated, default: false */ + AUTO_ROTATE_LANDSCAPE("auto-rotate-landscape", false), + /** Sets the PostScript language leven, default: {@see PSGenerator#DEFAULT_LANGUAGE_LEVEL}*/ + LANGUAGE_LEVEL("language-level", PSGenerator.DEFAULT_LANGUAGE_LEVEL), + /** Whether resources should be optimized in a post-processing run, default: false */ + OPTIMIZE_RESOURCES("optimize-resources", false), + /** Indicates whether the "safe setpagedevice" mode is active, default: false */ + SAFE_SET_PAGE_DEVICE("safe-set-page-device", false), + /** Indicates whether the PostScript output should be DSC compliant, default: true*/ + DSC_COMPLIANT("dsc-compliant", true), + RENDERING_MODE("rendering", PSRenderingMode.QUALITY); + + private final String name; + private final Object defaultValue; + + private PSRendererOption(String name, Object defaultValue) { + this.name = name; + this.defaultValue = defaultValue; + } + + public String getName() { + return name; + } + + public Object getDefaultValue() { + return defaultValue; + } +} diff --git a/src/java/org/apache/fop/render/ps/PSRenderingUtil.java b/src/java/org/apache/fop/render/ps/PSRenderingUtil.java index b22391718..4033c304f 100644 --- a/src/java/org/apache/fop/render/ps/PSRenderingUtil.java +++ b/src/java/org/apache/fop/render/ps/PSRenderingUtil.java @@ -33,11 +33,15 @@ import org.apache.fop.render.ps.extensions.PSCommentBefore; import org.apache.fop.render.ps.extensions.PSExtensionAttachment; import org.apache.fop.render.ps.extensions.PSSetupCode; +import static org.apache.fop.render.ps.PSRendererOption.AUTO_ROTATE_LANDSCAPE; +import static org.apache.fop.render.ps.PSRendererOption.LANGUAGE_LEVEL; +import static org.apache.fop.render.ps.PSRendererOption.OPTIMIZE_RESOURCES; + /** * Utility class which enables all sorts of features that are not directly connected to the * normal rendering process. */ -public class PSRenderingUtil implements PSConfigurationConstants { +public class PSRenderingUtil { private FOUserAgent userAgent; @@ -64,20 +68,21 @@ public class PSRenderingUtil implements PSConfigurationConstants { PSRenderingUtil(FOUserAgent userAgent) { this.userAgent = userAgent; + //PSRendererConfig confi = userAgent.getRendererConfig(rendererConfiguration, configCreator) initialize(); } private void initialize() { Object obj; - obj = userAgent.getRendererOptions().get(AUTO_ROTATE_LANDSCAPE); + obj = userAgent.getRendererOptions().get(AUTO_ROTATE_LANDSCAPE.getName()); if (obj != null) { setAutoRotateLandscape(booleanValueOf(obj)); } - obj = userAgent.getRendererOptions().get(LANGUAGE_LEVEL); + obj = userAgent.getRendererOptions().get(LANGUAGE_LEVEL.getName()); if (obj != null) { setLanguageLevel(intValueOf(obj)); } - obj = userAgent.getRendererOptions().get(OPTIMIZE_RESOURCES); + obj = userAgent.getRendererOptions().get(OPTIMIZE_RESOURCES.getName()); if (obj != null) { setOptimizeResources(booleanValueOf(obj)); } diff --git a/src/java/org/apache/fop/render/ps/PSSVGHandler.java b/src/java/org/apache/fop/render/ps/PSSVGHandler.java index c52f45332..e30f6391b 100644 --- a/src/java/org/apache/fop/render/ps/PSSVGHandler.java +++ b/src/java/org/apache/fop/render/ps/PSSVGHandler.java @@ -257,7 +257,7 @@ public class PSSVGHandler extends AbstractGenericSVGHandler BridgeContext ctx = new PSBridgeContext(ua, (strokeText ? null : psInfo.fontInfo), - context.getUserAgent().getFactory().getImageManager(), + context.getUserAgent().getImageManager(), context.getUserAgent().getImageSessionContext()); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) diff --git a/src/java/org/apache/fop/render/ps/PSTextPainter.java b/src/java/org/apache/fop/render/ps/PSTextPainter.java index 2b3afaec7..1f89dc8f0 100644 --- a/src/java/org/apache/fop/render/ps/PSTextPainter.java +++ b/src/java/org/apache/fop/render/ps/PSTextPainter.java @@ -52,7 +52,7 @@ import org.apache.fop.util.CharUtilities; import org.apache.fop.util.HexEncoder; /** - * Renders the attributed character iterator of a text node. + * Renders the attributed character iterator of a {@link org.apache.batik.gvt.TextNode TextNode}. * This class draws the text directly using PostScript text operators so * the text is not drawn using shapes which makes the PS files larger. * <p> diff --git a/src/java/org/apache/fop/render/ps/ResourceHandler.java b/src/java/org/apache/fop/render/ps/ResourceHandler.java index 5594897ba..95b544ec2 100644 --- a/src/java/org/apache/fop/render/ps/ResourceHandler.java +++ b/src/java/org/apache/fop/render/ps/ResourceHandler.java @@ -287,7 +287,7 @@ public class ResourceHandler implements DSCParserConstants, PSSupportedFlavors { throws IOException { final String uri = form.getImageURI(); - ImageManager manager = userAgent.getFactory().getImageManager(); + ImageManager manager = userAgent.getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = userAgent.getImageSessionContext(); @@ -299,7 +299,7 @@ public class ResourceHandler implements DSCParserConstants, PSSupportedFlavors { ImageFlavor[] flavors; ImageHandlerRegistry imageHandlerRegistry - = userAgent.getFactory().getImageHandlerRegistry(); + = userAgent.getImageHandlerRegistry(); flavors = imageHandlerRegistry.getSupportedFlavors(formContext); Map hints = ImageUtil.getDefaultHints(sessionContext); diff --git a/src/java/org/apache/fop/render/rtf/RTFHandler.java b/src/java/org/apache/fop/render/rtf/RTFHandler.java index 956ea8b57..6c2d7c03d 100644 --- a/src/java/org/apache/fop/render/rtf/RTFHandler.java +++ b/src/java/org/apache/fop/render/rtf/RTFHandler.java @@ -97,7 +97,6 @@ import org.apache.fop.fo.properties.EnumLength; import org.apache.fop.fonts.FontSetup; import org.apache.fop.layoutmgr.inline.ImageLayout; import org.apache.fop.layoutmgr.table.ColumnSetup; -import org.apache.fop.render.DefaultFontResolver; import org.apache.fop.render.RendererEventProducer; import org.apache.fop.render.rtf.rtflib.exceptions.RtfException; import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfAfterContainer; @@ -169,7 +168,7 @@ public class RTFHandler extends FOEventHandler { bDefer = true; boolean base14Kerning = false; - FontSetup.setup(fontInfo, null, new DefaultFontResolver(userAgent), base14Kerning); + FontSetup.setup(fontInfo, null, userAgent.getResourceResolver(), base14Kerning); } /** @@ -1086,7 +1085,7 @@ public class RTFHandler extends FOEventHandler { //set image data FOUserAgent userAgent = eg.getUserAgent(); - ImageManager manager = userAgent.getFactory().getImageManager(); + ImageManager manager = userAgent.getImageManager(); info = manager.getImageInfo(uri, userAgent.getImageSessionContext()); putGraphic(eg, info); @@ -1140,7 +1139,7 @@ public class RTFHandler extends FOEventHandler { ImageXMLDOM image = new ImageXMLDOM(info, doc, ns); FOUserAgent userAgent = ifo.getUserAgent(); - ImageManager manager = userAgent.getFactory().getImageManager(); + ImageManager manager = userAgent.getImageManager(); Map hints = ImageUtil.getDefaultHints(ua.getImageSessionContext()); Image converted = manager.convertImage(image, FLAVORS, hints); putGraphic(ifo, converted); @@ -1170,7 +1169,7 @@ public class RTFHandler extends FOEventHandler { throws IOException { try { FOUserAgent userAgent = abstractGraphic.getUserAgent(); - ImageManager manager = userAgent.getFactory().getImageManager(); + ImageManager manager = userAgent.getImageManager(); ImageSessionContext sessionContext = userAgent.getImageSessionContext(); Map hints = ImageUtil.getDefaultHints(sessionContext); Image image = manager.getImage(info, FLAVORS, hints, sessionContext); @@ -1701,7 +1700,7 @@ public class RTFHandler extends FOEventHandler { Region regionBefore = pagemaster.getRegion(Constants.FO_REGION_BEFORE); if (regionBefore != null) { - FONode staticBefore = (FONode) pageSequence.getFlowMap().get( + FONode staticBefore = pageSequence.getFlowMap().get( regionBefore.getRegionName()); if (staticBefore != null) { recurseFONode(staticBefore); @@ -1709,7 +1708,7 @@ public class RTFHandler extends FOEventHandler { } Region regionAfter = pagemaster.getRegion(Constants.FO_REGION_AFTER); if (regionAfter != null) { - FONode staticAfter = (FONode) pageSequence.getFlowMap().get( + FONode staticAfter = pageSequence.getFlowMap().get( regionAfter.getRegionName()); if (staticAfter != null) { recurseFONode(staticAfter); diff --git a/src/java/org/apache/fop/render/txt/TXTRendererConfigurator.java b/src/java/org/apache/fop/render/txt/TXTRendererConfigurator.java index 59c3bf5e6..a600047ae 100644 --- a/src/java/org/apache/fop/render/txt/TXTRendererConfigurator.java +++ b/src/java/org/apache/fop/render/txt/TXTRendererConfigurator.java @@ -19,24 +19,23 @@ package org.apache.fop.render.txt; -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.render.DefaultRendererConfigurator; import org.apache.fop.render.Renderer; +import org.apache.fop.render.RendererConfig.RendererConfigParser; /** * TXT Renderer configurator */ -public class TXTRendererConfigurator extends PrintRendererConfigurator { +public class TXTRendererConfigurator extends DefaultRendererConfigurator { /** * Default constructor * @param userAgent user agent */ - public TXTRendererConfigurator(FOUserAgent userAgent) { - super(userAgent); + public TXTRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) { + super(userAgent, rendererConfigParser); } /** @@ -45,10 +44,11 @@ public class TXTRendererConfigurator extends PrintRendererConfigurator { * @throws FOPException fop exception */ public void configure(Renderer renderer) throws FOPException { - Configuration cfg = super.getRendererConfig(renderer); - if (cfg != null) { - TXTRenderer txtRenderer = (TXTRenderer)renderer; - txtRenderer.setEncoding(cfg.getChild("encoding", true).getValue(null)); + TxtRendererConfig config = (TxtRendererConfig) getRendererConfig(renderer); + if (config != null) { + TXTRenderer txtRenderer = (TXTRenderer) renderer; + txtRenderer.setEncoding(config.getEncoding()); } } + } diff --git a/src/java/org/apache/fop/render/txt/TXTRendererMaker.java b/src/java/org/apache/fop/render/txt/TXTRendererMaker.java index 740866e0c..150338120 100644 --- a/src/java/org/apache/fop/render/txt/TXTRendererMaker.java +++ b/src/java/org/apache/fop/render/txt/TXTRendererMaker.java @@ -19,11 +19,12 @@ package org.apache.fop.render.txt; +import org.apache.fop.apps.FOPException; 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; +import org.apache.fop.render.txt.TxtRendererConfig.TxtRendererConfigParser; /** * RendererMaker for the Plain Text Renderer. @@ -32,22 +33,22 @@ public class TXTRendererMaker extends AbstractRendererMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_PLAIN_TEXT}; - /**{@inheritDoc} */ + @Override public Renderer makeRenderer(FOUserAgent userAgent) { return new TXTRenderer(userAgent); } - /**{@inheritDoc} */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return new TXTRendererConfigurator(userAgent); + @Override + public void configureRenderer(FOUserAgent userAgent, Renderer renderer) throws FOPException { + new TXTRendererConfigurator(userAgent, new TxtRendererConfigParser()).configure(renderer); } - /** {@inheritDoc} */ + @Override public boolean needsOutputStream() { return true; } - /** {@inheritDoc} */ + @Override public String[] getSupportedMimeTypes() { return MIMES; } diff --git a/src/java/org/apache/fop/render/txt/TxtRendererConfig.java b/src/java/org/apache/fop/render/txt/TxtRendererConfig.java new file mode 100644 index 000000000..f597ee518 --- /dev/null +++ b/src/java/org/apache/fop/render/txt/TxtRendererConfig.java @@ -0,0 +1,99 @@ +/* + * 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.txt; + +import java.util.EnumMap; + +import org.apache.avalon.framework.configuration.Configuration; + +import org.apache.fop.apps.FOPException; +import org.apache.fop.apps.FOUserAgent; +import org.apache.fop.apps.MimeConstants; +import org.apache.fop.fonts.DefaultFontConfig; +import org.apache.fop.fonts.DefaultFontConfig.DefaultFontConfigParser; +import org.apache.fop.render.RendererConfig; +import org.apache.fop.render.RendererConfigOption; + +/** + * The Text renderer configuration data object. + */ +public final class TxtRendererConfig implements RendererConfig { + + public enum TxtRendererOption implements RendererConfigOption { + ENCODING("encoding", "UTF-8"); + + private final String name; + private final Object defaultValue; + + private TxtRendererOption(String name, Object defaultValue) { + this.name = name; + this.defaultValue = defaultValue; + } + + public String getName() { + return name; + } + + public Object getDefaultValue() { + return defaultValue; + } + } + + private final EnumMap<TxtRendererOption, Object> params + = new EnumMap<TxtRendererOption, Object>(TxtRendererOption.class); + + private final DefaultFontConfig fontConfig; + + private TxtRendererConfig(DefaultFontConfig fontConfig) { + this.fontConfig = fontConfig; + } + + public DefaultFontConfig getFontInfoConfig() { + return fontConfig; + } + + public String getEncoding() { + return (String) params.get(TxtRendererOption.ENCODING); + } + + /** + * The Text renderer configuration data parser. + */ + public static final class TxtRendererConfigParser implements RendererConfigParser { + + /** {@inheritDoc} */ + public TxtRendererConfig build(FOUserAgent userAgent, Configuration cfg) throws FOPException { + TxtRendererConfig config = new TxtRendererConfig(new DefaultFontConfigParser().parse(cfg, + userAgent.validateStrictly())); + if (cfg != null) { + TxtRendererOption option = TxtRendererOption.ENCODING; + String value = cfg.getChild(option.getName(), true).getValue(null); + config.params.put(option, value != null ? value : option.getDefaultValue()); + } + return config; + } + + /** {@inheritDoc} */ + public String getMimeType() { + return MimeConstants.MIME_PLAIN_TEXT; + } + } + +} diff --git a/src/java/org/apache/fop/render/xml/XMLRendererMaker.java b/src/java/org/apache/fop/render/xml/XMLRendererMaker.java index f54c74b32..f0cd3a850 100644 --- a/src/java/org/apache/fop/render/xml/XMLRendererMaker.java +++ b/src/java/org/apache/fop/render/xml/XMLRendererMaker.java @@ -19,12 +19,15 @@ package org.apache.fop.render.xml; +import java.util.List; + +import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.MimeConstants; +import org.apache.fop.fonts.FontCollection; import org.apache.fop.render.AbstractRendererMaker; import org.apache.fop.render.PrintRendererConfigurator; import org.apache.fop.render.Renderer; -import org.apache.fop.render.RendererConfigurator; /** * RendererMaker for the Area Tree XML Renderer. @@ -33,22 +36,28 @@ public class XMLRendererMaker extends AbstractRendererMaker { private static final String[] MIMES = new String[] {MimeConstants.MIME_FOP_AREA_TREE}; - /**{@inheritDoc} */ + @Override public Renderer makeRenderer(FOUserAgent userAgent) { return new XMLRenderer(userAgent); } - /**{@inheritDoc} */ - public RendererConfigurator getConfigurator(FOUserAgent userAgent) { - return new PrintRendererConfigurator(userAgent); + @Override + public void configureRenderer(FOUserAgent userAgent, Renderer renderer) throws FOPException { + // TODO what constructor params? + new PrintRendererConfigurator(userAgent, null) { + @Override + protected List<FontCollection> getDefaultFontCollection() { + throw new UnsupportedOperationException(); + } + } .configure(renderer); } - /** {@inheritDoc} */ + @Override public boolean needsOutputStream() { return true; } - /** {@inheritDoc} */ + @Override public String[] getSupportedMimeTypes() { return MIMES; } |