libiscwt-java-5.3.20100629/0000755000175000017500000000000011412336240014754 5ustar twernertwernerlibiscwt-java-5.3.20100629/lib/0000755000175000017500000000000011412336240015522 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/0000755000175000017500000000000011412336240015543 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/overview.html0000644000175000017500000000164211055222542020304 0ustar twernertwerner This is a window toolkit and basic rendering abstraction layer.

Content

  1. Overview
  2. Implementation Details
  3. License
  4. Service and support

Overview

License

Service & Support

If you need further support, feel free to contact us. intarsys consulting GmbH
Bahnhofplatz 8
76137 Karlsruhe
Fon +49 721 38479-0
Fax +49 721 38479-60
info@intarsys.de
www.intarsys.de

For service and support contact

  1. EMail support: support@intarsys.de
libiscwt-java-5.3.20100629/src/de/0000755000175000017500000000000011412336240016133 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/0000755000175000017500000000000011412336240020007 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/0000755000175000017500000000000011412336240020604 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/common/0000755000175000017500000000000011412336240022074 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/common/IGraphicsObject.java0000644000175000017500000000342311052336546025752 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.common; /** * An abstract super interface for objects used in the rendering process. * */ public interface IGraphicsObject { public Object getData(); public void setData(Object data); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/common/IPaint.java0000644000175000017500000000376311052336546024145 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.common; import de.intarsys.cwt.environment.IGraphicsContext; /** * */ public interface IPaint { /** * @return */ public IPaint copy(); public float getAlphaValue(); public void setAlphaValue(float value); public void setBackgroundPaintFromGraphicsContext( IGraphicsContext graphicsContext); public void setForegroundPaintFromGraphicsContext( IGraphicsContext graphicsContext); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/common/BlendMode.java0000644000175000017500000000416011031105670024567 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.common; import de.intarsys.tools.enumeration.EnumItem; import de.intarsys.tools.enumeration.EnumMeta; /** * The available rendering modes. */ public class BlendMode extends EnumItem { public static final BlendMode NORMAL = new BlendMode("normal"); public static final BlendMode MULTIPLY = new BlendMode("multiply"); /** The meta data for the enumeration. */ public static final EnumMeta META = getMeta(BlendMode.class); static { NORMAL.setDefault(); } public BlendMode(String id) { super(id); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/common/IShape.java0000644000175000017500000000325011031105670024106 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.common; import java.awt.Shape; public interface IShape extends IGraphicsObject, Shape { } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/common/ShapeWrapper.java0000644000175000017500000000617511131667154025362 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.common; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import de.intarsys.tools.geometry.IShapeWrapper; public class ShapeWrapper implements IShape, IShapeWrapper { private Object data; private Shape shape; public ShapeWrapper(Shape shape) { super(); this.shape = shape; } public boolean contains(double x, double y) { return shape.contains(x, y); } public boolean contains(double x, double y, double w, double h) { return shape.contains(x, y, w, h); } public boolean contains(Point2D p) { return shape.contains(p); } public boolean contains(Rectangle2D r) { return shape.contains(r); } public Shape getBaseShape() { return shape; } public Rectangle getBounds() { return shape.getBounds(); } public Rectangle2D getBounds2D() { return shape.getBounds2D(); } public Object getData() { return data; } public PathIterator getPathIterator(AffineTransform at) { return shape.getPathIterator(at); } public PathIterator getPathIterator(AffineTransform at, double flatness) { return shape.getPathIterator(at, flatness); } public Shape getShape() { return shape; } public boolean intersects(double x, double y, double w, double h) { return shape.intersects(x, y, w, h); } public boolean intersects(Rectangle2D r) { return shape.intersects(r); } public void setData(Object pData) { data = pData; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/image/0000755000175000017500000000000011412336240021666 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/image/ImageException.java0000644000175000017500000000405711031105674025442 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.image; /** * * */ public class ImageException extends RuntimeException { /** * */ public ImageException() { super(); } /** * @param message */ public ImageException(String message) { super(message); } /** * @param message * @param cause */ public ImageException(String message, Throwable cause) { super(message, cause); } /** * @param cause */ public ImageException(Throwable cause) { super(cause); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/image/ImageTools.java0000644000175000017500000000741111411054016024574 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.image; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import javax.imageio.IIOException; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataFormatImpl; import javax.imageio.stream.ImageInputStream; import org.w3c.dom.Node; public class ImageTools { public static String extractJPEGColorSpaceType(ImageReader reader) throws IOException { IIOMetadata metadata; Node node; Node allegedChromaNode; Node allegedColorNode; Node name; try { metadata = reader.getImageMetadata(0); } catch (RuntimeException ex) { throw new ImageException(ex); } catch (IIOException ex) { throw new ImageException(ex); } node = metadata .getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName); /* * expect wanted nodes to always be there and to always have the needed * attribute */ allegedChromaNode = node.getFirstChild(); while (!allegedChromaNode.getLocalName().equals("Chroma")) { //$NON-NLS-1$ allegedChromaNode = allegedChromaNode.getNextSibling(); } allegedColorNode = allegedChromaNode.getFirstChild(); while (!allegedColorNode.getLocalName().equals("ColorSpaceType")) { //$NON-NLS-1$ allegedColorNode = allegedColorNode.getNextSibling(); } if ((name = allegedColorNode.getAttributes().getNamedItem("name")) == null) { //$NON-NLS-1$ throw new ImageException("color space not declared"); //$NON-NLS-1$ } return name.getNodeValue(); } public static String extractJPEGColorSpaceType(InputStream stream) throws IOException { ImageInputStream imageStream; imageStream = ImageIO.createImageInputStream(stream); try { Iterator readers; ImageReader reader; readers = ImageIO.getImageReaders(imageStream); if (!readers.hasNext()) { throw new ImageException("no reader for this image type"); } reader = readers.next(); try { imageStream.reset(); reader.setInput(imageStream); return extractJPEGColorSpaceType(reader); } finally { reader.dispose(); } } finally { imageStream.close(); } } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/image/IImageEntry.java0000644000175000017500000000342411032364662024720 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.image; import de.intarsys.tools.attribute.IAttributeSupport; public interface IImageEntry extends IImage, IAttributeSupport { public IImageContainer getContainer(); public int getIndex(); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/image/ImageContainer.java0000644000175000017500000000452411031105674025425 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.image; import java.io.IOException; import java.util.HashMap; import java.util.Map; /* * DOCME */ public abstract class ImageContainer implements IImageContainer { private boolean closed; private Map attributes = new HashMap(); protected ImageContainer() { super(); } abstract protected void basicClose() throws IOException; public void close() throws IOException { if (closed) { throw new IllegalStateException("already closed"); } closed = true; basicClose(); } public Object getAttribute(Object key) { return attributes.get(key); } public Object removeAttribute(Object key) { return attributes.remove(key); } public Object setAttribute(Object key, Object o) { return attributes.put(key, o); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/image/ImageMetadata.java0000644000175000017500000000672411031105674025227 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.image; import java.io.IOException; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import org.w3c.dom.Node; public class ImageMetadata { public static ImageMetadata createFromImageReader(ImageReader imageReader) throws IOException { IIOMetadata[] imageMetadata; imageMetadata = new IIOMetadata[imageReader.getNumImages(true)]; for (int index = 0; index < imageMetadata.length; index++) { imageMetadata[index] = imageReader.getImageMetadata(index); } return new ImageMetadata(imageReader.getStreamMetadata(), imageMetadata); } private IIOMetadata[] imageMetadata; private IIOMetadata streamMetadata; protected ImageMetadata() { super(); } public ImageMetadata(IIOMetadata paramStreamMetadata, IIOMetadata[] paramImageMetadata) { streamMetadata = paramStreamMetadata; imageMetadata = paramImageMetadata; } public Node getAsTree(String formatName) { Node root; root = new IIOMetadataNode("root"); if (streamMetadata != null) { root.appendChild(streamMetadata.getAsTree(formatName)); } for (int index = 0; index < imageMetadata.length; index++) { Node node; node = new IIOMetadataNode(String.valueOf(index)); root.appendChild(node); node.appendChild(imageMetadata[index].getAsTree(formatName)); } return root; } public IIOMetadata[] getImageMetadata() { return imageMetadata; } public String getNativeMetadataFormatName() { // expect at least 1 image metadata entry return imageMetadata[0].getNativeMetadataFormatName(); } public IIOMetadata getStreamMetadata() { return streamMetadata; } protected void setImageMetadata(IIOMetadata[] paramMetadata) { imageMetadata = paramMetadata; } protected void setStreamMetadata(IIOMetadata paramMetadata) { streamMetadata = paramMetadata; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/image/IImage.java0000644000175000017500000000347411032364662023703 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.image; import de.intarsys.cwt.environment.IGraphicsContext; public interface IImage { public void drawFromGraphicsContext(IGraphicsContext graphicsContext, float x, float y); public int getHeight(); public int getWidth(); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/image/IImageContainer.java0000644000175000017500000000375411037360164025545 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.image; import java.io.IOException; import de.intarsys.tools.attribute.IAttributeSupport; import de.intarsys.tools.locator.ILocator; public interface IImageContainer extends IAttributeSupport { public void close() throws IOException; public IImageEntry getImageAt(int index); public int getImageCount(); public ILocator getLocator(); public ImageMetadata getMetadata() throws IOException; } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/image/ImageEntry.java0000644000175000017500000000563111200605564024605 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.image; import java.io.IOException; import java.lang.ref.SoftReference; import de.intarsys.tools.attribute.AttributeMap; public abstract class ImageEntry implements IImageEntry { final private IImageContainer container; final private AttributeMap attributes = new AttributeMap(); private SoftReference delegate; protected ImageEntry(IImageContainer container) { super(); this.container = container; } public Object getAttribute(Object key) { return attributes.get(key); } public IImageContainer getContainer() { return container; } synchronized protected IImage getDelegate() { IImage image = null; if (delegate != null) { image = (IImage) delegate.get(); } if (image == null) { try { image = loadContent(); } catch (Exception e) { image = getErrorImage(e); } delegate = new SoftReference(image); } return image; } abstract protected IImage getErrorImage(Exception e); public int getHeight() { return getDelegate().getHeight(); } public int getWidth() { return getDelegate().getWidth(); } abstract protected IImage loadContent() throws IOException; public Object removeAttribute(Object key) { return attributes.remove(key); } public Object setAttribute(Object key, Object o) { return attributes.put(key, o); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/0000755000175000017500000000000011412336240021552 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/CommonFontProgram.java0000644000175000017500000000373711031105670026034 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; import de.intarsys.tools.locator.ILocator; abstract public class CommonFontProgram implements IFontProgram { final private ILocator locator; final private IFont font; public CommonFontProgram(IFont font, ILocator locator) { this.font = font; this.locator = locator; } public IFont getFont() { return font; } public ILocator getLocator() { return locator; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/type1/0000755000175000017500000000000011412336240022614 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/type1/Type1Font.java0000644000175000017500000000653011031105700025304 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.type1; import java.io.IOException; import de.intarsys.cwt.font.FontStyle; import de.intarsys.cwt.font.FontTools; import de.intarsys.cwt.font.afm.AFM; import de.intarsys.tools.locator.ILocator; /** * This is the skeleton for a type 1 font implementation. Up to now, we only * need the font metrics (.afm) part. */ public class Type1Font { public static Type1Font createFromLocator(ILocator locator) throws IOException { Type1Font result = new Type1Font(); result.setLocator(locator); result.initializeFromLocator(); return result; } private AFM afm; private ILocator locator; public Type1Font() { } public Type1Font(AFM afm) { this.afm = afm; } public String getFontFamilyName() { return FontTools.getFontFamilyName(getFontName()); } synchronized public AFM getFontMetrics() { return afm; } public String getFontName() { return afm.getFontName(); } public FontStyle getFontStyle() { return FontTools.getFontStyle(getFontName()); } public ILocator getLocator() { return locator; } protected void initializeAfm() throws IOException { ILocator parentLocator = getLocator().getParent(); if (parentLocator == null) { // can't lookup font metrics... return; } String localName = getLocator().getLocalName(); ILocator afmLocator = parentLocator.getChild(localName + ".afm"); afm = AFM.createFromLocator(afmLocator); } protected void initializeFromLocator() throws IOException { initializePfb(); initializeAfm(); } protected void initializePfb() { // currently we do not parse any information from the pfb.. } public boolean isSymbolFont() { return false; } protected void setLocator(ILocator locator) { this.locator = locator; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/IFontRegistry.java0000644000175000017500000000566111061743412025200 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; /** * A registry of {@link IFont} instances. * */ public interface IFontRegistry { /** * The {@link IFontFamily} instances formed by the {@link IFont} instances * in this {@link IFontRegistry}. * * @return The {@link IFontFamily} instances formed by the {@link IFont} * instances in this {@link IFontRegistry}. */ public IFontFamily[] getFontFamilies(); /** * The {@link IFont} instances in this {@link IFontRegistry}. * * @return The {@link IFont} instances in this {@link IFontRegistry}. * */ public IFont[] getFonts(); /** * The {@link IFont} selected by the {@link IFontQuery}. * * @param query * A {@link IFontQuery} describing a single {@link IFont}. * * @return The {@link IFont} selected by the {@link IFontQuery}. * */ public IFont lookupFont(IFontQuery query); /** * The {@link IFontFamily} selected by the {@link IFontQuery}. * * @param query * A {@link IFontQuery} describing a single {@link IFontFamily}. * * @return The {@link IFontFamily} selected by the {@link IFontQuery}. * */ public IFontFamily lookupFontFamily(IFontQuery query); /** * Add a new {@link IFont} to the {@link IFontRegistry}. * * @param font * The new {@link IFont} */ public void registerFont(IFont font); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontMapper.java0000644000175000017500000000526011041622672024500 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; import java.util.HashMap; import java.util.Map; /** * */ public class FontMapper { private static FontMapper Active = new FontMapper(); public static synchronized FontMapper get() { return Active; } public static synchronized void set(FontMapper mapper) { Active = mapper; } private Map fontMaps = new HashMap(); protected FontMapper() { super(); } public IFont lookupFont(String name) { FontMap fontMap = fontMaps.get(normalize(name)); if (fontMap == null) { return null; } return fontMap.getFont(); } protected String normalize(String name) { if (name == null) { return null; } return name.toLowerCase(); // StringBuilder result = new StringBuilder(); // for (int i = 0; i < name.length(); i++) { // char c = name.charAt(i); // if ((c == ' ') || (c == '_') || (c == '-')) { // continue; // } // result.append(Character.toLowerCase(c)); // } // return result.toString(); } public void registerFontMap(FontMap map) { fontMaps.put(normalize(map.getKey()), map); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontRegistry.java0000644000175000017500000000347211031105672025062 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; public class FontRegistry { private static IFontRegistry ACTIVE = new StandardFontRegistry(); static public IFontRegistry get() { return ACTIVE; } static public void set(IFontRegistry active) { ACTIVE = active; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/GenericFontProgram.java0000644000175000017500000000343311031105672026153 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; import de.intarsys.tools.locator.ILocator; public class GenericFontProgram extends CommonFontProgram { protected GenericFontProgram(IFont font, ILocator locator) { super(font, locator); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/GenericFont.java0000644000175000017500000001124611054474720024634 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; import de.intarsys.cwt.freetype.Face; import de.intarsys.cwt.freetype.SfntName; import de.intarsys.tools.locator.ILocator; public class GenericFont extends CommonFont { public static GenericFont createNew(ILocator locator, Face face) { String fontPSName = face.getPostscriptName(); String familyName = face.getFamilyName(); String styleName = face.getStyleName(); String fontName = null; // look up font name for TrueType int sfntCount = face.getSfntNameCount(); for (int i = 0; i < sfntCount; i++) { SfntName sfntName = face.getSfntName(i); if (sfntName.getNameId() == 4) { // full font name fontName = sfntName.getName(); if (sfntName.getPlatformId() == 3) { // try to use the microsoft platform name break; } } } if (fontPSName == null) { fontPSName = familyName; } if (fontName == null) { fontName = fontPSName; } FontStyle style = FontStyle.getFontStyle(styleName); // ...little bit ugly, but clean up someday GenericFont font = new GenericFont(); GenericFontProgram fontProgram = new GenericFontProgram(font, locator); font.setFontProgram(fontProgram); font.setFontFamilyName(familyName); font.setFontNamePostScript(fontPSName); font.setFontName(fontName); font.setFontStyle(style); String type = locator.getType(); if (type != null) { type = type.toLowerCase(); } if ("ttf".equals(type) || "ttc".equals(type) || "otf".equals(type) || "otc".equals(type)) { font.setFontType("TrueType"); } else if ("pfb".equals(type)) { font.setFontType("Type1"); } else { font.setFontType("Unknown"); } return font; } private String fontType; private String fontName; private String fontNamePostScript; private String fontFamilyName; private FontStyle fontStyle; protected GenericFont() { super(); } public String getFontFamilyName() { return fontFamilyName; } public String getFontName() { return fontName; } public String getFontNameCanonical() { String tempFamilyName = null; FontStyle tempStyle = null; if (getFontFamilyName() == null) { tempFamilyName = FontTools.getFontFamilyName(getFontName()); } else { tempFamilyName = getFontFamilyName(); } if (getFontStyle() == null) { tempStyle = FontTools.getFontStyle(getFontName()); } else { tempStyle = getFontStyle(); } return FontTools.createCanonicalName(tempFamilyName, tempStyle.getId()); } public String getFontNamePostScript() { return fontNamePostScript; } public FontStyle getFontStyle() { return fontStyle; } public String getFontType() { return fontType; } protected void setFontFamilyName(String familyName) { this.fontFamilyName = familyName; } protected void setFontName(String fontName) { this.fontName = fontName; } protected void setFontNamePostScript(String fontPSName) { this.fontNamePostScript = fontPSName; } protected void setFontStyle(FontStyle style) { this.fontStyle = style; } protected void setFontType(String fontType) { this.fontType = fontType; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontQuery.java0000644000175000017500000000342411054474720024364 0ustar twernertwernerpackage de.intarsys.cwt.font; public class FontQuery implements IFontQuery { /** * The font type requested */ private String fontType = null; /** * The font family requested */ private String fontFamilyName; /** * The font name requested */ private String fontName; /** * The font style required */ private FontStyle fontStyle; public FontQuery() { super(); } public FontQuery(String fontName) { super(); setFontName(fontName); } public FontQuery(String family, FontStyle style) { super(); setFontFamilyName(family); setFontStyle(style); } public FontQuery(String family, String style) { super(); setFontFamilyName(family); setFontStyle(FontStyle.getFontStyle(style)); } public String getFontFamilyName() { if (fontFamilyName == null) { return FontTools.getFontFamilyName(fontName); } else { return fontFamilyName; } } public String getFontName() { return fontName; } public Object getFontNameCanonical() { String tempFamilyName = getFontFamilyName(); FontStyle tempStyle = null; if (getFontStyle() == null) { tempStyle = FontTools.getFontStyle(fontName); } else { tempStyle = getFontStyle(); } return FontTools.createCanonicalName(tempFamilyName, tempStyle.getId()); } public FontStyle getFontStyle() { return fontStyle; } public String getFontType() { return fontType; } public void setFontFamilyName(String fontFamilyName) { this.fontFamilyName = fontFamilyName; } public void setFontName(String fontName) { this.fontName = fontName; } public void setFontStyle(FontStyle fontStyle) { this.fontStyle = fontStyle; } public void setFontType(String fontType) { this.fontType = fontType; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontStyle.java0000644000175000017500000000666511041675144024370 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; /** * */ public class FontStyle { /** The number of font styles */ public static final int COUNT = 4; /** The enumeration of supported font styles */ public static final FontStyle UNDEFINED = new FontStyle("?", -1); //$NON-NLS-1$ public static final FontStyle REGULAR = new FontStyle("Regular", 0); //$NON-NLS-1$ public static final FontStyle ITALIC = new FontStyle("Italic", 1); //$NON-NLS-1$ public static final FontStyle BOLD = new FontStyle("Bold", 2); //$NON-NLS-1$ public static final FontStyle BOLD_ITALIC = new FontStyle("BoldItalic", 3); //$NON-NLS-1$ public static FontStyle getFontStyle(String name) { if (name == null) { return REGULAR; } name = name.trim().toLowerCase(); boolean bold = false; boolean italic = false; if (name.indexOf("bold") >= 0) { //$NON-NLS-1$ bold = true; } if (name.indexOf("italic") >= 0) { //$NON-NLS-1$ italic = true; } if (name.indexOf("oblique") >= 0) { //$NON-NLS-1$ italic = true; } if (bold) { if (italic) { return BOLD_ITALIC; } else { return BOLD; } } else { if (italic) { return ITALIC; } else { return REGULAR; } } } /** The external representation of the font style */ private final String id; private final int index; private FontStyle(String label, int index) { this.id = label; this.index = index; } public FontStyle getBoldFlavor() { if (this == FontStyle.ITALIC) { return FontStyle.BOLD_ITALIC; } else { return FontStyle.BOLD; } } public String getId() { return id; } protected int getIndex() { return index; } public FontStyle getItalicFlavor() { if (this == FontStyle.BOLD) { return FontStyle.BOLD_ITALIC; } else { return FontStyle.ITALIC; } } @Override public String toString() { return getId(); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/IFont.java0000644000175000017500000000512211061743412023437 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; /** * An abstract font description object. * */ public interface IFont { /** * The font family name * * @return The font family name */ public String getFontFamilyName(); /** * The font name. This may deviate from the postscript font name for * TrueType fonts. * * @return The font name. */ public String getFontName(); /** * The canonical font name. * * @return The canonical font name. */ public String getFontNameCanonical(); /** * The postscript font name. * * @return The postscript font name. */ public String getFontNamePostScript(); /** * The referenced {@link IFontProgram}. * * @return The referenced {@link IFontProgram}. */ public IFontProgram getFontProgram(); /** * The font style. * * @return The font style. */ public FontStyle getFontStyle(); /** * The font type. This is for example "TrueType" or "Type1". * * @return The font type. */ public String getFontType(); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontMap.java0000644000175000017500000000407111031105670023761 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; /** * */ public abstract class FontMap { final private String name; final private FontMapper mapper; public FontMap(FontMapper mapper, String name) { super(); this.mapper = mapper; this.name = name; } public abstract IFont getFont(); public String getKey() { if (name == null) { return null; } return getName().toLowerCase(); } public FontMapper getMapper() { return mapper; } public String getName() { return name; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontFamily.java0000644000175000017500000000670011061743412024473 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * An abstraction of a fonts family. */ public class FontFamily implements IFontFamily { private final IFont[] fonts; private String name = ""; private String type = ""; public FontFamily(String name) { fonts = new IFont[FontStyle.COUNT]; this.name = name; } public String getFamilyName() { return name; } public IFont getFont(FontStyle style) { return fonts[style.getIndex()]; } public Iterator getFontIterator() { return new Iterator() { int index = 0; public boolean hasNext() { while (index < fonts.length) { if (fonts[index] != null) { return true; } index++; } return false; } public IFont next() { while (index < fonts.length) { if (fonts[index] != null) { return fonts[index++]; } index++; } throw new NoSuchElementException("no more fonts"); //$NON-NLS-1$ } public void remove() { throw new UnsupportedOperationException("can not remove font"); //$NON-NLS-1$ } }; } public IFont[] getFonts() { List result = new ArrayList(); for (int i = 0; i < fonts.length; i++) { if (fonts[i] != null) { result.add(fonts[i]); } } return result.toArray(new IFont[result.size()]); } public FontStyle[] getFontStyles() { List result = new ArrayList(); for (int i = 0; i < fonts.length; i++) { if (fonts[i] != null) { result.add(fonts[i].getFontStyle()); } } return result.toArray(new FontStyle[result.size()]); } public String getFontType() { return type; } public void registerFont(IFont font) { fonts[font.getFontStyle().getIndex()] = font; type = font.getFontType(); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/CommonFont.java0000644000175000017500000000357411031105672024505 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; abstract public class CommonFont implements IFont { private IFontProgram fontProgram; public CommonFont() { // } public IFontProgram getFontProgram() { return fontProgram; } protected void setFontProgram(IFontProgram fontProgram) { this.fontProgram = fontProgram; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/PACKAGE.java0000644000175000017500000000372511031105670023455 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; import java.util.logging.Logger; import de.intarsys.tools.logging.LogTools; import de.intarsys.tools.message.MessageBundle; import de.intarsys.tools.message.MessageBundleTools; public class PACKAGE { public final static MessageBundle Messages = MessageBundleTools .getMessageBundle(PACKAGE.class); public final static Logger Log = LogTools.getLogger(PACKAGE.class); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/IFontProgram.java0000644000175000017500000000362311061743412024773 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; import de.intarsys.tools.locator.ILocatorSupport; /** * An abstraction of the font program. * */ public interface IFontProgram extends ILocatorSupport { /** * The {@link IFont} implemented by this program. * * @return The {@link IFont} implemented by this program. */ public IFont getFont(); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontTools.java0000644000175000017500000000662011411054016024345 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; public class FontTools { static public String createCanonicalName(IFont font) { return createCanonicalName(font.getFontFamilyName(), font .getFontStyle().getId()); } static public String createCanonicalName(String fontFamilyName, String styleName) { return fontFamilyName.replaceAll("\\s", "") + "," + styleName; } public static String getFontFamilyName(String fontName) { if (fontName == null) { return null; } int posMinus = fontName.indexOf('-'); if (posMinus > 0) { fontName = fontName.substring(0, posMinus); } return fontName; } public static FontStyle getFontStyle(String fontName) { if (fontName == null) { return FontStyle.REGULAR; } int posMinus = fontName.indexOf('-'); if (posMinus > 0) { fontName = fontName.substring(posMinus + 1); } return FontStyle.getFontStyle(fontName); } static public IFont lookupFont(IFontQuery query) { IFont result = lookupFontOrMap(query); if (result == null && FontEnvironment.get().registerUserFonts()) { result = lookupFontOrMap(query); } // do not nest in the condition above! if (result == null && FontEnvironment.get().registerSystemFonts()) { result = lookupFontOrMap(query); } return result; } static protected IFont lookupFontOrMap(IFontQuery query) { IFont result = FontRegistry.get().lookupFont(query); if (result == null) { result = FontMapper.get().lookupFont(query.getFontName()); } return result; } static public void mapAlias(String name, String alias) { FontAliasMap map = new FontAliasMap(FontMapper.get(), name, alias); FontMapper.get().registerFontMap(map); } static public void mapFont(String name, IFont font) { FontFontMap map = new FontFontMap(FontMapper.get(), name, font); FontMapper.get().registerFontMap(map); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/afm/0000755000175000017500000000000011412336240022315 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/afm/package.html0000644000175000017500000000036011001364560024575 0ustar twernertwerner The afm parsing and model component.

This is separated from the other font related stuff, as there are no real dependencies into them and as such can be deployed standalone, for example with jPod. libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/afm/AFMParser.java0000644000175000017500000002405411061475664024763 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.afm; import java.io.IOException; import java.util.Arrays; import de.intarsys.tools.collection.ByteArrayTools; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.stream.FastByteArrayOutputStream; /** * A simple parser for AFM type definition files. * *

* See the "Adobe Font Metrics File Format Specification" *

*/ public class AFMParser { protected static final byte[] characterClass = new byte[256]; protected static final byte CHARCLASS_ANY = 0; protected static final byte CHARCLASS_DELIMITER = 1; protected static final byte CHARCLASS_DIGIT = 4; protected static final byte CHARCLASS_NUMBERSPECIAL = 5; protected static final byte CHARCLASS_TOKEN = 3; protected static final byte CHARCLASS_WHITESPACE = 2; private static final byte[] TOKEN_Comment = "Comment".getBytes(); //$NON-NLS-1$ private static final byte[] TOKEN_EndCharMetrics = "EndCharMetrics".getBytes(); //$NON-NLS-1$ private static final byte[] TOKEN_EndFlag = "End".getBytes(); //$NON-NLS-1$ private static final byte[] TOKEN_EndFontMetrics = "EndFontMetrics".getBytes(); //$NON-NLS-1$ private static final byte[] TOKEN_StartCharMetrics = "StartCharMetrics".getBytes(); //$NON-NLS-1$ private static final byte[] TOKEN_StartFlag = "Start".getBytes(); //$NON-NLS-1$ private static final byte[] TOKEN_StartFontMetrics = "StartFontMetrics".getBytes(); //$NON-NLS-1$ public static char CHAR_BS = '\b'; public static char CHAR_CR = '\r'; public static char CHAR_FF = '\f'; public static char CHAR_HT = '\t'; public static char CHAR_LF = '\n'; static { for (int i = 0; i < 256; i++) { characterClass[i] = CHARCLASS_ANY; } // delimiters characterClass['('] = CHARCLASS_DELIMITER; characterClass[')'] = CHARCLASS_DELIMITER; characterClass['<'] = CHARCLASS_DELIMITER; characterClass['>'] = CHARCLASS_DELIMITER; characterClass['['] = CHARCLASS_DELIMITER; characterClass[']'] = CHARCLASS_DELIMITER; characterClass['{'] = CHARCLASS_DELIMITER; characterClass['}'] = CHARCLASS_DELIMITER; characterClass['/'] = CHARCLASS_DELIMITER; characterClass['%'] = CHARCLASS_DELIMITER; // whitespace characterClass[' '] = CHARCLASS_WHITESPACE; characterClass['\t'] = CHARCLASS_WHITESPACE; characterClass['\r'] = CHARCLASS_WHITESPACE; characterClass['\n'] = CHARCLASS_WHITESPACE; characterClass[12] = CHARCLASS_WHITESPACE; characterClass[0] = CHARCLASS_WHITESPACE; // digits characterClass['0'] = CHARCLASS_DIGIT; characterClass['1'] = CHARCLASS_DIGIT; characterClass['2'] = CHARCLASS_DIGIT; characterClass['3'] = CHARCLASS_DIGIT; characterClass['4'] = CHARCLASS_DIGIT; characterClass['5'] = CHARCLASS_DIGIT; characterClass['6'] = CHARCLASS_DIGIT; characterClass['7'] = CHARCLASS_DIGIT; characterClass['8'] = CHARCLASS_DIGIT; characterClass['9'] = CHARCLASS_DIGIT; // number special characterClass['.'] = CHARCLASS_NUMBERSPECIAL; characterClass['-'] = CHARCLASS_NUMBERSPECIAL; characterClass['+'] = CHARCLASS_NUMBERSPECIAL; // alpha for (int i = 'a'; i <= 'z'; i++) { characterClass[i] = CHARCLASS_TOKEN; } for (int i = 'A'; i <= 'Z'; i++) { characterClass[i] = CHARCLASS_TOKEN; } } /** * evaluate to true if i is a valid line terminator. * * @param i * i a byte representation * * @return true if i is a valid line terminator */ public static final boolean isEOL(int i) { return (i == CHAR_CR) || (i == CHAR_LF) || (i == 12); } /** * evaluate to true if i is a valid whitespace. * * @param i * i a byte representation * * @return true if i is a valid whitespace */ public static final boolean isWhitespace(int i) { return characterClass[i] == CHARCLASS_WHITESPACE; } private AFM afm; private FastByteArrayOutputStream localStream = new FastByteArrayOutputStream(); /** * AFMParser constructor comment. */ public AFMParser(AFM afm) { super(); this.afm = afm; } /** * Parse a {@link AFM} object from the input stream is. * * @param is * The input stream containing the definition. * * @return The {@link AFM } parsed. * * @throws IOException */ public AFM parse(IRandomAccess random) throws IOException { read(random); return afm; } protected void read(IRandomAccess random) throws IOException { byte[] token = readToken(random); if (!Arrays.equals(token, TOKEN_StartFontMetrics)) { throw new IOException("afm stream does not start with " //$NON-NLS-1$ + new String(TOKEN_StartFontMetrics)); } readToken(random); token = readFontMetrics(random); if (token == null || !Arrays.equals(token, TOKEN_EndFontMetrics)) { throw new IOException("afm stream does not end with " //$NON-NLS-1$ + new String(TOKEN_EndFontMetrics)); } } /** * ignore this and any nested Start/End pair */ protected byte[] readBlock(IRandomAccess random) throws IOException { byte[] line = readLine(random); while (!ByteArrayTools.startsWith(line, TOKEN_EndFlag)) { if (ByteArrayTools.startsWith(line, TOKEN_Comment)) { // ignore } else { if (ByteArrayTools.startsWith(line, TOKEN_StartFlag)) { line = readBlock(random); } } line = readLine(random); } return line; } protected byte[] readCharMetrics(IRandomAccess random) throws IOException { // read count readToken(random); byte[] line = readLine(random); while (!ByteArrayTools.startsWith(line, TOKEN_EndCharMetrics)) { afm.addChar(AFMChar.create(new String(line))); line = readLine(random); } return line; } protected byte[] readFontMetrics(IRandomAccess random) throws IOException { byte[] token = readToken(random); while ((token != null) && !Arrays.equals(token, TOKEN_EndFontMetrics)) { if (Arrays.equals(token, TOKEN_Comment)) { // ignore line? } else { if (Arrays.equals(token, TOKEN_StartCharMetrics)) { token = readCharMetrics(random); } else { if (ByteArrayTools.startsWith(token, TOKEN_StartFlag)) { token = readBlock(random); } else { String value = new String(readLine(random)); afm.setAttribute(new String(token), value); } } } token = readToken(random); } return token; } /** * read a single line. * * @return the array of characters belonging to the line * * @throws IOException */ public byte[] readLine(IRandomAccess input) throws IOException { int next; while (true) { next = input.read(); if (next == -1) { return null; } else if ((next == ' ') || isWhitespace(next)) { continue; } else { break; } } return readLineElement(input, next); } protected byte[] readLineElement(IRandomAccess input, int next) throws IOException { localStream.reset(); localStream.write(next); do { next = input.read(); if (next == -1) { break; } else if (isEOL(next)) { // performance // shortcut break; } localStream.write(next); } while (true); return localStream.toByteArray(); } /** * read all characters until EOF or non space char appears. the first non * space char is pushed back so the next char read is the first non space * char. * * @throws IOException */ public void readSpaces(IRandomAccess input) throws IOException { int next = 0; while (true) { next = input.read(); if (next == -1) { break; } // performance shortcut for simple space if ((next == ' ') || isWhitespace(next)) { continue; } input.seekBy(-1); break; } } /** * read a single token. * * @return the array of characters belonging to the token * * @throws IOException */ public byte[] readToken(IRandomAccess input) throws IOException { int next; while (true) { next = input.read(); if (next == -1) { return null; } else if ((next == ' ') || isWhitespace(next)) { continue; } else { break; } } return readTokenElement(input, next); } protected byte[] readTokenElement(IRandomAccess input, int next) throws IOException { localStream.reset(); localStream.write(next); do { next = input.read(); if (next == -1) { break; } else if ((next == ' ') || isWhitespace(next)) { // performance // shortcut break; } localStream.write(next); } while (true); return localStream.toByteArray(); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/afm/AFM.java0000644000175000017500000001152611031105664023571 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.afm; import java.io.IOException; import java.util.HashMap; import java.util.Map; import de.intarsys.tools.locator.ILocator; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.stream.StreamTools; /** * A simple implementation for an adobe font metric object. * *

* This implementation will hold all afm attributes in a generic collection. The * char metrics are read explicitly and held in a list of AFMChar's. No other * information (like kerning) is extracted. *

* *

* See the "Adobe Font Metrics File Format Specification" *

*/ public class AFM { public static final String ATTR_FontName = "FontName"; //$NON-NLS-1$ public static AFM createFromLocator(ILocator locator) throws IOException { AFM result = new AFM(); result.setLocator(locator); result.initializeFromLocator(); return result; } public static AFM createNew() { return new AFM(); } private ILocator locator; // the chars described in the font metric file // ... organized by codePoint private Map charsByCode = new HashMap(); // ... organized by name private Map charsByName = new HashMap(); // attribute name/value pairs parsed form the font metric file private Map attributes = new HashMap(); protected AFM() { super(); } protected void addChar(AFMChar c) { if (c.getCode() != -1) { charsByCode.put(new Integer(c.getCode()), c); } if (c.getName() != null) { charsByName.put(c.getName(), c); } } /** * The string value for a generic attribute designated by name. * * @param name * The name of the attribute to lookup. * * @return The string value for a generic attribute designated by * name. */ public String getAttribute(String name) { return attributes.get(name); } /** * The character representation for a byte code point given in * codePoint. * * @param codePoint * The byte code point. * * @return The character representation for a byte code point given in * codePoint. */ public AFMChar getCharByCode(int codePoint) { return charsByCode.get(new Integer(codePoint)); } /** * The character representation for an adobe glyph name given in * name. * * @param name * The adobe glyph name. * * @return The character representation for an adobe glyph name given in * name. */ public AFMChar getCharByName(String name) { return charsByName.get(name); } public String getFontName() { return getAttribute(ATTR_FontName); } public ILocator getLocator() { return locator; } protected void initializeFromLocator() throws IOException { IRandomAccess random = null; try { random = getLocator().getRandomAccess(); AFMParser parser = new AFMParser(this); parser.parse(random); } finally { StreamTools.close(random); } } protected void setAttribute(String name, String value) { attributes.put(name, value); } protected void setLocator(ILocator locator) { this.locator = locator; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/afm/AFMChar.java0000644000175000017500000001204611031105664024365 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.afm; import java.util.StringTokenizer; import de.intarsys.tools.string.StringTools; /** * A simple implementation for an AFM char metric object * *

* This implementation will hold the information needed for implementing a * simple pdf field layout mechanism. All attributes but name, code, and with * are ignored. *

* *

* See the "Adobe Font Metrics File Format Specification" *

*/ public class AFMChar { /* * todo under construction */ // public static String AFM_TOKEN_WX = "WX"; //$NON-NLS-1$ public static String AFM_TOKEN_W = "W"; //$NON-NLS-1$ public static String AFM_TOKEN_W0X = "W0X"; //$NON-NLS-1$ public static String AFM_TOKEN_W0 = "W0"; //$NON-NLS-1$ public static String AFM_TOKEN_N = "N"; //$NON-NLS-1$ public static String AFM_TOKEN_CH = "CH"; //$NON-NLS-1$ public static String AFM_TOKEN_C = "C"; //$NON-NLS-1$ /** * Create a new glyph representation from the definition parsed from * glyph. * * @param glyph * A string containing a definition for the glyph. * * @return The new glyph representation. */ public static AFMChar create(String glyph) { int code = -1; int width = -1; String name = StringTools.EMPTY; StringTokenizer to = new StringTokenizer(glyph, ";"); //$NON-NLS-1$ while (to.hasMoreTokens()) { StringTokenizer tf = new StringTokenizer(to.nextToken()); if (!tf.hasMoreTokens()) { continue; } String field = tf.nextToken(); if (field.equals(AFM_TOKEN_C)) { code = Integer.parseInt(tf.nextToken()); } else if (field.equals(AFM_TOKEN_CH)) { String value = tf.nextToken(); code = Integer.parseInt(value.substring(1, value.length() - 1), 16); } else if (field.equals(AFM_TOKEN_WX)) { width = Integer.parseInt(tf.nextToken()); } else if (field.equals(AFM_TOKEN_W0X)) { width = Integer.parseInt(tf.nextToken()); } else if (field.equals(AFM_TOKEN_W)) { width = Integer.parseInt(tf.nextToken()); } else if (field.equals(AFM_TOKEN_W0)) { width = Integer.parseInt(tf.nextToken()); } else if (field.equals(AFM_TOKEN_N)) { name = tf.nextToken(); } } return new AFMChar(code, width, name); } // the char name private String name; // the char code or -1 private int code; // the char width or 0 private int width; /** * AFMChar constructor comment. * * @param code * docme * @param width * docme * @param name * docme */ protected AFMChar(int code, int width, String name) { super(); setCode(code); setWidth(width); setName(name); } /** * The glyphs code. * * @return The glyphs code. */ public int getCode() { return code; } /** * The glyphs name. * * @return The glyphs name. */ public java.lang.String getName() { return name; } /** * The glyphs width. * * @return The glyphs width. */ public int getWidth() { return width; } private void setCode(int newCode) { code = newCode; } private void setName(java.lang.String newName) { name = newName; } private void setWidth(int newWidth) { width = newWidth; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "<" + getCode() + ", " + getWidth() + ", " + getName() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/0000755000175000017500000000000011412336240023433 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTHorizontalHeader.java0000644000175000017500000000643411031105676030023 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; /** * */ public class TTHorizontalHeader { private short ascender; private short descender; private short lineGap; private int advanceWidthMax; private short minLeftSideBearing; private short minRightSideBearing; private short xMaxExtent; private short caretSlopeRise; private short caretSlopeRun; private int numberOfHMetrics; public int getAdvanceWidthMax() { return advanceWidthMax; } public short getAscender() { return ascender; } public short getCaretSlopeRise() { return caretSlopeRise; } public short getCaretSlopeRun() { return caretSlopeRun; } public short getDescender() { return descender; } public short getLineGap() { return lineGap; } public short getMinLeftSideBearing() { return minLeftSideBearing; } public short getMinRightSideBearing() { return minRightSideBearing; } public int getNumberOfHMetrics() { return numberOfHMetrics; } public short getXMaxExtent() { return xMaxExtent; } public void setAdvanceWidthMax(int i) { advanceWidthMax = i; } public void setAscender(short s) { ascender = s; } public void setCaretSlopeRise(short s) { caretSlopeRise = s; } public void setCaretSlopeRun(short s) { caretSlopeRun = s; } public void setDescender(short s) { descender = s; } public void setLineGap(short s) { lineGap = s; } public void setMinLeftSideBearing(short s) { minLeftSideBearing = s; } public void setMinRightSideBearing(short s) { minRightSideBearing = s; } public void setNumberOfHMetrics(int i) { numberOfHMetrics = i; } public void setXMaxExtent(short s) { xMaxExtent = s; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTFont.java0000644000175000017500000003017111412326542025462 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; import java.io.IOException; import java.util.Arrays; import java.util.Map; import de.intarsys.cwt.font.FontStyle; import de.intarsys.tools.locator.ILocator; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.stream.StreamTools; import de.intarsys.tools.string.StringTools; /** * This class represents a true type font. Currently only single font files are * supported. *

* This class is under construction and not meant for a complete TT * implementation. */ public class TTFont { public static final int ARG_1_AND_2_ARE_WORDS = 1; public static final int MORE_COMPONENTS = 32; public static final int SFNT_TRUETYPE = 0x00010000; public static final byte[] TABLE_CMAP = "cmap".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_CVT = "cvt ".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_FGPM = "fpgm".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_GLYF = "glyf".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_HEAD = "head".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_HHEA = "hhea".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_HMTX = "hmtx".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_LOCA = "loca".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_MAXP = "maxp".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_NAME = "name".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_OS2 = "OS/2".getBytes(); //$NON-NLS-1$ public static final byte[] TABLE_POST = "post".getBytes();//$NON-NLS-1$ public static final byte[] TABLE_PREP = "prep".getBytes(); //$NON-NLS-1$ public static final int WE_HAVE_A_SCALE = 8; public static final int WE_HAVE_A_TWO_BY_TWO = 128; public static final int WE_HAVE_AN_X_AND_Y_SCALE = 64; static public int align(int newLength) { return (newLength + 3) & (~3); } public static TTFont createFromLocator(ILocator locator) throws IOException { TTFont result = new TTFont(); result.setLocator(locator); result.initializeFromLocator(); return result; } /** objectified versions of the "cmap" tables and subtables */ private Map cmaps; // Font names in Postscript notation private String fontFamilyName = null; /** "objectified" version of the "head" table */ private TTFontHeader fontHeader; /** The style of this font */ private FontStyle fontStyle = FontStyle.REGULAR; /** objectified version of the "hmtx" table */ private int[] glyphWidths; /** objectified version of the "hhea" table */ private TTHorizontalHeader horizontalHeader; private ILocator locator; /** objectified version of the "os/2" table */ private TTMetrics metrics; /** objectified version of the "naming" table */ private TTNaming naming; /** objectified versions of the "post" table */ private TTPostScriptInformation postScriptInformation; private String psName = null; private int sfntVersion; /** the parsed table directory information */ private TTTable[] tables; /** * Create an empty true type font. */ protected TTFont() { super(); } public Map getCMaps() throws TrueTypeException { if (cmaps == null) { TTFontParser parser = new TTFontParser(); try { cmaps = parser.parseTable_cmap(getTable(TABLE_CMAP)); } catch (IOException e) { throw new TrueTypeException(e.getMessage()); } } return cmaps; } public Map getCMapsAt(int platformID, int platformSpecificID) throws TrueTypeException { String key = StringTools.EMPTY + platformID + ":" + platformSpecificID; //$NON-NLS-1$ Object result = getCMaps().get(key); if (result instanceof TTTable) { // not yet parsed TTFontParser parser = new TTFontParser(); try { Map submap = parser.parseTable_cmap_subtable((TTTable) result); getCMaps().put(key, submap); result = submap; } catch (IOException e) { throw new TrueTypeException(e.getMessage()); } } return (Map) result; } public String getFontFamilyName() { return fontFamilyName; } public TTFontHeader getFontHeader() throws TrueTypeException { if (fontHeader == null) { TTFontParser parser = new TTFontParser(); try { fontHeader = parser.parseTable_head(getTable(TABLE_HEAD)); } catch (IOException e) { throw new TrueTypeException(e.getMessage()); } } return fontHeader; } /* * (non-Javadoc) * * @see de.intarsys.font.IFont#getFontName() */ public String getFontName() { return getPsName(); } public FontStyle getFontStyle() { return fontStyle; } public int getGlyphWidth(int codePoint) throws TrueTypeException { if (codePoint < getGlyphWidths().length) { return getGlyphWidths()[codePoint]; } return getGlyphWidths()[getGlyphWidths().length - 1]; } protected int[] getGlyphWidths() throws TrueTypeException { if (glyphWidths == null) { TTFontParser parser = new TTFontParser(); try { glyphWidths = parser.parseTable_hmtx(getTable(TABLE_HMTX), getHorizontalHeader().getNumberOfHMetrics()); } catch (IOException e) { throw new TrueTypeException(e.getMessage()); } } return glyphWidths; } public TTHorizontalHeader getHorizontalHeader() throws TrueTypeException { if (horizontalHeader == null) { TTFontParser parser = new TTFontParser(); try { horizontalHeader = parser.parseTable_hhea(getTable(TABLE_HHEA)); } catch (IOException e) { throw new TrueTypeException(e.getMessage()); } } return horizontalHeader; } public ILocator getLocator() { return locator; } public TTMetrics getMetrics() throws TrueTypeException { if (metrics == null) { TTFontParser parser = new TTFontParser(); try { metrics = parser.parseTable_os2(getTable(TABLE_OS2)); } catch (IOException e) { throw new TrueTypeException(e.getMessage()); } } return metrics; } public TTNaming getNaming() throws TrueTypeException { if (naming == null) { TTFontParser parser = new TTFontParser(); try { TTTable table = getTable(TABLE_NAME); if (table != null) { naming = parser.parseTable_name(table); } } catch (IOException e) { throw new TrueTypeException(e.getMessage()); } } return naming; } public TTPostScriptInformation getPostScriptInformation() throws TrueTypeException { if (postScriptInformation == null) { TTFontParser parser = new TTFontParser(); try { postScriptInformation = parser .parseTable_post(getTable(TABLE_POST)); } catch (IOException e) { throw new TrueTypeException(e.getMessage()); } } return postScriptInformation; } public String getPsName() { return psName; } public int getSfntVersion() { return sfntVersion; } public TTTable getTable(byte[] name) { for (int i = 0; i < getTables().length; i++) { TTTable current = tables[i]; if (Arrays.equals(current.getName(), name)) { return current; } } return null; } public TTTable[] getTables() { return tables; } protected void initializeFromLocator() throws IOException { IRandomAccess random = null; try { random = getLocator().getRandomAccess(); TTFontParser parser = new TTFontParser(); parser.parseTables(this); try { setFontName(this); } catch (TrueTypeException e) { throw new IOException(e.getMessage()); } } finally { StreamTools.close(random); } } public void removeCMapsAt(int platformID, int platformSpecificID) throws TrueTypeException, IOException { TTTable data = getTable(TTFont.TABLE_CMAP); if (data == null) { return; } IRandomAccess random = data.getRandomAccess(); TTFontSerializer serializer = new TTFontSerializer(); TTFontParser parser = new TTFontParser(); try { boolean found = false; random.seek(0); // skip version int version = parser.readShort(random); int count = parser.readUShort(random); int i = 0; long readPos = random.getOffset(); long writePos = random.getOffset(); while (i < count) { random.seek(readPos); int tempPlatformID = parser.readUShort(random); int tempPlatformSpecificID = parser.readUShort(random); int offset = parser.readInt(random); if (platformID == tempPlatformID && platformSpecificID == tempPlatformSpecificID) { found = true; } else { if (readPos != writePos) { random.seek(writePos); serializer.writeShort(random, tempPlatformID); serializer.writeShort(random, tempPlatformSpecificID); serializer.writeInt(random, offset); } writePos = writePos + 8; } readPos = readPos + 8; i++; } if (found) { // clear removed entry random.seek(writePos); serializer.writeShort(random, 0); serializer.writeShort(random, 0); serializer.writeInt(random, 0); // random.seek(0); // skip version random.seekBy(2); // decrement count serializer.writeShort(random, count - 1); // } } finally { StreamTools.close(random); } cmaps = null; } protected void setFontFamilyName(String string) { fontFamilyName = string; } protected void setFontName(TTFont font) throws TrueTypeException { TTNaming tempNaming = font.getNaming(); if (tempNaming != null) { font.setFontFamilyName(tempNaming .getValue(ITTNamingIDs.FontFamilyName)); String styleName = tempNaming .getValue(ITTNamingIDs.FontSubfamilyName); font.setFontStyle(FontStyle.getFontStyle(styleName)); font.setPsName(tempNaming.getValue(ITTNamingIDs.PSName)); if (font.getPsName() == null) { // Here we should use operating system specific information // which can't be done by Java. So we use our own // implementation and hope we it works. // todo postscript name font.setPsName(font.getFontFamilyName() + "-" //$NON-NLS-1$ + font.getFontStyle().getId()); } } } protected void setFontStyle(FontStyle fontStyle) { this.fontStyle = fontStyle; } protected void setLocator(ILocator locator) { this.locator = locator; } public void setPsName(String string) { psName = string; } protected void setSfntVersion(int sfntVersion) { // this is not true for all valid font files, skip version check // if (sfntVersion != SFNT_TRUETYPE) { // throw new IOException("not a valid TTF file."); // } this.sfntVersion = sfntVersion; } protected void setTables(TTTable[] tables) { this.tables = tables; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTMetrics.java0000644000175000017500000001546411031105700026156 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; /** * */ public class TTMetrics { private short xAvgCharWidth; private int usWeightClass; private int usWidthClass; private int fsType; private short ySubscriptXSize; private short ySubscriptYSize; private short ySubscriptXOffset; private short ySubscriptYOffset; private short ySuperscriptXSize; private short ySuperscriptYSize; private short ySuperscriptXOffset; private short ySuperscriptYOffset; private short yStrikeoutSize; private short yStrikeoutPosition; private short sFamilyClass; private TTMetricsPanose panose; private byte[] achVendID = new byte[4]; private int fsSelection; private int usFirstCharIndex; private int usLastCharIndex; private short sTypoAscender; private short sTypoDescender; private short sTypoLineGap; private int usWinAscent; private int usWinDescent; private short sxHeight; private short sCapHeight; private int usDefaultChar; private int usBreakChar; private int usMaxContext; public byte[] getAchVendID() { return achVendID; } public int getFsSelection() { return fsSelection; } public int getFsType() { return fsType; } public TTMetricsPanose getPanose() { return panose; } public short getSCapHeight() { return sCapHeight; } public short getSFamilyClass() { return sFamilyClass; } public short getSTypoAscender() { return sTypoAscender; } public short getSTypoDescender() { return sTypoDescender; } public short getSTypoLineGap() { return sTypoLineGap; } public short getSxHeight() { return sxHeight; } public int getUsBreakChar() { return usBreakChar; } public int getUsDefaultChar() { return usDefaultChar; } public int getUsFirstCharIndex() { return usFirstCharIndex; } public int getUsLastCharIndex() { return usLastCharIndex; } public int getUsMaxContext() { return usMaxContext; } public int getUsWeightClass() { return usWeightClass; } public int getUsWidthClass() { return usWidthClass; } public int getUsWinAscent() { return usWinAscent; } public int getUsWinDescent() { return usWinDescent; } public short getXAvgCharWidth() { return xAvgCharWidth; } public short getYStrikeoutPosition() { return yStrikeoutPosition; } public short getYStrikeoutSize() { return yStrikeoutSize; } public short getYSubscriptXOffset() { return ySubscriptXOffset; } public short getYSubscriptXSize() { return ySubscriptXSize; } public short getYSubscriptYOffset() { return ySubscriptYOffset; } public short getYSubscriptYSize() { return ySubscriptYSize; } public short getYSuperscriptXOffset() { return ySuperscriptXOffset; } public short getYSuperscriptXSize() { return ySuperscriptXSize; } public short getYSuperscriptYOffset() { return ySuperscriptYOffset; } public short getYSuperscriptYSize() { return ySuperscriptYSize; } public void setAchVendID(byte[] bs) { achVendID = bs; } public void setFsSelection(int i) { fsSelection = i; } public void setFsType(int s) { fsType = s; } public void setPanose(byte[] bs) { if ((bs != null) && (bs.length == 10)) { panose = new TTMetricsPanose(bs); } } public void setSCapHeight(short capHeight) { sCapHeight = capHeight; } public void setSFamilyClass(short s) { sFamilyClass = s; } public void setSTypoAscender(short s) { sTypoAscender = s; } public void setSTypoDescender(short s) { sTypoDescender = s; } public void setSTypoLineGap(short s) { sTypoLineGap = s; } public void setSxHeight(short sxHeight) { this.sxHeight = sxHeight; } public void setUsBreakChar(int usBreakChar) { this.usBreakChar = usBreakChar; } public void setUsDefaultChar(int usDefaultChar) { this.usDefaultChar = usDefaultChar; } public void setUsFirstCharIndex(int i) { usFirstCharIndex = i; } public void setUsLastCharIndex(int i) { usLastCharIndex = i; } public void setUsMaxContext(int usMaxContext) { this.usMaxContext = usMaxContext; } public void setUsWeightClass(int i) { usWeightClass = i; } public void setUsWidthClass(int i) { usWidthClass = i; } public void setUsWinAscent(int i) { usWinAscent = i; } public void setUsWinDescent(int i) { usWinDescent = i; } public void setXAvgCharWidth(short s) { xAvgCharWidth = s; } public void setYStrikeoutPosition(short s) { yStrikeoutPosition = s; } public void setYStrikeoutSize(short s) { yStrikeoutSize = s; } public void setYSubscriptXOffset(short s) { ySubscriptXOffset = s; } public void setYSubscriptXSize(short s) { ySubscriptXSize = s; } public void setYSubscriptYOffset(short s) { ySubscriptYOffset = s; } public void setYSubscriptYSize(short s) { ySubscriptYSize = s; } public void setYSuperscriptXOffset(short s) { ySuperscriptXOffset = s; } public void setYSuperscriptXSize(short s) { ySuperscriptXSize = s; } public void setYSuperscriptYOffset(short s) { ySuperscriptYOffset = s; } public void setYSuperscriptYSize(short s) { ySuperscriptYSize = s; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TrueTypeException.java0000644000175000017500000000367011031105676027750 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; /** * */ public class TrueTypeException extends Exception { public TrueTypeException() { super(); } public TrueTypeException(String message) { super(message); } public TrueTypeException(String message, Throwable cause) { super(message, cause); } public TrueTypeException(Throwable cause) { super(cause); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTPostScriptInformation.java0000644000175000017500000000600211031105676031070 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; /** * */ public class TTPostScriptInformation { private float version = 0; // 0x00010000 for version 1.0 private float italicAngle; // Italic angle in counter-clockwise degrees // from the vertical. Zero for upright text, // negative for text that leans to the right // (forward). private int underlinePosition; // This is the suggested distance of the top // of the underline from the baseline // (negative values indicate below // baseline). private int underlineThickness; // Suggested values for the underline // thickness. private long isFixedPitch; // Set to 0 if the font is proportionally // spaced, non-zero if the font is not // proportionally spaced (i.e. monospaced). public TTPostScriptInformation() { } public long getIsFixedPitch() { return isFixedPitch; } public float getItalicAngle() { return italicAngle; } public int getUnderlinePosition() { return underlinePosition; } public int getUnderlineThickness() { return underlineThickness; } public float getVersion() { return version; } public void setIsFixedPitch(long l) { isFixedPitch = l; } public void setItalicAngle(float f) { italicAngle = f; } public void setUnderlinePosition(int i) { underlinePosition = i; } public void setUnderlineThickness(int i) { underlineThickness = i; } public void setVersion(float f) { version = f; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTNameRecord.java0000644000175000017500000000577411031105700026572 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; /** * */ public class TTNameRecord { private int platformID; private int encodingID; private int languageID; private int nameID; private int length; private String value; public TTNameRecord() { } public TTNameRecord(int platformID, int encodingID, int languageID, int nameID, String value) { super(); setPlatformID(platformID); setEncodingID(encodingID); setLanguageID(languageID); setNameID(nameID); setValue(value); } public int getEncodingID() { return encodingID; } public int getLanguageID() { return languageID; } public int getLength() { return length; } public int getNameID() { return nameID; } public int getPlatformID() { return platformID; } public String getValue() { return value; } public void setEncodingID(int i) { encodingID = i; } public void setLanguageID(int i) { languageID = i; } public void setLength(int i) { length = i; } public void setNameID(int i) { nameID = i; } public void setPlatformID(int i) { platformID = i; } public void setValue(String value) { /* * byte[] bytes = null; try { bytes = value.getBytes("UTF-16BE"); } * catch (Exception ignore) { } setData(bytes); */ this.value = value; } @Override public String toString() { return "ID:" + getNameID() + " Value:" + getValue(); //$NON-NLS-1$ //$NON-NLS-2$ } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTTable.java0000644000175000017500000000717311412326544025613 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; import java.io.IOException; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.randomaccess.RandomAccessByteArray; import de.intarsys.tools.randomaccess.RandomAccessViewport; import de.intarsys.tools.stream.StreamTools; /** * */ public class TTTable { private byte[] bytes; private int checksum = 0; private TTFont font; private long length; private byte[] name; private long offset; protected TTTable(TTFont font, long offset, long length) { super(); this.font = font; this.offset = offset; this.length = length; } protected int createChecksum() throws IOException { IRandomAccess random = getRandomAccess(); try { random.seek(0); long len = (random.getLength() + 3) / 4; int sum = 0; for (int i = 0; i < len; i++) { int v = random.read(); v = (v << 8) + random.read(); v = (v << 8) + random.read(); v = (v << 8) + random.read(); sum += v; } return sum; } finally { StreamTools.close(random); } } public int getChecksum() { if (checksum == 0) { try { checksum = createChecksum(); } catch (IOException e) { // } } return checksum; } public TTFont getFont() { return font; } public long getLength() { return length; } public byte[] getName() { return name; } public long getOffset() { return offset; } public IRandomAccess getRandomAccess() throws IOException { if (bytes != null) { return new RandomAccessByteArray(bytes); } IRandomAccess random = getFont().getLocator().getRandomAccess(); IRandomAccess viewport = new RandomAccessViewport(random, getOffset(), getLength()); return viewport; } protected void setBytes(byte[] pBytes) { bytes = pBytes; checksum = 0; length = pBytes.length; offset = 0; } protected void setChecksum(int i) { checksum = i; } public void setName(byte[] string) { name = string; } @Override public String toString() { return new String(getName()); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/ITTNamingIDs.java0000644000175000017500000001417411031105700026467 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; /** * */ public interface ITTNamingIDs { // Code Meaning // 0 Copyright notice. public static final int Copyright = 0; // 1 Font Family name. Up to four fonts can share the Font Family name, // forming a font style linking group (regular, italic, bold, bold italic - // as defined by OS/2.fsSelection bit settings). public static final int FontFamilyName = 1; // 2 Font Subfamily name. The Font Subfamily name distiguishes the font in a // group with the same Font Family name (name ID 1). This is assumed to // address style (italic, oblique) and weight (light, bold, black, etc.). A // font with no particular differences in weight or style (e.g. medium // weight, not italic and fsSelection bit 6 set) should have the string // "Regular" stored in this position. public static final int FontSubfamilyName = 2; // 3 Unique font identifier public static final int FontId = 3; // 4 Full font name; this should be a combination of strings 1 and 2. // Exception: if the font is "Regular" as indicated in string 2, then use // only the family name contained in string 1. public static final int FullFontName = 4; // 5 Version string. Should begin with the syntax 'Version // .' (upper case, lower case, or mixed, with a space // between "Version" and the number). public static final int Version = 5; // 6 Postscript name for the font; Name ID 6 specifies a string which is // used to invoke a PostScript language font that corresponds to this // OpenType font. If no name ID 6 is present, then there is no defined // method for invoking this font on a PostScript interpreter. public static final int PSName = 6; // 7 Trademark; this is used to save any trademark notice/information for // this font. Such information should be based on legal advice. This is // distinctly separate from the copyright. public static final int Trademark = 7; // 8 Manufacturer Name. public static final int ManufacturerName = 8; // 9 Designer; name of the designer of the typeface. public static final int DesignerName = 9; // 10 Description; description of the typeface. Can contain revision // information, usage recommendations, history, features, etc. public static final int Description = 10; // 11 URL Vendor; URL of font vendor (with protocol, e.g., http://, ftp://). // If a unique serial number is embedded in the URL, it can be used to // register the font. public static final int URLVendor = 11; // 12 URL Designer; URL of typeface designer (with protocol, e.g., http://, // ftp://). public static final int URLDesigner = 12; // 13 License Description; description of how the font may be legally used, // or different example scenarios for licensed use. This field should be // written in plain language, not legalese. public static final int LicenseDescription = 13; // 14 License Info URL; URL where additional licensing information can be // found. public static final int LicenseInfoURL = 14; // 15 Reserved; Set to zero. // 16 Preferred Family; For historical reasons, font families have contained // a maximum of four styles, but font designers may group more than four // fonts to a single family. The Preferred Family allows font designers to // include the preferred family grouping which contains more than four // fonts. This ID is only present if it is different from ID 1. public static final int PreferredFamily = 16; // 17 Preferred Subfamily; Allows font designers to include the preferred // subfamily grouping that is more descriptive than ID 2. This ID is only // present if it is different from ID 2 and must be unique for the the // Preferred Family. public static final int PreferredSubFamily = 17; // 18 Compatible Full (Macintosh only); On the Macintosh, the menu name is // constructed using the FOND resource. This usually matches the Full Name. // If you want the name of the font to appear differently than the Full // Name, you can insert the Compatible Full Name in ID 18. public static final int CompatibleFull = 18; // 19 Sample text; This can be the font name, or any other text that the // designer thinks is the best sample to display the font in. public static final int SampleText = 19; // 20 PostScript CID findfont name; Its presence in a font means that the // nameID 6 holds a PostScript font name that is meant to be used with the // "composefont" invocation in order to invoke the font in a PostScript // interpreter. See the definition of name ID 6. public static final int PS_CID = 20; } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTFontParser.java0000644000175000017500000006036111411054022026631 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; import java.io.IOException; import java.util.HashMap; import java.util.Map; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.stream.StreamTools; import de.intarsys.tools.string.StringTools; /** * Apple TT specification
* http://developer.apple.com/fonts/TTRefMan/RM06/Chap6.html
* Microsoft OpenType spec
* http://www.microsoft.com/typography/otspec/otff.htm */ public class TTFontParser { // todo support indexed fonts /** the parsed table directory information */ private TTTable[] tables; public TTFontParser() { } public Map parseTable_cmap(TTTable data) throws IOException { Map result = new HashMap(); IRandomAccess random = data.getRandomAccess(); try { random.seek(0); // skip version random.seekBy(2); int count = readUShort(random); for (int i = 0; i < count; i++) { int platformID = readUShort(random); int platformSpecificID = readUShort(random); int offset = readInt(random); TTTable subtable = new TTTable(data.getFont(), data.getOffset() + offset, -1); String key = StringTools.EMPTY + platformID + ":" + platformSpecificID; //$NON-NLS-1$ result.put(key, subtable); } return result; } finally { StreamTools.close(random); } } public Map parseTable_cmap_subtable(TTTable data) throws IOException { Map result = null; IRandomAccess random = data.getRandomAccess(); try { random.seek(0); int format = readUShort(random); switch (format) { case 0: result = readCMapFormat0(random); break; case 4: result = readCMapFormat4(random); break; case 6: result = readCMapFormat6(random); break; } return result; } finally { StreamTools.close(random); } } /** * This table gives global information about the font. * *

	 *  Type        Name        Description
	 *  FIXED        Table version number        0x00010000 for version 1.0.
	 *  FIXED        fontRevision        Set by font manufacturer.
	 *  ULONG        checkSumAdjustment        To compute:  set it to 0, sum the entire font as ULONG, then store 0xB1B0AFBA - sum.
	 *  ULONG        magicNumber        Set to 0x5F0F3CF5.
	 *  USHORT        flags        Bit 0 - baseline for font at y=0;
	 *                                         Bit 1 - left sidebearing at x=0;
	 *                                         Bit 2 - instructions may depend on point size;
	 *                                         Bit 3 - force ppem to integer values for all internal scaler math; may use fractional ppem sizes if this bit is clear;
	 *                                         Bit 4 - instructions may alter advance width (the advance widths might not scale linearly);
	 *                                         Note: All other bits must be zero.
	 *  USHORT        unitsPerEm        Valid range is from 16 to 16384
	 *  longDateTime        created        International date (8-byte field).
	 *  longDateTime        modified        International date (8-byte field).
	 *  FWORD        xMin        For all glyph bounding boxes.
	 *  FWORD        yMin        For all glyph bounding boxes.
	 *  FWORD        xMax        For all glyph bounding boxes.
	 *  FWORD        yMax        For all glyph bounding boxes.
	 *  USHORT        macStyle        Bit 0 bold (if set to 1); Bit 1 italic (if set to 1)Bits 2-15 reserved (set to 0).
	 *  USHORT        lowestRecPPEM        Smallest readable size in pixels.
	 *  SHORT        fontDirectionHint         0   Fully mixed directional glyphs; 1   Only strongly left to right; 2   Like 1 but also contains neutrals ;-1   Only strongly right to left;-2   Like -1 but also contains neutrals.
	 *  SHORT        indexToLocFormat        0 for short offsets, 1 for long.
	 *  SHORT        glyphDataFormat        0 for current format.
	 * 
* * @param data * docme * * @return docme * * @throws IOException * docme */ public TTFontHeader parseTable_head(TTTable data) throws IOException { TTFontHeader result = new TTFontHeader(); IRandomAccess random = data.getRandomAccess(); try { random.seek(0); // skip version // skip font Revision // skip checksum // skip magic number random.seekBy(16); result.setFlags(readUShort(random)); result.setUnitsPerEm(readUShort(random)); // skip created // skip modified random.seekBy(16); result.setXMin(readShort(random)); result.setYMin(readShort(random)); result.setXMax(readShort(random)); result.setYMax(readShort(random)); result.setMacStyle(readUShort(random)); // skip smallest size in pixels // skip font direction hint random.seekBy(4); result.setShortLocationFormat(readShort(random) == 0); return result; } finally { StreamTools.close(random); } } /** *
	 *  FIXED        Table version number        0x00010000 for version 1.0.
	 *  FWORD        Ascender        Typographic ascent.
	 *  FWORD        Descender        Typographic descent.
	 *  FWORD        LineGap        Typographic line gap. Negative LineGap values are treated as zero in Windows 3.1, System 6, and System 7.
	 *  UFWORD        advanceWidthMax        Maximum advance width value in ‘hmtx’ table.
	 *  FWORD        minLeftSideBearing        Minimum left sidebearing value in ‘hmtx’ table.
	 *  FWORD        minRightSideBearing        Minimum right sidebearing value; calculated as Min(aw - lsb - (xMax - xMin)).
	 *  FWORD        xMaxExtent        Max(lsb + (xMax - xMin)).
	 *  SHORT        caretSlopeRise        Used to calculate the slope of the cursor (rise/run); 1 for vertical.
	 *  SHORT        caretSlopeRun        0 for vertical.
	 *  SHORT        (reserved)        set to 0
	 *  SHORT        (reserved)        set to 0
	 *  SHORT        (reserved)        set to 0
	 *  SHORT        (reserved)        set to 0
	 *  SHORT        (reserved)        set to 0
	 *  SHORT        metricDataFormat        0 for current format.
	 *  USHORT        numberOfHMetrics        Number of hMetric entries in  ‘hmtx’ table; may be smaller than the total number of glyphs in the font.
	 * 
* * @param data * docme * * @return docme * * @throws IOException * docme */ public TTHorizontalHeader parseTable_hhea(TTTable data) throws IOException { TTHorizontalHeader result = new TTHorizontalHeader(); IRandomAccess random = data.getRandomAccess(); try { random.seek(0); // skip version random.seekBy(4); result.setAscender(readShort(random)); result.setDescender(readShort(random)); result.setLineGap(readShort(random)); result.setAdvanceWidthMax(readUShort(random)); result.setMinLeftSideBearing(readShort(random)); result.setMinRightSideBearing(readShort(random)); result.setXMaxExtent(readShort(random)); result.setCaretSlopeRise(readShort(random)); result.setCaretSlopeRun(readShort(random)); // skip random.seekBy(12); result.setNumberOfHMetrics(readUShort(random)); // skip rest return result; } finally { StreamTools.close(random); } } /** *
	 * The type longHorMetric is defined as an array where each element has
	 * two parts: the advance width, which is of type USHORT, and the left side
	 * bearing, which is of type SHORT. These fields are in font design units.
	 *  typedef struct         _longHorMetric {
	 *                 USHORT        advanceWidth;
	 *                 SHORT                lsb;
	 *  }  longHorMetric;
	 * 
	 *  Field Type Description
	 *  hMetrics longHorMetric [numberOfHMetrics] Paired advance width and
	 *                                 left side bearing values for each glyph. The value
	 *                                 numOfHMetrics comes from the 'hhea' table. If the font is
	 *                                 monospaced, only one entry need be in the array, but that
	 *                                 entry is required. The last entry applies to all subsequent
	 *                                 glyphs.
	 *  leftSideBearing SHORT[ ] Here the advanceWidth is assumed to be the
	 *                                 same as the advanceWidth for the last entry above. The
	 *                                 number of entries in this array is derived from numGlyphs
	 *                                 (from 'maxp' table) minus numberOfHMetrics. This generally
	 *                                 is used with a run of monospaced glyphs (e.g., Kanji fonts
	 *                                 or Courier fonts). Only one run is allowed and it must be
	 *                                 at the end. This allows a monospaced font to vary the left
	 *                                 side bearing values for each glyph.
	 * 
* * @param data * docme * @param count * docme * * @return docme * * @throws IOException * docme */ public int[] parseTable_hmtx(TTTable data, int count) throws IOException { int[] widths = new int[count]; IRandomAccess random = data.getRandomAccess(); try { random.seek(0); for (int i = 0; i < count; i++) { widths[i] = readUShort(random); readShort(random); } return widths; } finally { StreamTools.close(random); } } public int[] parseTable_loca(TTTable data, boolean shortLocationFormat) throws IOException { int count = 0; int[] locations; IRandomAccess random = data.getRandomAccess(); try { random.seek(0); if (shortLocationFormat) { count = (int) random.getLength() / 2; locations = new int[count]; for (int i = 0; i < count; i++) { locations[i] = readUShort(random) << 1; } } else { count = (int) random.getLength() / 4; locations = new int[count]; for (int i = 0; i < count; i++) { locations[i] = readInt(random); } } return locations; } finally { StreamTools.close(random); } } public TTNaming parseTable_name(TTTable data) throws IOException { TTNaming result = new TTNaming(); IRandomAccess random = data.getRandomAccess(); try { random.seek(0); // skip format random.seekBy(2); // USHORT count Number of name records. int count = readUShort(random); // USHORT stringOffset Offset to start of string storage (from start // of // table). int stringTableOffset = readUShort(random); // Namerecords follow for (int i = 0; i < count; i++) { TTNameRecord record = readNameRecord(random, stringTableOffset); // filter for Microsoft-Plattform and Language=American if ((record.getPlatformID() == 3) && (record.getLanguageID() == 1033)) { result.add(record.getNameID(), record); } } return result; } finally { StreamTools.close(random); } } /** *
	 *  USHORT        version        0x0001
	 *  SHORT        xAvgCharWidth;
	 *  USHORT        usWeightClass;
	 *  USHORT        usWidthClass;
	 *  SHORT        fsType;
	 *  SHORT        ySubscriptXSize;
	 *  SHORT        ySubscriptYSize;
	 *  SHORT        ySubscriptXOffset;
	 *  SHORT        ySubscriptYOffset;
	 *  SHORT        ySuperscriptXSize;
	 *  SHORT        ySuperscriptYSize;
	 *  SHORT        ySuperscriptXOffset;
	 *  SHORT        ySuperscriptYOffset;
	 *  SHORT        yStrikeoutSize;
	 *  SHORT        yStrikeoutPosition;
	 *  SHORT        sFamilyClass;
	 *  PANOSE        panose;
	 *  ULONG        ulUnicodeRange1        Bits 0–31
	 *  ULONG        ulUnicodeRange2        Bits 32–63
	 *  ULONG        ulUnicodeRange3        Bits 64–95
	 *  ULONG        ulUnicodeRange4        Bits 96–127
	 *  CHAR        achVendID[4];
	 *  USHORT        fsSelection;
	 *  USHORT        usFirstCharIndex
	 *  USHORT        usLastCharIndex
	 *  USHORT        sTypoAscender
	 *  USHORT        sTypoDescender
	 *  USHORT        sTypoLineGap
	 *  USHORT        usWinAscent
	 *  USHORT        usWinDescent
	 *  ULONG        ulCodePageRange1        Bits 0-31
	 *  ULONG        ulCodePageRange2        Bits 32-63
	 *  SHORT                  sxHeight
	 *         SHORT                 sCapHeight
	 *         USHORT                 usDefaultChar
	 *         USHORT                 usBreakChar
	 *         USHORT                 usMaxContext
	 * 
* * @param data * docme * * @return docme * * @throws IOException * docme */ public TTMetrics parseTable_os2(TTTable data) throws IOException { TTMetrics result = new TTMetrics(); IRandomAccess random = data.getRandomAccess(); try { random.seek(0); // skip version random.seekBy(2); result.setXAvgCharWidth(readShort(random)); result.setUsWeightClass(readUShort(random)); result.setUsWidthClass(readUShort(random)); result.setFsType(readUShort(random)); result.setYSubscriptXSize(readShort(random)); result.setYSubscriptYSize(readShort(random)); result.setYSubscriptXOffset(readShort(random)); result.setYSubscriptYOffset(readShort(random)); result.setYSuperscriptXSize(readShort(random)); result.setYSuperscriptYSize(readShort(random)); result.setYSuperscriptXOffset(readShort(random)); result.setYSuperscriptYOffset(readShort(random)); result.setYStrikeoutSize(readShort(random)); result.setYStrikeoutPosition(readShort(random)); result.setSFamilyClass(readShort(random)); result.setPanose(readBytes(random, 10)); // skip unicode ranges // skip vendor id random.seekBy(20); result.setFsSelection(readUShort(random)); result.setUsFirstCharIndex(readUShort(random)); result.setUsLastCharIndex(readUShort(random)); result.setSTypoAscender(readShort(random)); result.setSTypoDescender(readShort(random)); result.setSTypoLineGap(readShort(random)); result.setUsWinAscent(readUShort(random)); result.setUsWinDescent(readUShort(random)); result.setSxHeight(readShort(random)); result.setSCapHeight(readShort(random)); result.setUsDefaultChar(readUShort(random)); result.setUsMaxContext(readUShort(random)); // skip rest return result; } finally { StreamTools.close(random); } } /** *
	 * Type         Name                 Description
	 * Fixed         Version         0x00010000 for version 1.0
	 *                                         0x00020000 for version 2.0
	 *                                         0x00025000 for version 2.5 (deprecated)
	 *                                         0x00030000 for version 3.0
	 * Fixed         italicAngle         Italic angle in counter-clockwise degrees from the vertical. Zero for upright text, negative for text that leans to the right (forward).
	 * FWord         underlinePosition         This is the suggested distance of the top of the underline from the baseline (negative values indicate below baseline).
	 *                                                 The PostScript definition of this FontInfo dictionary key (the y coordinate of the center of the stroke) is not used for historical reasons. The value of the PostScript key may be calculated by subtracting half the underlineThickness from the value of this field.
	 * FWord         underlineThickness         Suggested values for the underline thickness.
	 * ULONG         isFixedPitch         Set to 0 if the font is proportionally spaced, non-zero if the font is not proportionally spaced (i.e. monospaced).
	 * ULONG         minMemType42         Minimum memory usage when an OpenType font is downloaded.
	 * ULONG         maxMemType42         Maximum memory usage when an OpenType font is downloaded.
	 * ULONG         minMemType1         Minimum memory usage when an OpenType font is downloaded as a Type 1 font.
	 * ULONG         maxMemType1         Maximum memory usage when an OpenType font is downloaded as a Type 1 font.
	 * 
* * @param data * docme * * @return docme * * @throws IOException * docme */ public TTPostScriptInformation parseTable_post(TTTable data) throws IOException { TTPostScriptInformation result = new TTPostScriptInformation(); IRandomAccess random = data.getRandomAccess(); try { random.seek(0); result.setVersion(readFixed(random)); result.setItalicAngle(readFixed(random)); result.setUnderlinePosition(readShort(random)); result.setUnderlineThickness(readShort(random)); return result; } finally { StreamTools.close(random); } } public TTTable[] parseTables(TTFont font) throws IOException { IRandomAccess random = null; try { random = font.getLocator().getRandomAccess(); readTables(font, random); font.setTables(tables); } finally { StreamTools.close(random); } return tables; } public byte[] readBytes(IRandomAccess random, int count) throws IOException { byte[] bytes = new byte[count]; int bytesRead = random.read(bytes); if (bytesRead < bytes.length) { return null; } return bytes; } protected Map readCMapFormat0(IRandomAccess random) throws IOException { Map result = new HashMap(); // skip length // skip language random.seekBy(4); for (int i = 0; i < 256; i++) { int glyphCode = random.read(); result.put(new Integer(i), new Integer(glyphCode)); } return result; } protected Map readCMapFormat4(IRandomAccess random) throws IOException { Map result = new HashMap(); int length = readUShort(random); // skip language random.seekBy(2); int segCount = readUShort(random) / 2; // skip hints random.seekBy(6); int[] endIndices = new int[segCount]; for (int i = 0; i < segCount; i++) { endIndices[i] = readUShort(random); } // skip reserved random.seekBy(2); int[] startIndices = new int[segCount]; for (int i = 0; i < segCount; i++) { startIndices[i] = readUShort(random); } int[] deltas = new int[segCount]; for (int i = 0; i < segCount; i++) { deltas[i] = readUShort(random); } int[] rangeOffsets = new int[segCount]; for (int i = 0; i < segCount; i++) { rangeOffsets[i] = readUShort(random); } int glyphIndexCount = (length / 2) - 8 - (segCount * 4); int[] glyphIndices = new int[glyphIndexCount]; for (int i = 0; i < glyphIndexCount; i++) { glyphIndices[i] = readUShort(random); } // now construct map int glyphCode; for (int i = 0; i < segCount; i++) { for (int charCode = startIndices[i]; (charCode <= endIndices[i]) && (charCode != 0xffff); charCode++) { if (rangeOffsets[i] == 0) { glyphCode = (deltas[i] + charCode) & 0xffff; } else { // index as described in open font specification int index = (charCode - startIndices[i]) + (rangeOffsets[i] / 2); // try emulate c pointer arithmetic.. index = index - segCount + i; glyphCode = glyphIndices[index]; if (glyphCode != 0) { glyphCode = (deltas[i] + glyphCode) & 0xffff; } } result.put(new Integer(charCode), new Integer(glyphCode)); } } return result; } protected Map readCMapFormat6(IRandomAccess random) throws IOException { Map result = new HashMap(); // skip length // skip language random.seekBy(4); int firstIndex = readUShort(random); int count = readUShort(random); int lastIndex = firstIndex + count; for (int i = firstIndex; i < lastIndex; i++) { int glyphCode = readUShort(random); result.put(new Integer(i), new Integer(glyphCode)); } return result; } public float readFixed(IRandomAccess random) throws IOException { int i = readInt(random); boolean negative = false; if (i < 0) { negative = true; i *= -1; } float hi = (i >> 16); float low = (i & 0x0000FFFF); while (low >= 1) { low = low / 10; } if (negative) { return -1 * (hi + low); } return hi + low; } public int readInt(IRandomAccess random) throws IOException { int b1 = random.read(); int b2 = random.read(); int b3 = random.read(); int b4 = random.read(); if ((b1 | b2 | b3 | b4) < 0) { throw new IOException("unexpected end of stream"); //$NON-NLS-1$ } return ((b1 << 24) + (b2 << 16) + (b3 << 8) + b4); } protected TTNameRecord readNameRecord(IRandomAccess random, int stringTableOffset) throws IOException { TTNameRecord record = new TTNameRecord(); // USHORT platformID Platform ID. record.setPlatformID(readUShort(random)); // USHORT encodingID Platform-specific encoding ID. record.setEncodingID(readUShort(random)); // USHORT languageID Language ID. record.setLanguageID(readUShort(random)); // USHORT nameID Name ID. record.setNameID(readUShort(random)); // USHORT length String length (in bytes). record.setLength(readUShort(random)); // USHORT offset String offset from start of storage area (in bytes). int nameOffset = readUShort(random); byte[] value = new byte[record.getLength()]; random.mark(); random.seek(stringTableOffset + nameOffset); random.read(value, 0, record.getLength()); record.setValue(new String(value, "UTF-16BE")); //$NON-NLS-1$ random.reset(); return record; } public short readShort(IRandomAccess random) throws IOException { int b1 = random.read(); int b2 = random.read(); if ((b1 | b2) < 0) { throw new IOException("unexpected end of stream"); //$NON-NLS-1$ } return (short) ((b1 << 8) + b2); } public TTTable readTable(TTFont font, IRandomAccess random) throws IOException { byte[] name = readBytes(random, 4); int checksum = readInt(random); int offset = readInt(random); int length = readInt(random); TTTable result = new TTTable(font, offset, length); result.setName(name); result.setChecksum(checksum); return result; } public void readTables(TTFont font, IRandomAccess random) throws IOException { font.setSfntVersion(readInt(random)); int tableCount = readUShort(random); // skip search range // skip entry selector // skip range shift random.seekBy(6); tables = new TTTable[tableCount]; for (int i = 0; i < tableCount; i++) { tables[i] = readTable(font, random); } } public long readUInt(IRandomAccess random) throws IOException { int b1 = random.read(); int b2 = random.read(); int b3 = random.read(); int b4 = random.read(); if ((b1 | b2 | b3 | b4) < 0) { throw new IOException("unexpected end of stream"); //$NON-NLS-1$ } return (((long) b1 << 24) + (b2 << 16) + (b3 << 8) + b4); } public int readUShort(IRandomAccess random) throws IOException { int b1 = random.read(); int b2 = random.read(); if ((b1 | b2) < 0) { throw new IOException("unexpected end of stream"); //$NON-NLS-1$ } return (b1 << 8) + b2; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/PACKAGE.java0000644000175000017500000000373611031105676025346 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; import java.util.logging.Logger; import de.intarsys.tools.logging.LogTools; import de.intarsys.tools.message.MessageBundle; import de.intarsys.tools.message.MessageBundleTools; public class PACKAGE { public final static MessageBundle Messages = MessageBundleTools .getMessageBundle(PACKAGE.class); public final static Logger Log = LogTools.getLogger(PACKAGE.class); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/CreateSubset.java0000644000175000017500000001316511356616274026714 0ustar twernertwernerpackage de.intarsys.cwt.font.truetype; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.randomaccess.RandomAccessByteArray; import de.intarsys.tools.stream.StreamTools; public class CreateSubset { public static byte[][] SubsetTables; static { // !!keep sorted!! SubsetTables = new byte[][] { // // TTFont.TABLE_CMAP, // TTFont.TABLE_CVT, // TTFont.TABLE_FGPM, // TTFont.TABLE_GLYF, // TTFont.TABLE_HEAD, // TTFont.TABLE_HHEA, // TTFont.TABLE_HMTX, // TTFont.TABLE_LOCA, // TTFont.TABLE_MAXP, // TTFont.TABLE_NAME, // TTFont.TABLE_OS2, // TTFont.TABLE_PREP // }; } final private TTFont font; final private Set glyphIndices; private TTFont result; public CreateSubset(TTFont font, Set glyphIndices) { super(); this.font = font; this.glyphIndices = glyphIndices; } /** * Add all dependent glyphs not yet included for any composite glyphs in the * set of glyphs. * * @param glyfRandom * @param locations * @param glyphs * @return * @throws IOException * @throws TrueTypeException */ protected Set addCompositeGlyphs(IRandomAccess glyfRandom, int[] locations, Set glyphs) throws IOException, TrueTypeException { Set allGlyphs = new HashSet(); allGlyphs.addAll(glyphs); for (Iterator i = glyphs.iterator(); i.hasNext();) { int codePoint = ((Integer) i.next()).intValue(); addCompositeGlyphs(glyfRandom, locations, allGlyphs, codePoint); } return allGlyphs; } /** * Add dependent glyphs not yet included for composite glyphs. * * @param glyfRandom * @param locations * @param glyphs * @param codePoint * @throws IOException * @throws TrueTypeException */ protected void addCompositeGlyphs(IRandomAccess glyfRandom, int[] locations, Set glyphs, int codePoint) throws IOException, TrueTypeException { if (locations[codePoint] == locations[codePoint + 1]) { return; } glyfRandom.seek(locations[codePoint]); TTFontParser parser = new TTFontParser(); int numContours = parser.readShort(glyfRandom); if (numContours >= 0) { return; } glyfRandom.seekBy(8); for (;;) { int flags = parser.readUShort(glyfRandom); int codePointRef = parser.readUShort(glyfRandom); glyphs.add(new Integer(codePointRef)); if ((flags & TTFont.MORE_COMPONENTS) == 0) { return; } int skip; if ((flags & TTFont.ARG_1_AND_2_ARE_WORDS) != 0) { skip = 4; } else { skip = 2; } if ((flags & TTFont.WE_HAVE_A_SCALE) != 0) { skip += 2; } else if ((flags & TTFont.WE_HAVE_AN_X_AND_Y_SCALE) != 0) { skip += 4; } if ((flags & TTFont.WE_HAVE_A_TWO_BY_TWO) != 0) { skip += 8; } glyfRandom.seekBy(skip); } } public TTFont compute() throws IOException, TrueTypeException { TTTable loca = getFont().getTable(TTFont.TABLE_LOCA); int[] locations = new TTFontParser().parseTable_loca(loca, getFont() .getFontHeader().isShortLocationFormat()); TTTable glyf = getFont().getTable(TTFont.TABLE_GLYF); IRandomAccess glyfRandom = glyf.getRandomAccess(); try { result = copySubset(); // always include glyph 0 getGlyphIndices().add(new Integer(0)); Set compositeGlyphs = addCompositeGlyphs(glyfRandom, locations, getGlyphIndices()); createGlyphTable(loca, glyf, glyfRandom, locations, compositeGlyphs, getFont().getFontHeader() .isShortLocationFormat()); return result; } finally { StreamTools.close(glyfRandom); } } protected TTFont copySubset() { TTFont resultFont = new TTFont(); List newTables = new ArrayList(); for (int i = 0; i < SubsetTables.length; i++) { TTTable table = getFont().getTable(SubsetTables[i]); if (table != null) { newTables.add(table); } } resultFont.setTables((TTTable[]) newTables.toArray(new TTTable[0])); return resultFont; } protected void createGlyphTable(TTTable loca, TTTable glyf, IRandomAccess glyfRandom, int[] oldLocations, Set glyphs, boolean shortFormat) throws IOException, TrueTypeException { // compute the total length for the new glyf table int newLength = 0; for (Iterator i = glyphs.iterator(); i.hasNext();) { int codePoint = ((Integer) i.next()).intValue(); if ((codePoint + 1) >= oldLocations.length) { continue; } newLength += (oldLocations[codePoint + 1] - oldLocations[codePoint]); } newLength = TTFont.align(newLength); // rebuild new glyf table int[] newLocations = new int[oldLocations.length]; byte[] newGlyfData = new byte[newLength]; int ptr = 0; for (int i = 0; i < oldLocations.length; i++) { newLocations[i] = ptr; if (glyphs.contains(new Integer(i))) { int glyfstart = oldLocations[i]; int glyflength = oldLocations[i + 1] - glyfstart; if (glyflength > 0) { glyfRandom.seek(glyfstart); glyfRandom.read(newGlyfData, ptr, glyflength); ptr += glyflength; } } } // store new loca table RandomAccessByteArray random = new RandomAccessByteArray(null); TTFontSerializer serializer = new TTFontSerializer(); serializer.write_loca(random, newLocations, shortFormat); loca.setBytes(random.toByteArray()); // store new glyf table glyf.setBytes(newGlyfData); } public TTFont getFont() { return font; } public Set getGlyphIndices() { return glyphIndices; } public TTFont getResult() { return result; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTFontHeader.java0000644000175000017500000000611111031105700026554 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; /** * */ public class TTFontHeader { public static int MACSTYLE_BOLD = 1 << 0; // Bit 0 public static int MACSTYLE_ITALIC = 1 << 1; // Bit 1 public static int MACSTYLE_UNDERLINE = 1 << 2; public static int MACSTYLE_OUTLINE = 1 << 3; public static int MACSTYLE_SHADOW = 1 << 4; public static int MACSTYLE_CONDENSED = 1 << 5; public static int MACSTYLE_EXTENDED = 1 << 6; private int flags; private int unitsPerEm; private short xMin; private short yMin; private short xMax; private short yMax; private int macStyle; private boolean shortLocationFormat; public int getFlags() { return flags; } public int getMacStyle() { return macStyle; } public int getUnitsPerEm() { return unitsPerEm; } public short getXMax() { return xMax; } public short getXMin() { return xMin; } public short getYMax() { return yMax; } public short getYMin() { return yMin; } public boolean isShortLocationFormat() { return shortLocationFormat; } public void setFlags(int i) { flags = i; } public void setMacStyle(int i) { macStyle = i; } public void setShortLocationFormat(boolean b) { shortLocationFormat = b; } public void setUnitsPerEm(int i) { unitsPerEm = i; } public void setXMax(short i) { xMax = i; } public void setXMin(short i) { xMin = i; } public void setYMax(short i) { yMax = i; } public void setYMin(short i) { yMin = i; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTMetricsPanose.java0000644000175000017500000000502711031105700027316 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; /** * */ public class TTMetricsPanose { public static int bFamilyType = 0; public static int bSerifStyle = 1; public static int bWeight = 2; public static int bProportion = 3; public static int bContrast = 4; public static int bStrokeVariation = 5; public static int bArmStyle = 6; public static int bLetterform = 7; public static int bMidline = 8; public static int bXHeight = 9; public static int cProportionMonospaced = 9; private byte[] panose; public TTMetricsPanose(byte[] panoseBytes) { if ((panoseBytes == null) || (panoseBytes.length != 10)) { throw new IllegalArgumentException( "TrueType table OS/2: panose bytes must not be null and exactly 10 bytes long"); //$NON-NLS-1$ } this.panose = panoseBytes; } public byte[] getPanose() { return panose; } public boolean isProportionMonospaced() { return getPanose()[bProportion] == cProportionMonospaced; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTNaming.java0000644000175000017500000000465511031105700025761 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * */ public class TTNaming { private List nameRecords; public TTNaming() { nameRecords = new ArrayList(20); } public void add(int nameId, TTNameRecord record) { getNameRecords().add(record); } public TTNameRecord getNameRecord(int nameId) { for (Iterator it = nameRecords.iterator(); it.hasNext();) { TTNameRecord record = (TTNameRecord) it.next(); if (record.getNameID() == nameId) { return record; } } return null; } public List getNameRecords() { return nameRecords; } public String getValue(int nameId) { TTNameRecord r = getNameRecord(nameId); if (r != null) { return r.getValue(); } return null; } public void setNameRecords(List list) { nameRecords = list; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/truetype/TTFontSerializer.java0000644000175000017500000001465311153723454027530 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font.truetype; import java.io.IOException; import de.intarsys.tools.randomaccess.IRandomAccess; import de.intarsys.tools.stream.StreamTools; /** * */ public class TTFontSerializer { private TTFont font; private int tableOffset = 0; public TTFontSerializer() { super(); } public TTFont getFont() { return font; } public void write(IRandomAccess random, TTFont pFont) throws IOException { this.font = pFont; writeFontHeader(random); writeTableDirectory(random); writeTables(random); } public void write_loca(IRandomAccess random, int[] locations, boolean shortFormat) throws IOException { for (int i = 0; i < locations.length; i++) { if (shortFormat) { writeShort(random, locations[i] >> 1); } else { writeInt(random, locations[i]); } } } public void write_name(IRandomAccess random, TTNameRecord[] names) throws IOException { int offset = 6 + (names.length * 12); writeShort(random, 0); writeShort(random, names.length); writeShort(random, offset); int nameOffset = 0; for (int i = 0; i < names.length; i++) { writeShort(random, names[i].getPlatformID()); writeShort(random, names[i].getEncodingID()); writeShort(random, names[i].getLanguageID()); writeShort(random, names[i].getNameID()); writeShort(random, names[i].getLength()); writeShort(random, nameOffset); nameOffset += names[i].getLength(); } for (int i = 0; i < names.length; i++) { writeBytes( random, names[i].getValue().getBytes("UTF-16BE"), 0, names[i].getLength()); //$NON-NLS-1$ } } public void writeByte(IRandomAccess random, int value) throws IOException { random.write(value); } public void writeBytes(IRandomAccess random, byte[] value, int off, int len) throws IOException { random.write(value, off, len); } /** *
	 * Fixed sfnt version 0x00010000 for version 1.0.
	 * USHORT numTables Number of tables.
	 * USHORT searchRange (Maximum power of 2 <= numTables) x 16.
	 * USHORT entrySelector Log2(maximum power of 2 <= numTables).
	 * USHORT rangeShift NumTables x 16-searchRange.
	 * 
* * @throws IOException */ protected void writeFontHeader(IRandomAccess random) throws IOException { int numTables = getFont().getTables().length; int maxPower = 1; int log2MaxPower = 0; while (maxPower <= numTables) { maxPower = maxPower << 1; log2MaxPower += 1; } if (log2MaxPower > 0) { // we are 1 step to far... maxPower = maxPower >> 1; log2MaxPower--; } writeInt(random, 0x00010000); writeShort(random, numTables); writeShort(random, maxPower << 4); writeShort(random, log2MaxPower); writeShort(random, (numTables - maxPower) << 4); } public void writeInt(IRandomAccess random, int value) throws IOException { random.write((byte) (value >> 24)); random.write((byte) (value >> 16)); random.write((byte) (value >> 8)); random.write((byte) (value)); } public void writeShort(IRandomAccess random, int value) throws IOException { random.write((byte) (value >> 8)); random.write((byte) (value)); } protected void writeTableDirectory(IRandomAccess random) throws IOException { // todo recompute table directory information int tableCount = getFont().getTables().length; tableOffset = (tableCount * 16) + 12; for (int i = 0; i < tableCount; i++) { TTTable table = getFont().getTables()[i]; writeTableDirectoryTable(random, table); } } protected void writeTableDirectoryTable(IRandomAccess random, TTTable table) throws IOException { int length = (int) table.getLength(); writeBytes(random, table.getName(), 0, table.getName().length); writeInt(random, table.getChecksum()); writeInt(random, tableOffset); writeInt(random, length); // table.setOffset(tableOffset); tableOffset = (tableOffset + length + 3) & (~3); } protected void writeTables(IRandomAccess random) throws IOException { int tableCount = getFont().getTables().length; /** * java.util.Arrays.sort(getFont().getTables(), new Comparator() { * public int compare(Object o1, Object o2) { return (int) (((TTTable) * o1).getOffset() - ((TTTable) o2).getOffset()); }}); */ for (int i = 0; i < tableCount; i++) { TTTable table = getFont().getTables()[i]; writeTablesTable(random, table); } } protected void writeTablesTable(IRandomAccess random, TTTable table) throws IOException { IRandomAccess tableRandom = table.getRandomAccess(); try { tableRandom.seek(0); int length = (int) table.getLength(); for (int i = 0; i < length; i++) { writeByte(random, tableRandom.read()); } // pad with zeros // todo make faster for (int i = length; i < ((length + 3) & (~3)); i++) { writeByte(random, (byte) 0); } } finally { StreamTools.close(tableRandom); } } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontEnvironment.java0000644000175000017500000002255011411054016025551 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; import java.awt.Font; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import sun.font.FontManager; import de.intarsys.cwt.freetype.Face; import de.intarsys.cwt.freetype.Freetype; import de.intarsys.cwt.freetype.Library; import de.intarsys.tools.installresource.InstallFileList; import de.intarsys.tools.locator.FileLocator; import de.intarsys.tools.stream.StreamTools; /** * */ public class FontEnvironment { private static final Logger Log = PACKAGE.Log; private static FontEnvironment Unique = new FontEnvironment(); static public FontEnvironment get() { return Unique; } static public void set(FontEnvironment environment) { Unique = environment; } private List fontClassLoaders = new ArrayList(); private List fontDirectories = new ArrayList(); private List fontFiles = new ArrayList(); private boolean registeredSystem = false; private boolean registeredUser = false; public FontEnvironment() { registerFontClassLoader(getClass().getClassLoader()); } synchronized public ClassLoader[] getFontClassLoaders() { return fontClassLoaders .toArray(new ClassLoader[fontClassLoaders.size()]); } synchronized public File[] getFontDirectories() { return fontDirectories.toArray(new File[fontDirectories.size()]); } synchronized public File[] getFontFiles() { return fontFiles.toArray(new File[fontFiles.size()]); } /** * This method determines the system's font directories. * * @return an array containing the font directory paths found on the local * system */ synchronized public File[] getSystemFontDirectories() { String definition = null; // force FontManager initialization Font.decode("dummy").getFamily(); //$NON-NLS-1$ definition = FontManager.getFontPath(true); if (definition == null) { return new File[0]; } String[] names = definition.split(System.getProperty("path.separator")); //$NON-NLS-1$ File[] files = new File[names.length]; for (int i = 0; i < names.length; i++) { files[i] = new File(names[i]); } return files; } protected void loadFontClassLoader(Library library, ClassLoader loader) { try { InstallFileList installer = new InstallFileList("fonts", "fonts.list", false); installer.loadAll(); File[] roots = installer.getFiles(); for (int i = 0; i < roots.length; i++) { File root = roots[i]; File[] fontFiles = root.listFiles(); for (int j = 0; j < fontFiles.length; j++) { File file = fontFiles[j]; try { processFontFile(library, file); } catch (IOException e) { Log.log(Level.WARNING, "error loading font '" + file.getName() + "'", e); } finally { } } } } catch (IOException e) { Log.log(Level.WARNING, "error looking up 'font/fonts.list' resources", e); } } protected void loadFontDirectory(Library library, File directory) { if (!directory.exists()) { return; } if (!directory.isDirectory()) { return; } File[] files = directory.listFiles(); if (files == null) { return; } for (int i = 0; i < files.length; i++) { File file = files[i]; loadFontFile(library, file); } } protected void loadFontFile(Library library, File file) { if (!file.isFile()) { return; } String filepath = file.getAbsolutePath(); try { /* * the absolute path/canonical path check is used to find out if the * file path contains a symbolic link. if so we can ignore the file * because it will also show up in another directory as a "real" * file. */ if (!filepath.equals(file.getCanonicalPath())) { return; } } catch (IOException ex) { return; } loadFontUnchecked(library, filepath); } protected void loadFontMapClassLoader(Library library, ClassLoader loader) { try { Enumeration urls = loader.getResources("fonts/fonts.maps"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); InputStream is = null; try { is = url.openStream(); parseMaps(library, loader, is); } catch (IOException e) { Log.log(Level.WARNING, "error loading 'fonts/fonts.maps' from '" + url + "'", e); } finally { StreamTools.close(is); } } } catch (IOException e) { Log.log(Level.WARNING, "error looking up 'font/fonts.maps' resources", e); } } protected IFont loadFontUnchecked(Library library, String filepath) { FileLocator locator = new FileLocator(filepath); Face face = library.newFace(filepath, 0); if (face != null) { IFont font = null; try { font = GenericFont.createNew(locator, face); FontRegistry.get().registerFont(font); } finally { face.doneFace(); } return font; } else { // Log.log(Level.WARNING, "can't register font for " + filepath); return null; } } protected void loadSystemFonts(Library library) { File[] files; files = getSystemFontDirectories(); for (int i = 0; i < files.length; i++) { File directory = files[i]; loadFontDirectory(library, directory); } } protected void loadUserFonts(Library library) { File[] files; files = getFontDirectories(); for (int i = 0; i < files.length; i++) { File directory = files[i]; loadFontDirectory(library, directory); } files = getFontFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; loadFontFile(library, file); } ClassLoader[] loaders = getFontClassLoaders(); for (int i = 0; i < loaders.length; i++) { ClassLoader loader = loaders[i]; loadFontClassLoader(library, loader); loadFontMapClassLoader(library, loader); } } protected void parseMaps(Library library, ClassLoader loader, InputStream is) throws IOException { StringBuilder sb = new StringBuilder(); int i = is.read(); while (i != -1) { if (i == '\n') { String map = sb.toString().trim(); processFontMap(library, loader, map); sb.setLength(0); i = is.read(); continue; } sb.append((char) i); i = is.read(); } String map = sb.toString().trim(); processFontMap(library, loader, map); } protected void processFontFile(Library library, File file) throws IOException { IFont font = loadFontUnchecked(library, file.getAbsolutePath()); if (font == null) { return; } FontTools.mapFont(font.getFontName(), font); } protected void processFontMap(Library library, ClassLoader loader, String map) throws IOException { if (map.length() == 0 || map.startsWith("#")) { return; } String[] split = map.split("\\="); if (split.length < 2) { return; } FontTools.mapAlias(split[0], split[1]); } public synchronized void registerFontClassLoader(ClassLoader loader) { fontClassLoaders.add(loader); } public synchronized void registerFontDirectory(File directory) { fontDirectories.add(directory); } synchronized public void registerFontFile(File file) { fontFiles.add(file); } synchronized public boolean registerSystemFonts() { if (registeredSystem) { return false; } registeredSystem = true; Library library = Freetype.initFreeType(); try { loadSystemFonts(library); } finally { library.doneFreeType(); } return true; } synchronized public boolean registerUserFonts() { if (registeredUser) { return false; } registeredUser = true; Library library = Freetype.initFreeType(); try { loadUserFonts(library); } finally { library.doneFreeType(); } return true; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/StandardFontRegistry.java0000644000175000017500000002005511411054016026534 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import de.intarsys.tools.collection.ListTools; /** * */ public class StandardFontRegistry implements IFontRegistry { private final Map fontFamilyMap = new HashMap(); private final List fontFamilies = new ArrayList(); private final Map fontMap = new HashMap(); private final List fonts = new ArrayList(); public StandardFontRegistry() { // } protected IFont basicLookup(String key, IFontQuery query) { if (key == null) { return null; } Object result = fontMap.get(key); if (result == null) { return null; } else if (result instanceof IFont) { return (IFont) result; } else { // collision // there are a number of ill declared fonts around.... for (Iterator it = ((List) result).iterator(); it.hasNext();) { IFont font = (IFont) it.next(); if (basicMatchFamilyStyle(query, font)) { return font; } } for (Iterator it = ((List) result).iterator(); it.hasNext();) { IFont font = (IFont) it.next(); if (basicMatchFamily(query, font)) { return font; } } return null; } } protected boolean basicMatchFamily(IFontQuery query, IFont font) { return query.getFontFamilyName().indexOf(font.getFontFamilyName()) >= 0; } protected boolean basicMatchFamilyStyle(IFontQuery query, IFont font) { return query.getFontNameCanonical().equals(font.getFontNameCanonical()); } protected void basicRegister(String key, IFont value) { // overwrite - this is the most obvious case Object previous = fontMap.put(key, value); if (previous == null) { return; } if (previous instanceof List) { ((List) previous).add(value); // reset, was overwritten fontMap.put(key, previous); } else { // new entry fontMap.put(key, ListTools.with(previous, value)); } } synchronized public IFontFamily[] getFontFamilies() { FontEnvironment.get().registerUserFonts(); FontEnvironment.get().registerSystemFonts(); return fontFamilies.toArray(new IFontFamily[fontFamilies.size()]); } synchronized public IFont[] getFonts() { FontEnvironment.get().registerUserFonts(); FontEnvironment.get().registerSystemFonts(); return fonts.toArray(new IFont[fonts.size()]); } protected Object getLookupKeyFontFamily(IFontQuery query) { StringBuilder sb = new StringBuilder(); sb.append("["); if (query.getFontType() == null) { sb.append("Any"); } else { sb.append(query.getFontType()); } sb.append("]"); sb.append(query.getFontFamilyName()); return sb.toString(); } protected String getLookupKeyFontName(IFontQuery query) { if (query.getFontName() == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append("["); if (query.getFontType() == null) { sb.append("Any"); } else { sb.append(query.getFontType()); } sb.append("]"); sb.append(query.getFontName()); return sb.toString(); } protected String getLookupKeyFontNameAsCanonical(IFontQuery query) { if (query.getFontName() == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append("["); if (query.getFontType() == null) { sb.append("Any"); } else { sb.append(query.getFontType()); } sb.append("-canonical]"); sb.append(query.getFontName()); return sb.toString(); } protected String getLookupKeyFontNameCanonical(IFontQuery query) { StringBuilder sb = new StringBuilder(); sb.append("["); if (query.getFontType() == null) { sb.append("Any"); } else { sb.append(query.getFontType()); } sb.append("-canonical]"); sb.append(query.getFontNameCanonical()); return sb.toString(); } protected String getLookupKeyFontNamePostScript(IFontQuery query) { if (query.getFontName() == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append("["); if (query.getFontType() == null) { sb.append("Any"); } else { sb.append(query.getFontType()); } sb.append("-postscript]"); sb.append(query.getFontName()); return sb.toString(); } public IFont lookupFont(IFontQuery query) { // best fallbacks ever IFont result = basicLookup(getLookupKeyFontName(query), query); if (result == null) { result = basicLookup(getLookupKeyFontNamePostScript(query), query); if (result == null) { result = basicLookup(getLookupKeyFontNameCanonical(query), query); if (result == null) { result = basicLookup( getLookupKeyFontNameAsCanonical(query), query); } } } return result; } public IFontFamily lookupFontFamily(IFontQuery query) { return fontFamilyMap.get(getLookupKeyFontFamily(query)); } public void registerFont(IFont font) { String type = font.getFontType(); String familyName = font.getFontFamilyName(); if (familyName != null) { String familyKey = "[" + type + "]" + familyName; IFontFamily fontFamily = fontFamilyMap.get(familyKey); if (fontFamily == null) { fontFamily = new FontFamily(familyName); fontFamilyMap.put(familyKey, fontFamily); fontFamilies.add(fontFamily); } fontFamily.registerFont(font); // familyKey = "[Any]" + familyName; fontFamily = fontFamilyMap.get(familyKey); if (fontFamily == null) { fontFamily = new FontFamily(familyName); fontFamilyMap.put(familyKey, fontFamily); } fontFamily.registerFont(font); } String fontName = font.getFontName(); String fontNamePostScript = font.getFontNamePostScript(); String fontNameCanonical = font.getFontNameCanonical(); String fontKey; fontKey = "[" + type + "]" + fontName; basicRegister(fontKey, font); fontKey = "[" + type + "-postscript]" + fontNamePostScript; basicRegister(fontKey, font); fontKey = "[" + type + "-canonical]" + fontNameCanonical; basicRegister(fontKey, font); fontKey = "[Any]" + fontName; basicRegister(fontKey, font); fontKey = "[Any-postscript]" + fontNamePostScript; basicRegister(fontKey, font); fontKey = "[Any-canonical]" + fontNameCanonical; basicRegister(fontKey, font); // fonts.add(font); } protected String removeSpaces(String name) { int pos = 0; while ((pos = name.indexOf(' ')) != -1) { name = name.substring(0, pos) + name.substring(pos + 1); } return name; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontAliasMap.java0000644000175000017500000000366411031105670024742 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; /** * */ public class FontAliasMap extends FontMap { final private String alias; public FontAliasMap(FontMapper mapper, String name, String alias) { super(mapper, name); this.alias = alias; } public String getAlias() { return alias; } @Override public IFont getFont() { return getMapper().lookupFont(getAlias()); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/IFontFamily.java0000644000175000017500000000545111061743412024606 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; /** * The family a font belongs to. This is a collection of similar fonts that are * different with respect to their style. * */ public interface IFontFamily { /** * for example * * @return for example */ public String getFamilyName(); /** * The {@link IFont} within the family with a specific {@link FontStyle} or * null. * * @param style * The requested style. * @return The {@link IFont} within the family with a specific * {@link FontStyle} or null. */ public IFont getFont(FontStyle style); /** * All {@link IFont} instances within this family. * * @return All {@link IFont} instances within this family. */ public IFont[] getFonts(); /** * The supported {@link FontStyle} instances in this family. * * @return The supported {@link FontStyle} instances in this family. * */ public FontStyle[] getFontStyles(); /** * The font type. This is for example "TrueType" or "Type1". * * @return The font type. */ public String getFontType(); /** * Add a new {@link IFont} to this family. * * @param font * The new {@link IFont} */ public void registerFont(IFont font); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/FontFontMap.java0000644000175000017500000000353411031105670024613 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.font; /** * */ public class FontFontMap extends FontMap { private final IFont font; public FontFontMap(FontMapper mapper, String name, IFont font) { super(mapper, name); this.font = font; } @Override public IFont getFont() { return font; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/font/IFontQuery.java0000644000175000017500000000204711122530220024455 0ustar twernertwernerpackage de.intarsys.cwt.font; /** * An object that can select {@link IFont} instances within a collection. * */ public interface IFontQuery { /** * The desired font family for the {@link IFont}. * * @return The desired font family for the {@link IFont}. */ public String getFontFamilyName(); /** * The desired font name for the {@link IFont}. * * @return The desired font name for the {@link IFont}. */ public String getFontName(); /** * The desired font name for the {@link IFont}. * * @return The desired font name for the {@link IFont}. */ public Object getFontNameCanonical(); /** * The desired font style for the {@link IFont}. * * @return The desired font style for the {@link IFont}. */ public FontStyle getFontStyle(); /** * The desired font type for the {@link IFont} (such as "Type1" or * "TrueType"). nullindicates a font of any type. * * @return The desired font type for the {@link IFont}. */ public String getFontType(); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/0000755000175000017500000000000011412336240021421 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/image/0000755000175000017500000000000011412336240022503 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/image/ImageConverterSwt2Awt.java0000644000175000017500000000525711032364660027532 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.swt.image; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.WritableRaster; import org.eclipse.swt.graphics.ImageData; import de.intarsys.cwt.awt.image.CwtAwtImageTools; public class ImageConverterSwt2Awt { private BufferedImage bufferedImage; private ImageData imageData; public ImageConverterSwt2Awt(ImageData imageData) { this.imageData = imageData; } protected BufferedImage createBufferedImage() { ColorModel colorModel; WritableRaster raster; // will only work if device independent image is standard rgb // TODO we also have others colorModel = CwtAwtImageTools.getRgbColorModel(); raster = colorModel.createCompatibleWritableRaster( getImageData().width, getImageData().height); raster.setDataElements(0, 0, getImageData().data); return new BufferedImage(colorModel, raster, false, null); } public BufferedImage getBufferedImage() { if (bufferedImage == null) { bufferedImage = createBufferedImage(); } return bufferedImage; } public ImageData getImageData() { return imageData; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/image/ISwtPaint.java0000644000175000017500000000346011032364660025240 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.swt.image; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Resource; import de.intarsys.cwt.common.IPaint; public interface ISwtPaint extends IPaint { public Resource toResource(Device device); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/image/SwtCompatibleRaster.java0000644000175000017500000012575311032364660027326 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.swt.image; import java.awt.Point; import java.awt.Rectangle; import java.awt.image.ComponentSampleModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.PixelInterleavedSampleModel; import java.awt.image.Raster; import java.awt.image.RasterFormatException; import java.awt.image.SampleModel; import java.awt.image.SinglePixelPackedSampleModel; import java.awt.image.WritableRaster; public class SwtCompatibleRaster extends WritableRaster { /** private band offset for use by native code */ protected int bandOffset; /** If packed == true, the SampleModel's bit masks. */ int[] bitMasks; /** If packed == true, the SampleModel's bit offsets. */ int[] bitOffsets; /** The image data array. */ protected byte[] data; /** Data offsets for each band of image data. */ protected int[] dataOffsets; /** * The DataBuffer offset, minus sampleModelTranslateX*pixelStride, minus * sampleModelTranslateY*scanlineStride, used to calculate pixel offsets. */ int dbOffset; int dbOffsetPacked; /** True if the data offsets range from 0 to (pixelStride - 1) in order. */ boolean inOrder; /** A cached copy of minX + width for use in bounds checks. */ private int maxX; /** A cached copy of minY + height for use in bounds checks. */ private int maxY; /** True if a SinglePixelPackedSampleModel is being used. */ boolean packed = false; /** Pixel stride of the image data contained in this Raster. */ protected int pixelStride; /** Scanline stride of the image data contained in this Raster. */ protected int scanlineStride; int type; public SwtCompatibleRaster(SampleModel paramSampleModel, DataBuffer paramDataBuffer, Point origin) { this(paramSampleModel, paramDataBuffer, new Rectangle(origin.x, origin.y, paramSampleModel.getWidth(), paramSampleModel .getHeight()), origin, null); } public SwtCompatibleRaster(SampleModel paramSampleModel, DataBuffer paramDataBuffer, Rectangle aRegion, Point origin, WritableRaster paramParent) { super(paramSampleModel, paramDataBuffer, aRegion, origin, paramParent); this.maxX = minX + width; this.maxY = minY + height; if (!(dataBuffer instanceof DataBufferByte)) { throw new RasterFormatException("SwtCompatibleRasters must have " + "byte DataBuffers"); } DataBufferByte dbb = (DataBufferByte) dataBuffer; this.data = dbb.getData(); int xOffset = aRegion.x - origin.x; int yOffset = aRegion.y - origin.y; if (sampleModel instanceof PixelInterleavedSampleModel || (sampleModel instanceof ComponentSampleModel && isInterleaved((ComponentSampleModel) sampleModel))) { ComponentSampleModel csm = (ComponentSampleModel) sampleModel; this.scanlineStride = csm.getScanlineStride(); this.pixelStride = csm.getPixelStride(); this.dataOffsets = csm.getBandOffsets(); for (int i = 0; i < getNumDataElements(); i++) { dataOffsets[i] += xOffset * pixelStride + yOffset * scanlineStride; } } else if (sampleModel instanceof SinglePixelPackedSampleModel) { SinglePixelPackedSampleModel sppsm = (SinglePixelPackedSampleModel) sampleModel; this.packed = true; this.bitMasks = sppsm.getBitMasks(); this.bitOffsets = sppsm.getBitOffsets(); this.scanlineStride = sppsm.getScanlineStride(); this.pixelStride = 1; this.dataOffsets = new int[1]; this.dataOffsets[0] = dbb.getOffset(); dataOffsets[0] += xOffset * pixelStride + yOffset * scanlineStride; } else { throw new RasterFormatException( "SwtCompatibleRasters must " + "have PixelInterleavedSampleModel, SinglePixelPackedSampleModel" + " or interleaved ComponentSampleModel. Sample model is " + sampleModel); } this.bandOffset = this.dataOffsets[0]; this.dbOffsetPacked = dataBuffer.getOffset() - sampleModelTranslateY * scanlineStride - sampleModelTranslateX * pixelStride; this.dbOffset = dbOffsetPacked - (xOffset * pixelStride + yOffset * scanlineStride); // Set inOrder to true if the data elements are in order and // have no gaps between them this.inOrder = false; if (numDataElements == pixelStride) { inOrder = true; for (int i = 1; i < numDataElements; i++) { if (dataOffsets[i] - dataOffsets[0] != i) { inOrder = false; break; } } } verify(false); } public SwtCompatibleRaster(SampleModel paramSampleModel, Point origin) { super(paramSampleModel, origin); } /** * Creates a subraster given a region of the raster. The x and y coordinates * specify the horizontal and vertical offsets from the upper-left corner of * this raster to the upper-left corner of the subraster. A subset of the * bands of the parent Raster may be specified. If this is null, then all * the bands are present in the subRaster. A translation to the subRaster * may also be specified. Note that the subraster will reference the same * DataBuffer as the parent raster, but using different offsets. * * @param x * X offset. * @param y * Y offset. * @param width * Width (in pixels) of the subraster. * @param height * Height (in pixels) of the subraster. * @param x0 * Translated X origin of the subraster. * @param y0 * Translated Y origin of the subraster. * @param bandList * Array of band indices. * @exception RasterFormatException * if the specified bounding box is outside of the parent * raster. */ @Override public Raster createChild(int x, int y, int width, int height, int x0, int y0, int[] bandList) { return createWritableChild(x, y, width, height, x0, y0, bandList); } /** * Creates a Raster with the same layout and the same width and height, and * with new zeroed data arrays. If the Raster is a subRaster, this will call * createCompatibleRaster(width, height). */ @Override public WritableRaster createCompatibleWritableRaster() { return createCompatibleWritableRaster(width, height); } /** * Creates a Raster with the same layout but using a different width and * height, and with new zeroed data arrays. */ @Override public WritableRaster createCompatibleWritableRaster(int w, int h) { if (w <= 0 || h <= 0) { throw new RasterFormatException("negative " + ((w <= 0) ? "width" : "height")); } SampleModel sm = sampleModel.createCompatibleSampleModel(w, h); return new SwtCompatibleRaster(sm, new Point(0, 0)); } /** * Creates a Writable subRaster given a region of the Raster. The x and y * coordinates specify the horizontal and vertical offsets from the * upper-left corner of this Raster to the upper-left corner of the * subRaster. A subset of the bands of the parent Raster may be specified. * If this is null, then all the bands are present in the subRaster. A * translation to the subRaster may also be specified. Note that the * subRaster will reference the same DataBuffer as the parent Raster, but * using different offsets. * * @param x * X offset. * @param y * Y offset. * @param width * Width (in pixels) of the subraster. * @param height * Height (in pixels) of the subraster. * @param x0 * Translated X origin of the subraster. * @param y0 * Translated Y origin of the subraster. * @param bandList * Array of band indices. * @exception RasterFormatException * if the specified bounding box is outside of the parent * Raster. */ @Override public WritableRaster createWritableChild(int x, int y, int width, int height, int x0, int y0, int[] bandList) { if (x < this.minX) { throw new RasterFormatException("x lies outside the raster"); } if (y < this.minY) { throw new RasterFormatException("y lies outside the raster"); } if ((x + width < x) || (x + width > this.minX + this.width)) { throw new RasterFormatException("(x + width) is outside of Raster"); } if ((y + height < y) || (y + height > this.minY + this.height)) { throw new RasterFormatException("(y + height) is outside of Raster"); } SampleModel sm; if (bandList != null) sm = sampleModel.createSubsetSampleModel(bandList); else sm = sampleModel; int deltaX = x0 - x; int deltaY = y0 - y; return new SwtCompatibleRaster(sm, dataBuffer, new Rectangle(x0, y0, width, height), new Point(sampleModelTranslateX + deltaX, sampleModelTranslateY + deltaY), this); } /** * Returns a byte array of data elements from the specified rectangular * region. An ArrayIndexOutOfBounds exception will be thrown at runtime if * the pixel coordinates are out of bounds. * *
	 * byte[] bandData = raster.getByteData(x, y, w, h, null);
	 * int numDataElements = raster.getnumDataElements();
	 * byte[] pixel = new byte[numDataElements];
	 * // To find a data element at location (x2, y2)
	 * System.arraycopy(bandData, ((y2 - y) * w + (x2 - x)) * numDataElements, pixel,
	 * 		0, numDataElements);
	 * 
* * @param x * The X coordinate of the upper left pixel location. * @param y * The Y coordinate of the upper left pixel location. * @param width * Width of the pixel rectangle. * @param height * Height of the pixel rectangle. * @param outData * If non-null, data elements for all bands at the specified * location are returned in this array. * @return Data array with data elements for all bands. */ public byte[] getByteData(int x, int y, int w, int h, byte[] outData) { if ((x < this.minX) || (y < this.minY) || (x + w > this.maxX) || (y + h > this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } if (outData == null) { outData = new byte[numDataElements * w * h]; } int yoff = (y - minY) * scanlineStride + (x - minX) * pixelStride; int xoff; int off = 0; int xstart; int ystart; if (inOrder) { yoff += dataOffsets[0]; int rowBytes = w * pixelStride; if (scanlineStride == rowBytes) { System.arraycopy(data, yoff, outData, off, rowBytes * h); } else { for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { System.arraycopy(data, yoff, outData, off, rowBytes); off += rowBytes; } } } else if (numDataElements == 1) { yoff += dataOffsets[0]; for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { outData[off++] = data[xoff]; } } } else if (numDataElements == 2) { yoff += dataOffsets[0]; int d1 = dataOffsets[1] - dataOffsets[0]; for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { outData[off++] = data[xoff]; outData[off++] = data[xoff + d1]; } } } else if (numDataElements == 3) { yoff += dataOffsets[0]; int d1 = dataOffsets[1] - dataOffsets[0]; int d2 = dataOffsets[2] - dataOffsets[0]; for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { outData[off++] = data[xoff]; outData[off++] = data[xoff + d1]; outData[off++] = data[xoff + d2]; } } } else if (numDataElements == 4) { yoff += dataOffsets[0]; int d1 = dataOffsets[1] - dataOffsets[0]; int d2 = dataOffsets[2] - dataOffsets[0]; int d3 = dataOffsets[3] - dataOffsets[0]; for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { outData[off++] = data[xoff]; outData[off++] = data[xoff + d1]; outData[off++] = data[xoff + d2]; outData[off++] = data[xoff + d3]; } } } else { for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { for (int c = 0; c < numDataElements; c++) { outData[off++] = data[dataOffsets[c] + xoff]; } } } } return outData; } /** * Returns a byte array of data elements from the specified rectangular * region for the specified band. An ArrayIndexOutOfBounds exception will be * thrown at runtime if the pixel coordinates are out of bounds. * *
	 * byte[] bandData = raster.getByteData(x, y, w, h, null);
	 * 
	 * // To find the data element at location (x2, y2)
	 * byte bandElement = bandData[((y2 - y) * w + (x2 - x))];
	 * 
* * @param x * The X coordinate of the upper left pixel location. * @param y * The Y coordinate of the upper left pixel location. * @param width * Width of the pixel rectangle. * @param height * Height of the pixel rectangle. * @param band * The band to return. * @param outData * If non-null, data elements for all bands at the specified * location are returned in this array. * @return Data array with data elements for all bands. */ public byte[] getByteData(int x, int y, int w, int h, int band, byte[] outData) { // Bounds check for 'band' will be performed automatically if ((x < this.minX) || (y < this.minY) || (x + w > this.maxX) || (y + h > this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } if (outData == null) { outData = new byte[w * h]; } int yoff = (y - minY) * scanlineStride + (x - minX) * pixelStride + dataOffsets[band]; int xoff; int off = 0; int xstart; int ystart; if (pixelStride == 1) { if (scanlineStride == w) { System.arraycopy(data, yoff, outData, 0, w * h); } else { for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { System.arraycopy(data, yoff, outData, off, w); off += w; } } } else { for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { outData[off++] = data[xoff]; } } } return outData; } /** * Returns an array of data elements from the specified rectangular region. * An ArrayIndexOutOfBounds exception will be thrown at runtime if the pixel * coordinates are out of bounds. A ClassCastException will be thrown if the * input object is non null and references anything other than an array of * transferType. * *
	 * byte[] bandData = (byte[]) raster.getDataElements(x, y, w, h, null);
	 * int numDataElements = raster.getNumDataElements();
	 * byte[] pixel = new byte[numDataElements];
	 * // To find a data element at location (x2, y2)
	 * System.arraycopy(bandData, ((y2 - y) * w + (x2 - x)) * numDataElements, pixel,
	 * 		0, numDataElements);
	 * 
* * @param x * The X coordinate of the upper left pixel location. * @param y * The Y coordinate of the upper left pixel location. * @param width * Width of the pixel rectangle. * @param height * Height of the pixel rectangle. * @param outData * An object reference to an array of type defined by * getTransferType() and length w*h*getNumDataElements(). If null * an array of appropriate type and size will be allocated. * @return An object reference to an array of type defined by * getTransferType() with the request pixel data. */ @Override public Object getDataElements(int x, int y, int w, int h, Object obj) { return getByteData(x, y, w, h, (byte[]) obj); } /** * Returns the data elements for all bands at the specified location. An * ArrayIndexOutOfBounds exception will be thrown at runtime if the pixel * coordinate is out of bounds. A ClassCastException will be thrown if the * input object is non null and references anything other than an array of * transferType. * * @param actualX * The X coordinate of the pixel location. * @param actualY * The Y coordinate of the pixel location. * @param outData * An object reference to an array of type defined by * getTransferType() and length getNumDataElements(). If null an * array of appropriate type and size will be allocated. * @return An object reference to an array of type defined by * getTransferType() with the request pixel data. */ @Override public Object getDataElements(int actualX, int actualY, Object obj) { byte outData[]; if (obj == null) { outData = new byte[numDataElements]; } else { outData = (byte[]) obj; } if ((actualX < this.minX) || (actualY < this.minY) || (actualX >= this.maxX) || (actualY >= this.maxY)) { for (int band = 0; band < numDataElements; band++) { outData[band] = 0; } return outData; } int off = (actualY - minY) * scanlineStride + (actualX - minX) * pixelStride; for (int band = 0; band < numDataElements; band++) { outData[band] = data[dataOffsets[band] + off]; } return outData; } /** * Returns the data offset for the specified band. The data offset is the * index into the data array in which the first sample of the first scanline * is stored. * * @param band * The band whose offset is returned. */ public int getDataOffset(int band) { return dataOffsets[band]; } /** * Returns a copy of the data offsets array. For each band the data offset * is the index into the band's data array, of the first sample of the band. */ public int[] getDataOffsets() { return dataOffsets.clone(); } /** * Returns a reference to the data array. */ public byte[] getDataStorage() { return data; } @Override public int[] getPixels(int x, int y, int w, int h, int[] iArray) { if ((x < this.minX) || (y < this.minY) || (x + w > this.maxX) || (y + h > this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } int pixels[]; if (iArray != null) { pixels = iArray; } else { pixels = new int[w * h * numBands]; } int lineOffset = y * scanlineStride + x * pixelStride; int dstOffset = 0; if (packed) { lineOffset += dbOffsetPacked; for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { int value = data[lineOffset + i]; for (int k = 0; k < numBands; k++) { pixels[dstOffset++] = (value & bitMasks[k]) >>> bitOffsets[k]; } } lineOffset += scanlineStride; } } else { lineOffset += dbOffset; int d0 = dataOffsets[0]; if (numBands == 1) { for (int j = 0; j < h; j++) { int pixelOffset = lineOffset + d0; for (int i = 0; i < w; i++) { pixels[dstOffset++] = data[pixelOffset] & 0xff; pixelOffset += pixelStride; } lineOffset += scanlineStride; } } else if (numBands == 2) { int d1 = dataOffsets[1] - d0; for (int j = 0; j < h; j++) { int pixelOffset = lineOffset + d0; for (int i = 0; i < w; i++) { pixels[dstOffset++] = data[pixelOffset] & 0xff; pixels[dstOffset++] = data[pixelOffset + d1] & 0xff; pixelOffset += pixelStride; } lineOffset += scanlineStride; } } else if (numBands == 3) { int d1 = dataOffsets[1] - d0; int d2 = dataOffsets[2] - d0; for (int j = 0; j < h; j++) { int pixelOffset = lineOffset + d0; for (int i = 0; i < w; i++) { pixels[dstOffset++] = data[pixelOffset] & 0xff; pixels[dstOffset++] = data[pixelOffset + d1] & 0xff; pixels[dstOffset++] = data[pixelOffset + d2] & 0xff; pixelOffset += pixelStride; } lineOffset += scanlineStride; } } else if (numBands == 4) { int d1 = dataOffsets[1] - d0; int d2 = dataOffsets[2] - d0; int d3 = dataOffsets[3] - d0; for (int j = 0; j < h; j++) { int pixelOffset = lineOffset + d0; for (int i = 0; i < w; i++) { pixels[dstOffset++] = data[pixelOffset] & 0xff; pixels[dstOffset++] = data[pixelOffset + d1] & 0xff; pixels[dstOffset++] = data[pixelOffset + d2] & 0xff; pixels[dstOffset++] = data[pixelOffset + d3] & 0xff; pixelOffset += pixelStride; } lineOffset += scanlineStride; } } else { for (int j = 0; j < h; j++) { int pixelOffset = lineOffset; for (int i = 0; i < w; i++) { for (int k = 0; k < numBands; k++) { pixels[dstOffset++] = data[pixelOffset + dataOffsets[k]] & 0xff; } pixelOffset += pixelStride; } lineOffset += scanlineStride; } } } return pixels; } /** * Returns pixel stride -- the number of data array elements between two * samples for the same band on the same scanline. */ public int getPixelStride() { return pixelStride; } @Override public int getSample(int x, int y, int b) { if ((x < this.minX) || (y < this.minY) || (x >= this.maxX) || (y >= this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } if (packed) { int offset = y * scanlineStride + x + dbOffsetPacked; byte sample = data[offset]; return (sample & bitMasks[b]) >>> bitOffsets[b]; } else { int offset = y * scanlineStride + x * pixelStride + dbOffset; return data[offset + dataOffsets[b]] & 0xff; } } @Override public int[] getSamples(int x, int y, int w, int h, int b, int[] iArray) { if ((x < this.minX) || (y < this.minY) || (x + w > this.maxX) || (y + h > this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } int samples[]; if (iArray != null) { samples = iArray; } else { samples = new int[w * h]; } int lineOffset = y * scanlineStride + x * pixelStride; int dstOffset = 0; if (packed) { lineOffset += dbOffsetPacked; int bitMask = bitMasks[b]; int bitOffset = bitOffsets[b]; for (int j = 0; j < h; j++) { int sampleOffset = lineOffset; for (int i = 0; i < w; i++) { int value = data[sampleOffset++]; samples[dstOffset++] = ((value & bitMask) >>> bitOffset); } lineOffset += scanlineStride; } } else { lineOffset += dbOffset + dataOffsets[b]; for (int j = 0; j < h; j++) { int sampleOffset = lineOffset; for (int i = 0; i < w; i++) { samples[dstOffset++] = data[sampleOffset] & 0xff; sampleOffset += pixelStride; } lineOffset += scanlineStride; } } return samples; } /** * Returns the scanline stride -- the number of data array elements between * a given sample and the sample in the same column of the next row in the * same band. */ public int getScanlineStride() { return scanlineStride; } /** * * Analyzes a ComponentSampleModel to determine if it can function as a * PixelInterleavedSampleModel. In order to do so, it must use only bank 0 * of its DataBuffer, and the data offsets must span a range of less than * pixelStride. * *

* These properties are trivially true for a 1-banded SampleModel. */ private boolean isInterleaved(ComponentSampleModel sm) { // Analyze ComponentSampleModel to determine if it has the // properties of a PixelInterleavedSampleModel int numBands = sampleModel.getNumBands(); if (numBands == 1) { return true; } // Determine banks used int[] bankIndices = sm.getBankIndices(); for (int i = 0; i < numBands; i++) { if (bankIndices[i] != 0) { return false; } } // Determine range of band offsets int[] bandOffsets = sm.getBandOffsets(); int minOffset = bandOffsets[0]; int maxOffset = minOffset; for (int i = 1; i < numBands; i++) { int offset = bandOffsets[i]; if (offset < minOffset) { minOffset = offset; } if (offset > maxOffset) { maxOffset = offset; } } if (maxOffset - minOffset >= sm.getPixelStride()) { return false; } return true; } /** * Stores a byte array of data elements into the specified rectangular * region. An ArrayIndexOutOfBounds exception will be thrown at runtime if * the pixel coordinates are out of bounds. The data elements in the data * array are assumed to be packed. That is, a data element for the nth band * at location (x2, y2) would be found at: * *

	 * inData[((y2 - y) * w + (x2 - x)) * numDataElements + n]
	 * 
* * @param x * The X coordinate of the upper left pixel location. * @param y * The Y coordinate of the upper left pixel location. * @param w * Width of the pixel rectangle. * @param h * Height of the pixel rectangle. * @param inData * The data elements to be stored. */ public void putByteData(int x, int y, int w, int h, byte[] inData) { if ((x < this.minX) || (y < this.minY) || (x + w > this.maxX) || (y + h > this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } int yoff = (y - minY) * scanlineStride + (x - minX) * pixelStride; int xoff; int off = 0; int xstart; int ystart; if (inOrder) { yoff += dataOffsets[0]; int rowBytes = w * pixelStride; if (rowBytes == scanlineStride) { System.arraycopy(inData, 0, data, yoff, rowBytes * h); } else { for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { System.arraycopy(inData, off, data, yoff, rowBytes); off += rowBytes; } } } else if (numDataElements == 1) { yoff += dataOffsets[0]; for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { data[xoff] = inData[off++]; } } } else if (numDataElements == 2) { yoff += dataOffsets[0]; int d1 = dataOffsets[1] - dataOffsets[0]; for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { data[xoff] = inData[off++]; data[xoff + d1] = inData[off++]; } } } else if (numDataElements == 3) { yoff += dataOffsets[0]; int d1 = dataOffsets[1] - dataOffsets[0]; int d2 = dataOffsets[2] - dataOffsets[0]; for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { data[xoff] = inData[off++]; data[xoff + d1] = inData[off++]; data[xoff + d2] = inData[off++]; } } } else if (numDataElements == 4) { yoff += dataOffsets[0]; int d1 = dataOffsets[1] - dataOffsets[0]; int d2 = dataOffsets[2] - dataOffsets[0]; int d3 = dataOffsets[3] - dataOffsets[0]; for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { data[xoff] = inData[off++]; data[xoff + d1] = inData[off++]; data[xoff + d2] = inData[off++]; data[xoff + d3] = inData[off++]; } } } else { for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { for (int c = 0; c < numDataElements; c++) { data[dataOffsets[c] + xoff] = inData[off++]; } } } } } /** * Stores a byte array of data elements into the specified rectangular * region for the specified band. An ArrayIndexOutOfBounds exception will be * thrown at runtime if the pixel coordinates are out of bounds. The data * elements in the data array are assumed to be packed. That is, a data * element at location (x2, y2) would be found at: * *
	 * inData[((y2 - y) * w + (x2 - x)) + n]
	 * 
* * @param x * The X coordinate of the upper left pixel location. * @param y * The Y coordinate of the upper left pixel location. * @param w * Width of the pixel rectangle. * @param h * Height of the pixel rectangle. * @param band * The band to set. * @param inData * The data elements to be stored. */ public void putByteData(int x, int y, int w, int h, int band, byte[] inData) { // Bounds check for 'band' will be performed automatically if ((x < this.minX) || (y < this.minY) || (x + w > this.maxX) || (y + h > this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } int yoff = (y - minY) * scanlineStride + (x - minX) * pixelStride + dataOffsets[band]; int xoff; int off = 0; int xstart; int ystart; if (pixelStride == 1) { if (scanlineStride == w) { System.arraycopy(inData, 0, data, yoff, w * h); } else { for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { System.arraycopy(inData, off, data, yoff, w); off += w; } } } else { for (ystart = 0; ystart < h; ystart++, yoff += scanlineStride) { xoff = yoff; for (xstart = 0; xstart < w; xstart++, xoff += pixelStride) { data[xoff] = inData[off++]; } } } } /** * Stores the Raster data at the specified location. * * @param dstX * The absolute X coordinate of the destination pixel that will * receive a copy of the upper-left pixel of the inRaster * @param dstY * The absolute Y coordinate of the destination pixel that will * receive a copy of the upper-left pixel of the inRaster * @param srcX * The absolute X coordinate of the upper-left source pixel that * will be copied into this Raster * @param srcY * The absolute Y coordinate of the upper-left source pixel that * will be copied into this Raster * @param width * The number of pixels to store horizontally * @param height * The number of pixels to store vertically * @param inRaster * Raster of data to place at x,y location. */ private void setDataElements(int dstX, int dstY, int srcX, int srcY, int width, int height, Raster inRaster) { // Assume bounds checking has been performed previously if (width <= 0 || height <= 0) { return; } // Write inRaster (minX, minY) to (dstX, dstY) int srcOffX = inRaster.getMinX(); int srcOffY = inRaster.getMinY(); Object tdata = null; if (inRaster instanceof SwtCompatibleRaster) { SwtCompatibleRaster bct = (SwtCompatibleRaster) inRaster; byte[] bdata = bct.getDataStorage(); // copy whole scanlines if (inOrder && bct.inOrder && pixelStride == bct.pixelStride) { int toff = bct.getDataOffset(0); int tss = bct.getScanlineStride(); int tps = bct.getPixelStride(); int srcOffset = toff + (srcY - srcOffY) * tss + (srcX - srcOffX) * tps; int dstOffset = dataOffsets[0] + (dstY - minY) * scanlineStride + (dstX - minX) * pixelStride; int nbytes = width * pixelStride; for (int tmpY = 0; tmpY < height; tmpY++) { System.arraycopy(bdata, srcOffset, data, dstOffset, nbytes); srcOffset += tss; dstOffset += scanlineStride; } return; } } for (int startY = 0; startY < height; startY++) { // Grab one scanline at a time tdata = inRaster.getDataElements(srcOffX, srcOffY + startY, width, 1, tdata); setDataElements(dstX, dstY + startY, width, 1, tdata); } } /** * Stores an array of data elements into the specified rectangular region. * An ArrayIndexOutOfBounds exception will be thrown at runtime if the pixel * coordinates are out of bounds. A ClassCastException will be thrown if the * input object is non null and references anything other than an array of * transferType. The data elements in the data array are assumed to be * packed. That is, a data element for the nth band at location (x2, y2) * would be found at: * *
	 * inData[((y2 - y) * w + (x2 - x)) * numDataElements + n]
	 * 
* * @param x * The X coordinate of the upper left pixel location. * @param y * The Y coordinate of the upper left pixel location. * @param w * Width of the pixel rectangle. * @param h * Height of the pixel rectangle. * @param inData * An object reference to an array of type defined by * getTransferType() and length w*h*getNumDataElements() * containing the pixel data to place between x,y and x+h, y+h. */ @Override public void setDataElements(int x, int y, int w, int h, Object obj) { putByteData(x, y, w, h, (byte[]) obj); } /** * Stores the data elements for all bands at the specified location. An * ArrayIndexOutOfBounds exception will be thrown at runtime if the pixel * coordinate is out of bounds. A ClassCastException will be thrown if the * input object is non null and references anything other than an array of * transferType. * * @param x * The X coordinate of the pixel location. * @param y * The Y coordinate of the pixel location. * @param inData * An object reference to an array of type defined by * getTransferType() and length getNumDataElements() containing * the pixel data to place at x,y. */ @Override public void setDataElements(int x, int y, Object obj) { if ((x < this.minX) || (y < this.minY) || (x >= this.maxX) || (y >= this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } byte inData[] = (byte[]) obj; int off = (y - minY) * scanlineStride + (x - minX) * pixelStride; for (int i = 0; i < numDataElements; i++) { data[dataOffsets[i] + off] = inData[i]; } } /** * Stores the Raster data at the specified location. An * ArrayIndexOutOfBounds exception will be thrown at runtime if the pixel * coordinates are out of bounds. * * @param x * The X coordinate of the pixel location. * @param y * The Y coordinate of the pixel location. * @param inRaster * Raster of data to place at x,y location. */ @Override public void setDataElements(int x, int y, Raster inRaster) { int srcOffX = inRaster.getMinX(); int srcOffY = inRaster.getMinY(); int dstOffX = x + srcOffX; int dstOffY = y + srcOffY; int width = inRaster.getWidth(); int height = inRaster.getHeight(); if ((dstOffX < this.minX) || (dstOffY < this.minY) || (dstOffX + width > this.maxX) || (dstOffY + height > this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } setDataElements(dstOffX, dstOffY, srcOffX, srcOffY, width, height, inRaster); } @Override public void setPixels(int x, int y, int w, int h, int[] iArray) { if ((x < this.minX) || (y < this.minY) || (x + w > this.maxX) || (y + h > this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } int lineOffset = y * scanlineStride + x * pixelStride; int srcOffset = 0; if (packed) { lineOffset += dbOffsetPacked; for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { int value = 0; for (int k = 0; k < numBands; k++) { int srcValue = iArray[srcOffset++]; value |= ((srcValue << bitOffsets[k]) & bitMasks[k]); } data[lineOffset + i] = (byte) value; } lineOffset += scanlineStride; } } else { lineOffset += dbOffset; int d0 = dataOffsets[0]; if (numBands == 1) { for (int j = 0; j < h; j++) { int pixelOffset = lineOffset + d0; for (int i = 0; i < w; i++) { data[pixelOffset] = (byte) iArray[srcOffset++]; pixelOffset += pixelStride; } lineOffset += scanlineStride; } } else if (numBands == 2) { int d1 = dataOffsets[1] - d0; for (int j = 0; j < h; j++) { int pixelOffset = lineOffset + d0; for (int i = 0; i < w; i++) { data[pixelOffset] = (byte) iArray[srcOffset++]; data[pixelOffset + d1] = (byte) iArray[srcOffset++]; pixelOffset += pixelStride; } lineOffset += scanlineStride; } } else if (numBands == 3) { int d1 = dataOffsets[1] - d0; int d2 = dataOffsets[2] - d0; for (int j = 0; j < h; j++) { int pixelOffset = lineOffset + d0; for (int i = 0; i < w; i++) { data[pixelOffset] = (byte) iArray[srcOffset++]; data[pixelOffset + d1] = (byte) iArray[srcOffset++]; data[pixelOffset + d2] = (byte) iArray[srcOffset++]; pixelOffset += pixelStride; } lineOffset += scanlineStride; } } else if (numBands == 4) { int d1 = dataOffsets[1] - d0; int d2 = dataOffsets[2] - d0; int d3 = dataOffsets[3] - d0; for (int j = 0; j < h; j++) { int pixelOffset = lineOffset + d0; for (int i = 0; i < w; i++) { data[pixelOffset] = (byte) iArray[srcOffset++]; data[pixelOffset + d1] = (byte) iArray[srcOffset++]; data[pixelOffset + d2] = (byte) iArray[srcOffset++]; data[pixelOffset + d3] = (byte) iArray[srcOffset++]; pixelOffset += pixelStride; } lineOffset += scanlineStride; } } else { for (int j = 0; j < h; j++) { int pixelOffset = lineOffset; for (int i = 0; i < w; i++) { for (int k = 0; k < numBands; k++) { data[pixelOffset + dataOffsets[k]] = (byte) iArray[srcOffset++]; } pixelOffset += pixelStride; } lineOffset += scanlineStride; } } } } @Override public void setRect(int dx, int dy, Raster srcRaster) { if (!(srcRaster instanceof SwtCompatibleRaster)) { super.setRect(dx, dy, srcRaster); return; } int width = srcRaster.getWidth(); int height = srcRaster.getHeight(); int srcOffX = srcRaster.getMinX(); int srcOffY = srcRaster.getMinY(); int dstOffX = dx + srcOffX; int dstOffY = dy + srcOffY; // Clip to this raster if (dstOffX < this.minX) { int skipX = minX - dstOffX; width -= skipX; srcOffX += skipX; dstOffX = this.minX; } if (dstOffY < this.minY) { int skipY = this.minY - dstOffY; height -= skipY; srcOffY += skipY; dstOffY = this.minY; } if (dstOffX + width > this.maxX) { width = this.maxX - dstOffX; } if (dstOffY + height > this.maxY) { height = this.maxY - dstOffY; } setDataElements(dstOffX, dstOffY, srcOffX, srcOffY, width, height, srcRaster); } @Override public void setSample(int x, int y, int b, int s) { if ((x < this.minX) || (y < this.minY) || (x >= this.maxX) || (y >= this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } if (packed) { int offset = y * scanlineStride + x + dbOffsetPacked; int bitMask = bitMasks[b]; byte value = data[offset]; value &= ~bitMask; value |= (s << bitOffsets[b]) & bitMask; data[offset] = value; } else { int offset = y * scanlineStride + x * pixelStride + dbOffset; data[offset + dataOffsets[b]] = (byte) s; } } @Override public void setSamples(int x, int y, int w, int h, int b, int iArray[]) { if ((x < this.minX) || (y < this.minY) || (x + w > this.maxX) || (y + h > this.maxY)) { throw new ArrayIndexOutOfBoundsException( "Coordinate out of bounds!"); } int lineOffset = y * scanlineStride + x * pixelStride; int srcOffset = 0; if (packed) { lineOffset += dbOffsetPacked; int bitMask = bitMasks[b]; for (int j = 0; j < h; j++) { int sampleOffset = lineOffset; for (int i = 0; i < w; i++) { byte value = data[sampleOffset]; value &= ~bitMask; int sample = iArray[srcOffset++]; value |= (sample << bitOffsets[b]) & bitMask; data[sampleOffset++] = value; } lineOffset += scanlineStride; } } else { lineOffset += dbOffset + dataOffsets[b]; for (int i = 0; i < h; i++) { int sampleOffset = lineOffset; for (int j = 0; j < w; j++) { data[sampleOffset] = (byte) iArray[srcOffset++]; sampleOffset += pixelStride; } lineOffset += scanlineStride; } } } @Override public String toString() { return new String("SwtCompatibleRaster: width = " + width + " height = " + height + " #numDataElements " + numDataElements // +" xOff = "+xOffset+" yOff = "+yOffset + " dataOff[0] = " + dataOffsets[0]); } /** * Verify that the layout parameters are consistent with the data. If * strictCheck is false, this method will check for ArrayIndexOutOfBounds * conditions. If strictCheck is true, this method will check for additional * error conditions such as line wraparound (width of a line greater than * the scanline stride). * * @return String Error string, if the layout is incompatible with the data. * Otherwise returns null. */ private void verify(boolean strictCheck) { int maxSize = 0; int size; for (int i = 0; i < numDataElements; i++) { size = (height - 1) * scanlineStride + (width - 1) * pixelStride + dataOffsets[i]; if (size > maxSize) { maxSize = size; } } if (data.length < maxSize) { throw new RasterFormatException("Data array too small (should be " + maxSize + " )"); } } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/image/ISwtImage.java0000644000175000017500000000357011032364660025211 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.swt.image; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import de.intarsys.cwt.image.IImage; public interface ISwtImage extends IImage { public Image getImage(Device device); public ImageData getImageData(); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/image/CwtSwtImage.java0000644000175000017500000001165611411054014025550 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.swt.image; import java.util.Arrays; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Transform; import org.eclipse.swt.printing.Printer; import de.intarsys.cwt.environment.IGraphicsContext; import de.intarsys.cwt.swt.environment.CwtSwtGraphicsContext; public class CwtSwtImage implements ISwtImage { public static final boolean IS_GTK = "gtk".equals(SWT.getPlatform()); //$NON-NLS-1$ private int height; private Image swtImage; private ImageData swtImageData; private int width; public CwtSwtImage(ImageData imageData) { swtImageData = imageData; setWidth(imageData.width); setHeight(imageData.height); } protected Image createSwtImage(Device device) { return new Image(device, getImageData()); } public void drawFromGraphicsContext(IGraphicsContext graphicsContext, float x, float y) { Transform transform; GC gc = ((CwtSwtGraphicsContext) graphicsContext).getGc(); ImageData imageData = getImageData(); /* * swt seems to have a size limit for images; above a certain size * images are simply not displayed anymore; don't know the exact value */ transform = null; if (imageData.data.length > (Integer.MAX_VALUE >> 7)) { // arbitrary float[] elements; Transform tempTransform; double scaleX; double scaleY; transform = new Transform(gc.getDevice()); gc.getTransform(transform); elements = new float[6]; transform.getElements(elements); double tx = elements[0]; double ty = elements[3]; double sx = elements[1]; double sy = elements[2]; scaleX = Math.pow((tx * tx) + (sy * sy), 0.5); scaleY = Math.pow((ty * ty) + (sx * sx), 0.5); imageData = imageData.scaledTo((int) Math.round(imageData.width * scaleX), (int) Math.round(imageData.height * scaleY)); tempTransform = new Transform(gc.getDevice(), elements); tempTransform.scale((float) (1 / scaleX), (float) (1 / scaleY)); gc.setTransform(tempTransform); tempTransform.dispose(); } try { // workaround for eclipse bug #174027 byte[] bytes = null; if (IS_GTK && gc.getDevice() instanceof Printer) { if (imageData.transparentPixel == -1 && imageData.alphaData == null && imageData.maskData == null) { bytes = new byte[imageData.width * imageData.height]; Arrays.fill(bytes, (byte) -1); imageData.alphaData = bytes; } } try { Image deviceImage = new Image(gc.getDevice(), imageData); try { gc.drawImage(deviceImage, (int) x, (int) y); } finally { deviceImage.dispose(); } } finally { if (bytes != null) { imageData.alphaData = null; } } } finally { if (transform != null) { gc.setTransform(transform); transform.dispose(); } } } public int getHeight() { return height; } public Image getImage(Device device) { if (swtImage == null) { swtImage = createSwtImage(device); } return swtImage; } public ImageData getImageData() { return swtImageData; } public int getWidth() { return width; } protected void setHeight(int paramHeight) { height = paramHeight; } protected void setWidth(int paramWidth) { width = paramWidth; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/image/ImageConverterAwt2Swt.java0000644000175000017500000002651211113525412027521 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.swt.image; import java.awt.Point; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; import java.awt.image.ComponentSampleModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.IndexColorModel; import java.awt.image.PixelInterleavedSampleModel; import java.awt.image.SampleModel; import java.awt.image.WritableRaster; import java.util.HashMap; import java.util.Map; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.graphics.RGB; import sun.awt.image.ByteInterleavedRaster; import sun.awt.image.BytePackedRaster; import de.intarsys.cwt.awt.image.CwtAwtImageTools; import de.intarsys.tools.system.SystemTools; import de.intarsys.tools.valueholder.IValueHolder; import de.intarsys.tools.valueholder.ObjectValueHolder; public class ImageConverterAwt2Swt { static class OS_Other implements OS_Switch { public PaletteData createRgbPaletteData() { return new PaletteData(0xFF0000, 0xFF00, 0xFF); } public void initializeRgbBandOffsets(int[] bandOffsets) { for (int index = 0; index < 3; index++) { bandOffsets[index] = index; } } } static interface OS_Switch { PaletteData createRgbPaletteData(); void initializeRgbBandOffsets(int[] bandOffsets); } static class OS_Windows implements OS_Switch { public PaletteData createRgbPaletteData() { return new PaletteData(0xFF, 0xFF00, 0xFF0000); } public void initializeRgbBandOffsets(int[] bandOffsets) { for (int index = 0; index < 3; index++) { bandOffsets[index] = 2 - index; } } } private static Map> ConvertOps; private static OS_Switch OsSwitch; static { ConvertOps = new HashMap>(); if (SystemTools.isWindows()) { OsSwitch = new OS_Windows(); } else { OsSwitch = new OS_Other(); } } public static BufferedImage createSwtCompatibleAwtImage(int width, int height, boolean transparent) { ComponentColorModel colorModel; int bands; int[] bandOffsets; SampleModel sampleModel; DataBuffer dataBuffer; WritableRaster raster; if (transparent) { colorModel = CwtAwtImageTools.getRgbTransparentColorModel(); } else { colorModel = CwtAwtImageTools.getRgbColorModel(); } bands = colorModel.getNumComponents(); bandOffsets = new int[bands]; OsSwitch.initializeRgbBandOffsets(bandOffsets); if (bandOffsets.length > 3) { bandOffsets[3] = 3; } sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, bands, width * bands, bandOffsets); dataBuffer = new DataBufferByte(width * height * bands); raster = new SwtCompatibleRaster(sampleModel, dataBuffer, new Point(0, 0)); return new BufferedImage(colorModel, raster, false, null); } protected static Map> getConvertOps() { return ConvertOps; } private BufferedImage bufferedImage; private ImageData imageData; public ImageConverterAwt2Swt(BufferedImage paramBufferedImage) { bufferedImage = paramBufferedImage; } protected void computeValuesFromAwtImage(int depth, IValueHolder palette, IValueHolder scanlinePad, IValueHolder transparentPixel) { SampleModel sampleModel; ColorModel colorModel; sampleModel = getBufferedImage().getSampleModel(); if (sampleModel.getDataType() != DataBuffer.TYPE_BYTE) { throw new IllegalStateException(); } colorModel = getBufferedImage().getColorModel(); if (!colorModel.getColorSpace().isCS_sRGB()) { throw new IllegalStateException(); } if (colorModel instanceof ComponentColorModel) { if (!(sampleModel instanceof ComponentSampleModel)) { throw new IllegalStateException(); } computeValuesPaletteDirect((ComponentSampleModel) sampleModel, (ComponentColorModel) colorModel, palette, scanlinePad, transparentPixel); return; } else if (colorModel instanceof IndexColorModel) { computeValuesPaletteIndexed((IndexColorModel) colorModel, depth, palette, scanlinePad, transparentPixel); return; } throw new IllegalStateException(); } protected void computeValuesPaletteDirect(ComponentSampleModel sampleModel, ComponentColorModel colorModel, IValueHolder palette, IValueHolder scanlinePad, IValueHolder transparentPixel) { int[] componentSize; int[] bandOffsets; PaletteData paletteData; componentSize = colorModel.getComponentSize(); for (int index = 0; index < componentSize.length; index++) { if (componentSize[index] != 8) { throw new IllegalStateException(); } } bandOffsets = (sampleModel).getBandOffsets(); if (bandOffsets.length == 4 && bandOffsets[3] != 3) { throw new IllegalStateException(); } paletteData = new PaletteData(0xFF0000 >> (bandOffsets[0] << 3), 0xFF0000 >> (bandOffsets[1] << 3), 0xFF0000 >> (bandOffsets[2] << 3)); palette.set(paletteData); scanlinePad.set(3); } protected void computeValuesPaletteIndexed(IndexColorModel colorModel, int depth, IValueHolder paletteHolder, IValueHolder scanlinePadHolder, IValueHolder transparentPixelHolder) { int[] awtRgb; RGB[] swtRgb; awtRgb = new int[colorModel.getMapSize()]; colorModel.getRGBs(awtRgb); swtRgb = new RGB[(int) Math.pow(2, depth)]; for (int index = 0; index < awtRgb.length; index++) { RGB rgb; rgb = new RGB((awtRgb[index] >> 16) & 0xFF, (awtRgb[index] >> 8) & 0xFF, awtRgb[index] & 0xFF); swtRgb[index] = rgb; } for (int index = awtRgb.length; index < swtRgb.length; index++) { swtRgb[index] = new RGB(0, 0, 0); } paletteHolder.set(new PaletteData(swtRgb)); scanlinePadHolder.set(1); transparentPixelHolder.set(colorModel.getTransparentPixel()); } protected void convert(BufferedImage srcImage, BufferedImage destImage) { ColorSpace srcColorSpace; ColorSpace destColorSpace; Map srcMatchingConvertOps; ColorConvertOp matchingConvertOp; srcColorSpace = srcImage.getColorModel().getColorSpace(); destColorSpace = destImage.getColorModel().getColorSpace(); srcMatchingConvertOps = getConvertOps().get(srcColorSpace); if (srcMatchingConvertOps == null) { srcMatchingConvertOps = new HashMap(); getConvertOps().put(srcColorSpace, srcMatchingConvertOps); matchingConvertOp = null; } else { matchingConvertOp = srcMatchingConvertOps.get(destColorSpace); } if (matchingConvertOp == null) { matchingConvertOp = new ColorConvertOp(null); srcMatchingConvertOps.put(destColorSpace, matchingConvertOp); } matchingConvertOp.filter(srcImage, destImage); } protected ImageData createImageData() { ColorModel colorModel; int depth; IValueHolder palette; IValueHolder scanlinePad; IValueHolder transparentPixel; WritableRaster raster; byte[] bytes; byte[] rgbBytes; byte[] alphaBytes; colorModel = getBufferedImage().getColorModel(); depth = colorModel.getPixelSize(); if (colorModel.getTransparency() == Transparency.TRANSLUCENT) { depth = depth / colorModel.getNumComponents() * colorModel.getNumColorComponents(); } palette = new ObjectValueHolder(null); scanlinePad = new ObjectValueHolder(0); transparentPixel = new ObjectValueHolder(-1); try { computeValuesFromAwtImage(depth, palette, scanlinePad, transparentPixel); raster = getBufferedImage().getRaster(); } catch (IllegalStateException ex) { BufferedImage newBufferedImage; newBufferedImage = createSwtCompatibleAwtImage(getBufferedImage() .getWidth(), getBufferedImage().getHeight(), colorModel .hasAlpha()); /* * this yields inexact colors but is much faster than drawing on the * new image */ // TODO is there a way to improve this? convert(getBufferedImage(), newBufferedImage); depth = 24; palette.set(OsSwitch.createRgbPaletteData()); scanlinePad.set(3); raster = newBufferedImage.getRaster(); } if (raster instanceof SwtCompatibleRaster) { bytes = ((SwtCompatibleRaster) raster).getDataStorage(); } else if (raster instanceof ByteInterleavedRaster) { // TODO this is a sun... class bytes = ((ByteInterleavedRaster) raster).getDataStorage(); } else if (raster instanceof BytePackedRaster) { // TODO this is a sun... class bytes = ((BytePackedRaster) raster).getDataStorage(); } else { bytes = (byte[]) raster.getDataElements(raster.getMinX(), raster .getMinY(), raster.getWidth(), raster.getHeight(), null); } if (((PaletteData) palette.get()).isDirect && colorModel.hasAlpha()) { alphaBytes = new byte[bytes.length / 4]; rgbBytes = new byte[bytes.length / 4 * 3]; for (int index = 0; index < alphaBytes.length; index++) { rgbBytes[index * 3] = bytes[index * 4]; rgbBytes[(index * 3) + 1] = bytes[(index * 4) + 1]; rgbBytes[(index * 3) + 2] = bytes[(index * 4) + 2]; alphaBytes[index] = bytes[(index * 4) + 3]; } } else { alphaBytes = null; rgbBytes = bytes; } imageData = new ImageData(getBufferedImage().getWidth(), getBufferedImage().getHeight(), depth, (PaletteData) palette .get(), (Integer) scanlinePad.get(), rgbBytes); imageData.transparentPixel = (Integer) transparentPixel.get(); if (alphaBytes != null) { imageData.alphaData = alphaBytes; } return imageData; } public BufferedImage getBufferedImage() { return bufferedImage; } public ImageData getImageData() { if (imageData == null) { imageData = createImageData(); } return imageData; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/image/CwtSwtImageTools.java0000644000175000017500000000510111032364660026567 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.swt.image; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.graphics.RGB; public class CwtSwtImageTools { private static PaletteData[] GrayPalettes; private static PaletteData RgbPalette; public static PaletteData getGrayPalette(int bits) { int paletteIndex; if (GrayPalettes == null) { GrayPalettes = new PaletteData[4]; } paletteIndex = (int) (Math.log(bits) / Math.log(2)); if (GrayPalettes[paletteIndex] == null) { RGB[] colors; colors = new RGB[(int) Math.pow(2, bits)]; for (int index = 0; index < colors.length; index++) { int value; value = (int) (index * (float) 255 / (colors.length - 1)); colors[index] = new RGB(value, value, value); } GrayPalettes[paletteIndex] = new PaletteData(colors); } return GrayPalettes[paletteIndex]; } public static PaletteData getRgbPalette() { if (RgbPalette == null) { RgbPalette = new PaletteData(0xFF0000, 0xFF00, 0xFF); } return RgbPalette; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/environment/0000755000175000017500000000000011412336240023765 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/environment/CwtSwtGraphicsEnvironment.java0000644000175000017500000000361211032364662032002 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.swt.environment; import de.intarsys.cwt.environment.IGraphicsEnvironment; public class CwtSwtGraphicsEnvironment implements IGraphicsEnvironment { final private static CwtSwtGraphicsEnvironment ACTIVE = new CwtSwtGraphicsEnvironment(); static public CwtSwtGraphicsEnvironment get() { return ACTIVE; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/swt/environment/CwtSwtGraphicsContext.java0000644000175000017500000006473011411054014031116 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.swt.environment; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.RenderingHints.Key; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.PathIterator; import java.awt.geom.Rectangle2D; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.LineAttributes; import org.eclipse.swt.graphics.Path; import org.eclipse.swt.graphics.Pattern; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.Region; import org.eclipse.swt.graphics.Transform; import de.intarsys.cwt.common.BlendMode; import de.intarsys.cwt.common.IGraphicsObject; import de.intarsys.cwt.common.IPaint; import de.intarsys.cwt.environment.IGraphicsContext; import de.intarsys.cwt.environment.IGraphicsEnvironment; import de.intarsys.cwt.image.IImage; import de.intarsys.tools.geometry.ApplySpaceChangeShape; import de.intarsys.tools.geometry.ShapeTools; import de.intarsys.tools.geometry.TransformedShape; import de.intarsys.tools.resourcetracker.ResourceTracker; /** * An {@link IGraphicsContext} mapping to SWT. *

* It is currently not safe to use this {@link IGraphicsContext} concurrently. */ public class CwtSwtGraphicsContext implements IGraphicsContext { static final int BACKGROUND = 1 << 1; static final int FOREGROUND = 1 << 0; /** * A tracker handling path resources used by shapes. The path will be * disposed when the shape is no longer referenced. */ private static ResourceTracker tracker = new ResourceTracker() { @Override protected void basicDispose(Object resource) { ((Path) resource).dispose(); } }; static public Path toPath(Device device, PathIterator pathIterator) { Path path; float[] coords; path = new Path(device); if (pathIterator.isDone()) { // empty path, might result from intersection path.addRectangle(0, 0, 0, 0); return path; } coords = new float[6]; while (!pathIterator.isDone()) { int type; type = pathIterator.currentSegment(coords); switch (type) { case PathIterator.SEG_CLOSE: path.close(); break; case PathIterator.SEG_CUBICTO: path.cubicTo(coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]); break; case PathIterator.SEG_LINETO: path.lineTo(coords[0], coords[1]); break; case PathIterator.SEG_MOVETO: path.moveTo(coords[0], coords[1]); break; case PathIterator.SEG_QUADTO: path.quadTo(coords[0], coords[1], coords[2], coords[3]); break; default: throw new InternalError( "Program execution should not reach this point."); } pathIterator.next(); } return path; } static public Rectangle2D toRectangle2D(Rectangle rect) { return new Rectangle2D.Float(rect.x, rect.y, rect.width, rect.height); } /** * This methods intentionally duplicated to avoid compile time dependency.. * */ static public Transform toTransform(Device device, AffineTransform at) { double[] tempElements = new double[6]; at.getMatrix(tempElements); return new Transform(device, (float) tempElements[0], (float) tempElements[1], (float) tempElements[2], (float) tempElements[3], (float) tempElements[4], (float) tempElements[5]); } /** * This methods intentionally duplicated to avoid compile time dependency.. * */ static public Transform toTransform(Device device, Transform st, AffineTransform at) { if (st == null) { return new Transform(device, (float) at.getScaleX(), (float) at .getShearX(), (float) at.getShearY(), (float) at .getScaleY(), (float) at.getTranslateX(), (float) at .getTranslateY()); } st.setElements((float) at.getScaleX(), (float) at.getShearX(), (float) at.getShearY(), (float) at.getScaleY(), (float) at .getTranslateX(), (float) at.getTranslateY()); return st; } private boolean applyAlphaBackground; private boolean applyAlphaForeground; private boolean applyTransform = false; private Color backgroundColor; private Pattern backgroundPattern; private BlendMode blendMode = BlendMode.META.getDefault(); private AffineTransform cachedAWTShapeTransform; private Transform cachedSWTShapeTransform; private TransformedShape currentClip; private AffineTransform currentTransform; private Device device; private float[] elements = new float[6]; private double[] flatmatrix = new double[6]; private org.eclipse.swt.graphics.Font font; private Transform fontTransform; private Color foregroundColor; private Pattern foregroundPattern; private GC gc; private int swtBackgroundAlpha; private org.eclipse.swt.graphics.Color swtBackgroundColor; private int swtForegroundAlpha; private org.eclipse.swt.graphics.Color swtForegroundColor; private Transform swtTransform; public CwtSwtGraphicsContext(GC paramGC, Device paramDevice) { swtBackgroundAlpha = 255; swtBackgroundColor = null; backgroundColor = null; device = paramDevice; font = null; swtForegroundAlpha = 255; swtForegroundColor = null; foregroundColor = null; gc = paramGC; applyAlphaForeground = false; applyAlphaBackground = false; swtTransform = new Transform(paramDevice); paramGC.getTransform(swtTransform); swtTransform.getElements(elements); currentTransform = new AffineTransform(elements); // this is the "default" clipping Rectangle2D rect = toRectangle2D(paramGC.getClipping()); currentClip = ApplySpaceChangeShape.create(new Area(rect), currentTransform); // when setting to SWT.DEFAULT here curved shapes (like letters) will // look awful on gtk paramGC.setAntialias(SWT.OFF); paramGC.setInterpolation(SWT.NONE); } protected void applyAlphaBackground() { if (applyAlphaBackground) { applyAlphaBackground = false; if (gc.getAlpha() != swtBackgroundAlpha) { gc.setAlpha(swtBackgroundAlpha); if (swtForegroundAlpha != swtBackgroundAlpha) { applyAlphaForeground = true; } } } } protected void applyAlphaForeground() { if (applyAlphaForeground) { applyAlphaForeground = false; if (gc.getAlpha() != swtForegroundAlpha) { gc.setAlpha(swtForegroundAlpha); if (swtBackgroundAlpha != swtForegroundAlpha) { applyAlphaBackground = true; } } } } protected void applyClip() { if (currentClip == null) { gc.setClipping((Region) null); } else { // transform gc before clip is set applyTransform(); PathIterator pathIterator = currentClip.getPathIterator(null); if (pathIterator.getWindingRule() == PathIterator.WIND_EVEN_ODD) { gc.setFillRule(SWT.FILL_EVEN_ODD); } else { gc.setFillRule(SWT.FILL_WINDING); } Path clipPath = toPath(device, pathIterator); gc.setClipping(clipPath); clipPath.dispose(); } } protected void applyTransform() { if (applyTransform) { applyTransform = false; currentTransform.getMatrix(flatmatrix); swtTransform.setElements((float) flatmatrix[0], (float) flatmatrix[1], (float) flatmatrix[2], (float) flatmatrix[3], (float) flatmatrix[4], (float) flatmatrix[5]); gc.setTransform(swtTransform); } } public void clip(Shape shape) { Area tempShape = ShapeTools.createArea(shape, false); if (currentClip == null) { currentClip = ApplySpaceChangeShape.create(tempShape, currentTransform); } else { Area tempClip = ShapeTools.createArea(currentClip, true); tempClip.intersect(tempShape); currentClip = ApplySpaceChangeShape.create(tempClip, currentTransform); } applyClip(); } protected Path createPath(Shape s) { Path path; if (s instanceof IGraphicsObject) { path = (Path) ((IGraphicsObject) s).getData(); if (path != null && !path.isDisposed() && !path.getDevice().isDisposed()) { return path; } } if (s instanceof Rectangle2D) { Rectangle2D rect = (Rectangle2D) s; path = new Path(device); path.addRectangle((float) rect.getX(), (float) rect.getY(), (float) rect.getWidth(), (float) rect.getHeight()); } else { path = toPath(device, s.getPathIterator(null)); } tracker.trackPhantom(s, path); if (s instanceof IGraphicsObject) { ((IGraphicsObject) s).setData(path); } return path; } public void dispose() { // The underlying GC might be used beyond the lifetime of this // IGraphicsContext implementation. Thus we have to assert that eventual // transformation resettings are propagated properly to the GC. applyTransform(); if (swtBackgroundColor != null) { swtBackgroundColor.dispose(); } if (backgroundPattern != null) { backgroundPattern.dispose(); } if (font != null) { font.dispose(); } if (fontTransform != null) { fontTransform.dispose(); } if (swtForegroundColor != null) { swtForegroundColor.dispose(); } if (foregroundPattern != null) { foregroundPattern.dispose(); } if (swtTransform != null) { swtTransform.dispose(); } if (cachedSWTShapeTransform != null) { cachedSWTShapeTransform.dispose(); } } public void draw(Shape s) { applyAlphaForeground(); if (s instanceof TransformedShape && gc.getForegroundPattern() == null) { AffineTransform awtShapeTransform = ((TransformedShape) s) .getTransform(); if (awtShapeTransform != null) { // do NOT applyTransform here if (awtShapeTransform != cachedAWTShapeTransform) { cachedAWTShapeTransform = awtShapeTransform; if (cachedSWTShapeTransform != null) { cachedSWTShapeTransform.dispose(); } cachedSWTShapeTransform = toTransform(device, awtShapeTransform); } Transform tempTransform = new Transform(device); currentTransform.getMatrix(flatmatrix); tempTransform.setElements((float) flatmatrix[0], (float) flatmatrix[1], (float) flatmatrix[2], (float) flatmatrix[3], (float) flatmatrix[4], (float) flatmatrix[5]); tempTransform.multiply(cachedSWTShapeTransform); gc.setTransform(tempTransform); } else { applyTransform(); } Shape baseShape = ((TransformedShape) s).getBaseShape(); gc.drawPath(createPath(baseShape)); gc.setTransform(swtTransform); } else { applyTransform(); gc.drawPath(createPath(s)); } } public void drawImage(IImage image, float x, float y) { applyAlphaBackground(); applyTransform(); image.drawFromGraphicsContext(this, x, y); } public void drawString(String s, float x, float y) { applyTransform(); boolean reset; applyAlphaForeground(); reset = false; if (fontTransform != null) { float[] point; if (swtTransform == null) { swtTransform = new Transform(device); } gc.getTransform(swtTransform); swtTransform.getElements(elements); swtTransform.translate(x, y); point = new float[] { 0, 0 - gc.textExtent(s).y }; fontTransform.transform(point); swtTransform.translate(point[0], point[1]); swtTransform.multiply(fontTransform); gc.setTransform(swtTransform); reset = true; } try { gc.drawString(s, 0, 0); } finally { if (reset) { swtTransform.setElements(elements[0], elements[1], elements[2], elements[3], elements[4], elements[5]); gc.setTransform(swtTransform); } } } public void fill(Shape s) { applyAlphaBackground(); if (s instanceof TransformedShape && gc.getBackgroundPattern() == null) { AffineTransform awtShapeTransform = ((TransformedShape) s) .getTransform(); if (awtShapeTransform != null) { // do NOT applyTransform here if (awtShapeTransform != cachedAWTShapeTransform) { cachedAWTShapeTransform = awtShapeTransform; if (cachedSWTShapeTransform != null) { cachedSWTShapeTransform.dispose(); } cachedSWTShapeTransform = toTransform(device, awtShapeTransform); } Transform tempTransform = new Transform(device); currentTransform.getMatrix(flatmatrix); tempTransform.setElements((float) flatmatrix[0], (float) flatmatrix[1], (float) flatmatrix[2], (float) flatmatrix[3], (float) flatmatrix[4], (float) flatmatrix[5]); tempTransform.multiply(cachedSWTShapeTransform); gc.setTransform(tempTransform); } else { applyTransform(); } Shape baseShape = ((TransformedShape) s).getBaseShape(); if (ShapeTools.getWindingRule(baseShape) == PathIterator.WIND_EVEN_ODD) { gc.setFillRule(SWT.FILL_EVEN_ODD); } else { gc.setFillRule(SWT.FILL_WINDING); } Path path = createPath(baseShape); gc.fillPath(path); gc.setTransform(swtTransform); } else { applyTransform(); PathIterator pathIterator = s.getPathIterator(null); if (pathIterator.getWindingRule() == PathIterator.WIND_EVEN_ODD) { gc.setFillRule(SWT.FILL_EVEN_ODD); } else { gc.setFillRule(SWT.FILL_WINDING); } Path path = createPath(s); gc.fillPath(path); } } public Color getBackgroundColor() { if (backgroundColor == null) { RGB rgb = swtBackgroundColor.getRGB(); backgroundColor = new Color(rgb.red, rgb.green, rgb.blue); } return backgroundColor; } public BlendMode getBlendMode() { return blendMode; } public Shape getClip() { if (currentClip == null) { return null; } return (Shape) currentClip.clone(); } public Device getDevice() { return device; } public Font getFont() { // TODO; return null; } public FontRenderContext getFontRenderContext() { // TODO return null; } public Color getForegroundColor() { if (foregroundColor == null) { RGB rgb = swtForegroundColor.getRGB(); foregroundColor = new Color(rgb.red, rgb.green, rgb.blue); } return foregroundColor; } public GC getGc() { return gc; } public IGraphicsEnvironment getGraphicsEnvironment() { return CwtSwtGraphicsEnvironment.get(); } public RenderingHints getRenderingHints() { RenderingHints renderingHints; int value; renderingHints = new RenderingHints(null); value = gc.getAntialias(); if (value == SWT.DEFAULT) { renderingHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_DEFAULT); } else if (value == SWT.OFF) { renderingHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } else { renderingHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } value = gc.getInterpolation(); if (value == SWT.HIGH) { renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); } else { renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } value = gc.getTextAntialias(); if (value == SWT.DEFAULT) { renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT); } else if (value == SWT.OFF) { renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } else { renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } // TODO transfer other values return renderingHints; } public AffineTransform getTransform() { return (AffineTransform) currentTransform.clone(); } protected float[] getTransformationValues(AffineTransform tx) { tx.getMatrix(flatmatrix); elements[0] = (float) flatmatrix[0]; elements[1] = (float) flatmatrix[1]; elements[2] = (float) flatmatrix[2]; elements[3] = (float) flatmatrix[3]; elements[4] = (float) flatmatrix[4]; elements[5] = (float) flatmatrix[5]; return elements; } public void resetAdvanced() { gc.setAdvanced(false); } public void rotate(float theta) { currentTransform.rotate(theta); applyTransform = true; if (currentClip != null) { currentClip.invalidate(); } } public void scale(float x, float y) { currentTransform.scale(x, y); applyTransform = true; if (currentClip != null) { currentClip.invalidate(); } } public void setBackgroundColor(Color color) { backgroundColor = color; swtBackgroundAlpha = color.getAlpha(); applyAlphaBackground = true; org.eclipse.swt.graphics.Color newColor = new org.eclipse.swt.graphics.Color( device, color.getRed(), color.getGreen(), color.getBlue()); setBackgroundColor(newColor); } public void setBackgroundColor(org.eclipse.swt.graphics.Color resource) { if (swtBackgroundColor != null) { swtBackgroundColor.dispose(); } swtBackgroundColor = resource; backgroundColor = null; gc.setBackground(swtBackgroundColor); } public void setBackgroundPaint(IPaint paint) { swtBackgroundAlpha = (int) (paint.getAlphaValue() * 255); applyAlphaBackground = true; paint.setBackgroundPaintFromGraphicsContext(this); } public void setBackgroundPattern(Pattern resource) { if (backgroundPattern != null) { backgroundPattern.dispose(); } backgroundPattern = resource; gc.setBackgroundPattern(backgroundPattern); } public void setBlendMode(BlendMode blendMode) { this.blendMode = blendMode; } public void setClip(Shape shape) { if (shape == null) { currentClip = null; } else { currentClip = ApplySpaceChangeShape.create(ShapeTools .createArea(shape, false), currentTransform); } applyClip(); } public void setFont(Font awtFont) { int style; AffineTransform tx; if (font != null) { font.dispose(); } style = SWT.NORMAL; if ((awtFont.getStyle() & Font.BOLD) > 0) { style |= SWT.BOLD; } if ((awtFont.getStyle() & Font.ITALIC) > 0) { style |= SWT.ITALIC; } if (fontTransform != null) { fontTransform.dispose(); } if ((tx = awtFont.getTransform()).isIdentity()) { fontTransform = null; } else { fontTransform = new Transform(device, getTransformationValues(tx)); } font = new org.eclipse.swt.graphics.Font(device, awtFont.getFontName(), awtFont.getSize(), style); gc.setFont(font); } public void setForegroundColor(Color color) { foregroundColor = color; swtForegroundAlpha = color.getAlpha(); applyAlphaForeground = true; org.eclipse.swt.graphics.Color newColor = new org.eclipse.swt.graphics.Color( device, color.getRed(), color.getGreen(), color.getBlue()); setForegroundColor(newColor); } public void setForegroundColor(org.eclipse.swt.graphics.Color resource) { if (swtForegroundColor != null) { swtForegroundColor.dispose(); } swtForegroundColor = resource; foregroundColor = null; gc.setForeground(swtForegroundColor); } public void setForegroundPaint(IPaint paint) { swtForegroundAlpha = (int) (paint.getAlphaValue() * 255); applyAlphaForeground = true; paint.setForegroundPaintFromGraphicsContext(this); } public void setForegroundPattern(Pattern resource) { if (foregroundPattern != null) { foregroundPattern.dispose(); } foregroundPattern = resource; gc.setForegroundPattern(foregroundPattern); } public void setRenderingHint(Key hintKey, Object hintValue) { if (hintKey == RenderingHints.KEY_ALPHA_INTERPOLATION) { // TODO might not have an equivalent return; } if (hintKey == RenderingHints.KEY_ANTIALIASING) { if (hintValue == RenderingHints.VALUE_ANTIALIAS_DEFAULT) { gc.setAntialias(SWT.DEFAULT); } else if (hintValue == RenderingHints.VALUE_ANTIALIAS_OFF) { gc.setAntialias(SWT.OFF); } else { gc.setAntialias(SWT.ON); } return; } if (hintKey == RenderingHints.KEY_COLOR_RENDERING) { // TODO might not have an equivalent return; } if (hintKey == RenderingHints.KEY_DITHERING) { // TODO might not have an equivalent return; } if (hintKey == RenderingHints.KEY_FRACTIONALMETRICS) { // TODO might not have an equivalent return; } if (hintKey == RenderingHints.KEY_INTERPOLATION) { if (hintValue == RenderingHints.VALUE_INTERPOLATION_BICUBIC) { gc.setInterpolation(SWT.HIGH); } else if (hintValue == RenderingHints.VALUE_INTERPOLATION_BILINEAR) { gc.setInterpolation(SWT.HIGH); } else { gc.setInterpolation(SWT.LOW); } return; } if (hintKey == RenderingHints.KEY_RENDERING) { // TODO might not have an equivalent return; } if (hintKey == RenderingHints.KEY_STROKE_CONTROL) { // TODO might not have an equivalent return; } if (hintKey == RenderingHints.KEY_TEXT_ANTIALIASING) { if (hintValue == RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT) { gc.setTextAntialias(SWT.DEFAULT); } else if (hintValue == RenderingHints.VALUE_TEXT_ANTIALIAS_OFF) { gc.setTextAntialias(SWT.OFF); } else { gc.setTextAntialias(SWT.ON); } } } public void setRenderingHints(Map hints) { if (hints.containsKey(RenderingHints.KEY_ALPHA_INTERPOLATION)) { // TODO } if (hints.containsKey(RenderingHints.KEY_ANTIALIASING)) { if (hints.get(RenderingHints.KEY_ANTIALIASING) == RenderingHints.VALUE_ANTIALIAS_DEFAULT) { gc.setAntialias(SWT.DEFAULT); } else if (hints.get(RenderingHints.KEY_ANTIALIASING) == RenderingHints.VALUE_ANTIALIAS_OFF) { gc.setAntialias(SWT.OFF); } else { gc.setAntialias(SWT.ON); } } else { gc.setAntialias(SWT.DEFAULT); } if (hints.containsKey(RenderingHints.KEY_COLOR_RENDERING)) { // TODO } if (hints.containsKey(RenderingHints.KEY_DITHERING)) { // TODO } if (hints.containsKey(RenderingHints.KEY_FRACTIONALMETRICS)) { // TODO } if (hints.containsKey(RenderingHints.KEY_INTERPOLATION)) { // TODO assign values if (hints.get(RenderingHints.KEY_INTERPOLATION) == RenderingHints.VALUE_INTERPOLATION_BICUBIC) { gc.setInterpolation(SWT.HIGH); } else if (hints.get(RenderingHints.KEY_INTERPOLATION) == RenderingHints.VALUE_INTERPOLATION_BILINEAR) { gc.setInterpolation(SWT.HIGH); } else { gc.setInterpolation(SWT.LOW); } } else { gc.setInterpolation(SWT.NONE); } if (hints.containsKey(RenderingHints.KEY_RENDERING)) { // TODO } if (hints.containsKey(RenderingHints.KEY_STROKE_CONTROL)) { // TODO } if (hints.containsKey(RenderingHints.KEY_TEXT_ANTIALIASING)) { if (hints.get(RenderingHints.KEY_TEXT_ANTIALIASING) == RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT) { gc.setTextAntialias(SWT.DEFAULT); } else if (hints.get(RenderingHints.KEY_TEXT_ANTIALIASING) == RenderingHints.VALUE_TEXT_ANTIALIAS_OFF) { gc.setTextAntialias(SWT.OFF); } else { gc.setTextAntialias(SWT.ON); } } else { gc.setTextAntialias(SWT.DEFAULT); } } public void setStroke(Stroke s) { if (s instanceof BasicStroke) { BasicStroke stroke; LineAttributes attributes; float[] dash; int value; stroke = (BasicStroke) s; attributes = new LineAttributes(stroke.getLineWidth()); dash = stroke.getDashArray(); if (dash == null) { attributes.style = SWT.LINE_SOLID; } else { for (int index = 0; index < dash.length; index++) { if (dash[index] <= 0) { // workaround for strange dash definitions,this will NOT // create a semantically equal dash! dash[index] = 1f; } } attributes.style = SWT.LINE_CUSTOM; attributes.dash = dash; } value = stroke.getEndCap(); if (value == BasicStroke.CAP_BUTT) { attributes.cap = SWT.CAP_FLAT; } else if (value == BasicStroke.CAP_ROUND) { attributes.cap = SWT.CAP_ROUND; } else { attributes.cap = SWT.CAP_SQUARE; } value = stroke.getLineJoin(); if (value == BasicStroke.JOIN_BEVEL) { attributes.join = SWT.JOIN_BEVEL; } else if (value == BasicStroke.JOIN_MITER) { attributes.join = SWT.JOIN_MITER; } else { attributes.join = SWT.JOIN_ROUND; } gc.setLineAttributes(attributes); // workaround for swt bug #210412 - set explicitly gc.setLineCap(attributes.cap); return; } // TODO do we use others? } public void setTransform(AffineTransform pTransform) { currentTransform = (AffineTransform) pTransform.clone(); applyTransform = true; if (currentClip != null) { currentClip = ApplySpaceChangeShape.setTransform(currentClip, currentTransform); } } public java.awt.Point textExtent(String s) { Point extent = gc.textExtent(s); return new java.awt.Point(extent.x, extent.y); } public void transform(AffineTransform deltaTransform) { currentTransform.concatenate(deltaTransform); applyTransform = true; if (currentClip != null) { currentClip.invalidate(); } } public void translate(float x, float y) { currentTransform.translate(x, y); applyTransform = true; if (currentClip != null) { currentClip.invalidate(); } } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/awt/0000755000175000017500000000000011412336240021377 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/awt/image/0000755000175000017500000000000011412336240022461 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/awt/image/IAwtImage.java0000644000175000017500000000375011052336544025147 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.awt.image; import java.awt.image.BufferedImage; import de.intarsys.cwt.image.IImage; /** * An {@link IImage} that recognizes itself as an AWT (enabled) image. * */ public interface IAwtImage extends IImage { /** * The {@link BufferedImage} that represents this image. * * @return The {@link BufferedImage} that represents this image. */ public BufferedImage getBufferedImage(); } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/awt/image/CwtAwtImage.java0000644000175000017500000000537411052336544025520 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.awt.image; import java.awt.image.BufferedImage; import de.intarsys.cwt.awt.environment.CwtAwtGraphicsContext; import de.intarsys.cwt.environment.IGraphicsContext; import de.intarsys.cwt.image.IImage; /** * The concrete implementation for an {@link IImage} for AWT. */ public class CwtAwtImage implements IAwtImage { private BufferedImage awtImage; private int height; private int width; protected CwtAwtImage() { super(); } public CwtAwtImage(BufferedImage bufferedImage) { super(); awtImage = bufferedImage; setWidth(bufferedImage.getWidth()); setHeight(bufferedImage.getHeight()); } public void drawFromGraphicsContext(IGraphicsContext graphicsContext, float x, float y) { CwtAwtGraphicsContext awtGC = (CwtAwtGraphicsContext) graphicsContext; awtGC.getGraphics().drawImage(awtImage, (int) x, (int) y, null); } public BufferedImage getBufferedImage() { return awtImage; } public int getHeight() { return height; } public int getWidth() { return width; } protected void setHeight(int paramHeight) { height = paramHeight; } protected void setWidth(int paramWidth) { width = paramWidth; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/awt/image/CwtAwtImageTools.java0000644000175000017500000000673511052336544026543 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.awt.image; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; /** * Tool methods for the AWT CWT image implementation */ public class CwtAwtImageTools { private static ComponentColorModel GrayColorModel; private static ComponentColorModel GrayTransparentColorModel; public static ComponentColorModel RgbColorModel; public static ComponentColorModel RgbTransparentColorModel; public static ComponentColorModel getGrayColorModel() { if (CwtAwtImageTools.GrayColorModel == null) { CwtAwtImageTools.GrayColorModel = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); } return CwtAwtImageTools.GrayColorModel; } public static ComponentColorModel getGrayTransparentColorModel() { if (CwtAwtImageTools.GrayTransparentColorModel == null) { CwtAwtImageTools.GrayTransparentColorModel = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); } return CwtAwtImageTools.GrayTransparentColorModel; } public static ComponentColorModel getRgbColorModel() { if (CwtAwtImageTools.RgbColorModel == null) { CwtAwtImageTools.RgbColorModel = new ComponentColorModel(ColorSpace .getInstance(ColorSpace.CS_sRGB), false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); } return CwtAwtImageTools.RgbColorModel; } public static ComponentColorModel getRgbTransparentColorModel() { if (CwtAwtImageTools.RgbTransparentColorModel == null) { CwtAwtImageTools.RgbTransparentColorModel = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); } return CwtAwtImageTools.RgbTransparentColorModel; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/awt/environment/0000755000175000017500000000000011412336240023743 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/awt/environment/CwtAwtGraphicsContext.java0000644000175000017500000001426011411054024031044 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.awt.environment; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.RenderingHints.Key; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.util.Map; import de.intarsys.cwt.common.BlendMode; import de.intarsys.cwt.common.IPaint; import de.intarsys.cwt.environment.IGraphicsContext; import de.intarsys.cwt.environment.IGraphicsEnvironment; import de.intarsys.cwt.image.IImage; /** * The AWT implementation of {@link IGraphicsContext} * */ public class CwtAwtGraphicsContext implements IGraphicsContext { private BlendMode blendMode = BlendMode.META.getDefault(); private Graphics2D graphics; private Paint paintActive; private Paint paintBackground; private Paint paintForeground; public CwtAwtGraphicsContext(Graphics2D paramGraphics) { graphics = paramGraphics; } public void clip(Shape shape) { if (shape == null) { return; } if (shape.getPathIterator(null).isDone()) { return; } graphics.clip(shape); } public void dispose() { graphics.dispose(); } public void disposeClip(Object clip) { // nothing to do for awt } public void draw(Shape s) { if (paintActive != paintForeground) { graphics.setPaint(paintForeground); paintActive = paintForeground; } graphics.draw(s); } public void drawImage(IImage image, float x, float y) { image.drawFromGraphicsContext(this, x, y); } public void drawString(String s, float x, float y) { if (paintActive != paintForeground) { graphics.setPaint(paintForeground); paintActive = paintForeground; } graphics.drawString(s, x, y); } public void fill(Shape s) { if (paintActive != paintBackground) { graphics.setPaint(paintBackground); paintActive = paintBackground; } graphics.fill(s); } public Color getBackgroundColor() { if (paintBackground instanceof Color) { return (Color) paintBackground; } return graphics.getBackground(); } public BlendMode getBlendMode() { return blendMode; } public Shape getClip() { return graphics.getClip(); } public Font getFont() { return graphics.getFont(); } public FontRenderContext getFontRenderContext() { return graphics.getFontRenderContext(); } public Color getForegroundColor() { if (paintForeground instanceof Color) { return (Color) paintForeground; } return graphics.getColor(); } public Graphics2D getGraphics() { return graphics; } public IGraphicsEnvironment getGraphicsEnvironment() { return CwtAwtGraphicsEnvironment.get(); } public RenderingHints getRenderingHints() { return graphics.getRenderingHints(); } public AffineTransform getTransform() { return graphics.getTransform(); } public void resetAdvanced() { // } public void rotate(float theta) { graphics.rotate(theta); } public void scale(float x, float y) { graphics.scale(x, y); } public void setBackgroundColor(Color color) { graphics.setBackground(color); paintBackground = color; } public void setBackgroundPaint(IPaint paint) { paint.setBackgroundPaintFromGraphicsContext(this); } public void setBackgroundPaint(Paint paint) { paintBackground = paint; } public void setBlendMode(BlendMode blendMode) { this.blendMode = blendMode; } public void setClip(Shape shape) { if (shape == null) { graphics.setClip(null); return; } if (shape.getPathIterator(null).isDone()) { // empty clipping path, might result from intersection; will result // in no clipping at all graphics.setClip(0, 0, 0, 0); return; } graphics.setClip(shape); } public void setFont(Font font) { graphics.setFont(font); } public void setForegroundColor(Color c) { paintForeground = c; } public void setForegroundPaint(IPaint paint) { paint.setForegroundPaintFromGraphicsContext(this); } public void setForegroundPaint(Paint paint) { paintForeground = paint; } public void setRenderingHint(Key hintKey, Object hintValue) { graphics.setRenderingHint(hintKey, hintValue); } public void setRenderingHints(Map hints) { graphics.setRenderingHints(hints); } public void setStroke(Stroke s) { graphics.setStroke(s); } public void setTransform(AffineTransform Tx) { graphics.setTransform(Tx); } public void transform(AffineTransform Tx) { graphics.transform(Tx); } public void translate(float x, float y) { graphics.translate(x, y); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/awt/environment/CwtAwtGraphicsEnvironment.java0000644000175000017500000000372411052336544031742 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.awt.environment; import de.intarsys.cwt.environment.IGraphicsEnvironment; /** * The AWT implementation of {@link IGraphicsEnvironment} * */ public class CwtAwtGraphicsEnvironment implements IGraphicsEnvironment { final private static CwtAwtGraphicsEnvironment ACTIVE = new CwtAwtGraphicsEnvironment(); static public CwtAwtGraphicsEnvironment get() { return ACTIVE; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/hybrid/0000755000175000017500000000000011412336240022065 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/hybrid/image/0000755000175000017500000000000011412336240023147 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/hybrid/image/ImageIOImageContainer.java0000644000175000017500000001506211411054014030071 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.hybrid.image; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.spi.IIORegistry; import javax.imageio.spi.ImageReaderSpi; import javax.imageio.stream.ImageInputStream; import de.intarsys.cwt.image.IImage; import de.intarsys.cwt.image.IImageEntry; import de.intarsys.cwt.image.ImageContainer; import de.intarsys.cwt.image.ImageMetadata; import de.intarsys.tools.locator.ILocator; import de.intarsys.tools.stream.StreamTools; /* * DOCME */ public class ImageIOImageContainer extends ImageContainer { static public ImageIOImageContainer createFromLocator(ILocator locator) throws IOException { ImageReaderSpi provider = lookupProviderBySuffix(locator.getType()); if (provider == null) { throw new IllegalArgumentException("unknown suffix"); } return createFromLocator(locator, provider); } static public ImageIOImageContainer createFromLocator(ILocator locator, ImageReaderSpi provider) throws IOException { ImageIOImageContainer container = new ImageIOImageContainer(locator, provider); container.open(); return container; } static public ImageIOImageContainer createFromLocator(ILocator locator, String formatName) throws IOException { ImageReaderSpi provider = lookupProviderByFormatName(formatName); if (provider == null) { throw new IllegalArgumentException("unknown format name"); } return createFromLocator(locator, provider); } static protected ImageReaderSpi lookupProviderByFormatName(String formatName) { if (formatName == null) { return null; } for (Iterator iter = IIORegistry.getDefaultInstance() .getServiceProviders(ImageReaderSpi.class, true); iter .hasNext();) { ImageReaderSpi provider = (ImageReaderSpi) iter.next(); String[] names = provider.getFormatNames(); for (int index = 0; index < names.length; index++) { String currentName = names[index]; if (formatName.equalsIgnoreCase(currentName)) { return provider; } } } return null; } static protected ImageReaderSpi lookupProviderBySuffix(String fileSuffix) { if (fileSuffix == null) { return null; } for (Iterator iter = IIORegistry.getDefaultInstance() .getServiceProviders(ImageReaderSpi.class, true); iter .hasNext();) { ImageReaderSpi provider = (ImageReaderSpi) iter.next(); String[] suffixes = provider.getFileSuffixes(); for (int index = 0; index < suffixes.length; index++) { String currentSuffix = suffixes[index]; if (fileSuffix.equalsIgnoreCase(currentSuffix)) { return provider; } } } return null; } private ILocator locator; private ImageReader imageReader; private ImageInputStream imageStream; private ImageReaderSpi provider; private int count; private ImageMetadata metadata; private List imageEntries = new ArrayList(); private InputStream inputStream; protected ImageIOImageContainer(ILocator locator, ImageReaderSpi provider) { super(); this.locator = locator; this.provider = provider; } @Override protected void basicClose() throws IOException { if (imageReader != null) { imageReader.dispose(); imageReader = null; } if (imageStream != null) { imageStream.close(); imageStream = null; } // must close the input stream ourself! imageStream is not required // (and FileCacheImapgeInputStream really doesn't) to close! StreamTools.close(inputStream); } public IImageEntry getImageAt(int index) { if (index >= getImageCount()) { throw new IllegalArgumentException("invalid index"); } return (IImageEntry) imageEntries.get(index); } public int getImageCount() { return count; } public ILocator getLocator() { return locator; } synchronized public ImageMetadata getMetadata() throws IOException { if (metadata == null) { metadata = ImageMetadata.createFromImageReader(imageReader); } return metadata; } protected IImage loadImage(int index) throws IOException { if (index >= getImageCount()) { throw new IllegalArgumentException("invalid index"); } BufferedImage bufferedImage = imageReader.read(index++); if (bufferedImage == null) { return null; } return new CwtHybridImage(bufferedImage); } protected void open() throws IOException { try { inputStream = getLocator().getInputStream(); imageStream = ImageIO.createImageInputStream(inputStream); imageReader = provider.createReaderInstance(); imageReader.setInput(imageStream); count = imageReader.getNumImages(true); for (int i = 0; i < count; i++) { imageEntries.add(new ImageIOImageEntry(this, i)); } } catch (IOException e) { basicClose(); throw e; } catch (Exception e) { basicClose(); throw new IOException("unexpected exception opening file"); } } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/hybrid/image/ImageIOImageEntry.java0000644000175000017500000000722311057252730027263 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.hybrid.image; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import de.intarsys.cwt.awt.image.IAwtImage; import de.intarsys.cwt.environment.IGraphicsContext; import de.intarsys.cwt.image.IImage; import de.intarsys.cwt.image.IImageContainer; import de.intarsys.cwt.image.ImageEntry; import de.intarsys.cwt.swt.image.ISwtImage; public class ImageIOImageEntry extends ImageEntry implements IAwtImage, ISwtImage { private static final int width = 400; private static final int height = 400; private int index; public ImageIOImageEntry(IImageContainer container, int index) { super(container); this.index = index; } public void drawFromGraphicsContext(IGraphicsContext graphicsContext, float x, float y) { getDelegate().drawFromGraphicsContext(graphicsContext, x, y); } public BufferedImage getBufferedImage() { return ((IAwtImage) getDelegate()).getBufferedImage(); } @Override synchronized protected IImage getErrorImage(Exception e) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gc = image.createGraphics(); gc.setBackground(Color.WHITE); gc.fillRect(0, 0, width, height); gc.setColor(Color.RED); gc.drawLine(0, 0, width, height); gc.drawLine(0, height, width, 0); gc.setColor(Color.BLACK); gc.drawString("error loading image (" + e.getMessage() + ")", 10, 20); return new CwtHybridImage(image); } public Image getImage(Device device) { return ((ISwtImage) getDelegate()).getImage(device); } public ImageData getImageData() { return ((ISwtImage) getDelegate()).getImageData(); } public int getIndex() { return index; } @Override protected IImage loadContent() throws IOException { return myContainer().loadImage(getIndex()); } private ImageIOImageContainer myContainer() { return (ImageIOImageContainer) getContainer(); } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/hybrid/image/CwtHybridImage.java0000644000175000017500000000672411037324046026671 0ustar twernertwernerpackage de.intarsys.cwt.hybrid.image; import java.awt.image.BufferedImage; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import de.intarsys.cwt.awt.environment.CwtAwtGraphicsContext; import de.intarsys.cwt.awt.image.CwtAwtImage; import de.intarsys.cwt.awt.image.IAwtImage; import de.intarsys.cwt.environment.IGraphicsContext; import de.intarsys.cwt.swt.environment.CwtSwtGraphicsContext; import de.intarsys.cwt.swt.image.CwtSwtImage; import de.intarsys.cwt.swt.image.ISwtImage; import de.intarsys.cwt.swt.image.ImageConverterAwt2Swt; import de.intarsys.cwt.swt.image.ImageConverterSwt2Awt; public class CwtHybridImage implements IAwtImage, ISwtImage { private CwtAwtImage awtImage; private CwtSwtImage swtImage; public CwtHybridImage(BufferedImage bufferedImage) { super(); this.awtImage = new CwtAwtImage(bufferedImage); } public CwtHybridImage(CwtAwtImage awtImage) { super(); this.awtImage = awtImage; } public CwtHybridImage(CwtSwtImage swtImage) { super(); this.swtImage = swtImage; } public CwtHybridImage(ImageData imageData) { super(); this.swtImage = new CwtSwtImage(imageData); } protected CwtAwtImage createAwtImage() { ImageConverterSwt2Awt converter = new ImageConverterSwt2Awt(swtImage .getImageData()); BufferedImage bufferedImage = converter.getBufferedImage(); return new CwtAwtImage(bufferedImage); } protected CwtSwtImage createSwtImage() { ImageConverterAwt2Swt converter = new ImageConverterAwt2Swt(awtImage .getBufferedImage()); ImageData imageData = converter.getImageData(); return new CwtSwtImage(imageData); } protected void drawFromAwt(CwtAwtGraphicsContext graphicsContext, float x, float y) { if (awtImage == null) { awtImage = createAwtImage(); } graphicsContext.drawImage(awtImage, x, y); } public void drawFromGraphicsContext(IGraphicsContext graphicsContext, float x, float y) { if (graphicsContext instanceof CwtSwtGraphicsContext) { drawFromSwt((CwtSwtGraphicsContext) graphicsContext, x, y); } else if (graphicsContext instanceof CwtAwtGraphicsContext) { drawFromAwt((CwtAwtGraphicsContext) graphicsContext, x, y); } else { throw new IllegalArgumentException("graphicsContext not supported"); } } protected void drawFromSwt(CwtSwtGraphicsContext graphicsContext, float x, float y) { if (swtImage == null) { try { swtImage = createSwtImage(); } catch (RuntimeException e) { // todo 0 dummy / error image return; } } CwtSwtGraphicsContext gc = graphicsContext; graphicsContext.drawImage(swtImage, x, y); } public BufferedImage getBufferedImage() { if (awtImage == null) { awtImage = createAwtImage(); } return awtImage.getBufferedImage(); } public int getHeight() { if (swtImage != null) { return swtImage.getHeight(); } if (awtImage != null) { return awtImage.getHeight(); } return 0; } public Image getImage(Device device) { if (swtImage == null) { swtImage = createSwtImage(); } return swtImage.getImage(device); } public ImageData getImageData() { if (swtImage == null) { swtImage = createSwtImage(); } return swtImage.getImageData(); } public int getWidth() { if (swtImage != null) { return swtImage.getWidth(); } if (awtImage != null) { return awtImage.getWidth(); } return 0; } } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/environment/0000755000175000017500000000000011412336240023150 5ustar twernertwernerlibiscwt-java-5.3.20100629/src/de/intarsys/cwt/environment/IGraphicsEnvironment.java0000644000175000017500000000330711052336546030125 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.environment; /** * The graphics environment for the active platform. * */ public interface IGraphicsEnvironment { } libiscwt-java-5.3.20100629/src/de/intarsys/cwt/environment/package.html0000644000175000017500000000032211052336546025437 0ustar twernertwerner An abstract graphics platform implementation.

The main intention is to abstract from AWT and SWT and provide a suitable virtual environment for rendering PDF primitives. libiscwt-java-5.3.20100629/src/de/intarsys/cwt/environment/IGraphicsContext.java0000644000175000017500000001312611053007220027226 0ustar twernertwerner/* * Copyright (c) 2008, intarsys consulting GmbH * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of intarsys nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.intarsys.cwt.environment; import java.awt.Color; import java.awt.Font; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.RenderingHints.Key; import java.awt.geom.AffineTransform; import java.util.Map; import de.intarsys.cwt.common.IPaint; import de.intarsys.cwt.image.IImage; /** * A platform independent (SWT, AWT) description of a graphics context. *

* The primary goal of this one is derived from the requirements enforced by * processing a PDF context stream. */ public interface IGraphicsContext { /** * Clip the subsequent drawing operations to the shape. This adds the new * clip shape to the existing one. * * @param shape */ public void clip(Shape shape); /** * Dispose the current context and all its resources. */ public void dispose(); /** * Draw s using the current graphics context state. * * @param s */ public void draw(Shape s); /** * Draw image image at coordinates x, * y. * * @param image * @param x * @param y */ public void drawImage(IImage image, float x, float y); /** * Draw a plain text string in the graphics. * * @param text * @param x * @param y */ public void drawString(String text, float x, float y); /** * Fill s using the current graphics context state. * * @param s */ public void fill(Shape s); /** * The current background color. * * @return */ public Color getBackgroundColor(); /** * The current clip. * * @return */ public Shape getClip(); /** * The current foregroumd color. * * @return */ public Color getForegroundColor(); /** * The associated {@link IGraphicsEnvironment} * * @return */ public IGraphicsEnvironment getGraphicsEnvironment(); /** * The current {@link RenderingHints} * * @return */ public RenderingHints getRenderingHints(); /** * The transformatiom currentlz active. * * @return */ public AffineTransform getTransform(); /** * Rotate the currently active transformation by theta. * * @param theta */ public void rotate(float theta); /** * Scale the currently active transformation by x, * y * * @param theta */ public void scale(float x, float y); /** * Assign a new background color. * * @param color */ public void setBackgroundColor(Color color); /** * Assign a new background {@link IPaint}. * * @param paint */ public void setBackgroundPaint(IPaint paint); /** * Assign the new shape as the clipping shape. * * @param shape */ public void setClip(Shape shape); /** * Set the current font for writing plain text in the graphics. * * @param font */ public void setFont(Font font); /** * Assign a new foreground color. * * @param c */ public void setForegroundColor(Color c); /** * Assign a new foreground {@link IPaint} * * @param paint */ public void setForegroundPaint(IPaint paint); /** * Set a specific rendering hint. * * @param hintKey * @param hintValue */ public void setRenderingHint(Key hintKey, Object hintValue); /** * Assign the currently active rendering hints. * * @param hints */ public void setRenderingHints(Map hints); /** * Assign the currently active {@link Stroke} * * @param s */ public void setStroke(Stroke s); /** * Set the currently active {@link AffineTransform} * * @param Tx */ public void setTransform(AffineTransform Tx); /** * Transform the {@link IGraphicsEnvironment} by transform * * @param transform */ public void transform(AffineTransform transform); /** * translate the currently active transformation by x, * y * * @param theta */ public void translate(float x, float y); } libiscwt-java-5.3.20100629/doc/0000755000175000017500000000000011412336240015521 5ustar twernertwernerlibiscwt-java-5.3.20100629/doc/3rd_party_licenses/0000755000175000017500000000000011412336240021315 5ustar twernertwernerlibiscwt-java-5.3.20100629/doc/3rd_party_licenses/lgpl-2.1.txt0000644000175000017500000006447211220404462023326 0ustar twernertwerner GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libiscwt-java-5.3.20100629/doc/3rd_party_licenses/freetype_license.txt0000644000175000017500000000241011031114350025371 0ustar twernertwerner The FreeType 2 font engine is copyrighted work and cannot be used legally without a software license. In order to make this project usable to a vast majority of developers, we distribute it under two mutually exclusive open-source licenses. This means that *you* must choose *one* of the two licenses described below, then obey all its terms and conditions when using FreeType 2 in any of your projects or products. - The FreeType License, found in the file `FTL.TXT', which is similar to the original BSD license *with* an advertising clause that forces you to explicitly cite the FreeType project in your product's documentation. All details are in the license file. This license is suited to products which don't use the GNU General Public License. - The GNU General Public License version 2, found in `GPL.TXT' (any later version can be used also), for programs which already use the GPL. Note that the FTL is incompatible with the GPL due to its advertisement clause. The contributed PCF driver comes with a license similar to that of the X Window System. It is compatible to the above two licenses (see file src/pcf/readme). --- end of licence.txt --- libiscwt-java-5.3.20100629/doc/3rd_party_licenses/jna_license.txt0000644000175000017500000000026511030721450024330 0ustar twernertwernerThis program uses jna (https://jna.dev.java.net/). jna is governed by the LGPL license, available in this directory. jna source code is available at https://jna.dev.java.net/.libiscwt-java-5.3.20100629/doc/3rd_party_licenses/FTL.txt0000644000175000017500000001576611031114350022513 0ustar twernertwerner The FreeType Project LICENSE ---------------------------- 2002-Apr-11 Copyright 1996-2002 by David Turner, Robert Wilhelm, and Werner Lemberg Introduction ============ The FreeType Project is distributed in several archive packages; some of them may contain, in addition to the FreeType font engine, various tools and contributions which rely on, or relate to, the FreeType Project. This license applies to all files found in such packages, and which do not fall under their own explicit license. The license affects thus the FreeType font engine, the test programs, documentation and makefiles, at the very least. This license was inspired by the BSD, Artistic, and IJG (Independent JPEG Group) licenses, which all encourage inclusion and use of free software in commercial and freeware products alike. As a consequence, its main points are that: o We don't promise that this software works. However, we will be interested in any kind of bug reports. (`as is' distribution) o You can use this software for whatever you want, in parts or full form, without having to pay us. (`royalty-free' usage) o You may not pretend that you wrote this software. If you use it, or only parts of it, in a program, you must acknowledge somewhere in your documentation that you have used the FreeType code. (`credits') We specifically permit and encourage the inclusion of this software, with or without modifications, in commercial products. We disclaim all warranties covering The FreeType Project and assume no liability related to The FreeType Project. Finally, many people asked us for a preferred form for a credit/disclaimer to use in compliance with this license. We thus encourage you to use the following text: """ Portions of this software are copyright © 1996-2002 The FreeType Project (www.freetype.org). All rights reserved. """ Legal Terms =========== 0. Definitions -------------- Throughout this license, the terms `package', `FreeType Project', and `FreeType archive' refer to the set of files originally distributed by the authors (David Turner, Robert Wilhelm, and Werner Lemberg) as the `FreeType Project', be they named as alpha, beta or final release. `You' refers to the licensee, or person using the project, where `using' is a generic term including compiling the project's source code as well as linking it to form a `program' or `executable'. This program is referred to as `a program using the FreeType engine'. This license applies to all files distributed in the original FreeType Project, including all source code, binaries and documentation, unless otherwise stated in the file in its original, unmodified form as distributed in the original archive. If you are unsure whether or not a particular file is covered by this license, you must contact us to verify this. The FreeType Project is copyright (C) 1996-2000 by David Turner, Robert Wilhelm, and Werner Lemberg. All rights reserved except as specified below. 1. No Warranty -------------- THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO USE, OF THE FREETYPE PROJECT. 2. Redistribution ----------------- This license grants a worldwide, royalty-free, perpetual and irrevocable right and license to use, execute, perform, compile, display, copy, create derivative works of, distribute and sublicense the FreeType Project (in both source and object code forms) and derivative works thereof for any purpose; and to authorize others to exercise some or all of the rights granted herein, subject to the following conditions: o Redistribution of source code must retain this license file (`FTL.TXT') unaltered; any additions, deletions or changes to the original files must be clearly indicated in accompanying documentation. The copyright notices of the unaltered, original files must be preserved in all copies of source files. o Redistribution in binary form must provide a disclaimer that states that the software is based in part of the work of the FreeType Team, in the distribution documentation. We also encourage you to put an URL to the FreeType web page in your documentation, though this isn't mandatory. These conditions apply to any software derived from or based on the FreeType Project, not just the unmodified files. If you use our work, you must acknowledge us. However, no fee need be paid to us. 3. Advertising -------------- Neither the FreeType authors and contributors nor you shall use the name of the other for commercial, advertising, or promotional purposes without specific prior written permission. We suggest, but do not require, that you use one or more of the following phrases to refer to this software in your documentation or advertising materials: `FreeType Project', `FreeType Engine', `FreeType library', or `FreeType Distribution'. As you have not signed this license, you are not required to accept it. However, as the FreeType Project is copyrighted material, only this license, or another one contracted with the authors, grants you the right to use, distribute, and modify it. Therefore, by using, distributing, or modifying the FreeType Project, you indicate that you understand and accept all the terms of this license. 4. Contacts ----------- There are two mailing lists related to FreeType: o freetype@freetype.org Discusses general use and applications of FreeType, as well as future and wanted additions to the library and distribution. If you are looking for support, start in this list if you haven't found anything to help you in the documentation. o devel@freetype.org Discusses bugs, as well as engine internals, design issues, specific licenses, porting, etc. o http://www.freetype.org Holds the current FreeType web page, which will allow you to download our latest development version and read online documentation. You can also contact us individually at: David Turner Robert Wilhelm Werner Lemberg --- end of LICENSE.TXT --- libiscwt-java-5.3.20100629/javadoc/0000755000175000017500000000000011412336240016363 5ustar twernertwerner